-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenaicompat.go
More file actions
165 lines (146 loc) · 4.28 KB
/
openaicompat.go
File metadata and controls
165 lines (146 loc) · 4.28 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package iteragent
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// OpenAICompatConfig configures an OpenAI-compatible provider.
type OpenAICompatConfig struct {
BaseURL string
Model string
APIKey string
}
type openaiCompatProvider struct {
cfg OpenAICompatConfig
client *http.Client
}
// NewOpenAICompat returns an OpenAI-compatible provider.
// The returned provider implements both Provider and TokenStreamer.
func NewOpenAICompat(cfg OpenAICompatConfig) Provider {
return &openaiCompatProvider{
cfg: cfg,
client: &http.Client{Timeout: 120 * time.Second},
}
}
func (p *openaiCompatProvider) Name() string {
return fmt.Sprintf("openai-compat(%s)", p.cfg.Model)
}
type openaiResponse struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
Error *struct {
Message string `json:"message"`
} `json:"error,omitempty"`
}
// openaiReasoningEffort maps ThinkingLevel to reasoning_effort string for OpenAI.
func openaiReasoningEffort(level ThinkingLevel) string {
switch level {
case ThinkingLevelMinimal, ThinkingLevelLow:
return "low"
case ThinkingLevelMedium:
return "medium"
case ThinkingLevelHigh:
return "high"
default:
return ""
}
}
// supportsReasoningEffort returns true if the base URL is an OpenAI endpoint.
func (p *openaiCompatProvider) supportsReasoningEffort() bool {
return strings.Contains(p.cfg.BaseURL, "openai.com")
}
// buildOpenAIBody constructs the JSON request body for OpenAI-compat completions.
func (p *openaiCompatProvider) buildOpenAIBody(messages []Message, opt CompletionOptions, stream bool) ([]byte, error) {
reqMap := map[string]interface{}{
"model": p.cfg.Model,
"messages": messages,
"stream": stream,
}
if opt.MaxTokens > 0 {
reqMap["max_tokens"] = opt.MaxTokens
}
if opt.Temperature > 0 {
reqMap["temperature"] = opt.Temperature
}
if p.supportsReasoningEffort() && opt.ThinkingLevel != ThinkingLevelOff && opt.ThinkingLevel != "" {
if effort := openaiReasoningEffort(opt.ThinkingLevel); effort != "" {
reqMap["reasoning_effort"] = effort
}
}
return json.Marshal(reqMap)
}
// CompleteStream implements TokenStreamer using OpenAI SSE format.
func (p *openaiCompatProvider) CompleteStream(ctx context.Context, messages []Message, opt CompletionOptions, onToken func(string)) (string, error) {
body, err := p.buildOpenAIBody(messages, opt, true)
if err != nil {
return "", fmt.Errorf("marshal request: %w", err)
}
headers := map[string]string{
"Authorization": "Bearer " + p.cfg.APIKey,
}
var full strings.Builder
sseClient := NewSSEClient()
err = sseClient.Stream(ctx, p.cfg.BaseURL+"/chat/completions", headers, 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("openai stream: %w", err)
}
result := full.String()
if result == "" {
return "", fmt.Errorf("empty streaming response from openai-compat")
}
return result, nil
}
func (p *openaiCompatProvider) Complete(ctx context.Context, messages []Message, opts ...CompletionOptions) (string, error) {
var opt CompletionOptions
if len(opts) > 0 {
opt = opts[0]
}
body, err := p.buildOpenAIBody(messages, opt, false)
if err != nil {
return "", fmt.Errorf("marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", p.cfg.BaseURL+"/chat/completions", 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("http request: %w", err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("read response: %w", err)
}
var result openaiResponse
if err := json.Unmarshal(raw, &result); err != nil {
return "", fmt.Errorf("unmarshal response: %w", err)
}
if result.Error != nil {
return "", fmt.Errorf("openai error: %s", result.Error.Message)
}
if len(result.Choices) == 0 {
return "", fmt.Errorf("empty response from openai")
}
return result.Choices[0].Message.Content, nil
}