@@ -0,0 +1,281 @@
1+package provider
2+
3+import (
4+ "bufio"
5+ "context"
6+ "encoding/json"
7+ "io"
8+ "strings"
9+
10+ "github.com/rs/zerolog/log"
11+)
12+
13+const roleSystem = "system"
14+
15+// Anthropic Messages API request types.
16+
17+type anthropicRequest struct {
18+ Model string `json:"model"`
19+ Messages []anthropicMessage `json:"messages"`
20+ System string `json:"system,omitempty"`
21+ MaxTokens int `json:"max_tokens"`
22+ Temperature float64 `json:"temperature,omitempty"`
23+ Stream bool `json:"stream"`
24+ Tools []anthropicTool `json:"tools,omitempty"`
25+}
26+
27+type anthropicMessage struct {
28+ Role string `json:"role"`
29+ Content interface{} `json:"content"` // string or []anthropicContentBlock
30+}
31+
32+// anthropicTextBlock is a "text" content block.
33+type anthropicTextBlock struct {
34+ Type string `json:"type"` // "text"
35+ Text string `json:"text"`
36+}
37+
38+// anthropicToolUseBlock is a "tool_use" content block.
39+type anthropicToolUseBlock struct {
40+ Type string `json:"type"` // "tool_use"
41+ ID string `json:"id"`
42+ Name string `json:"name"`
43+ Input json.RawMessage `json:"input"`
44+}
45+
46+// anthropicToolResultBlock is a "tool_result" content block.
47+type anthropicToolResultBlock struct {
48+ Type string `json:"type"` // "tool_result"
49+ ToolUseID string `json:"tool_use_id"`
50+ Content string `json:"content"`
51+}
52+
53+type anthropicTool struct {
54+ Name string `json:"name"`
55+ Description string `json:"description,omitempty"`
56+ InputSchema interface{} `json:"input_schema"`
57+}
58+
59+// Anthropic SSE streaming response types.
60+
61+type anthropicContentBlockStart struct {
62+ Type string `json:"type"`
63+ Index int `json:"index"`
64+ ContentBlock struct {
65+ Type string `json:"type"` // "text" or "tool_use"
66+ Text string `json:"text,omitempty"`
67+ ID string `json:"id,omitempty"`
68+ Name string `json:"name,omitempty"`
69+ } `json:"content_block"`
70+}
71+
72+type anthropicContentBlockDelta struct {
73+ Type string `json:"type"`
74+ Index int `json:"index"`
75+ Delta struct {
76+ Type string `json:"type"` // "text_delta", "thinking_delta", "input_json_delta", "signature_delta"
77+ Text string `json:"text,omitempty"`
78+ Thinking string `json:"thinking,omitempty"`
79+ PartialJSON string `json:"partial_json,omitempty"`
80+ } `json:"delta"`
81+}
82+
83+// toAnthropicMessages converts provider-agnostic messages to Anthropic Messages API format.
84+// Returns (system, messages) — system is extracted and hoisted out.
85+func toAnthropicMessages(messages []Message) (string, []anthropicMessage) {
86+ var systemParts []string
87+ var result []anthropicMessage
88+
89+ for _, m := range messages {
90+ if m.Role == roleSystem {
91+ systemParts = append(systemParts, m.Content)
92+ continue
93+ }
94+
95+ if m.Role == "tool" {
96+ // Tool results become user messages with tool_result content blocks
97+ result = append(result, anthropicMessage{
98+ Role: "user",
99+ Content: []anthropicToolResultBlock{
100+ {
101+ Type: "tool_result",
102+ ToolUseID: m.ToolCallID,
103+ Content: m.Content,
104+ },
105+ },
106+ })
107+ continue
108+ }
109+
110+ if m.Role == "assistant" && len(m.ToolCalls) > 0 {
111+ // Assistant message with tool calls
112+ var blocks []interface{}
113+ if m.Content != "" {
114+ blocks = append(blocks, anthropicTextBlock{
115+ Type: "text",
116+ Text: m.Content,
117+ })
118+ }
119+ for _, tc := range m.ToolCalls {
120+ input := tc.Arguments
121+ if len(input) == 0 {
122+ input = json.RawMessage(`{}`)
123+ }
124+ blocks = append(blocks, anthropicToolUseBlock{
125+ Type: "tool_use",
126+ ID: tc.ID,
127+ Name: tc.Name,
128+ Input: input,
129+ })
130+ }
131+ result = append(result, anthropicMessage{
132+ Role: "assistant",
133+ Content: blocks,
134+ })
135+ continue
136+ }
137+
138+ // Simple text message
139+ result = append(result, anthropicMessage{
140+ Role: m.Role,
141+ Content: m.Content,
142+ })
143+ }
144+
145+ return strings.Join(systemParts, "\n\n"), result
146+}
147+
148+// toAnthropicTools converts provider-agnostic tools to Anthropic tool format.
149+func toAnthropicTools(tools []Tool) ([]anthropicTool, error) {
150+ if tools == nil {
151+ return nil, nil
152+ }
153+ result := make([]anthropicTool, len(tools))
154+ for i, t := range tools {
155+ var schema interface{}
156+ if len(t.Parameters) > 0 {
157+ if err := json.Unmarshal(t.Parameters, &schema); err != nil {
158+ return nil, err
159+ }
160+ }
161+ if schema == nil {
162+ schema = map[string]interface{}{
163+ "type": "object",
164+ "properties": map[string]interface{}{},
165+ }
166+ }
167+ result[i] = anthropicTool{
168+ Name: t.Name,
169+ Description: t.Description,
170+ InputSchema: schema,
171+ }
172+ }
173+ return result, nil
174+}
175+
176+// parseAnthropicSSEStream reads Anthropic Messages API SSE events and emits StreamEvents.
177+//
178+// Anthropic SSE format:
179+//
180+// event: message_start / content_block_start / content_block_delta /
181+// content_block_stop / message_delta / message_stop / ping
182+// data: { JSON payload }
183+func parseAnthropicSSEStream(ctx context.Context, reader io.Reader, ch chan<- StreamEvent) {
184+ scanner := bufio.NewScanner(reader)
185+ scanner.Buffer(make([]byte, 0, 64*1024), 512*1024)
186+
187+ // Track tool call index mapping: anthropic block index -> our tool call counter
188+ toolCallCount := 0
189+ blockIsToolUse := make(map[int]bool)
190+ blockToolIndex := make(map[int]int)
191+
192+ var currentEventType string
193+
194+ for scanner.Scan() {
195+ line := scanner.Text()
196+
197+ // Parse event type line
198+ if strings.HasPrefix(line, "event: ") {
199+ currentEventType = strings.TrimPrefix(line, "event: ")
200+ continue
201+ }
202+
203+ // Parse data line
204+ if !strings.HasPrefix(line, "data: ") {
205+ continue
206+ }
207+ data := strings.TrimPrefix(line, "data: ")
208+
209+ switch currentEventType {
210+ case "message_stop":
211+ trySend(ctx, ch, StreamEvent{Type: EventDone})
212+ return
213+
214+ case "content_block_start":
215+ var evt anthropicContentBlockStart
216+ if err := json.Unmarshal([]byte(data), &evt); err != nil {
217+ log.Warn().Err(err).Msg("Failed to parse anthropic content_block_start")
218+ continue
219+ }
220+ if evt.ContentBlock.Type == "tool_use" {
221+ idx := toolCallCount
222+ toolCallCount++
223+ blockIsToolUse[evt.Index] = true
224+ blockToolIndex[evt.Index] = idx
225+ if !trySend(ctx, ch, StreamEvent{
226+ Type: EventToolCallBegin,
227+ ToolCallIndex: idx,
228+ ToolCallID: evt.ContentBlock.ID,
229+ ToolCallName: evt.ContentBlock.Name,
230+ }) {
231+ return
232+ }
233+ }
234+
235+ case "content_block_delta":
236+ var evt anthropicContentBlockDelta
237+ if err := json.Unmarshal([]byte(data), &evt); err != nil {
238+ log.Warn().Err(err).Msg("Failed to parse anthropic content_block_delta")
239+ continue
240+ }
241+
242+ switch evt.Delta.Type {
243+ case "text_delta":
244+ if evt.Delta.Text != "" {
245+ if !trySend(ctx, ch, StreamEvent{Type: EventContentDelta, Content: evt.Delta.Text}) {
246+ return
247+ }
248+ }
249+ case "thinking_delta":
250+ if evt.Delta.Thinking != "" {
251+ if !trySend(ctx, ch, StreamEvent{Type: EventReasoningDelta, Content: evt.Delta.Thinking}) {
252+ return
253+ }
254+ }
255+ case "input_json_delta":
256+ if evt.Delta.PartialJSON != "" && blockIsToolUse[evt.Index] {
257+ if !trySend(ctx, ch, StreamEvent{
258+ Type: EventToolCallDelta,
259+ ToolCallIndex: blockToolIndex[evt.Index],
260+ ToolCallArgs: evt.Delta.PartialJSON,
261+ }) {
262+ return
263+ }
264+ }
265+ }
266+
267+ case "ping", "message_start", "message_delta", "content_block_stop":
268+ // Ignored
269+ }
270+
271+ currentEventType = ""
272+ }
273+
274+ if err := scanner.Err(); err != nil {
275+ trySend(ctx, ch, StreamEvent{Type: EventError, Err: err})
276+ return
277+ }
278+
279+ // Stream ended without message_stop
280+ trySend(ctx, ch, StreamEvent{Type: EventDone})
281+}