openai.go

320 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
// Package openai provides an OpenAI implementation of assistant.Backend.
package openai

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

	"congo.gg/pkg/assistant"
)

const defaultBaseURL = "https://api.openai.com/v1"

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

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

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

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

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

	b := &backend{
		apiKey:  apiKey,
		baseURL: defaultBaseURL,
		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 chatResponse
	if err := json.NewDecoder(respBody).Decode(&resp); err != nil {
		return nil, fmt.Errorf("failed to decode response: %w", err)
	}

	if len(resp.Choices) == 0 {
		return nil, assistant.ErrEmptyResponse
	}

	choice := resp.Choices[0]
	return &assistant.ChatResponse{
		Content:      choice.Message.Content,
		ToolCalls:    convertToolCalls(choice.Message.ToolCalls),
		FinishReason: choice.FinishReason,
		Usage: assistant.Usage{
			PromptTokens:     resp.Usage.PromptTokens,
			CompletionTokens: resp.Usage.CompletionTokens,
			TotalTokens:      resp.Usage.TotalTokens,
		},
	}, 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))

	// Add system message if present
	if req.System != "" {
		messages = append(messages, map[string]any{
			"role":    "system",
			"content": req.System,
		})
	}

	// Convert messages (skip system — handled above)
	for _, m := range req.Messages {
		if m.Role == assistant.RoleSystem {
			continue
		}
		msg := map[string]any{
			"role":    m.Role,
			"content": m.Content,
		}

		if len(m.ToolCalls) > 0 {
			toolCalls := make([]map[string]any, len(m.ToolCalls))
			for i, tc := range m.ToolCalls {
				toolCalls[i] = map[string]any{
					"id":   tc.ID,
					"type": "function",
					"function": map[string]any{
						"name":      tc.Name,
						"arguments": tc.Arguments,
					},
				}
			}
			msg["tool_calls"] = toolCalls
		}

		if m.ToolCallID != "" {
			msg["tool_call_id"] = m.ToolCallID
		}

		messages = append(messages, msg)
	}

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

	if req.MaxTokens > 0 {
		body["max_completion_tokens"] = req.MaxTokens
	}

	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{
				"type": "function",
				"function": map[string]any{
					"name":        t.Name,
					"description": t.Description,
				},
			}
			if t.Parameters != nil {
				tool["function"].(map[string]any)["parameters"] = t.Parameters
			}
			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+"/chat/completions", 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("Authorization", "Bearer "+b.apiKey)

	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
}

// --- OpenAI API types ---

type chatResponse struct {
	Choices []struct {
		Message struct {
			Content   string `json:"content"`
			ToolCalls []struct {
				ID       string `json:"id"`
				Type     string `json:"type"`
				Function struct {
					Name      string `json:"name"`
					Arguments string `json:"arguments"`
				} `json:"function"`
			} `json:"tool_calls"`
		} `json:"message"`
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

type streamChunk struct {
	Choices []struct {
		Delta struct {
			Content   string `json:"content"`
			ToolCalls []struct {
				Index    int    `json:"index"`
				ID       string `json:"id"`
				Type     string `json:"type"`
				Function struct {
					Name      string `json:"name"`
					Arguments string `json:"arguments"`
				} `json:"function"`
			} `json:"tool_calls"`
		} `json:"delta"`
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
}

func convertToolCalls(calls []struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Function struct {
		Name      string `json:"name"`
		Arguments string `json:"arguments"`
	} `json:"function"`
}) []assistant.ToolCall {
	result := make([]assistant.ToolCall, len(calls))
	for i, c := range calls {
		result[i] = assistant.ToolCall{
			ID:        c.ID,
			Name:      c.Function.Name,
			Arguments: c.Function.Arguments,
		}
	}
	return result
}

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

	if len(chunk.Choices) == 0 {
		return &assistant.StreamEvent{Type: assistant.EventContentDelta}, nil
	}

	choice := chunk.Choices[0]

	// Content delta
	if choice.Delta.Content != "" {
		return &assistant.StreamEvent{
			Type:    assistant.EventContentDelta,
			Content: choice.Delta.Content,
		}, nil
	}

	// Tool call
	if len(choice.Delta.ToolCalls) > 0 {
		tc := choice.Delta.ToolCalls[0]
		if tc.ID != "" {
			// New tool call
			return &assistant.StreamEvent{
				Type: assistant.EventToolCallStart,
				ToolCall: &assistant.ToolCall{
					ID:        tc.ID,
					Name:      tc.Function.Name,
					Arguments: tc.Function.Arguments,
				},
				ToolIndex: tc.Index,
			}, nil
		}
		// Tool call delta (arguments continuation)
		return &assistant.StreamEvent{
			Type: assistant.EventToolCallDelta,
			ToolCall: &assistant.ToolCall{
				Arguments: tc.Function.Arguments,
			},
			ToolIndex: tc.Index,
		}, nil
	}

	// Done
	if choice.FinishReason != "" {
		return &assistant.StreamEvent{Type: assistant.EventDone}, nil
	}

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