| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 1 | package oai |
| 2 | |
| 3 | import ( |
| 4 | "cmp" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "log/slog" |
| 10 | "math/rand/v2" |
| 11 | "net/http" |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 12 | "strings" |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 13 | "time" |
| 14 | |
| 15 | "github.com/sashabaranov/go-openai" |
| 16 | "sketch.dev/llm" |
| 17 | ) |
| 18 | |
| 19 | const ( |
| 20 | DefaultMaxTokens = 8192 |
| 21 | |
| 22 | OpenAIURL = "https://api.openai.com/v1" |
| 23 | FireworksURL = "https://api.fireworks.ai/inference/v1" |
| 24 | LlamaCPPURL = "http://localhost:8080/v1" |
| 25 | TogetherURL = "https://api.together.xyz/v1" |
| 26 | GeminiURL = "https://generativelanguage.googleapis.com/v1beta/openai/" |
| Josh Bleecher Snyder | fa66703 | 2025-05-07 14:13:27 -0700 | [diff] [blame] | 27 | MistralURL = "https://api.mistral.ai/v1" |
| Josh Bleecher Snyder | 2edd62e | 2025-07-14 12:44:51 -0700 | [diff] [blame] | 28 | MoonshotURL = "https://api.moonshot.ai/v1" |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 29 | |
| 30 | // Environment variable names for API keys |
| 31 | OpenAIAPIKeyEnv = "OPENAI_API_KEY" |
| 32 | FireworksAPIKeyEnv = "FIREWORKS_API_KEY" |
| 33 | TogetherAPIKeyEnv = "TOGETHER_API_KEY" |
| 34 | GeminiAPIKeyEnv = "GEMINI_API_KEY" |
| Josh Bleecher Snyder | fa66703 | 2025-05-07 14:13:27 -0700 | [diff] [blame] | 35 | MistralAPIKeyEnv = "MISTRAL_API_KEY" |
| Josh Bleecher Snyder | 2edd62e | 2025-07-14 12:44:51 -0700 | [diff] [blame] | 36 | MoonshotAPIKeyEnv = "MOONSHOT_API_KEY" |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 37 | ) |
| 38 | |
| 39 | type Model struct { |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 40 | UserName string // provided by the user to identify this model (e.g. "gpt4.1") |
| 41 | ModelName string // provided to the service provide to specify which model to use (e.g. "gpt-4.1-2025-04-14") |
| 42 | URL string |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 43 | APIKeyEnv string // environment variable name for the API key |
| 44 | IsReasoningModel bool // whether this model is a reasoning model (e.g. O3, O4-mini) |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 45 | } |
| 46 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 47 | var ( |
| 48 | DefaultModel = GPT41 |
| 49 | |
| 50 | GPT41 = Model{ |
| 51 | UserName: "gpt4.1", |
| 52 | ModelName: "gpt-4.1-2025-04-14", |
| 53 | URL: OpenAIURL, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 54 | APIKeyEnv: OpenAIAPIKeyEnv, |
| 55 | } |
| 56 | |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 57 | GPT4o = Model{ |
| 58 | UserName: "gpt4o", |
| 59 | ModelName: "gpt-4o-2024-08-06", |
| 60 | URL: OpenAIURL, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 61 | APIKeyEnv: OpenAIAPIKeyEnv, |
| 62 | } |
| 63 | |
| 64 | GPT4oMini = Model{ |
| 65 | UserName: "gpt4o-mini", |
| 66 | ModelName: "gpt-4o-mini-2024-07-18", |
| 67 | URL: OpenAIURL, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 68 | APIKeyEnv: OpenAIAPIKeyEnv, |
| 69 | } |
| 70 | |
| 71 | GPT41Mini = Model{ |
| 72 | UserName: "gpt4.1-mini", |
| 73 | ModelName: "gpt-4.1-mini-2025-04-14", |
| 74 | URL: OpenAIURL, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 75 | APIKeyEnv: OpenAIAPIKeyEnv, |
| 76 | } |
| 77 | |
| 78 | GPT41Nano = Model{ |
| 79 | UserName: "gpt4.1-nano", |
| 80 | ModelName: "gpt-4.1-nano-2025-04-14", |
| 81 | URL: OpenAIURL, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 82 | APIKeyEnv: OpenAIAPIKeyEnv, |
| 83 | } |
| 84 | |
| 85 | O3 = Model{ |
| 86 | UserName: "o3", |
| 87 | ModelName: "o3-2025-04-16", |
| 88 | URL: OpenAIURL, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 89 | APIKeyEnv: OpenAIAPIKeyEnv, |
| 90 | IsReasoningModel: true, |
| 91 | } |
| 92 | |
| 93 | O4Mini = Model{ |
| 94 | UserName: "o4-mini", |
| 95 | ModelName: "o4-mini-2025-04-16", |
| 96 | URL: OpenAIURL, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 97 | APIKeyEnv: OpenAIAPIKeyEnv, |
| 98 | IsReasoningModel: true, |
| 99 | } |
| 100 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 101 | Gemini25Flash = Model{ |
| 102 | UserName: "gemini-flash-2.5", |
| 103 | ModelName: "gemini-2.5-flash-preview-04-17", |
| 104 | URL: GeminiURL, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 105 | APIKeyEnv: GeminiAPIKeyEnv, |
| 106 | } |
| 107 | |
| 108 | Gemini25Pro = Model{ |
| 109 | UserName: "gemini-pro-2.5", |
| 110 | ModelName: "gemini-2.5-pro-preview-03-25", |
| 111 | URL: GeminiURL, |
| 112 | // GRRRR. Really?? |
| 113 | // Input is: $1.25, prompts <= 200k tokens, $2.50, prompts > 200k tokens |
| 114 | // Output is: $10.00, prompts <= 200k tokens, $15.00, prompts > 200k |
| 115 | // Caching is: $0.31, prompts <= 200k tokens, $0.625, prompts > 200k, $4.50 / 1,000,000 tokens per hour |
| 116 | // Whatever that means. Are we caching? I have no idea. |
| 117 | // How do you always manage to be the annoying one, Google? |
| 118 | // I'm not complicating things just for you. |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 119 | APIKeyEnv: GeminiAPIKeyEnv, |
| 120 | } |
| 121 | |
| 122 | TogetherDeepseekV3 = Model{ |
| 123 | UserName: "together-deepseek-v3", |
| 124 | ModelName: "deepseek-ai/DeepSeek-V3", |
| 125 | URL: TogetherURL, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 126 | APIKeyEnv: TogetherAPIKeyEnv, |
| 127 | } |
| 128 | |
| Josh Bleecher Snyder | d1bd519 | 2025-06-02 14:10:52 -0700 | [diff] [blame] | 129 | TogetherDeepseekR1 = Model{ |
| 130 | UserName: "together-deepseek-r1", |
| 131 | ModelName: "deepseek-ai/DeepSeek-R1", |
| 132 | URL: TogetherURL, |
| Josh Bleecher Snyder | d1bd519 | 2025-06-02 14:10:52 -0700 | [diff] [blame] | 133 | APIKeyEnv: TogetherAPIKeyEnv, |
| 134 | } |
| 135 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 136 | TogetherLlama4Maverick = Model{ |
| 137 | UserName: "together-llama4-maverick", |
| 138 | ModelName: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", |
| 139 | URL: TogetherURL, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 140 | APIKeyEnv: TogetherAPIKeyEnv, |
| 141 | } |
| 142 | |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 143 | FireworksLlama4Maverick = Model{ |
| 144 | UserName: "fireworks-llama4-maverick", |
| 145 | ModelName: "accounts/fireworks/models/llama4-maverick-instruct-basic", |
| 146 | URL: FireworksURL, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 147 | APIKeyEnv: FireworksAPIKeyEnv, |
| 148 | } |
| 149 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 150 | TogetherLlama3_3_70B = Model{ |
| 151 | UserName: "together-llama3-70b", |
| 152 | ModelName: "meta-llama/Llama-3.3-70B-Instruct-Turbo", |
| 153 | URL: TogetherURL, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 154 | APIKeyEnv: TogetherAPIKeyEnv, |
| 155 | } |
| 156 | |
| 157 | TogetherMistralSmall = Model{ |
| 158 | UserName: "together-mistral-small", |
| 159 | ModelName: "mistralai/Mistral-Small-24B-Instruct-2501", |
| 160 | URL: TogetherURL, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 161 | APIKeyEnv: TogetherAPIKeyEnv, |
| 162 | } |
| 163 | |
| Josh Bleecher Snyder | 3e21308 | 2025-05-02 13:22:02 -0700 | [diff] [blame] | 164 | TogetherQwen3 = Model{ |
| 165 | UserName: "together-qwen3", |
| 166 | ModelName: "Qwen/Qwen3-235B-A22B-fp8-tput", |
| 167 | URL: TogetherURL, |
| Josh Bleecher Snyder | 3e21308 | 2025-05-02 13:22:02 -0700 | [diff] [blame] | 168 | APIKeyEnv: TogetherAPIKeyEnv, |
| 169 | } |
| 170 | |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 171 | TogetherGemma2 = Model{ |
| 172 | UserName: "together-gemma2", |
| 173 | ModelName: "google/gemma-2-27b-it", |
| 174 | URL: TogetherURL, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 175 | APIKeyEnv: TogetherAPIKeyEnv, |
| 176 | } |
| 177 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 178 | LlamaCPP = Model{ |
| 179 | UserName: "llama.cpp", |
| 180 | ModelName: "llama.cpp local model", |
| 181 | URL: LlamaCPPURL, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 182 | } |
| 183 | |
| 184 | FireworksDeepseekV3 = Model{ |
| 185 | UserName: "fireworks-deepseek-v3", |
| 186 | ModelName: "accounts/fireworks/models/deepseek-v3-0324", |
| 187 | URL: FireworksURL, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 188 | APIKeyEnv: FireworksAPIKeyEnv, |
| 189 | } |
| Josh Bleecher Snyder | fa66703 | 2025-05-07 14:13:27 -0700 | [diff] [blame] | 190 | |
| Josh Bleecher Snyder | 2edd62e | 2025-07-14 12:44:51 -0700 | [diff] [blame] | 191 | MoonshotKimiK2 = Model{ |
| 192 | UserName: "moonshot-kimi-k2", |
| 193 | ModelName: "moonshot-v1-auto", |
| 194 | URL: MoonshotURL, |
| 195 | APIKeyEnv: MoonshotAPIKeyEnv, |
| 196 | } |
| 197 | |
| Josh Bleecher Snyder | fa66703 | 2025-05-07 14:13:27 -0700 | [diff] [blame] | 198 | MistralMedium = Model{ |
| 199 | UserName: "mistral-medium-3", |
| 200 | ModelName: "mistral-medium-latest", |
| 201 | URL: MistralURL, |
| Josh Bleecher Snyder | fa66703 | 2025-05-07 14:13:27 -0700 | [diff] [blame] | 202 | APIKeyEnv: MistralAPIKeyEnv, |
| 203 | } |
| Josh Bleecher Snyder | 1a648f3 | 2025-05-21 17:15:04 +0000 | [diff] [blame] | 204 | |
| 205 | DevstralSmall = Model{ |
| 206 | UserName: "devstral-small", |
| 207 | ModelName: "devstral-small-latest", |
| 208 | URL: MistralURL, |
| Josh Bleecher Snyder | 1a648f3 | 2025-05-21 17:15:04 +0000 | [diff] [blame] | 209 | APIKeyEnv: MistralAPIKeyEnv, |
| 210 | } |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 211 | ) |
| 212 | |
| 213 | // Service provides chat completions. |
| 214 | // Fields should not be altered concurrently with calling any method on Service. |
| 215 | type Service struct { |
| 216 | HTTPC *http.Client // defaults to http.DefaultClient if nil |
| 217 | APIKey string // optional, if not set will try to load from env var |
| 218 | Model Model // defaults to DefaultModel if zero value |
| 219 | MaxTokens int // defaults to DefaultMaxTokens if zero |
| 220 | Org string // optional - organization ID |
| Josh Bleecher Snyder | 57afbca | 2025-07-23 13:29:59 -0700 | [diff] [blame] | 221 | DumpLLM bool // whether to dump request/response text to files for debugging; defaults to false |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 222 | } |
| 223 | |
| 224 | var _ llm.Service = (*Service)(nil) |
| 225 | |
| 226 | // ModelsRegistry is a registry of all known models with their user-friendly names. |
| 227 | var ModelsRegistry = []Model{ |
| 228 | GPT41, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 229 | GPT41Mini, |
| 230 | GPT41Nano, |
| 231 | GPT4o, |
| 232 | GPT4oMini, |
| 233 | O3, |
| 234 | O4Mini, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 235 | Gemini25Flash, |
| 236 | Gemini25Pro, |
| 237 | TogetherDeepseekV3, |
| Josh Bleecher Snyder | d1bd519 | 2025-06-02 14:10:52 -0700 | [diff] [blame] | 238 | TogetherDeepseekR1, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 239 | TogetherLlama4Maverick, |
| 240 | TogetherLlama3_3_70B, |
| 241 | TogetherMistralSmall, |
| Josh Bleecher Snyder | 3e21308 | 2025-05-02 13:22:02 -0700 | [diff] [blame] | 242 | TogetherQwen3, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 243 | TogetherGemma2, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 244 | LlamaCPP, |
| 245 | FireworksDeepseekV3, |
| Josh Bleecher Snyder | 2edd62e | 2025-07-14 12:44:51 -0700 | [diff] [blame] | 246 | MoonshotKimiK2, |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 247 | FireworksLlama4Maverick, |
| 248 | MistralMedium, |
| Josh Bleecher Snyder | 1a648f3 | 2025-05-21 17:15:04 +0000 | [diff] [blame] | 249 | DevstralSmall, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 250 | } |
| 251 | |
| 252 | // ListModels returns a list of all available models with their user-friendly names. |
| 253 | func ListModels() []string { |
| 254 | var names []string |
| 255 | for _, model := range ModelsRegistry { |
| 256 | if model.UserName != "" { |
| 257 | names = append(names, model.UserName) |
| 258 | } |
| 259 | } |
| 260 | return names |
| 261 | } |
| 262 | |
| 263 | // ModelByUserName returns a model by its user-friendly name. |
| 264 | // Returns nil if no model with the given name is found. |
| Josh Bleecher Snyder | 0530da0 | 2025-07-23 03:47:43 +0000 | [diff] [blame^] | 265 | func ModelByUserName(name string) Model { |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 266 | for _, model := range ModelsRegistry { |
| 267 | if model.UserName == name { |
| Josh Bleecher Snyder | 0530da0 | 2025-07-23 03:47:43 +0000 | [diff] [blame^] | 268 | return model |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 269 | } |
| 270 | } |
| Josh Bleecher Snyder | 0530da0 | 2025-07-23 03:47:43 +0000 | [diff] [blame^] | 271 | return Model{} |
| 272 | } |
| 273 | |
| 274 | func (m Model) IsZero() bool { |
| 275 | return m == Model{} |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 276 | } |
| 277 | |
| 278 | var ( |
| 279 | fromLLMRole = map[llm.MessageRole]string{ |
| 280 | llm.MessageRoleAssistant: "assistant", |
| 281 | llm.MessageRoleUser: "user", |
| 282 | } |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 283 | fromLLMToolChoiceType = map[llm.ToolChoiceType]string{ |
| 284 | llm.ToolChoiceTypeAuto: "auto", |
| 285 | llm.ToolChoiceTypeAny: "any", |
| 286 | llm.ToolChoiceTypeNone: "none", |
| 287 | llm.ToolChoiceTypeTool: "function", // OpenAI uses "function" instead of "tool" |
| 288 | } |
| 289 | toLLMRole = map[string]llm.MessageRole{ |
| 290 | "assistant": llm.MessageRoleAssistant, |
| 291 | "user": llm.MessageRoleUser, |
| 292 | } |
| 293 | toLLMStopReason = map[string]llm.StopReason{ |
| 294 | "stop": llm.StopReasonStopSequence, |
| 295 | "length": llm.StopReasonMaxTokens, |
| 296 | "tool_calls": llm.StopReasonToolUse, |
| 297 | "function_call": llm.StopReasonToolUse, // Map both to ToolUse |
| 298 | "content_filter": llm.StopReasonStopSequence, // No direct equivalent |
| 299 | } |
| 300 | ) |
| 301 | |
| 302 | // fromLLMContent converts llm.Content to the format expected by OpenAI. |
| 303 | func fromLLMContent(c llm.Content) (string, []openai.ToolCall) { |
| 304 | switch c.Type { |
| 305 | case llm.ContentTypeText: |
| 306 | return c.Text, nil |
| 307 | case llm.ContentTypeToolUse: |
| 308 | // For OpenAI, tool use is sent as a null content with tool_calls in the message |
| 309 | return "", []openai.ToolCall{ |
| 310 | { |
| 311 | Type: openai.ToolTypeFunction, |
| 312 | ID: c.ID, // Use the content ID if provided |
| 313 | Function: openai.FunctionCall{ |
| 314 | Name: c.ToolName, |
| 315 | Arguments: string(c.ToolInput), |
| 316 | }, |
| 317 | }, |
| 318 | } |
| 319 | case llm.ContentTypeToolResult: |
| 320 | // Tool results in OpenAI are sent as a separate message with tool_call_id |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 321 | // OpenAI doesn't support multiple content items or images in tool results |
| 322 | // Combine all text content into a single string |
| 323 | var resultText string |
| 324 | if len(c.ToolResult) > 0 { |
| 325 | // Collect all text from content objects |
| 326 | texts := make([]string, 0, len(c.ToolResult)) |
| 327 | for _, result := range c.ToolResult { |
| 328 | if result.Text != "" { |
| 329 | texts = append(texts, result.Text) |
| 330 | } |
| 331 | } |
| 332 | resultText = strings.Join(texts, "\n") |
| 333 | } |
| 334 | return resultText, nil |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 335 | default: |
| 336 | // For thinking or other types, convert to text |
| 337 | return c.Text, nil |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // fromLLMMessage converts llm.Message to OpenAI ChatCompletionMessage format |
| 342 | func fromLLMMessage(msg llm.Message) []openai.ChatCompletionMessage { |
| 343 | // For OpenAI, we need to handle tool results differently than regular messages |
| 344 | // Each tool result becomes its own message with role="tool" |
| 345 | |
| 346 | var messages []openai.ChatCompletionMessage |
| 347 | |
| 348 | // Check if this is a regular message or contains tool results |
| 349 | var regularContent []llm.Content |
| 350 | var toolResults []llm.Content |
| 351 | |
| 352 | for _, c := range msg.Content { |
| 353 | if c.Type == llm.ContentTypeToolResult { |
| 354 | toolResults = append(toolResults, c) |
| 355 | } else { |
| 356 | regularContent = append(regularContent, c) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // Process tool results as separate messages, but first |
| 361 | for _, tr := range toolResults { |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 362 | // Convert toolresult array to a string for OpenAI |
| 363 | var toolResultContent string |
| 364 | if len(tr.ToolResult) > 0 { |
| 365 | // For now, just use the first text content in the array |
| 366 | toolResultContent = tr.ToolResult[0].Text |
| 367 | } |
| 368 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 369 | m := openai.ChatCompletionMessage{ |
| 370 | Role: "tool", |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 371 | Content: cmp.Or(toolResultContent, " "), // Use empty space if empty to avoid omitempty issues |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 372 | ToolCallID: tr.ToolUseID, |
| 373 | } |
| 374 | messages = append(messages, m) |
| 375 | } |
| 376 | // Process regular content second |
| 377 | if len(regularContent) > 0 { |
| 378 | m := openai.ChatCompletionMessage{ |
| 379 | Role: fromLLMRole[msg.Role], |
| 380 | } |
| 381 | |
| 382 | // For assistant messages that contain tool calls |
| 383 | var toolCalls []openai.ToolCall |
| 384 | var textContent string |
| 385 | |
| 386 | for _, c := range regularContent { |
| 387 | content, tools := fromLLMContent(c) |
| 388 | if len(tools) > 0 { |
| 389 | toolCalls = append(toolCalls, tools...) |
| 390 | } else if content != "" { |
| 391 | if textContent != "" { |
| 392 | textContent += "\n" |
| 393 | } |
| 394 | textContent += content |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | m.Content = textContent |
| 399 | m.ToolCalls = toolCalls |
| 400 | |
| 401 | messages = append(messages, m) |
| 402 | } |
| 403 | |
| 404 | return messages |
| 405 | } |
| 406 | |
| 407 | // fromLLMToolChoice converts llm.ToolChoice to the format expected by OpenAI. |
| 408 | func fromLLMToolChoice(tc *llm.ToolChoice) any { |
| 409 | if tc == nil { |
| 410 | return nil |
| 411 | } |
| 412 | |
| 413 | if tc.Type == llm.ToolChoiceTypeTool && tc.Name != "" { |
| 414 | return openai.ToolChoice{ |
| 415 | Type: openai.ToolTypeFunction, |
| 416 | Function: openai.ToolFunction{ |
| 417 | Name: tc.Name, |
| 418 | }, |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | // For non-specific tool choice, just use the string |
| 423 | return fromLLMToolChoiceType[tc.Type] |
| 424 | } |
| 425 | |
| 426 | // fromLLMTool converts llm.Tool to the format expected by OpenAI. |
| 427 | func fromLLMTool(t *llm.Tool) openai.Tool { |
| 428 | return openai.Tool{ |
| 429 | Type: openai.ToolTypeFunction, |
| 430 | Function: &openai.FunctionDefinition{ |
| 431 | Name: t.Name, |
| 432 | Description: t.Description, |
| 433 | Parameters: t.InputSchema, |
| 434 | }, |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | // fromLLMSystem converts llm.SystemContent to an OpenAI system message. |
| 439 | func fromLLMSystem(systemContent []llm.SystemContent) []openai.ChatCompletionMessage { |
| 440 | if len(systemContent) == 0 { |
| 441 | return nil |
| 442 | } |
| 443 | |
| 444 | // Combine all system content into a single system message |
| 445 | var systemText string |
| 446 | for i, content := range systemContent { |
| 447 | if i > 0 && systemText != "" && content.Text != "" { |
| 448 | systemText += "\n" |
| 449 | } |
| 450 | systemText += content.Text |
| 451 | } |
| 452 | |
| 453 | if systemText == "" { |
| 454 | return nil |
| 455 | } |
| 456 | |
| 457 | return []openai.ChatCompletionMessage{ |
| 458 | { |
| 459 | Role: "system", |
| 460 | Content: systemText, |
| 461 | }, |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | // toRawLLMContent converts a raw content string from OpenAI to llm.Content. |
| 466 | func toRawLLMContent(content string) llm.Content { |
| 467 | return llm.Content{ |
| 468 | Type: llm.ContentTypeText, |
| 469 | Text: content, |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | // toToolCallLLMContent converts a tool call from OpenAI to llm.Content. |
| 474 | func toToolCallLLMContent(toolCall openai.ToolCall) llm.Content { |
| 475 | // Generate a content ID if needed |
| 476 | id := toolCall.ID |
| 477 | if id == "" { |
| 478 | // Create a deterministic ID based on the function name if no ID is provided |
| 479 | id = "tc_" + toolCall.Function.Name |
| 480 | } |
| 481 | |
| 482 | return llm.Content{ |
| 483 | ID: id, |
| 484 | Type: llm.ContentTypeToolUse, |
| 485 | ToolName: toolCall.Function.Name, |
| 486 | ToolInput: json.RawMessage(toolCall.Function.Arguments), |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | // toToolResultLLMContent converts a tool result message from OpenAI to llm.Content. |
| 491 | func toToolResultLLMContent(msg openai.ChatCompletionMessage) llm.Content { |
| 492 | return llm.Content{ |
| Philip Zeyliger | 72252cb | 2025-05-10 17:00:08 -0700 | [diff] [blame] | 493 | Type: llm.ContentTypeToolResult, |
| 494 | ToolUseID: msg.ToolCallID, |
| 495 | ToolResult: []llm.Content{{ |
| 496 | Type: llm.ContentTypeText, |
| 497 | Text: msg.Content, |
| 498 | }}, |
| 499 | ToolError: false, // OpenAI doesn't specify errors explicitly |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 500 | } |
| 501 | } |
| 502 | |
| 503 | // toLLMContents converts message content from OpenAI to []llm.Content. |
| 504 | func toLLMContents(msg openai.ChatCompletionMessage) []llm.Content { |
| 505 | var contents []llm.Content |
| 506 | |
| 507 | // If this is a tool response, handle it separately |
| 508 | if msg.Role == "tool" && msg.ToolCallID != "" { |
| 509 | return []llm.Content{toToolResultLLMContent(msg)} |
| 510 | } |
| 511 | |
| 512 | // If there's text content, add it |
| 513 | if msg.Content != "" { |
| 514 | contents = append(contents, toRawLLMContent(msg.Content)) |
| 515 | } |
| 516 | |
| 517 | // If there are tool calls, add them |
| 518 | for _, tc := range msg.ToolCalls { |
| 519 | contents = append(contents, toToolCallLLMContent(tc)) |
| 520 | } |
| 521 | |
| 522 | // If empty, add an empty text content |
| 523 | if len(contents) == 0 { |
| 524 | contents = append(contents, llm.Content{ |
| 525 | Type: llm.ContentTypeText, |
| 526 | Text: "", |
| 527 | }) |
| 528 | } |
| 529 | |
| 530 | return contents |
| 531 | } |
| 532 | |
| 533 | // toLLMUsage converts usage information from OpenAI to llm.Usage. |
| Josh Bleecher Snyder | 59bb27d | 2025-06-05 07:32:10 -0700 | [diff] [blame] | 534 | func (s *Service) toLLMUsage(au openai.Usage, headers http.Header) llm.Usage { |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 535 | // fmt.Printf("raw usage: %+v / %v / %v\n", au, au.PromptTokensDetails, au.CompletionTokensDetails) |
| 536 | in := uint64(au.PromptTokens) |
| 537 | var inc uint64 |
| 538 | if au.PromptTokensDetails != nil { |
| 539 | inc = uint64(au.PromptTokensDetails.CachedTokens) |
| 540 | } |
| 541 | out := uint64(au.CompletionTokens) |
| 542 | u := llm.Usage{ |
| 543 | InputTokens: in, |
| 544 | CacheReadInputTokens: inc, |
| 545 | CacheCreationInputTokens: in, |
| 546 | OutputTokens: out, |
| 547 | } |
| Josh Bleecher Snyder | 59bb27d | 2025-06-05 07:32:10 -0700 | [diff] [blame] | 548 | u.CostUSD = llm.CostUSDFromResponse(headers) |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 549 | return u |
| 550 | } |
| 551 | |
| 552 | // toLLMResponse converts the OpenAI response to llm.Response. |
| 553 | func (s *Service) toLLMResponse(r *openai.ChatCompletionResponse) *llm.Response { |
| 554 | // fmt.Printf("Raw response\n") |
| 555 | // enc := json.NewEncoder(os.Stdout) |
| 556 | // enc.SetIndent("", " ") |
| 557 | // enc.Encode(r) |
| 558 | // fmt.Printf("\n") |
| 559 | |
| 560 | if len(r.Choices) == 0 { |
| 561 | return &llm.Response{ |
| 562 | ID: r.ID, |
| 563 | Model: r.Model, |
| 564 | Role: llm.MessageRoleAssistant, |
| Josh Bleecher Snyder | 59bb27d | 2025-06-05 07:32:10 -0700 | [diff] [blame] | 565 | Usage: s.toLLMUsage(r.Usage, r.Header()), |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 566 | } |
| 567 | } |
| 568 | |
| 569 | // Process the primary choice |
| 570 | choice := r.Choices[0] |
| 571 | |
| 572 | return &llm.Response{ |
| 573 | ID: r.ID, |
| 574 | Model: r.Model, |
| 575 | Role: toRoleFromString(choice.Message.Role), |
| 576 | Content: toLLMContents(choice.Message), |
| 577 | StopReason: toStopReason(string(choice.FinishReason)), |
| Josh Bleecher Snyder | 59bb27d | 2025-06-05 07:32:10 -0700 | [diff] [blame] | 578 | Usage: s.toLLMUsage(r.Usage, r.Header()), |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 579 | } |
| 580 | } |
| 581 | |
| 582 | // toRoleFromString converts a role string to llm.MessageRole. |
| 583 | func toRoleFromString(role string) llm.MessageRole { |
| 584 | if role == "tool" || role == "system" || role == "function" { |
| 585 | return llm.MessageRoleAssistant // Map special roles to assistant for consistency |
| 586 | } |
| 587 | if mr, ok := toLLMRole[role]; ok { |
| 588 | return mr |
| 589 | } |
| 590 | return llm.MessageRoleUser // Default to user if unknown |
| 591 | } |
| 592 | |
| 593 | // toStopReason converts a finish reason string to llm.StopReason. |
| 594 | func toStopReason(reason string) llm.StopReason { |
| 595 | if sr, ok := toLLMStopReason[reason]; ok { |
| 596 | return sr |
| 597 | } |
| 598 | return llm.StopReasonStopSequence // Default |
| 599 | } |
| 600 | |
| Philip Zeyliger | b8a8f35 | 2025-06-02 07:39:37 -0700 | [diff] [blame] | 601 | // TokenContextWindow returns the maximum token context window size for this service |
| 602 | func (s *Service) TokenContextWindow() int { |
| 603 | model := cmp.Or(s.Model, DefaultModel) |
| 604 | |
| 605 | // OpenAI models generally have 128k context windows |
| 606 | // Some newer models have larger windows, but 128k is a safe default |
| 607 | switch model.ModelName { |
| 608 | case "gpt-4.1-2025-04-14", "gpt-4.1-mini-2025-04-14", "gpt-4.1-nano-2025-04-14": |
| 609 | return 200000 // 200k for newer GPT-4.1 models |
| 610 | case "gpt-4o-2024-08-06", "gpt-4o-mini-2024-07-18": |
| 611 | return 128000 // 128k for GPT-4o models |
| 612 | case "o3-2025-04-16", "o3-mini-2025-04-16": |
| 613 | return 200000 // 200k for O3 models |
| 614 | default: |
| 615 | // Default for unknown models |
| 616 | return 128000 |
| 617 | } |
| 618 | } |
| 619 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 620 | // Do sends a request to OpenAI using the go-openai package. |
| 621 | func (s *Service) Do(ctx context.Context, ir *llm.Request) (*llm.Response, error) { |
| 622 | // Configure the OpenAI client |
| 623 | httpc := cmp.Or(s.HTTPC, http.DefaultClient) |
| 624 | model := cmp.Or(s.Model, DefaultModel) |
| 625 | |
| 626 | // TODO: do this one during Service setup? maybe with a constructor instead? |
| 627 | config := openai.DefaultConfig(s.APIKey) |
| 628 | if model.URL != "" { |
| 629 | config.BaseURL = model.URL |
| 630 | } |
| 631 | if s.Org != "" { |
| 632 | config.OrgID = s.Org |
| 633 | } |
| 634 | config.HTTPClient = httpc |
| 635 | |
| 636 | client := openai.NewClientWithConfig(config) |
| 637 | |
| 638 | // Start with system messages if provided |
| 639 | var allMessages []openai.ChatCompletionMessage |
| 640 | if len(ir.System) > 0 { |
| 641 | sysMessages := fromLLMSystem(ir.System) |
| 642 | allMessages = append(allMessages, sysMessages...) |
| 643 | } |
| 644 | |
| 645 | // Add regular and tool messages |
| 646 | for _, msg := range ir.Messages { |
| 647 | msgs := fromLLMMessage(msg) |
| 648 | allMessages = append(allMessages, msgs...) |
| 649 | } |
| 650 | |
| 651 | // Convert tools |
| 652 | var tools []openai.Tool |
| 653 | for _, t := range ir.Tools { |
| 654 | tools = append(tools, fromLLMTool(t)) |
| 655 | } |
| 656 | |
| 657 | // Create the OpenAI request |
| 658 | req := openai.ChatCompletionRequest{ |
| 659 | Model: model.ModelName, |
| 660 | Messages: allMessages, |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 661 | Tools: tools, |
| 662 | ToolChoice: fromLLMToolChoice(ir.ToolChoice), // TODO: make fromLLMToolChoice return an error when a perfect translation is not possible |
| 663 | } |
| Josh Bleecher Snyder | 8236cbc | 2025-05-09 09:57:57 -0700 | [diff] [blame] | 664 | if model.IsReasoningModel { |
| 665 | req.MaxCompletionTokens = cmp.Or(s.MaxTokens, DefaultMaxTokens) |
| 666 | } else { |
| 667 | req.MaxTokens = cmp.Or(s.MaxTokens, DefaultMaxTokens) |
| 668 | } |
| Josh Bleecher Snyder | 57afbca | 2025-07-23 13:29:59 -0700 | [diff] [blame] | 669 | // Dump request if enabled |
| 670 | if s.DumpLLM { |
| 671 | if reqJSON, err := json.MarshalIndent(req, "", " "); err == nil { |
| 672 | // Construct the chat completions URL |
| 673 | baseURL := cmp.Or(model.URL, OpenAIURL) |
| 674 | url := baseURL + "/chat/completions" |
| 675 | if err := llm.DumpToFile("request", url, reqJSON); err != nil { |
| 676 | slog.WarnContext(ctx, "failed to dump openai request to file", "error", err) |
| 677 | } |
| 678 | } |
| 679 | } |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 680 | |
| 681 | // Retry mechanism |
| Josh Bleecher Snyder | 3841199 | 2025-05-16 17:51:03 +0000 | [diff] [blame] | 682 | backoff := []time.Duration{1 * time.Second, 2 * time.Second, 5 * time.Second, 10 * time.Second, 15 * time.Second} |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 683 | |
| 684 | // retry loop |
| Josh Bleecher Snyder | 3841199 | 2025-05-16 17:51:03 +0000 | [diff] [blame] | 685 | var errs error // accumulated errors across all attempts |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 686 | for attempts := 0; ; attempts++ { |
| Josh Bleecher Snyder | 3841199 | 2025-05-16 17:51:03 +0000 | [diff] [blame] | 687 | if attempts > 10 { |
| 688 | return nil, fmt.Errorf("openai request failed after %d attempts: %w", attempts, errs) |
| 689 | } |
| 690 | if attempts > 0 { |
| 691 | sleep := backoff[min(attempts, len(backoff)-1)] + time.Duration(rand.Int64N(int64(time.Second))) |
| 692 | slog.WarnContext(ctx, "openai request sleep before retry", "sleep", sleep, "attempts", attempts) |
| 693 | time.Sleep(sleep) |
| 694 | } |
| 695 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 696 | resp, err := client.CreateChatCompletion(ctx, req) |
| 697 | |
| 698 | // Handle successful response |
| 699 | if err == nil { |
| Josh Bleecher Snyder | 57afbca | 2025-07-23 13:29:59 -0700 | [diff] [blame] | 700 | // Dump response if enabled |
| 701 | if s.DumpLLM { |
| 702 | if respJSON, jsonErr := json.MarshalIndent(resp, "", " "); jsonErr == nil { |
| 703 | if dumpErr := llm.DumpToFile("response", "", respJSON); dumpErr != nil { |
| 704 | slog.WarnContext(ctx, "failed to dump openai response to file", "error", dumpErr) |
| 705 | } |
| 706 | } |
| 707 | } |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 708 | return s.toLLMResponse(&resp), nil |
| 709 | } |
| 710 | |
| 711 | // Handle errors |
| 712 | var apiErr *openai.APIError |
| 713 | if ok := errors.As(err, &apiErr); !ok { |
| Josh Bleecher Snyder | 3841199 | 2025-05-16 17:51:03 +0000 | [diff] [blame] | 714 | // Not an OpenAI API error, return immediately with accumulated errors |
| 715 | return nil, errors.Join(errs, err) |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 716 | } |
| 717 | |
| 718 | switch { |
| 719 | case apiErr.HTTPStatusCode >= 500: |
| 720 | // Server error, try again with backoff |
| Josh Bleecher Snyder | 3841199 | 2025-05-16 17:51:03 +0000 | [diff] [blame] | 721 | slog.WarnContext(ctx, "openai_request_failed", "error", apiErr.Error(), "status_code", apiErr.HTTPStatusCode) |
| 722 | errs = errors.Join(errs, fmt.Errorf("status %d: %s", apiErr.HTTPStatusCode, apiErr.Error())) |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 723 | continue |
| 724 | |
| 725 | case apiErr.HTTPStatusCode == 429: |
| Josh Bleecher Snyder | 3841199 | 2025-05-16 17:51:03 +0000 | [diff] [blame] | 726 | // Rate limited, accumulate error and retry |
| 727 | slog.WarnContext(ctx, "openai_request_rate_limited", "error", apiErr.Error()) |
| 728 | errs = errors.Join(errs, fmt.Errorf("status %d (rate limited): %s", apiErr.HTTPStatusCode, apiErr.Error())) |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 729 | continue |
| 730 | |
| Josh Bleecher Snyder | 3841199 | 2025-05-16 17:51:03 +0000 | [diff] [blame] | 731 | case apiErr.HTTPStatusCode >= 400 && apiErr.HTTPStatusCode < 500: |
| 732 | // Client error, probably unrecoverable |
| 733 | slog.WarnContext(ctx, "openai_request_failed", "error", apiErr.Error(), "status_code", apiErr.HTTPStatusCode) |
| 734 | return nil, errors.Join(errs, fmt.Errorf("status %d: %s", apiErr.HTTPStatusCode, apiErr.Error())) |
| 735 | |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 736 | default: |
| Josh Bleecher Snyder | 3841199 | 2025-05-16 17:51:03 +0000 | [diff] [blame] | 737 | // Other error, accumulate and retry |
| 738 | slog.WarnContext(ctx, "openai_request_failed", "error", apiErr.Error(), "status_code", apiErr.HTTPStatusCode) |
| 739 | errs = errors.Join(errs, fmt.Errorf("status %d: %s", apiErr.HTTPStatusCode, apiErr.Error())) |
| 740 | continue |
| Josh Bleecher Snyder | 4f84ab7 | 2025-04-22 16:40:54 -0700 | [diff] [blame] | 741 | } |
| 742 | } |
| 743 | } |