1package fantasy
2
3import "encoding/json"
4
5// ProviderOptionsData is an interface for provider-specific options data.
6// All implementations MUST also implement encoding/json.Marshaler and
7// encoding/json.Unmarshaler interfaces to ensure proper JSON serialization
8// with the provider registry system.
9//
10// Recommended implementation pattern using generic helpers:
11//
12// // Define type constants at the top of your file
13// const TypeMyProviderOptions = "myprovider.options"
14//
15// type MyProviderOptions struct {
16// Field string `json:"field"`
17// }
18//
19// // Register the type in init() - place at top of file after constants
20// func init() {
21// fantasy.RegisterProviderType(TypeMyProviderOptions, func(data []byte) (fantasy.ProviderOptionsData, error) {
22// var opts MyProviderOptions
23// if err := json.Unmarshal(data, &opts); err != nil {
24// return nil, err
25// }
26// return &opts, nil
27// })
28// }
29//
30// // Implement ProviderOptionsData interface
31// func (*MyProviderOptions) Options() {}
32//
33// // Implement json.Marshaler using the generic helper
34// func (m MyProviderOptions) MarshalJSON() ([]byte, error) {
35// type plain MyProviderOptions
36// return fantasy.MarshalProviderType(TypeMyProviderOptions, plain(m))
37// }
38//
39// // Implement json.Unmarshaler using the generic helper
40// // Note: Receives inner data after type routing by the registry.
41// func (m *MyProviderOptions) UnmarshalJSON(data []byte) error {
42// type plain MyProviderOptions
43// var p plain
44// if err := fantasy.UnmarshalProviderType(data, &p); err != nil {
45// return err
46// }
47// *m = MyProviderOptions(p)
48// return nil
49// }
50type ProviderOptionsData interface {
51 // Options is a marker method that identifies types implementing this interface.
52 Options()
53 json.Marshaler
54 json.Unmarshaler
55}
56
57// ProviderMetadata represents additional provider-specific metadata.
58// They are passed through from the provider to the AI SDK and enable
59// provider-specific results that can be fully encapsulated in the provider.
60//
61// The outer map is keyed by the provider name, and the inner
62// map is keyed by the provider-specific metadata key.
63//
64// Example:
65//
66// {
67// "anthropic": {
68// "signature": "sig....."
69// }
70// }
71type ProviderMetadata map[string]ProviderOptionsData
72
73// ProviderOptions represents additional provider-specific options.
74// Options are additional input to the provider. They are passed through
75// to the provider from the AI SDK and enable provider-specific functionality
76// that can be fully encapsulated in the provider.
77//
78// This enables us to quickly ship provider-specific functionality
79// without affecting the core AI SDK.
80//
81// The outer map is keyed by the provider name, and the inner
82// map is keyed by the provider-specific option key.
83//
84// Example:
85//
86// {
87// "anthropic": {
88// "cacheControl": { "type": "ephemeral" }
89// }
90// }
91type ProviderOptions map[string]ProviderOptionsData
92
93// FinishReason represents why a language model finished generating a response.
94//
95// Can be one of the following:
96// - `stop`: model generated stop sequence
97// - `length`: model generated maximum number of tokens
98// - `content-filter`: content filter violation stopped the model
99// - `tool-calls`: model triggered tool calls
100// - `error`: model stopped because of an error
101// - `other`: model stopped for other reasons
102// - `unknown`: the model has not transmitted a finish reason.
103type FinishReason string
104
105const (
106 // FinishReasonStop indicates the model generated a stop sequence.
107 FinishReasonStop FinishReason = "stop" // model generated stop sequence
108 // FinishReasonLength indicates the model generated maximum number of tokens.
109 FinishReasonLength FinishReason = "length" // model generated maximum number of tokens
110 // FinishReasonContentFilter indicates content filter violation stopped the model.
111 FinishReasonContentFilter FinishReason = "content-filter" // content filter violation stopped the model
112 // FinishReasonToolCalls indicates the model triggered tool calls.
113 FinishReasonToolCalls FinishReason = "tool-calls" // model triggered tool calls
114 // FinishReasonError indicates the model stopped because of an error.
115 FinishReasonError FinishReason = "error" // model stopped because of an error
116 // FinishReasonOther indicates the model stopped for other reasons.
117 FinishReasonOther FinishReason = "other" // model stopped for other reasons
118 // FinishReasonUnknown indicates the model has not transmitted a finish reason.
119 FinishReasonUnknown FinishReason = "unknown" // the model has not transmitted a finish reason
120)
121
122// Prompt represents a list of messages for the language model.
123type Prompt []Message
124
125// MessageRole represents the role of a message.
126type MessageRole string
127
128const (
129 // MessageRoleSystem represents a system message.
130 MessageRoleSystem MessageRole = "system"
131 // MessageRoleUser represents a user message.
132 MessageRoleUser MessageRole = "user"
133 // MessageRoleAssistant represents an assistant message.
134 MessageRoleAssistant MessageRole = "assistant"
135 // MessageRoleTool represents a tool message.
136 MessageRoleTool MessageRole = "tool"
137)
138
139// Message represents a message in a prompt.
140type Message struct {
141 Role MessageRole `json:"role"`
142 Content []MessagePart `json:"content"`
143 ProviderOptions ProviderOptions `json:"provider_options"`
144}
145
146// AsContentType converts a Content interface to a specific content type.
147func AsContentType[T Content](content Content) (T, bool) {
148 var zero T
149 if content == nil {
150 return zero, false
151 }
152 switch v := any(content).(type) {
153 case T:
154 return v, true
155 case *T:
156 return *v, true
157 default:
158 return zero, false
159 }
160}
161
162// AsMessagePart converts a MessagePart interface to a specific message part type.
163func AsMessagePart[T MessagePart](content MessagePart) (T, bool) {
164 var zero T
165 if content == nil {
166 return zero, false
167 }
168 switch v := any(content).(type) {
169 case T:
170 return v, true
171 case *T:
172 return *v, true
173 default:
174 return zero, false
175 }
176}
177
178// MessagePart represents a part of a message content.
179type MessagePart interface {
180 GetType() ContentType
181 Options() ProviderOptions
182}
183
184// TextPart represents text content in a message.
185type TextPart struct {
186 Text string `json:"text"`
187 ProviderOptions ProviderOptions `json:"provider_options"`
188}
189
190// GetType returns the type of the text part.
191func (t TextPart) GetType() ContentType {
192 return ContentTypeText
193}
194
195// Options returns the provider options for the text part.
196func (t TextPart) Options() ProviderOptions {
197 return t.ProviderOptions
198}
199
200// ReasoningPart represents reasoning content in a message.
201type ReasoningPart struct {
202 Text string `json:"text"`
203 ProviderOptions ProviderOptions `json:"provider_options"`
204}
205
206// GetType returns the type of the reasoning part.
207func (r ReasoningPart) GetType() ContentType {
208 return ContentTypeReasoning
209}
210
211// Options returns the provider options for the reasoning part.
212func (r ReasoningPart) Options() ProviderOptions {
213 return r.ProviderOptions
214}
215
216// FilePart represents file content in a message.
217type FilePart struct {
218 Filename string `json:"filename"`
219 Data []byte `json:"data"`
220 MediaType string `json:"media_type"`
221 ProviderOptions ProviderOptions `json:"provider_options"`
222}
223
224// GetType returns the type of the file part.
225func (f FilePart) GetType() ContentType {
226 return ContentTypeFile
227}
228
229// Options returns the provider options for the file part.
230func (f FilePart) Options() ProviderOptions {
231 return f.ProviderOptions
232}
233
234// ToolCallPart represents a tool call in a message.
235type ToolCallPart struct {
236 ToolCallID string `json:"tool_call_id"`
237 ToolName string `json:"tool_name"`
238 Input string `json:"input"` // the json string
239 ProviderExecuted bool `json:"provider_executed"`
240 ProviderOptions ProviderOptions `json:"provider_options"`
241}
242
243// GetType returns the type of the tool call part.
244func (t ToolCallPart) GetType() ContentType {
245 return ContentTypeToolCall
246}
247
248// Options returns the provider options for the tool call part.
249func (t ToolCallPart) Options() ProviderOptions {
250 return t.ProviderOptions
251}
252
253// ToolResultPart represents a tool result in a message.
254type ToolResultPart struct {
255 ToolCallID string `json:"tool_call_id"`
256 Output ToolResultOutputContent `json:"output"`
257 ProviderOptions ProviderOptions `json:"provider_options"`
258}
259
260// GetType returns the type of the tool result part.
261func (t ToolResultPart) GetType() ContentType {
262 return ContentTypeToolResult
263}
264
265// Options returns the provider options for the tool result part.
266func (t ToolResultPart) Options() ProviderOptions {
267 return t.ProviderOptions
268}
269
270// ToolResultContentType represents the type of tool result output.
271type ToolResultContentType string
272
273const (
274 // ToolResultContentTypeText represents text output.
275 ToolResultContentTypeText ToolResultContentType = "text"
276 // ToolResultContentTypeError represents error text output.
277 ToolResultContentTypeError ToolResultContentType = "error"
278 // ToolResultContentTypeMedia represents content output.
279 ToolResultContentTypeMedia ToolResultContentType = "media"
280)
281
282// ToolResultOutputContent represents the output content of a tool result.
283type ToolResultOutputContent interface {
284 GetType() ToolResultContentType
285}
286
287// ToolResultOutputContentText represents text output content of a tool result.
288type ToolResultOutputContentText struct {
289 Text string `json:"text"`
290}
291
292// GetType returns the type of the tool result output content text.
293func (t ToolResultOutputContentText) GetType() ToolResultContentType {
294 return ToolResultContentTypeText
295}
296
297// ToolResultOutputContentError represents error output content of a tool result.
298type ToolResultOutputContentError struct {
299 Error error `json:"error"`
300}
301
302// GetType returns the type of the tool result output content error.
303func (t ToolResultOutputContentError) GetType() ToolResultContentType {
304 return ToolResultContentTypeError
305}
306
307// ToolResultOutputContentMedia represents media output content of a tool result.
308type ToolResultOutputContentMedia struct {
309 Data string `json:"data"` // for media type (base64)
310 MediaType string `json:"media_type"` // for media type
311}
312
313// GetType returns the type of the tool result output content media.
314func (t ToolResultOutputContentMedia) GetType() ToolResultContentType {
315 return ToolResultContentTypeMedia
316}
317
318// AsToolResultOutputType converts a ToolResultOutputContent interface to a specific type.
319func AsToolResultOutputType[T ToolResultOutputContent](content ToolResultOutputContent) (T, bool) {
320 var zero T
321 if content == nil {
322 return zero, false
323 }
324 switch v := any(content).(type) {
325 case T:
326 return v, true
327 case *T:
328 return *v, true
329 default:
330 return zero, false
331 }
332}
333
334// ContentType represents the type of content.
335type ContentType string
336
337const (
338 // ContentTypeText represents text content.
339 ContentTypeText ContentType = "text"
340 // ContentTypeReasoning represents reasoning content.
341 ContentTypeReasoning ContentType = "reasoning"
342 // ContentTypeFile represents file content.
343 ContentTypeFile ContentType = "file"
344 // ContentTypeSource represents source content.
345 ContentTypeSource ContentType = "source"
346 // ContentTypeToolCall represents a tool call.
347 ContentTypeToolCall ContentType = "tool-call"
348 // ContentTypeToolResult represents a tool result.
349 ContentTypeToolResult ContentType = "tool-result"
350)
351
352// Content represents generated content from the model.
353type Content interface {
354 GetType() ContentType
355}
356
357// TextContent represents text that the model has generated.
358type TextContent struct {
359 // The text content.
360 Text string `json:"text"`
361 ProviderMetadata ProviderMetadata `json:"provider_metadata"`
362}
363
364// GetType returns the type of the text content.
365func (t TextContent) GetType() ContentType {
366 return ContentTypeText
367}
368
369// ReasoningContent represents reasoning that the model has generated.
370type ReasoningContent struct {
371 Text string `json:"text"`
372 ProviderMetadata ProviderMetadata `json:"provider_metadata"`
373}
374
375// GetType returns the type of the reasoning content.
376func (r ReasoningContent) GetType() ContentType {
377 return ContentTypeReasoning
378}
379
380// FileContent represents a file that has been generated by the model.
381// Generated files as base64 encoded strings or binary data.
382// The files should be returned without any unnecessary conversion.
383type FileContent struct {
384 // The IANA media type of the file, e.g. `image/png` or `audio/mp3`.
385 // @see https://www.iana.org/assignments/media-types/media-types.xhtml
386 MediaType string `json:"media_type"`
387 // Generated file data as binary data.
388 Data []byte `json:"data"`
389 ProviderMetadata ProviderMetadata `json:"provider_metadata"`
390}
391
392// GetType returns the type of the file content.
393func (f FileContent) GetType() ContentType {
394 return ContentTypeFile
395}
396
397// SourceType represents the type of source.
398type SourceType string
399
400const (
401 // SourceTypeURL represents a URL source.
402 SourceTypeURL SourceType = "url"
403 // SourceTypeDocument represents a document source.
404 SourceTypeDocument SourceType = "document"
405)
406
407// SourceContent represents a source that has been used as input to generate the response.
408type SourceContent struct {
409 SourceType SourceType `json:"source_type"` // "url" or "document"
410 ID string `json:"id"`
411 URL string `json:"url"` // for URL sources
412 Title string `json:"title"`
413 MediaType string `json:"media_type"` // for document sources (IANA media type)
414 Filename string `json:"filename"` // for document sources
415 ProviderMetadata ProviderMetadata `json:"provider_metadata"`
416}
417
418// GetType returns the type of the source content.
419func (s SourceContent) GetType() ContentType {
420 return ContentTypeSource
421}
422
423// ToolCallContent represents tool calls that the model has generated.
424type ToolCallContent struct {
425 ToolCallID string `json:"tool_call_id"`
426 ToolName string `json:"tool_name"`
427 // Stringified JSON object with the tool call arguments.
428 // Must match the parameters schema of the tool.
429 Input string `json:"input"`
430 // Whether the tool call will be executed by the provider.
431 // If this flag is not set or is false, the tool call will be executed by the client.
432 ProviderExecuted bool `json:"provider_executed"`
433 // Additional provider-specific metadata for the tool call.
434 ProviderMetadata ProviderMetadata `json:"provider_metadata"`
435 // Whether this tool call is invalid (failed validation/parsing)
436 Invalid bool `json:"invalid,omitempty"`
437 // Error that occurred during validation/parsing (only set if Invalid is true)
438 ValidationError error `json:"validation_error,omitempty"`
439}
440
441// GetType returns the type of the tool call content.
442func (t ToolCallContent) GetType() ContentType {
443 return ContentTypeToolCall
444}
445
446// ToolResultContent represents result of a tool call that has been executed by the provider.
447type ToolResultContent struct {
448 // The ID of the tool call that this result is associated with.
449 ToolCallID string `json:"tool_call_id"`
450 // Name of the tool that generated this result.
451 ToolName string `json:"tool_name"`
452 // Result of the tool call. This is a JSON-serializable object.
453 Result ToolResultOutputContent `json:"result"`
454 ClientMetadata string `json:"client_metadata"` // Metadata from the client that executed the tool
455 // Whether the tool result was generated by the provider.
456 // If this flag is set to true, the tool result was generated by the provider.
457 // If this flag is not set or is false, the tool result was generated by the client.
458 ProviderExecuted bool `json:"provider_executed"`
459 // Additional provider-specific metadata for the tool result.
460 ProviderMetadata ProviderMetadata `json:"provider_metadata"`
461}
462
463// GetType returns the type of the tool result content.
464func (t ToolResultContent) GetType() ContentType {
465 return ContentTypeToolResult
466}
467
468// ToolType represents the type of tool.
469type ToolType string
470
471const (
472 // ToolTypeFunction represents a function tool.
473 ToolTypeFunction ToolType = "function"
474 // ToolTypeProviderDefined represents a provider-defined tool.
475 ToolTypeProviderDefined ToolType = "provider-defined"
476)
477
478// Tool represents a tool that can be used by the model.
479//
480// Note: this is **not** the user-facing tool definition. The AI SDK methods will
481// map the user-facing tool definitions to this format.
482type Tool interface {
483 GetType() ToolType
484 GetName() string
485}
486
487// FunctionTool represents a function tool.
488//
489// A tool has a name, a description, and a set of parameters.
490type FunctionTool struct {
491 // Name of the tool. Unique within this model call.
492 Name string `json:"name"`
493 // Description of the tool. The language model uses this to understand the
494 // tool's purpose and to provide better completion suggestions.
495 Description string `json:"description"`
496 // InputSchema - the parameters that the tool expects. The language model uses this to
497 // understand the tool's input requirements and to provide matching suggestions.
498 InputSchema map[string]any `json:"input_schema"` // JSON Schema
499 // ProviderOptions are provider-specific options for the tool.
500 ProviderOptions ProviderOptions `json:"provider_options"`
501}
502
503// GetType returns the type of the function tool.
504func (f FunctionTool) GetType() ToolType {
505 return ToolTypeFunction
506}
507
508// GetName returns the name of the function tool.
509func (f FunctionTool) GetName() string {
510 return f.Name
511}
512
513// ProviderDefinedTool represents the configuration of a tool that is defined by the provider.
514type ProviderDefinedTool struct {
515 // ID of the tool. Should follow the format `<provider-name>.<unique-tool-name>`.
516 ID string `json:"id"`
517 // Name of the tool that the user must use in the tool set.
518 Name string `json:"name"`
519 // Args for configuring the tool. Must match the expected arguments defined by the provider for this tool.
520 Args map[string]any `json:"args"`
521}
522
523// GetType returns the type of the provider-defined tool.
524func (p ProviderDefinedTool) GetType() ToolType {
525 return ToolTypeProviderDefined
526}
527
528// GetName returns the name of the provider-defined tool.
529func (p ProviderDefinedTool) GetName() string {
530 return p.Name
531}
532
533// NewUserMessage creates a new user message with the given prompt and optional files.
534func NewUserMessage(prompt string, files ...FilePart) Message {
535 content := []MessagePart{
536 TextPart{
537 Text: prompt,
538 },
539 }
540
541 for _, f := range files {
542 content = append(content, f)
543 }
544
545 return Message{
546 Role: MessageRoleUser,
547 Content: content,
548 }
549}
550
551// NewSystemMessage creates a new system message with the given prompts.
552func NewSystemMessage(prompt ...string) Message {
553 content := make([]MessagePart, 0, len(prompt))
554 for _, p := range prompt {
555 content = append(content, TextPart{Text: p})
556 }
557
558 return Message{
559 Role: MessageRoleSystem,
560 Content: content,
561 }
562}