-
-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathopencode_go.go
More file actions
284 lines (239 loc) · 9 KB
/
Copy pathopencode_go.go
File metadata and controls
284 lines (239 loc) · 9 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package provider
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/routatic/proxy/internal/client"
"github.com/routatic/proxy/internal/config"
"github.com/routatic/proxy/internal/core"
"github.com/routatic/proxy/internal/transformer"
"github.com/routatic/proxy/pkg/types"
)
// OpenCodeGoProvider implements core.Provider for the OpenCode Go backend.
type OpenCodeGoProvider struct {
baseProvider
}
// NewOpenCodeGoProvider creates a new OpenCodeGoProvider.
func NewOpenCodeGoProvider(atomic *config.AtomicConfig) *OpenCodeGoProvider {
return &OpenCodeGoProvider{baseProvider: newBaseProvider(atomic)}
}
// Name returns the provider identifier.
func (p *OpenCodeGoProvider) Name() string { return "opencode-go" }
// Capabilities returns provider-level capabilities.
func (p *OpenCodeGoProvider) Capabilities() core.ProviderCapabilities {
return core.ProviderCapabilities{
SupportsStreaming: true,
SupportsTools: true,
SupportsThinking: true,
SupportsImageInput: true,
MaxContextLength: 128_000,
DefaultMaxTokens: 4096,
}
}
// ModelCapabilities returns per-model capabilities. Returns false if unknown.
func (p *OpenCodeGoProvider) ModelCapabilities(modelID string) (core.ProviderCapabilities, bool) {
caps := p.Capabilities()
// qwen3.7-max has a larger context window on the Go provider.
if modelID == "qwen3.7-max" {
caps.MaxContextLength = 1_000_000
}
// MiniMax models support 1M context.
switch modelID {
case "minimax-m2.5", "minimax-m2.7", "minimax-m3":
caps.MaxContextLength = 1_000_000
}
return caps, true
}
// WireFormat returns the wire format for the given model on the Go provider.
func (p *OpenCodeGoProvider) WireFormat(modelID string) core.WireFormat {
if isAnthropicNativeGo(modelID) {
return core.WireFormatAnthropic
}
return core.WireFormatOpenAIChat
}
func isAnthropicNativeGo(modelID string) bool {
switch modelID {
case "minimax-m2.5", "minimax-m2.7", "minimax-m3",
"qwen3.5-plus", "qwen3.6-plus", "qwen3.7-plus", "qwen3.7-max":
return true
default:
return false
}
}
// RoundTripName returns the model ID to use in the upstream request.
func (p *OpenCodeGoProvider) RoundTripName(model config.ModelConfig) string {
return model.ModelID
}
// StreamIdleTimeout returns the maximum gap between bytes on an active stream.
func (p *OpenCodeGoProvider) StreamIdleTimeout(model config.ModelConfig) time.Duration {
const fallback = 5 * time.Minute
cfg := p.atomic.Get()
ms := cfg.OpenCodeGo.StreamTimeoutMs
if ms <= 0 {
ms = cfg.OpenCodeGo.TimeoutMs
}
if ms <= 0 {
return fallback
}
return time.Duration(ms) * time.Millisecond
}
// Execute sends a non-streaming request and returns the response.
func (p *OpenCodeGoProvider) Execute(ctx context.Context, req *core.NormalizedRequest, model config.ModelConfig) (*core.ExecuteResult, error) {
switch p.WireFormat(model.ModelID) {
case core.WireFormatAnthropic:
return p.executeAnthropic(ctx, req, model)
default:
return p.executeOpenAI(ctx, req, model)
}
}
// Stream sends a streaming request and returns an io.ReadCloser for SSE events.
func (p *OpenCodeGoProvider) Stream(ctx context.Context, req *core.NormalizedRequest, model config.ModelConfig) (io.ReadCloser, error) {
switch p.WireFormat(model.ModelID) {
case core.WireFormatAnthropic:
return p.streamAnthropic(ctx, req, model)
default:
return p.streamOpenAI(ctx, req, model)
}
}
// ── OpenAI Chat Completions ────────────────────────────────────────────
func (p *OpenCodeGoProvider) executeOpenAI(ctx context.Context, req *core.NormalizedRequest, model config.ModelConfig) (*core.ExecuteResult, error) {
cfg := p.atomic.Get()
endpoint := cfg.OpenCodeGo.BaseURL
apiKey := p.nextAPIKey(cfg.EffectiveAPIKeys())
openaiReq := transformer.TransformRequestFromNormalized(req, model)
streamFalse := false
openaiReq.Stream = &streamFalse
start := time.Now()
resp, err := p.doRequest(ctx, endpoint, apiKey, openaiReq, false)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
var chatResp types.ChatCompletionResponse
if err := json.Unmarshal(body, &chatResp); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
normResp := transformer.OpenAIResponseToNormalized(&chatResp, model.ModelID)
anthropicResp := core.DenormalizeResponse(normResp)
resultBody, err := json.Marshal(anthropicResp)
if err != nil {
return nil, fmt.Errorf("failed to marshal response: %w", err)
}
return &core.ExecuteResult{
Body: resultBody,
ModelID: model.ModelID,
Latency: time.Since(start),
}, nil
}
func (p *OpenCodeGoProvider) streamOpenAI(ctx context.Context, req *core.NormalizedRequest, model config.ModelConfig) (io.ReadCloser, error) {
cfg := p.atomic.Get()
endpoint := cfg.OpenCodeGo.BaseURL
apiKey := p.nextAPIKey(cfg.EffectiveAPIKeys())
openaiReq := transformer.TransformRequestFromNormalized(req, model)
streamTrue := true
openaiReq.Stream = &streamTrue
resp, err := p.doRequest(ctx, endpoint, apiKey, openaiReq, true)
if err != nil {
return nil, err
}
return resp.Body, nil
}
// ── Anthropic Messages ────────────────────────────────────────────────
func (p *OpenCodeGoProvider) executeAnthropic(ctx context.Context, req *core.NormalizedRequest, model config.ModelConfig) (*core.ExecuteResult, error) {
cfg := p.atomic.Get()
endpoint := cfg.OpenCodeGo.AnthropicBaseURL
apiKey := p.nextAPIKey(cfg.EffectiveAPIKeys())
anthropicReq := transformer.NormalizedToAnthropic(req, model)
rawBody, err := json.Marshal(anthropicReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal anthropic request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(rawBody))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+apiKey)
httpReq.Header.Set("x-api-key", apiKey)
start := time.Now()
resp, err := p.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= http.StatusBadRequest {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, &client.APIError{StatusCode: resp.StatusCode, Body: string(bodyBytes)}
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
return &core.ExecuteResult{
Body: body,
ModelID: model.ModelID,
Latency: time.Since(start),
}, nil
}
func (p *OpenCodeGoProvider) streamAnthropic(ctx context.Context, req *core.NormalizedRequest, model config.ModelConfig) (io.ReadCloser, error) {
cfg := p.atomic.Get()
endpoint := cfg.OpenCodeGo.AnthropicBaseURL
apiKey := p.nextAPIKey(cfg.EffectiveAPIKeys())
anthropicReq := transformer.NormalizedToAnthropic(req, model)
rawBody, err := json.Marshal(anthropicReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal anthropic request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(rawBody))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+apiKey)
httpReq.Header.Set("x-api-key", apiKey)
httpReq.Header.Set("Accept", "text/event-stream")
resp, err := p.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
if resp.StatusCode >= http.StatusBadRequest {
bodyBytes, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return nil, &client.APIError{StatusCode: resp.StatusCode, Body: string(bodyBytes)}
}
return resp.Body, nil
}
// ── HTTP helpers ──────────────────────────────────────────────────────
func (p *OpenCodeGoProvider) doRequest(ctx context.Context, endpoint, apiKey string, req any, stream bool) (*http.Response, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+apiKey)
if stream {
httpReq.Header.Set("Accept", "text/event-stream")
}
resp, err := p.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
if resp.StatusCode >= http.StatusBadRequest {
bodyBytes, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return nil, &client.APIError{StatusCode: resp.StatusCode, Body: string(bodyBytes)}
}
return resp, nil
}