anthropic.go

361 lines
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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
// Package anthropic provides an Anthropic implementation of assistant.Backend.
package anthropic

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"congo.gg/pkg/assistant"
)

const (
	defaultBaseURL    = "https://api.anthropic.com/v1"
	defaultAPIVersion = "2023-06-01"
)

// backend implements assistant.Backend for Anthropic.
type backend struct {
	apiKey     string
	baseURL    string
	apiVersion string
	client     *http.Client
}

// Option configures the Anthropic backend.
type Option func(*backend)

// WithBaseURL sets a custom base URL.
func WithBaseURL(url string) Option {
	return func(b *backend) {
		b.baseURL = url
	}
}

// WithAPIVersion sets a custom API version.
func WithAPIVersion(version string) Option {
	return func(b *backend) {
		b.apiVersion = version
	}
}

// WithHTTPClient sets a custom HTTP client.
func WithHTTPClient(client *http.Client) Option {
	return func(b *backend) {
		b.client = client
	}
}

// New creates an Anthropic assistant.
func New(apiKey string, opts ...Option) (*assistant.Assistant, error) {
	if apiKey == "" {
		return nil, assistant.ErrNoAPIKey
	}

	b := &backend{
		apiKey:     apiKey,
		baseURL:    defaultBaseURL,
		apiVersion: defaultAPIVersion,
		client:     http.DefaultClient,
	}

	for _, opt := range opts {
		opt(b)
	}

	return &assistant.Assistant{Backend: b}, nil
}

// Chat sends a chat completion request.
func (b *backend) Chat(ctx context.Context, req assistant.ChatRequest) (*assistant.ChatResponse, error) {
	body := b.buildRequest(req, false)

	respBody, err := b.doRequest(ctx, body)
	if err != nil {
		return nil, err
	}
	defer respBody.Close()

	var resp messageResponse
	if err := json.NewDecoder(respBody).Decode(&resp); err != nil {
		return nil, fmt.Errorf("failed to decode response: %w", err)
	}

	return b.convertResponse(&resp), nil
}

// Stream sends a streaming chat completion request.
func (b *backend) Stream(ctx context.Context, req assistant.ChatRequest) (*assistant.StreamReader, error) {
	body := b.buildRequest(req, true)

	respBody, err := b.doRequest(ctx, body)
	if err != nil {
		return nil, err
	}

	return assistant.NewStreamReader(respBody, parseStreamEvent), nil
}

func (b *backend) buildRequest(req assistant.ChatRequest, stream bool) map[string]any {
	messages := make([]map[string]any, 0, len(req.Messages))

	// Convert messages
	for _, m := range req.Messages {
		// Skip system messages (handled separately)
		if m.Role == assistant.RoleSystem {
			continue
		}

		role := m.Role
		if role == assistant.RoleTool {
			// Anthropic uses "user" role with tool_result content
			role = "user"
		}

		msg := map[string]any{
			"role": role,
		}

		// Handle different message types
		if m.Role == assistant.RoleTool {
			// Tool result
			msg["content"] = []map[string]any{{
				"type":        "tool_result",
				"tool_use_id": m.ToolCallID,
				"content":     m.Content,
			}}
		} else if len(m.ToolCalls) > 0 {
			// Assistant message with tool use
			content := make([]map[string]any, 0)
			if m.Content != "" {
				content = append(content, map[string]any{
					"type": "text",
					"text": m.Content,
				})
			}
			for _, tc := range m.ToolCalls {
				input := make(map[string]any)
				if tc.Arguments != "" {
					if err := json.Unmarshal([]byte(tc.Arguments), &input); err != nil {
						// Log malformed JSON but send empty input rather than silently proceeding
						// with partial data. The agent will see missing arguments and can retry.
						input = map[string]any{"_error": fmt.Sprintf("malformed arguments: %s", err)}
					}
				}
				content = append(content, map[string]any{
					"type":  "tool_use",
					"id":    tc.ID,
					"name":  tc.Name,
					"input": input,
				})
			}
			msg["content"] = content
		} else {
			msg["content"] = m.Content
		}

		messages = append(messages, msg)
	}

	body := map[string]any{
		"model":    req.Model,
		"messages": messages,
		"stream":   stream,
	}

	// Add system message
	if req.System != "" {
		body["system"] = req.System
	}

	if req.MaxTokens > 0 {
		body["max_tokens"] = req.MaxTokens
	} else {
		body["max_tokens"] = 4096 // Anthropic requires max_tokens
	}

	if req.Temperature != nil {
		body["temperature"] = *req.Temperature
	}

	if len(req.Tools) > 0 {
		tools := make([]map[string]any, len(req.Tools))
		for i, t := range req.Tools {
			tool := map[string]any{
				"name":        t.Name,
				"description": t.Description,
			}
			if t.Parameters != nil {
				tool["input_schema"] = t.Parameters
			} else {
				tool["input_schema"] = map[string]any{"type": "object"}
			}
			tools[i] = tool
		}
		body["tools"] = tools
	}

	return body
}

