xonecas.io
6312
Ga

go-opencode-ai-zen-sdk / commit 0359249

feat: normalized zen provider sdk

xonecas2026-02-17 035924957efeee9ef1375525531e3b5b8d93cc3c

24 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

.golangci.yml+17−0
@@ -0,0 +1,17 @@
1+run:
2+ timeout: 5m
3+ tests: true
4+
5+linters:
6+ enable:
7+ - errcheck
8+ - gofmt
9+ - goimports
10+ - govet
11+ - ineffassign
12+ - staticcheck
13+ - typecheck
14+ - unused
15+
16+issues:
17+ exclude-use-default: false
README.md+144−0
@@ -0,0 +1,144 @@
1+# go-opencode-ai-zen-sdk
2+
3+Minimal Go SDK for OpenCode Zen.
4+
5+## Install
6+
7+```bash
8+go get github.com/sacenox/go-opencode-ai-zen-sdk
9+```
10+
11+## Usage
12+
13+```go
14+package main
15+
16+import (
17+ "context"
18+ "encoding/json"
19+ "fmt"
20+
21+ zen "github.com/sacenox/go-opencode-ai-zen-sdk"
22+)
23+
24+func main() {
25+ client, err := zen.NewClient(zen.Config{APIKey: "your-key"})
26+ if err != nil {
27+ panic(err)
28+ }
29+
30+ req := zen.UnifiedRequest{
31+ Model: "gpt-5.2-codex",
32+ Body: map[string]any{
33+ "input": "Write a Go hello world",
34+ },
35+ }
36+
37+ resp, err := client.UnifiedCreate(context.Background(), req)
38+ if err != nil {
39+ panic(err)
40+ }
41+
42+ var payload map[string]any
43+ _ = json.Unmarshal(resp.Body, &payload)
44+ fmt.Println(payload)
45+}
46+```
47+
48+## Normalized Request (reasoning + tools)
49+
50+```go
51+req := zen.NormalizedRequest{
52+ Model: "gpt-5.2-codex",
53+ System: "You are a precise coding assistant.",
54+ Messages: []zen.NormalizedMessage{
55+ {Role: "user", Content: "Explain what a mutex is."},
56+ },
57+ Reasoning: &zen.NormalizedReasoning{Effort: "low"},
58+ Tools: []zen.NormalizedTool{
59+ {
60+ Name: "lookup",
61+ Description: "Query internal docs",
62+ Parameters: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}`),
63+ },
64+ },
65+ ToolChoice: &zen.NormalizedToolChoice{Type: zen.ToolChoiceAuto},
66+}
67+
68+resp, err := client.UnifiedCreateNormalized(ctx, req)
69+if err != nil {
70+ panic(err)
71+}
72+fmt.Println(string(resp.Body))
73+```
74+
75+## Gemini (models endpoint)
76+
77+```go
78+req := zen.GeminiRequest{
79+ Contents: []zen.GeminiContent{
80+ {Role: "user", Parts: []zen.GeminiPart{{Text: "Explain Go interfaces"}}},
81+ },
82+}
83+
84+resp, err := client.CreateModelContentTyped(ctx, "gemini-3-pro", req)
85+if err != nil {
86+ panic(err)
87+}
88+fmt.Println(string(resp))
89+```
90+
91+## Streaming
92+
93+```go
94+events, errs, err := client.UnifiedStream(ctx, zen.UnifiedRequest{
95+ Model: "gpt-5.2-codex",
96+ Stream: true,
97+ Body: map[string]any{
98+ "input": "Stream me a poem",
99+ "stream": true,
100+ },
101+})
102+if err != nil {
103+ panic(err)
104+}
105+
106+for ev := range events {
107+ fmt.Println(ev.Event, string(ev.Data))
108+}
109+
110+if err := <-errs; err != nil {
111+ panic(err)
112+}
113+```
114+
115+## List Models
116+
117+```go
118+resp, err := client.ListModels(ctx)
119+if err != nil {
120+ panic(err)
121+}
122+fmt.Println(len(resp.Data))
123+```
124+
125+## Development
126+
127+```bash
128+gofmt -w *.go
129+go test ./...
130+golangci-lint run
131+```
132+
133+## Disclaimer
134+
135+This project is not affiliated with opencode.ai.
136+
137+## Notes
138+
139+- Base URL defaults to `https://opencode.ai/zen/v1`.
140+- Unified routing uses model prefixes:
141+ - `gpt-*` -> `/responses`
142+ - `claude-*` -> `/messages`
143+ - `gemini-*` -> `/models/<model>`
144+ - fallback -> `/chat/completions`
chat_completions.go+55−0
@@ -0,0 +1,55 @@
1+package zen
2+
3+import (
4+ "context"
5+ "encoding/json"
6+)
7+
8+func (c *Client) CreateChatCompletion(ctx context.Context, body any, raw json.RawMessage) (json.RawMessage, error) {
9+ payload, err := jsonBody(body, raw)
10+ if err != nil {
11+ return nil, err
12+ }
13+ data, _, err := c.doRequest(ctx, "POST", "/chat/completions", payload)
14+ if err != nil {
15+ return nil, err
16+ }
17+ return json.RawMessage(data), nil
18+}
19+
20+func (c *Client) CreateChatCompletionTyped(ctx context.Context, req ChatCompletionsRequest) (json.RawMessage, error) {
21+ return c.CreateChatCompletion(ctx, req, nil)
22+}
23+
24+func (c *Client) StreamChatCompletion(ctx context.Context, body any, raw json.RawMessage) (<-chan StreamEvent, <-chan error, error) {
25+ payload, err := jsonBody(body, raw)
26+ if err != nil {
27+ return nil, nil, err
28+ }
29+
30+ stream, err := c.startStream(ctx, "POST", "/chat/completions", payload)
31+ if err != nil {
32+ return nil, nil, err
33+ }
34+
35+ errs := make(chan error, 1)
36+ out := make(chan StreamEvent)
37+ go func() {
38+ defer close(out)
39+ defer close(errs)
40+ defer func() { _ = stream.Close() }()
41+
42+ for ev := range stream.Events {
43+ out <- ev
44+ }
45+ if stream.Err != nil {
46+ errs <- stream.Err
47+ }
48+ }()
49+
50+ return out, errs, nil
51+}
52+
53+func (c *Client) StreamChatCompletionTyped(ctx context.Context, req ChatCompletionsRequest) (<-chan StreamEvent, <-chan error, error) {
54+ return c.StreamChatCompletion(ctx, req, nil)
55+}
client.go+31−0
@@ -0,0 +1,31 @@
1+package zen
2+
3+import (
4+ "context"
5+ "net/http"
6+)
7+
8+type Client struct {
9+ cfg Config
10+ httpClient *http.Client
11+}
12+
13+func NewClient(cfg Config) (*Client, error) {
14+ if err := cfg.applyDefaults(); err != nil {
15+ return nil, err
16+ }
17+
18+ httpClient := cfg.HTTPClient
19+ if httpClient == nil {
20+ httpClient = &http.Client{Timeout: cfg.Timeout}
21+ }
22+
23+ return &Client{
24+ cfg: cfg,
25+ httpClient: httpClient,
26+ }, nil
27+}
28+
29+func (c *Client) Do(ctx context.Context, method, path string, body []byte) ([]byte, http.Header, error) {
30+ return c.doRequest(ctx, method, path, body)
31+}
config.go+57−0
@@ -0,0 +1,57 @@
1+package zen
2+
3+import (
4+ "errors"
5+ "net/http"
6+ "strings"
7+ "time"
8+)
9+
10+const defaultBaseURL = "https://opencode.ai/zen/v1"
11+
12+type RetryConfig struct {
13+ MaxRetries int
14+ RetryOnNonIdempotent bool
15+ Backoff func(attempt int) time.Duration
16+}
17+
18+type Config struct {
19+ APIKey string
20+ BaseURL string
21+ Timeout time.Duration
22+ UserAgent string
23+ HTTPClient *http.Client
24+ Retry RetryConfig
25+}
26+
27+func (c *Config) applyDefaults() error {
28+ if strings.TrimSpace(c.APIKey) == "" {
29+ return errors.New("zen: API key is required")
30+ }
31+
32+ if strings.TrimSpace(c.BaseURL) == "" {
33+ c.BaseURL = defaultBaseURL
34+ }
35+
36+ c.BaseURL = strings.TrimRight(c.BaseURL, "/")
37+
38+ if c.Timeout == 0 {
39+ c.Timeout = 60 * time.Second
40+ }
41+
42+ if strings.TrimSpace(c.UserAgent) == "" {
43+ c.UserAgent = "go-opencode-zen-sdk/0.1"
44+ }
45+
46+ if c.Retry.Backoff == nil {
47+ c.Retry.Backoff = func(attempt int) time.Duration {
48+ base := 200 * time.Millisecond
49+ if attempt <= 0 {
50+ return base
51+ }
52+ return base * time.Duration(1<<attempt)
53+ }
54+ }
55+
56+ return nil
57+}
errors.go+54−0
@@ -0,0 +1,54 @@
1+package zen
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "net/http"
7+)
8+
9+type APIError struct {
10+ StatusCode int
11+ RequestID string
12+ Message string
13+ Body []byte
14+}
15+
16+func (e *APIError) Error() string {
17+ if e.Message == "" {
18+ return fmt.Sprintf("zen: request failed with status %d", e.StatusCode)
19+ }
20+ return fmt.Sprintf("zen: request failed with status %d: %s", e.StatusCode, e.Message)
21+}
22+
23+type apiErrorEnvelope struct {
24+ Error struct {
25+ Message string `json:"message"`
26+ Type string `json:"type"`
27+ Code string `json:"code"`
28+ } `json:"error"`
29+ Message string `json:"message"`
30+}
31+
32+func newAPIError(status int, header http.Header, body []byte) *APIError {
33+ reqID := header.Get("x-request-id")
34+ if reqID == "" {
35+ reqID = header.Get("request-id")
36+ }
37+
38+ msg := ""
39+ var env apiErrorEnvelope
40+ if err := json.Unmarshal(body, &env); err == nil {
41+ if env.Error.Message != "" {
42+ msg = env.Error.Message
43+ } else if env.Message != "" {
44+ msg = env.Message
45+ }
46+ }
47+
48+ return &APIError{
49+ StatusCode: status,
50+ RequestID: reqID,
51+ Message: msg,
52+ Body: body,
53+ }
54+}
gemini.go+55−0
@@ -0,0 +1,55 @@
1+package zen
2+
3+import (
4+ "context"
5+ "encoding/json"
6+)
7+
8+func (c *Client) CreateModelContent(ctx context.Context, model string, body any, raw json.RawMessage) (json.RawMessage, error) {
9+ payload, err := jsonBody(body, raw)
10+ if err != nil {
11+ return nil, err
12+ }
13+ data, _, err := c.doRequest(ctx, "POST", "/models/"+model, payload)
14+ if err != nil {
15+ return nil, err
16+ }
17+ return json.RawMessage(data), nil
18+}
19+
20+func (c *Client) CreateModelContentTyped(ctx context.Context, model string, req GeminiRequest) (json.RawMessage, error) {
21+ return c.CreateModelContent(ctx, model, req, nil)
22+}
23+
24+func (c *Client) StreamModelContent(ctx context.Context, model string, body any, raw json.RawMessage) (<-chan StreamEvent, <-chan error, error) {
25+ payload, err := jsonBody(body, raw)
26+ if err != nil {
27+ return nil, nil, err
28+ }
29+
30+ stream, err := c.startStream(ctx, "POST", "/models/"+model, payload)
31+ if err != nil {
32+ return nil, nil, err
33+ }
34+
35+ errs := make(chan error, 1)
36+ out := make(chan StreamEvent)
37+ go func() {
38+ defer close(out)
39+ defer close(errs)
40+ defer func() { _ = stream.Close() }()
41+
42+ for ev := range stream.Events {
43+ out <- ev
44+ }
45+ if stream.Err != nil {
46+ errs <- stream.Err
47+ }
48+ }()
49+
50+ return out, errs, nil
51+}
52+
53+func (c *Client) StreamModelContentTyped(ctx context.Context, model string, req GeminiRequest) (<-chan StreamEvent, <-chan error, error) {
54+ return c.StreamModelContent(ctx, model, req, nil)
55+}
go.mod+3−0
@@ -0,0 +1,3 @@
1+module github.com/sacenox/go-opencode-ai-zen-sdk
2+
3+go 1.22
http.go+101−0
@@ -0,0 +1,101 @@
1+package zen
2+
3+import (
4+ "bytes"
5+ "context"
6+ "encoding/json"
7+ "io"
8+ "net/http"
9+ "strings"
10+ "time"
11+)
12+
13+var retryableStatus = map[int]bool{
14+ http.StatusTooManyRequests: true,
15+ http.StatusInternalServerError: true,
16+ http.StatusBadGateway: true,
17+ http.StatusServiceUnavailable: true,
18+ http.StatusGatewayTimeout: true,
19+}
20+
21+func (c *Client) doRequest(ctx context.Context, method, path string, body []byte) ([]byte, http.Header, error) {
22+ url := joinURL(c.cfg.BaseURL, path)
23+ if body == nil {
24+ body = []byte{}
25+ }
26+
27+ retries := c.cfg.Retry.MaxRetries
28+ if !isIdempotent(method) && !c.cfg.Retry.RetryOnNonIdempotent {
29+ retries = 0
30+ }
31+
32+ var lastErr error
33+ for attempt := 0; attempt <= retries; attempt++ {
34+ req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(body))
35+ if err != nil {
36+ return nil, nil, err
37+ }
38+
39+ if len(body) > 0 {
40+ req.Header.Set("Content-Type", "application/json")
41+ }
42+ req.Header.Set("Authorization", "Bearer "+c.cfg.APIKey)
43+ req.Header.Set("User-Agent", c.cfg.UserAgent)
44+
45+ resp, err := c.httpClient.Do(req)
46+ if err != nil {
47+ lastErr = err
48+ if attempt < retries {
49+ time.Sleep(c.cfg.Retry.Backoff(attempt))
50+ continue
51+ }
52+ return nil, nil, err
53+ }
54+
55+ payload, readErr := io.ReadAll(resp.Body)
56+ _ = resp.Body.Close()
57+ if readErr != nil {
58+ return nil, resp.Header, readErr
59+ }
60+
61+ if resp.StatusCode >= 200 && resp.StatusCode < 300 {
62+ return payload, resp.Header, nil
63+ }
64+
65+ apiErr := newAPIError(resp.StatusCode, resp.Header, payload)
66+ lastErr = apiErr
67+ if attempt < retries && retryableStatus[resp.StatusCode] {
68+ time.Sleep(c.cfg.Retry.Backoff(attempt))
69+ continue
70+ }
71+ return nil, resp.Header, apiErr
72+ }
73+
74+ return nil, nil, lastErr
75+}
76+
77+func jsonBody(v any, raw json.RawMessage) ([]byte, error) {
78+ if raw != nil {
79+ return raw, nil
80+ }
81+ if v == nil {
82+ return []byte("{}"), nil
83+ }
84+ return json.Marshal(v)
85+}
86+
87+func joinURL(base, path string) string {
88+ if strings.HasPrefix(path, "/") {
89+ return base + path
90+ }
91+ return base + "/" + path
92+}
93+
94+func isIdempotent(method string) bool {
95+ switch strings.ToUpper(method) {
96+ case http.MethodGet, http.MethodHead, http.MethodOptions:
97+ return true
98+ default:
99+ return false
100+ }
101+}
marshal.go+18−0
@@ -0,0 +1,18 @@
1+package zen
2+
3+import "encoding/json"
4+
5+func marshalWithExtra(base map[string]any, extra map[string]any) ([]byte, error) {
6+ if len(extra) == 0 {
7+ return json.Marshal(base)
8+ }
9+
10+ for k, v := range extra {
11+ if _, exists := base[k]; exists {
12+ continue
13+ }
14+ base[k] = v
15+ }
16+
17+ return json.Marshal(base)
18+}
messages.go+55−0
@@ -0,0 +1,55 @@
1+package zen
2+
3+import (
4+ "context"
5+ "encoding/json"
6+)
7+
8+func (c *Client) CreateMessage(ctx context.Context, body any, raw json.RawMessage) (json.RawMessage, error) {
9+ payload, err := jsonBody(body, raw)
10+ if err != nil {
11+ return nil, err
12+ }
13+ data, _, err := c.doRequest(ctx, "POST", "/messages", payload)
14+ if err != nil {
15+ return nil, err
16+ }
17+ return json.RawMessage(data), nil
18+}
19+
20+func (c *Client) CreateMessageTyped(ctx context.Context, req MessagesRequest) (json.RawMessage, error) {
21+ return c.CreateMessage(ctx, req, nil)
22+}
23+
24+func (c *Client) StreamMessage(ctx context.Context, body any, raw json.RawMessage) (<-chan StreamEvent, <-chan error, error) {
25+ payload, err := jsonBody(body, raw)
26+ if err != nil {
27+ return nil, nil, err
28+ }
29+
30+ stream, err := c.startStream(ctx, "POST", "/messages", payload)
31+ if err != nil {
32+ return nil, nil, err
33+ }
34+
35+ errs := make(chan error, 1)
36+ out := make(chan StreamEvent)
37+ go func() {
38+ defer close(out)
39+ defer close(errs)
40+ defer func() { _ = stream.Close() }()
41+
42+ for ev := range stream.Events {
43+ out <- ev
44+ }
45+ if stream.Err != nil {
46+ errs <- stream.Err
47+ }
48+ }()
49+
50+ return out, errs, nil
51+}
52+
53+func (c *Client) StreamMessageTyped(ctx context.Context, req MessagesRequest) (<-chan StreamEvent, <-chan error, error) {
54+ return c.StreamMessage(ctx, req, nil)
55+}
models.go+31−0
@@ -0,0 +1,31 @@
1+package zen
2+
3+import (
4+ "context"
5+ "encoding/json"
6+)
7+
8+type ModelsResponse struct {
9+ Data []Model `json:"data"`
10+ Raw json.RawMessage `json:"-"`
11+}
12+
13+type Model struct {
14+ ID string `json:"id"`
15+ Object string `json:"object"`
16+ OwnedBy string `json:"owned_by"`
17+}
18+
19+func (c *Client) ListModels(ctx context.Context) (*ModelsResponse, error) {
20+ data, _, err := c.doRequest(ctx, "GET", "/models", nil)
21+ if err != nil {
22+ return nil, err
23+ }
24+
25+ var resp ModelsResponse
26+ if err := json.Unmarshal(data, &resp); err != nil {
27+ return nil, err
28+ }
29+ resp.Raw = json.RawMessage(data)
30+ return &resp, nil
31+}
normalize_helpers_test.go+75−0
@@ -0,0 +1,75 @@
1+package zen
2+
3+import "testing"
4+
5+func TestMapOpenAIToolChoice(t *testing.T) {
6+ _, err := mapOpenAIToolChoice(NormalizedToolChoice{Type: ToolChoiceTool})
7+ if err == nil {
8+ t.Fatalf("expected error for missing tool name")
9+ }
10+
11+ choice, err := mapOpenAIToolChoice(NormalizedToolChoice{Type: ToolChoiceAuto})
12+ if err != nil {
13+ t.Fatalf("unexpected error: %v", err)
14+ }
15+ if choice != "auto" {
16+ t.Fatalf("expected auto, got %v", choice)
17+ }
18+}
19+
20+func TestMapAnthropicToolChoice(t *testing.T) {
21+ choice, err := mapAnthropicToolChoice(NormalizedToolChoice{Type: ToolChoiceNone})
22+ if err != nil {
23+ t.Fatalf("unexpected error: %v", err)
24+ }
25+ if choice != nil {
26+ t.Fatalf("expected nil choice for none")
27+ }
28+}
29+
30+func TestMapGeminiToolChoice(t *testing.T) {
31+ _, err := mapGeminiToolChoice(NormalizedToolChoice{Type: ToolChoiceTool})
32+ if err == nil {
33+ t.Fatalf("expected error for missing tool name")
34+ }
35+
36+ choice, err := mapGeminiToolChoice(NormalizedToolChoice{Type: ToolChoiceRequired})
37+ if err != nil {
38+ t.Fatalf("unexpected error: %v", err)
39+ }
40+ if choice == nil || choice.FunctionCallingConfig == nil || choice.FunctionCallingConfig.Mode != "ANY" {
41+ t.Fatalf("expected ANY mode")
42+ }
43+}
44+
45+func TestNormalizeAnthropicMessages(t *testing.T) {
46+ system, msgs := normalizeAnthropicMessages("base", []NormalizedMessage{
47+ {Role: "system", Content: "sys"},
48+ {Role: "developer", Content: "dev"},
49+ {Role: "user", Content: "hi"},
50+ })
51+ if system == "" {
52+ t.Fatalf("expected system to be combined")
53+ }
54+ if len(msgs) != 1 || msgs[0].Role != "user" {
55+ t.Fatalf("expected only user message")
56+ }
57+}
58+
59+func TestMapEffortToBudget(t *testing.T) {
60+ if mapEffortToBudget("low") == 0 {
61+ t.Fatalf("expected non-zero budget")
62+ }
63+ if mapEffortToBudget("unknown") != 0 {
64+ t.Fatalf("expected zero budget")
65+ }
66+}
67+
68+func TestMapEffortToThinkingLevel(t *testing.T) {
69+ if mapEffortToThinkingLevel("medium") != "MEDIUM" {
70+ t.Fatalf("expected MEDIUM level")
71+ }
72+ if mapEffortToThinkingLevel("unknown") != "" {
73+ t.Fatalf("expected empty level")
74+ }
75+}
normalized.go+360−0
@@ -0,0 +1,360 @@
1+package zen
2+
3+import (
4+ "encoding/json"
5+ "errors"
6+ "strings"
7+)
8+
9+type ToolChoiceType string
10+
11+const (
12+ ToolChoiceAuto ToolChoiceType = "auto"
13+ ToolChoiceNone ToolChoiceType = "none"
14+ ToolChoiceRequired ToolChoiceType = "required"
15+ ToolChoiceTool ToolChoiceType = "tool"
16+)
17+
18+type NormalizedToolChoice struct {
19+ Type ToolChoiceType
20+ Name string
21+}
22+
23+type NormalizedTool struct {
24+ Name string
25+ Description string
26+ Parameters json.RawMessage
27+}
28+
29+type NormalizedReasoning struct {
30+ Effort string
31+ BudgetTokens int
32+}
33+
34+type NormalizedMessage struct {
35+ Role string
36+ Content string
37+}
38+
39+type NormalizedRequest struct {
40+ Model string
41+ System string
42+ Messages []NormalizedMessage
43+ Tools []NormalizedTool
44+ ToolChoice *NormalizedToolChoice
45+ Reasoning *NormalizedReasoning
46+ Temperature *float64
47+ MaxTokens *int
48+ Stream bool
49+ Endpoint EndpointType
50+ Extra map[string]any
51+}
52+
53+func (r NormalizedRequest) ToResponsesRequest() (*ResponsesRequest, error) {
54+ req := &ResponsesRequest{
55+ Model: r.Model,
56+ Instructions: r.System,
57+ Temperature: r.Temperature,
58+ MaxOutputTokens: r.MaxTokens,
59+ Stream: r.Stream,
60+ Extra: r.Extra,
61+ }
62+
63+ if len(r.Messages) == 0 {
64+ req.Input = ""
65+ } else {
66+ messages := make([]ResponsesInputMessage, 0, len(r.Messages))
67+ for _, m := range r.Messages {
68+ messages = append(messages, ResponsesInputMessage(m))
69+ }
70+ req.Input = messages
71+ }
72+
73+ if r.Reasoning != nil && r.Reasoning.Effort != "" {
74+ req.Reasoning = &ResponsesReasoning{Effort: r.Reasoning.Effort}
75+ }
76+
77+ if len(r.Tools) > 0 {
78+ req.Tools = make([]ResponsesTool, 0, len(r.Tools))
79+ for _, t := range r.Tools {
80+ req.Tools = append(req.Tools, ResponsesTool{
81+ Type: "function",
82+ Function: ResponsesToolFunction(t),
83+ })
84+ }
85+ }
86+
87+ if r.ToolChoice != nil {
88+ choice, err := mapOpenAIToolChoice(*r.ToolChoice)
89+ if err != nil {
90+ return nil, err
91+ }
92+ req.ToolChoice = choice
93+ }
94+
95+ return req, nil
96+}
97+
98+func (r NormalizedRequest) ToChatCompletionsRequest() (*ChatCompletionsRequest, error) {
99+ messages := make([]ChatMessage, 0, len(r.Messages)+1)
100+ if strings.TrimSpace(r.System) != "" {
101+ messages = append(messages, ChatMessage{Role: "system", Content: r.System})
102+ }
103+ for _, m := range r.Messages {
104+ messages = append(messages, ChatMessage(m))
105+ }
106+
107+ req := &ChatCompletionsRequest{
108+ Model: r.Model,
109+ Messages: messages,
110+ Temperature: r.Temperature,
111+ MaxTokens: r.MaxTokens,
112+ Stream: r.Stream,
113+ Extra: r.Extra,
114+ }
115+
116+ if r.Reasoning != nil && r.Reasoning.Effort != "" {
117+ req.Reasoning = &ChatReasoning{Effort: r.Reasoning.Effort}
118+ }
119+
120+ if len(r.Tools) > 0 {
121+ req.Tools = make([]ChatTool, 0, len(r.Tools))
122+ for _, t := range r.Tools {
123+ req.Tools = append(req.Tools, ChatTool{
124+ Type: "function",
125+ Function: ChatToolFunction(t),
126+ })
127+ }
128+ }
129+
130+ if r.ToolChoice != nil {
131+ choice, err := mapOpenAIToolChoice(*r.ToolChoice)
132+ if err != nil {
133+ return nil, err
134+ }
135+ req.ToolChoice = choice
136+ }
137+
138+ return req, nil
139+}
140+
141+func (r NormalizedRequest) ToMessagesRequest() (*MessagesRequest, error) {
142+ system, messages := normalizeAnthropicMessages(r.System, r.Messages)
143+ req := &MessagesRequest{
144+ Model: r.Model,
145+ System: system,
146+ Messages: messages,
147+ Temperature: r.Temperature,
148+ MaxTokens: r.MaxTokens,
149+ Stream: r.Stream,
150+ Extra: r.Extra,
151+ }
152+
153+ if r.Reasoning != nil {
154+ budget := r.Reasoning.BudgetTokens
155+ if budget == 0 && r.Reasoning.Effort != "" {
156+ budget = mapEffortToBudget(r.Reasoning.Effort)
157+ }
158+ if budget > 0 {
159+ req.Thinking = &AnthropicThinking{Type: "enabled", BudgetTokens: budget}
160+ }
161+ }
162+
163+ if r.ToolChoice != nil && r.ToolChoice.Type == ToolChoiceNone {
164+ return req, nil
165+ }
166+
167+ if len(r.Tools) > 0 {
168+ req.Tools = make([]AnthropicTool, 0, len(r.Tools))
169+ for _, t := range r.Tools {
170+ req.Tools = append(req.Tools, AnthropicTool{
171+ Name: t.Name,
172+ Description: t.Description,
173+ InputSchema: t.Parameters,
174+ })
175+ }
176+ }
177+
178+ if r.ToolChoice != nil {
179+ choice, err := mapAnthropicToolChoice(*r.ToolChoice)
180+ if err != nil {
181+ return nil, err
182+ }
183+ req.ToolChoice = choice
184+ }
185+
186+ return req, nil
187+}
188+
189+func (r NormalizedRequest) ToGeminiRequest() (*GeminiRequest, error) {
190+ contents := make([]GeminiContent, 0, len(r.Messages))
191+ for _, m := range r.Messages {
192+ role := strings.ToLower(strings.TrimSpace(m.Role))
193+ if role == "assistant" {
194+ role = "model"
195+ }
196+ contents = append(contents, GeminiContent{
197+ Role: role,
198+ Parts: []GeminiPart{{Text: m.Content}},
199+ })
200+ }
201+
202+ var systemInstruction *GeminiContent
203+ if strings.TrimSpace(r.System) != "" {
204+ systemInstruction = &GeminiContent{
205+ Role: "system",
206+ Parts: []GeminiPart{{Text: r.System}},
207+ }
208+ }
209+
210+ req := &GeminiRequest{
211+ Contents: contents,
212+ SystemInstruction: systemInstruction,
213+ Stream: r.Stream,
214+ Extra: r.Extra,
215+ }
216+
217+ config := &GeminiGenerationConfig{
218+ Temperature: r.Temperature,
219+ MaxOutputTokens: r.MaxTokens,
220+ }
221+ if r.Reasoning != nil && r.Reasoning.Effort != "" {
222+ level := mapEffortToThinkingLevel(r.Reasoning.Effort)
223+ if level != "" {
224+ config.ThinkingConfig = &GeminiThinkingConfig{ThinkingLevel: level}
225+ }
226+ }
227+ if config.Temperature != nil || config.MaxOutputTokens != nil || config.ThinkingConfig != nil {
228+ req.GenerationConfig = config
229+ }
230+
231+ if len(r.Tools) > 0 {
232+ tool := GeminiTool{FunctionDeclarations: make([]GeminiFunctionDeclaration, 0, len(r.Tools))}
233+ for _, t := range r.Tools {
234+ tool.FunctionDeclarations = append(tool.FunctionDeclarations, GeminiFunctionDeclaration(t))
235+ }
236+ req.Tools = []GeminiTool{tool}
237+ }
238+
239+ if r.ToolChoice != nil {
240+ config, err := mapGeminiToolChoice(*r.ToolChoice)
241+ if err != nil {
242+ return nil, err
243+ }
244+ if config != nil {
245+ req.ToolConfig = config
246+ }
247+ }
248+
249+ return req, nil
250+}
251+
252+func mapOpenAIToolChoice(choice NormalizedToolChoice) (any, error) {
253+ switch choice.Type {
254+ case ToolChoiceAuto:
255+ return "auto", nil
256+ case ToolChoiceNone:
257+ return "none", nil
258+ case ToolChoiceRequired:
259+ return "required", nil
260+ case ToolChoiceTool:
261+ if strings.TrimSpace(choice.Name) == "" {
262+ return nil, errors.New("zen: tool choice name is required")
263+ }
264+ return map[string]any{
265+ "type": "function",
266+ "function": map[string]any{
267+ "name": choice.Name,
268+ },
269+ }, nil
270+ default:
271+ return nil, errors.New("zen: unsupported tool choice")
272+ }
273+}
274+
275+func mapAnthropicToolChoice(choice NormalizedToolChoice) (*AnthropicToolChoice, error) {
276+ switch choice.Type {
277+ case ToolChoiceAuto:
278+ return &AnthropicToolChoice{Type: "auto"}, nil
279+ case ToolChoiceRequired:
280+ return &AnthropicToolChoice{Type: "any"}, nil
281+ case ToolChoiceTool:
282+ if strings.TrimSpace(choice.Name) == "" {
283+ return nil, errors.New("zen: tool choice name is required")
284+ }
285+ return &AnthropicToolChoice{Type: "tool", Name: choice.Name}, nil
286+ case ToolChoiceNone:
287+ return nil, nil
288+ default:
289+ return nil, errors.New("zen: unsupported tool choice")
290+ }
Cut short: this commit's diff is over 1000 lines.
normalized_test.go+123−0
Cut short: this commit's diff is over 1000 lines.
responses.go+55−0
Cut short: this commit's diff is over 1000 lines.
stream.go+122−0
Cut short: this commit's diff is over 1000 lines.
stream_test.go+56−0
Cut short: this commit's diff is over 1000 lines.
types_chat.go+62−0
Cut short: this commit's diff is over 1000 lines.
types_gemini.go+74−0
Cut short: this commit's diff is over 1000 lines.
types_messages.go+67−0
Cut short: this commit's diff is over 1000 lines.
types_responses.go+68−0
Cut short: this commit's diff is over 1000 lines.
unified.go+241−0
Cut short: this commit's diff is over 1000 lines.
unified_test.go+122−0
Cut short: this commit's diff is over 1000 lines.