|
| 1 | +package iteragent |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +type nvidiaProvider struct { |
| 14 | + cfg OpenAICompatConfig |
| 15 | + client *http.Client |
| 16 | +} |
| 17 | + |
| 18 | +func NewNvidia(cfg OpenAICompatConfig) Provider { |
| 19 | + return &nvidiaProvider{ |
| 20 | + cfg: cfg, |
| 21 | + client: &http.Client{Timeout: 120 * time.Second}, |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +func (p *nvidiaProvider) Name() string { |
| 26 | + return fmt.Sprintf("nvidia(%s)", p.cfg.Model) |
| 27 | +} |
| 28 | + |
| 29 | +func (p *nvidiaProvider) Complete(ctx context.Context, messages []Message) (string, error) { |
| 30 | + url := p.cfg.BaseURL + "/chat/completions" |
| 31 | + if p.cfg.BaseURL == "" { |
| 32 | + url = "https://integrate.api.nvidia.com/v1/chat/completions" |
| 33 | + } |
| 34 | + |
| 35 | + reqBody := openaiRequest{ |
| 36 | + Model: p.cfg.Model, |
| 37 | + Messages: messages, |
| 38 | + Stream: false, |
| 39 | + } |
| 40 | + |
| 41 | + body, err := json.Marshal(reqBody) |
| 42 | + if err != nil { |
| 43 | + return "", fmt.Errorf("marshal request: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body)) |
| 47 | + if err != nil { |
| 48 | + return "", fmt.Errorf("create request: %w", err) |
| 49 | + } |
| 50 | + |
| 51 | + req.Header.Set("Content-Type", "application/json") |
| 52 | + req.Header.Set("Authorization", "Bearer "+p.cfg.APIKey) |
| 53 | + |
| 54 | + resp, err := p.client.Do(req) |
| 55 | + if err != nil { |
| 56 | + return "", fmt.Errorf("do request: %w", err) |
| 57 | + } |
| 58 | + defer resp.Body.Close() |
| 59 | + |
| 60 | + respBody, err := io.ReadAll(resp.Body) |
| 61 | + if err != nil { |
| 62 | + return "", fmt.Errorf("read response: %w", err) |
| 63 | + } |
| 64 | + |
| 65 | + if resp.StatusCode != 200 { |
| 66 | + return "", fmt.Errorf("nvidia API error (%d): %s", resp.StatusCode, string(respBody)) |
| 67 | + } |
| 68 | + |
| 69 | + var parsed openaiResponse |
| 70 | + if err := json.Unmarshal(respBody, &parsed); err != nil { |
| 71 | + return "", fmt.Errorf("unmarshal response: %w", err) |
| 72 | + } |
| 73 | + |
| 74 | + if len(parsed.Choices) == 0 { |
| 75 | + return "", fmt.Errorf("no response from nvidia") |
| 76 | + } |
| 77 | + |
| 78 | + return parsed.Choices[0].Message.Content, nil |
| 79 | +} |
0 commit comments