blob: 3de6b7faf798aea105ffb6541774f2ca622a63c1 [file] [log] [blame]
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -07001// Package llm provides a unified interface for interacting with LLMs.
2package llm
3
4import (
5 "context"
6 "encoding/json"
7 "fmt"
8 "log/slog"
9 "strings"
10 "time"
11)
12
13type Service interface {
14 // Do sends a request to an LLM.
15 Do(context.Context, *Request) (*Response, error)
16}
17
18// MustSchema validates that schema is a valid JSON schema and returns it as a json.RawMessage.
19// It panics if the schema is invalid.
20func MustSchema(schema string) json.RawMessage {
21 // TODO: validate schema, for now just make sure it's valid JSON
22 schema = strings.TrimSpace(schema)
23 bytes := []byte(schema)
24 if !json.Valid(bytes) {
25 panic("invalid JSON schema: " + schema)
26 }
27 return json.RawMessage(bytes)
28}
29
Josh Bleecher Snyder74d690e2025-05-14 18:16:03 -070030func EmptySchema() json.RawMessage {
31 return MustSchema(`{"type": "object", "properties": {}}`)
32}
33
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070034type Request struct {
35 Messages []Message
36 ToolChoice *ToolChoice
37 Tools []*Tool
38 System []SystemContent
39}
40
41// Message represents a message in the conversation.
42type Message struct {
43 Role MessageRole
44 Content []Content
45 ToolUse *ToolUse // use to control whether/which tool to use
46}
47
48// ToolUse represents a tool use in the message content.
49type ToolUse struct {
50 ID string
51 Name string
52}
53
54type ToolChoice struct {
55 Type ToolChoiceType
56 Name string
57}
58
59type SystemContent struct {
60 Text string
61 Type string
62 Cache bool
63}
64
65// Tool represents a tool available to an LLM.
66type Tool struct {
67 Name string
68 // Type is used by the text editor tool; see
69 // https://docs.anthropic.com/en/docs/build-with-claude/tool-use/text-editor-tool
70 Type string
71 Description string
72 InputSchema json.RawMessage
Sean McCullough021557a2025-05-05 23:20:53 +000073 // EndsTurn indicates that this tool should cause the model to end its turn when used
74 EndsTurn bool
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070075
76 // The Run function is automatically called when the tool is used.
77 // Run functions may be called concurrently with each other and themselves.
78 // The input to Run function is the input to the tool, as provided by Claude, in compliance with the input schema.
79 // The outputs from Run will be sent back to Claude.
80 // If you do not want to respond to the tool call request from Claude, return ErrDoNotRespond.
81 // ctx contains extra (rarely used) tool call information; retrieve it with ToolCallInfoFromContext.
Philip Zeyliger72252cb2025-05-10 17:00:08 -070082 Run func(ctx context.Context, input json.RawMessage) ([]Content, error) `json:"-"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070083}
84
85type Content struct {
86 ID string
87 Type ContentType
88 Text string
89
Philip Zeyliger72252cb2025-05-10 17:00:08 -070090 // Media type for image content
91 MediaType string
92
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070093 // for thinking
94 Thinking string
95 Data string
96 Signature string
97
98 // for tool_use
99 ToolName string
100 ToolInput json.RawMessage
101
102 // for tool_result
103 ToolUseID string
104 ToolError bool
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700105 ToolResult []Content
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700106
107 // timing information for tool_result; added externally; not sent to the LLM
108 ToolUseStartTime *time.Time
109 ToolUseEndTime *time.Time
110
111 Cache bool
112}
113
114func StringContent(s string) Content {
115 return Content{Type: ContentTypeText, Text: s}
116}
117
118// ContentsAttr returns contents as a slog.Attr.
119// It is meant for logging.
120func ContentsAttr(contents []Content) slog.Attr {
121 var contentAttrs []any // slog.Attr
122 for _, content := range contents {
123 var attrs []any // slog.Attr
124 switch content.Type {
125 case ContentTypeText:
126 attrs = append(attrs, slog.String("text", content.Text))
127 case ContentTypeToolUse:
128 attrs = append(attrs, slog.String("tool_name", content.ToolName))
129 attrs = append(attrs, slog.String("tool_input", string(content.ToolInput)))
130 case ContentTypeToolResult:
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700131 attrs = append(attrs, slog.Any("tool_result", content.ToolResult))
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700132 attrs = append(attrs, slog.Bool("tool_error", content.ToolError))
133 case ContentTypeThinking:
134 attrs = append(attrs, slog.String("thinking", content.Text))
135 default:
136 attrs = append(attrs, slog.String("unknown_content_type", content.Type.String()))
137 attrs = append(attrs, slog.Any("text", content)) // just log it all raw, better to have too much than not enough
138 }
139 contentAttrs = append(contentAttrs, slog.Group(content.ID, attrs...))
140 }
141 return slog.Group("contents", contentAttrs...)
142}
143
144type (
145 MessageRole int
146 ContentType int
147 ToolChoiceType int
148 StopReason int
149)
150
151//go:generate go tool golang.org/x/tools/cmd/stringer -type=MessageRole,ContentType,ToolChoiceType,StopReason -output=llm_string.go
152
153const (
154 MessageRoleUser MessageRole = iota
155 MessageRoleAssistant
156
157 ContentTypeText ContentType = iota
158 ContentTypeThinking
159 ContentTypeRedactedThinking
160 ContentTypeToolUse
161 ContentTypeToolResult
162
163 ToolChoiceTypeAuto ToolChoiceType = iota // default
164 ToolChoiceTypeAny // any tool, but must use one
165 ToolChoiceTypeNone // no tools allowed
166 ToolChoiceTypeTool // must use the tool specified in the Name field
167
168 StopReasonStopSequence StopReason = iota
169 StopReasonMaxTokens
170 StopReasonEndTurn
171 StopReasonToolUse
172)
173
174type Response struct {
175 ID string
176 Type string
177 Role MessageRole
178 Model string
179 Content []Content
180 StopReason StopReason
181 StopSequence *string
182 Usage Usage
183 StartTime *time.Time
184 EndTime *time.Time
185}
186
187func (m *Response) ToMessage() Message {
188 return Message{
189 Role: m.Role,
190 Content: m.Content,
191 }
192}
193
194// Usage represents the billing and rate-limit usage.
195// Most LLM structs do not have JSON tags, to avoid accidental direct use in specific providers.
196// However, the front-end uses this struct, and it relies on its JSON serialization.
197// Do NOT use this struct directly when implementing an llm.Service.
198type Usage struct {
199 InputTokens uint64 `json:"input_tokens"`
200 CacheCreationInputTokens uint64 `json:"cache_creation_input_tokens"`
201 CacheReadInputTokens uint64 `json:"cache_read_input_tokens"`
202 OutputTokens uint64 `json:"output_tokens"`
203 CostUSD float64 `json:"cost_usd"`
204}
205
206func (u *Usage) Add(other Usage) {
207 u.InputTokens += other.InputTokens
208 u.CacheCreationInputTokens += other.CacheCreationInputTokens
209 u.CacheReadInputTokens += other.CacheReadInputTokens
210 u.OutputTokens += other.OutputTokens
211 u.CostUSD += other.CostUSD
212}
213
214func (u *Usage) String() string {
215 return fmt.Sprintf("in: %d, out: %d", u.InputTokens, u.OutputTokens)
216}
217
218func (u *Usage) IsZero() bool {
219 return *u == Usage{}
220}
221
222func (u *Usage) Attr() slog.Attr {
223 return slog.Group("usage",
224 slog.Uint64("input_tokens", u.InputTokens),
225 slog.Uint64("output_tokens", u.OutputTokens),
226 slog.Uint64("cache_creation_input_tokens", u.CacheCreationInputTokens),
227 slog.Uint64("cache_read_input_tokens", u.CacheReadInputTokens),
228 slog.Float64("cost_usd", u.CostUSD),
229 )
230}
231
232// UserStringMessage creates a user message with a single text content item.
233func UserStringMessage(text string) Message {
234 return Message{
235 Role: MessageRoleUser,
236 Content: []Content{StringContent(text)},
237 }
238}
Philip Zeyliger72252cb2025-05-10 17:00:08 -0700239
240// TextContent creates a simple text content for tool results.
241// This is a helper function to create the most common type of tool result content.
242func TextContent(text string) []Content {
243 return []Content{{
244 Type: ContentTypeText,
245 Text: text,
246 }}
247}
248
249// ImageContent creates an image content for tool results.
250// MediaType should be "image/jpeg" or "image/png"
251func ImageContent(text string, mediaType string, base64Data string) []Content {
252 return []Content{{
253 Type: ContentTypeText,
254 Text: text,
255 MediaType: mediaType,
256 Data: base64Data,
257 }}
258}