func (b *backend) doRequest(ctx context.Context, body map[string]any) (io.ReadCloser, error) {
	jsonBody, err := json.Marshal(body)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal request: %w", err)
	}

	httpReq, err := http.NewRequestWithContext(ctx, "POST", b.baseURL+"/messages", bytes.NewReader(jsonBody))
	if err != nil {
		return nil, fmt.Errorf("failed to create request: %w", err)
	}

	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("x-api-key", b.apiKey)
	httpReq.Header.Set("anthropic-version", b.apiVersion)

	resp, err := b.client.Do(httpReq)
	if err != nil {
		return nil, fmt.Errorf("request failed: %w", err)
	}

	if resp.StatusCode != http.StatusOK {
		return nil, assistant.ParseErrorResponse(resp)
	}

	return resp.Body, nil
}

func (b *backend) convertResponse(resp *messageResponse) *assistant.ChatResponse {
	var content string
	var toolCalls []assistant.ToolCall

	for _, block := range resp.Content {
		switch block.Type {
		case "text":
			content = block.Text
		case "tool_use":
			args, _ := json.Marshal(block.Input)
			toolCalls = append(toolCalls, assistant.ToolCall{
				ID:        block.ID,
				Name:      block.Name,
				Arguments: string(args),
			})
		}
	}

	finishReason := "stop"
	if resp.StopReason == "tool_use" {
		finishReason = "tool_calls"
	}

	return &assistant.ChatResponse{
		Content:      content,
		ToolCalls:    toolCalls,
		FinishReason: finishReason,
		Usage: assistant.Usage{
			PromptTokens:     resp.Usage.InputTokens,
			CompletionTokens: resp.Usage.OutputTokens,
			TotalTokens:      resp.Usage.InputTokens + resp.Usage.OutputTokens,
		},
	}
}

// --- Anthropic API types ---

type messageResponse struct {
	Content []struct {
		Type  string         `json:"type"`
		Text  string         `json:"text,omitempty"`
		ID    string         `json:"id,omitempty"`
		Name  string         `json:"name,omitempty"`
		Input map[string]any `json:"input,omitempty"`
	} `json:"content"`
	StopReason string `json:"stop_reason"`
	Usage      struct {
		InputTokens  int `json:"input_tokens"`
		OutputTokens int `json:"output_tokens"`
	} `json:"usage"`
}

type streamEvent struct {
	Type         string `json:"type"`
	Index        int    `json:"index,omitempty"`
	ContentBlock *struct {
		Type  string         `json:"type"`
		ID    string         `json:"id,omitempty"`
		Name  string         `json:"name,omitempty"`
		Text  string         `json:"text,omitempty"`
		Input map[string]any `json:"input,omitempty"`
	} `json:"content_block,omitempty"`
	Delta *struct {
		Type        string `json:"type"`
		Text        string `json:"text,omitempty"`
		PartialJSON string `json:"partial_json,omitempty"`
	} `json:"delta,omitempty"`
	Usage *struct {
		InputTokens  int `json:"input_tokens"`
		OutputTokens int `json:"output_tokens"`
	} `json:"usage,omitempty"`
}

func parseStreamEvent(data string) (*assistant.StreamEvent, error) {
	var event streamEvent
	if err := json.Unmarshal([]byte(data), &event); err != nil {
		return nil, err
	}

	switch event.Type {
	case "content_block_start":
		if event.ContentBlock != nil {
			if event.ContentBlock.Type == "tool_use" {
				return &assistant.StreamEvent{
					Type: assistant.EventToolCallStart,
					ToolCall: &assistant.ToolCall{
						ID:   event.ContentBlock.ID,
						Name: event.ContentBlock.Name,
					},
					ToolIndex: event.Index,
				}, nil
			}
		}

	case "content_block_delta":
		if event.Delta != nil {
			if event.Delta.Type == "text_delta" {
				return &assistant.StreamEvent{
					Type:    assistant.EventContentDelta,
					Content: event.Delta.Text,
				}, nil
			}
			if event.Delta.Type == "input_json_delta" {
				return &assistant.StreamEvent{
					Type: assistant.EventToolCallDelta,
					ToolCall: &assistant.ToolCall{
						Arguments: event.Delta.PartialJSON,
					},
					ToolIndex: event.Index,
				}, nil
			}
		}

	case "message_stop":
		return &assistant.StreamEvent{Type: assistant.EventDone}, nil

	case "message_delta":
		if event.Usage != nil {
			return &assistant.StreamEvent{
				Type: assistant.EventDone,
				Usage: &assistant.Usage{
					PromptTokens:     event.Usage.InputTokens,
					CompletionTokens: event.Usage.OutputTokens,
					TotalTokens:      event.Usage.InputTokens + event.Usage.OutputTokens,
				},
			}, nil
		}
	}

	return &assistant.StreamEvent{Type: assistant.EventContentDelta}, nil
}