-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnvidia.go
More file actions
126 lines (108 loc) · 2.96 KB
/
nvidia.go
File metadata and controls
126 lines (108 loc) · 2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package iteragent
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
type nvidiaProvider struct {
cfg OpenAICompatConfig
client *http.Client
}
func NewNvidia(cfg OpenAICompatConfig) Provider {
return &nvidiaProvider{
cfg: cfg,
client: &http.Client{Timeout: 120 * time.Second},
}
}
func (p *nvidiaProvider) Name() string {
return fmt.Sprintf("nvidia(%s)", p.cfg.Model)
}
func (p *nvidiaProvider) Complete(ctx context.Context, messages []Message, opts ...CompletionOptions) (string, error) {
url := p.cfg.BaseURL
if url == "" {
url = "https://integrate.api.nvidia.com/v1/chat/completions"
} else {
url = url + "/chat/completions"
}
reqBody := map[string]interface{}{
"model": p.cfg.Model,
"messages": messages,
"stream": false,
}
body, err := json.Marshal(reqBody)
if err != nil {
return "", fmt.Errorf("marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
if err != nil {
return "", fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+p.cfg.APIKey)
resp, err := p.client.Do(req)
if err != nil {
return "", fmt.Errorf("do request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("read response: %w", err)
}
if resp.StatusCode != 200 {
return "", fmt.Errorf("nvidia API error (%d): %s", resp.StatusCode, string(respBody))
}
var parsed openaiResponse
if err := json.Unmarshal(respBody, &parsed); err != nil {
return "", fmt.Errorf("unmarshal response: %w", err)
}
if len(parsed.Choices) == 0 {
return "", fmt.Errorf("no response from nvidia")
}
return parsed.Choices[0].Message.Content, nil
}
// CompleteStream implements TokenStreamer for Nvidia using the OpenAI-compatible SSE endpoint.
func (p *nvidiaProvider) CompleteStream(ctx context.Context, messages []Message, opt CompletionOptions, onToken func(string)) (string, error) {
url := p.cfg.BaseURL
if url == "" {
url = "https://integrate.api.nvidia.com/v1/chat/completions"
} else {
url = url + "/chat/completions"
}
reqBody := map[string]interface{}{
"model": p.cfg.Model,
"messages": messages,
"stream": true,
}
if opt.MaxTokens > 0 {
reqBody["max_tokens"] = opt.MaxTokens
}
if opt.Temperature > 0 {
reqBody["temperature"] = opt.Temperature
}
body, err := json.Marshal(reqBody)
if err != nil {
return "", fmt.Errorf("marshal request: %w", err)
}
var full strings.Builder
sseClient := NewSSEClient()
err = sseClient.Stream(ctx, url, map[string]string{"Authorization": "Bearer " + p.cfg.APIKey}, body, func(e SSEEvent) {
if e.Data == "[DONE]" {
return
}
if token, ok := ParseOpenAISSE(e.Data); ok && token != "" {
full.WriteString(token)
if onToken != nil {
onToken(token)
}
}
})
if err != nil {
return "", fmt.Errorf("nvidia stream: %w", err)
}
return full.String(), nil
}