Documentation
¶
Overview ¶
Package ai is a provider-neutral Go SDK for language, embedding and reranking models.
Index ¶
- Variables
- func As[T any](model any) (T, bool)
- func DecodeChoice[T ~string](res *TextResult) (T, error)
- func DecodeObject[T any](res *TextResult) (T, error)
- func DeleteFile(ctx context.Context, model any, id string) error
- func Elements[E any](s *ObjectStream[[]E]) iter.Seq[E]
- func ProviderValue[T any](d ProviderData, key string) (T, bool)
- func ToolErrorf(format string, args ...any) error
- type APIError
- type Approval
- type ApprovalInput
- type BatchCall
- type BatchEntry
- type BatchItem
- type BatchJob
- func (j *BatchJob) Cancel(ctx context.Context) error
- func (j *BatchJob) Err() error
- func (j *BatchJob) ID() string
- func (j *BatchJob) Results(ctx context.Context) iter.Seq[BatchResult]
- func (j *BatchJob) Status(ctx context.Context) (BatchStatus, error)
- func (j *BatchJob) Wait(ctx context.Context, interval time.Duration) error
- func (j *BatchJob) WithOutput(id string, out Output) *BatchJob
- type BatchResult
- type BatchState
- type BatchStatus
- type Batches
- type Call
- type Citation
- type Custom
- type Decision
- type EmbedCall
- type EmbedRequest
- type EmbedResponse
- type EmbedResult
- type EmbeddingMiddleware
- type EmbeddingModel
- type File
- type FileList
- type FileListCall
- type FileListRequest
- type FileUpload
- type FileUploadCall
- type Files
- type FinishReason
- type ImageCall
- type ImageMiddleware
- type ImageModel
- type ImageRequest
- type ImageResponse
- type ImageResult
- type InputType
- type JobError
- type LanguageModel
- type Limiter
- type Message
- type Middleware
- type NoSuchModelError
- type NoSuchToolError
- type ObjectStream
- type Output
- type OutputError
- type OutputSpec
- type Part
- type Parts
- type Provider
- type ProviderData
- type ProviderOptions
- type Ranked
- type Reasoning
- type ReasoningDelta
- type ReasoningEffort
- type ReasoningEnd
- type ReasoningStart
- type Registry
- type RerankCall
- type RerankModel
- type RerankRequest
- type RerankResponse
- type RerankResult
- type Response
- type RetryError
- type Role
- type Segment
- type SpeechCall
- type SpeechModel
- type SpeechRequest
- type SpeechResponse
- type SpeechResult
- type SpeechStream
- type SpeechStreamCall
- type SpeechStreamModel
- type SpeechStreamRequest
- type SpeechStreamResponse
- type Step
- type StepEnd
- type StepInfo
- type StepRequest
- type StepStart
- type StepState
- type StopCondition
- type StreamFinish
- type StreamPart
- type StreamResponse
- type StreamStart
- type Telemetry
- type Text
- type TextDelta
- type TextEnd
- type TextRequest
- type TextResult
- func GenerateChoice[T ~string](ctx context.Context, m LanguageModel, req TextRequest, choices ...T) (T, *TextResult, error)
- func GenerateJSON(ctx context.Context, m LanguageModel, req TextRequest) (json.RawMessage, *TextResult, error)
- func GenerateObject[T any](ctx context.Context, m LanguageModel, req TextRequest) (T, *TextResult, error)
- func GenerateText(ctx context.Context, m LanguageModel, req TextRequest) (*TextResult, error)
- type TextStart
- type TextStream
- type Timeouts
- type Tool
- type ToolApprovalRequest
- type ToolApprovalResponse
- type ToolCall
- type ToolChoice
- type ToolChoiceMode
- type ToolError
- type ToolFailed
- type ToolInputDelta
- type ToolInputEnd
- type ToolInputStart
- type ToolOutput
- type ToolResult
- type TranscribeCall
- type TranscribeRequest
- type TranscribeResponse
- type TranscribeResult
- type TranscribeStream
- type TranscribeStreamRequest
- type TranscribeStreamResponse
- type TranscriptionModel
- type TranscriptionStreamModel
- type Usage
- type VideoCall
- type VideoJob
- type VideoModel
- type VideoPoll
- type VideoRequest
- type VideoResult
- type Warning
Examples ¶
- APIError
- APIError.Retryable
- Allow
- AlwaysAsk
- As
- AskUser
- Assistant
- BatchJob.Cancel
- BatchJob.Err
- BatchJob.ID
- BatchJob.Results
- BatchJob.Status
- BatchJob.Wait
- BatchJob.WithOutput
- BatchState.Done
- ChoiceOutput
- DecodeChoice
- DecodeObject
- DefaultSettings
- DeleteFile
- Deny
- Elements
- Embed
- ExtractReasoning
- Fallback
- GenerateChoice
- GenerateImage
- GenerateJSON
- GenerateObject
- GenerateObject (Invalid)
- GenerateSpeech
- GenerateText
- GenerateText (StepLimit)
- GenerateText (Tools)
- GenerateVideo
- GetFile
- HasToolCall
- JSONOutput
- ListFiles
- MaxTotalTokens
- NewClientTool
- NewTool
- ObjectOutput
- ObjectStream.Err
- ObjectStream.Partials
- ObjectStream.Parts
- ObjectStream.Result
- Parts
- ProviderData.WithRaw
- ProviderData.WithValue
- ProviderValue
- Providers
- Registry.EmbeddingModel
- Registry.LanguageModel
- Registry.RerankModel
- Rerank
- ResumeBatch
- SpeechStream.Audio
- SpeechStream.Err
- SpeechStream.MediaType
- StartBatch
- StreamObject
- StreamSpeech
- StreamText
- StreamTranscribe
- TextRequest.Clone
- TextRequest.WithMessages
- TextStream.Err
- TextStream.Parts
- TextStream.Result
- TextStream.Text
- Texts
- Tool.WithApproval
- Tool.WithTimeout
- ToolChoice.Mode
- ToolChoice.Name
- ToolErrorf
- ToolNamed
- ToolNone
- ToolRequired
- Transcribe
- TranscribeStream.Err
- TranscribeStream.Segments
- UploadFile
- User
- UserParts
- WrapEmbeddingModel
- WrapImageModel
- WrapModel
Constants ¶
This section is empty.
Variables ¶
var ( ErrRateLimit = errors.New("ai: rate limited") ErrQuota = errors.New("ai: quota exceeded") ErrAuth = errors.New("ai: authentication failed") ErrContextTooLong = errors.New("ai: context too long") ErrStreamConsumed = errors.New("ai: stream already consumed") ErrStreamActive = errors.New("ai: stream is being consumed") ErrDuplicateTool = errors.New("ai: duplicate tool name") ErrInvalidApproval = errors.New("ai: invalid tool approval") )
var ErrUnsupported = errors.New("ai: operation not supported by this model")
Functions ¶
func As ¶
As searches model and everything it wraps depth-first, following Unwrap() with LanguageModel, EmbeddingModel or ImageModel results and Unwrap() []LanguageModel, and returns the first match.
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
inner := aitest.NewModel()
wrapped := ai.WrapModel(ai.Fallback(inner), ai.Middleware{})
found, ok := ai.As[*aitest.Model](wrapped)
fmt.Println(ok, found == inner)
}
Output: true true
func DecodeChoice ¶
func DecodeChoice[T ~string](res *TextResult) (T, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"result":"b"}`)))
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Output: ai.ChoiceOutput("a", "b")})
choice, err := ai.DecodeChoice[string](res)
fmt.Println(choice, err)
}
Output: b <nil>
func DecodeObject ¶
func DecodeObject[T any](res *TextResult) (T, error)
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
res := &ai.TextResult{Text: `{"n":7}`}
v, err := ai.DecodeObject[struct {
N int `json:"n"`
}](res)
fmt.Println(v.N, err)
}
Output: 7 <nil>
func DeleteFile ¶
Example ¶
package main
import (
"context"
"fmt"
"strings"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
store := aitest.NewFiles()
ctx := context.Background()
up, err := ai.UploadFile(ctx, store, ai.FileUpload{Data: strings.NewReader("x")})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(ai.DeleteFile(ctx, store, aitest.FileID(up)))
_, err = ai.GetFile(ctx, store, aitest.FileID(up))
fmt.Println(err != nil)
}
Output: <nil> true
func Elements ¶
func Elements[E any](s *ObjectStream[[]E]) iter.Seq[E]
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type item struct {
Title string `json:"title"`
}
model := aitest.NewModel(aitest.Turn(aitest.TextChunks(`{"result":[{"title":"a"},`, `{"title":"b"}]}`)))
s := ai.StreamObject[[]item](context.Background(), model, ai.TextRequest{})
for it := range ai.Elements(s) {
fmt.Println(it.Title)
}
if err := s.Err(); err != nil {
fmt.Println(err)
}
}
Output: a b
func ProviderValue ¶
func ProviderValue[T any](d ProviderData, key string) (T, bool)
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
data := ai.ProviderData{}.WithRaw("openai", json.RawMessage(`{"itemId":"rs_1"}`))
v, ok := ai.ProviderValue[struct {
ItemID string `json:"itemId"`
}](data, "openai")
fmt.Println(v.ItemID, ok)
}
Output: rs_1 true
func ToolErrorf ¶
Example ¶
lookup := ai.NewTool("lookup", "Look up a city", func(context.Context, struct{}) (string, error) {
return "", ai.ToolErrorf("unknown city %q", "Oz")
})
model := aitest.NewModel(aitest.Turn(aitest.ToolCall("lookup", `{}`)), aitest.Turn(aitest.Text("sorry")))
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Tools: []ai.Tool{lookup}})
for _, r := range resultsOf(res.Messages) {
fmt.Println(r.Output.Text)
}
Output: unknown city "Oz"
Types ¶
type APIError ¶
type APIError struct {
Provider string
StatusCode int
Code string
Message string
RequestID string
RetryAfter time.Duration
Body string
ShouldRetry *bool
ContextTooLong bool
}
APIError.Body holds the raw provider response and is never part of Error(). ShouldRetry, when non-nil, carries the provider's explicit retry instruction and overrides the status-based default. ContextTooLong is set by the provider adapter when it recognizes a context-length failure that the generic checks in Is miss.
Example ¶
package main
import (
"errors"
"fmt"
"net/http"
"github.com/minodevss/ai-go"
)
func main() {
err := &ai.APIError{Provider: "openai", StatusCode: http.StatusTooManyRequests, Code: "rate_limit_exceeded", Message: "slow down", Body: "{raw}"}
fmt.Println(err)
fmt.Println(errors.Is(err, ai.ErrRateLimit), err.Retryable())
}
Output: ai: openai: status 429 (rate_limit_exceeded): slow down true true
func (*APIError) Retryable ¶
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/minodevss/ai-go"
)
func main() {
rateLimited := &ai.APIError{Provider: "openai", StatusCode: http.StatusTooManyRequests}
badRequest := &ai.APIError{Provider: "openai", StatusCode: http.StatusBadRequest}
fmt.Println(rateLimited.Retryable(), badRequest.Retryable())
}
Output: true false
type Approval ¶
Approval's zero value asks the user.
func Allow ¶
func Allow() Approval
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
policy := func(_ context.Context, in ai.ApprovalInput) ai.Approval {
if in.Tainted {
return ai.AskUser("output of an untrusted tool is in context")
}
return ai.Allow()
}
fmt.Println(policy(context.Background(), ai.ApprovalInput{}).Decision == ai.DecisionAllow)
fmt.Println(policy(context.Background(), ai.ApprovalInput{Tainted: true}).Decision == ai.DecisionAsk)
}
Output: true true
func AlwaysAsk ¶
func AlwaysAsk(context.Context, ApprovalInput) Approval
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
approval := ai.AlwaysAsk(context.Background(), ai.ApprovalInput{})
fmt.Println(approval.Decision == ai.DecisionAsk)
}
Output: true
func AskUser ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
policy := func(_ context.Context, in ai.ApprovalInput) ai.Approval {
return ai.AskUser("deleting " + in.Call.Name + " cannot be undone")
}
remove := ai.NewTool("remove", "Remove a record", func(context.Context, struct{}) (string, error) { return "removed", nil }).
WithApproval(policy)
model := aitest.NewModel(aitest.Turn(aitest.ToolCall("remove", `{}`)))
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Tools: []ai.Tool{remove}})
fmt.Println(res.FinishReason)
}
Output: approval-pending
func Deny ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
policy := func(_ context.Context, in ai.ApprovalInput) ai.Approval {
if in.Call.Name == "drop_table" {
return ai.Deny("never allowed")
}
return ai.Allow()
}
a := policy(context.Background(), ai.ApprovalInput{Call: ai.ToolCall{Name: "drop_table"}})
fmt.Println(a.Decision == ai.DecisionDeny, a.Reason)
}
Output: true never allowed
type ApprovalInput ¶
type BatchCall ¶
BatchCall is one request of a batch. ID is unique within the batch and is how results are matched.
type BatchEntry ¶
BatchEntry is one result line of a batch; exactly one of Response and Err is set.
type BatchItem ¶
type BatchItem struct {
ID string
Request TextRequest
}
type BatchJob ¶
type BatchJob struct {
// contains filtered or unexported fields
}
BatchJob is not safe for concurrent use. Err returns the error that ended the latest Results iteration.
func ResumeBatch ¶
func ResumeBatch(model LanguageModel, id string) *BatchJob
ResumeBatch returns a handle to a batch started earlier. Call WithOutput for each item whose result goes through DecodeObject or DecodeChoice.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewBatchModel()
job := ai.ResumeBatch(model, "batch_42")
st, err := job.Status(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(job.ID(), st.State, st.State.Done())
}
Output: batch_42 completed true
func StartBatch ¶
StartBatch submits single-step requests to a provider's batch API. The model must itself implement Batches: Fallback and wrapped models are rejected, because their routing and middleware cannot run inside a provider batch. Requests with tool Execute functions, PrepareStep, OnStepEnd, StopWhen or MaxSteps above 1 are rejected, because a batch cannot run a loop.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewBatchModel(aitest.Turn(aitest.Text("blue")), aitest.Turn(aitest.Text("green")))
items := []ai.BatchItem{
{ID: "q1", Request: ai.TextRequest{Messages: []ai.Message{ai.User("Reply with blue.")}}},
{ID: "q2", Request: ai.TextRequest{Messages: []ai.Message{ai.User("Reply with green.")}}},
}
ctx := context.Background()
job, err := ai.StartBatch(ctx, model, items)
if err != nil {
fmt.Println(err)
return
}
if err := job.Wait(ctx, time.Second); err != nil {
fmt.Println(err)
return
}
answers := map[string]string{}
for r := range job.Results(ctx) {
answers[r.ID] = r.Result.Text
}
fmt.Println(job.Err(), answers["q1"], answers["q2"])
}
Output: <nil> blue green
func (*BatchJob) Cancel ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewBatchModel(aitest.States(ai.BatchRunning))
job := ai.ResumeBatch(model, "batch_1")
fmt.Println(job.Cancel(context.Background()), model.Canceled())
}
Output: <nil> true
func (*BatchJob) Err ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewBatchModel()
job := ai.ResumeBatch(model, "batch_7")
for range job.Results(context.Background()) {
}
fmt.Println(job.Err())
}
Output: <nil>
func (*BatchJob) ID ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewBatchModel()
job, err := ai.StartBatch(context.Background(), model, []ai.BatchItem{{ID: "q1", Request: ai.TextRequest{Messages: []ai.Message{ai.User("hi")}}}})
fmt.Println(job.ID() != "", err)
}
Output: true <nil>
func (*BatchJob) Results ¶
Results yields one result per request line the provider returned, in provider order, not request order. Match by ID.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewBatchModel(aitest.Turn(aitest.Text("blue")))
items := []ai.BatchItem{{ID: "q1", Request: ai.TextRequest{Messages: []ai.Message{ai.User("Reply with blue.")}}}}
ctx := context.Background()
job, err := ai.StartBatch(ctx, model, items)
if err != nil {
fmt.Println(err)
return
}
for r := range job.Results(ctx) {
fmt.Println(r.ID, r.Result.Text, r.Err)
}
}
Output: q1 blue <nil>
func (*BatchJob) Status ¶
func (j *BatchJob) Status(ctx context.Context) (BatchStatus, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewBatchModel(aitest.States(ai.BatchRunning, ai.BatchCompleted))
job := ai.ResumeBatch(model, "batch_7")
for range 2 {
st, err := job.Status(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(st.State, st.State.Done())
}
}
Output: running false completed true
func (*BatchJob) Wait ¶
Wait polls every interval (0 = 30s) until the batch is done. It returns nil for every final state except BatchFailed, so partial results of expired or canceled batches stay readable.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewBatchModel(aitest.States(ai.BatchRunning, ai.BatchCompleted))
job := ai.ResumeBatch(model, "batch_7")
err := job.Wait(context.Background(), time.Millisecond)
fmt.Println(err)
}
Output: <nil>
func (*BatchJob) WithOutput ¶
WithOutput sets the Output that DecodeObject and DecodeChoice use for the result of item id, and returns j.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type answer struct {
Color string `json:"color"`
}
model := aitest.NewBatchModel(aitest.Turn(aitest.Text(`{"color":"blue"}`)))
items := []ai.BatchItem{{ID: "q1", Request: ai.TextRequest{Messages: []ai.Message{ai.User("Pick a color.")}}}}
ctx := context.Background()
job, err := ai.StartBatch(ctx, model, items)
if err != nil {
fmt.Println(err)
return
}
job.WithOutput("q1", ai.ObjectOutput[answer]())
for r := range job.Results(ctx) {
v, err := ai.DecodeObject[answer](r.Result)
fmt.Println(v.Color, err)
}
}
Output: blue <nil>
type BatchResult ¶
type BatchResult struct {
ID string
Result *TextResult
Err error
}
type BatchState ¶
type BatchState string
const ( BatchValidating BatchState = "validating" BatchRunning BatchState = "running" BatchFinalizing BatchState = "finalizing" BatchCanceling BatchState = "canceling" BatchCompleted BatchState = "completed" BatchFailed BatchState = "failed" BatchExpired BatchState = "expired" BatchCanceled BatchState = "canceled" )
func (BatchState) Done ¶
func (s BatchState) Done() bool
Done reports whether the batch can no longer change state.
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
fmt.Println(ai.BatchRunning.Done(), ai.BatchCompleted.Done())
}
Output: false true
type BatchStatus ¶
type Batches ¶
type Batches interface {
StartBatch(ctx context.Context, calls []BatchCall) (string, error)
BatchStatus(ctx context.Context, id string) (*BatchStatus, error)
BatchResults(ctx context.Context, id string) iter.Seq2[BatchEntry, error]
CancelBatch(ctx context.Context, id string) error
}
Batches is the capability of language models whose provider runs requests asynchronously at a discount. A provider implements it on a concrete model, never on wrappers.
type Call ¶
type Call struct {
Instructions []Text
Messages []Message
Tools []Tool
ToolChoice ToolChoice
Output *OutputSpec
MaxOutputTokens int
Temperature *float64
TopP *float64
TopK int
PresencePenalty *float64
FrequencyPenalty *float64
Seed *int
StopSequences []string
Reasoning ReasoningEffort
Headers http.Header
Provider ProviderData
}
type Citation ¶
type Citation struct {
Kind string `json:"kind,omitzero"`
URL string `json:"url,omitzero"`
Title string `json:"title,omitzero"`
CitedText string `json:"citedText,omitzero"`
DocIndex *int `json:"docIndex,omitzero"`
Start int `json:"start,omitzero"`
End int `json:"end,omitzero"`
Provider ProviderData `json:"provider,omitzero"`
}
type Custom ¶
type Custom struct {
Kind string `json:"kind"`
Data json.RawMessage `json:"data,omitzero"`
Provider ProviderData `json:"provider,omitzero"`
}
func (Custom) MarshalJSON ¶
type EmbedCall ¶
type EmbedRequest ¶
type EmbedRequest struct {
Texts []string
Inputs []Parts
InputType InputType
Dimensions int
Concurrency int
MaxRetries *int
Headers http.Header
Provider ProviderData
}
EmbedRequest takes exactly one of Texts or Inputs. Inputs are split into batches of the model's MaxBatch and sent Concurrency batches at a time (0 = 1).
type EmbedResponse ¶
type EmbedResult ¶
func Embed ¶
func Embed(ctx context.Context, m EmbeddingModel, req EmbedRequest) (*EmbedResult, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewEmbeddingModel(aitest.MaxBatch(2))
res, err := ai.Embed(context.Background(), model, ai.EmbedRequest{
Texts: []string{"a", "bb", "ccc"},
InputType: ai.InputDocument,
Concurrency: 2,
})
fmt.Println(len(res.Embeddings), len(model.Calls()), err)
}
Output: 3 2 <nil>
type EmbeddingMiddleware ¶
type EmbeddingMiddleware struct {
TransformRequest func(ctx context.Context, c *EmbedCall) error
WrapEmbed func(ctx context.Context, c *EmbedCall, next func(context.Context, *EmbedCall) (*EmbedResponse, error)) (*EmbedResponse, error)
}
EmbeddingMiddleware hooks run in order: TransformRequest on a clone of the call, then WrapEmbed around the model.
type EmbeddingModel ¶
type EmbeddingModel interface {
Provider() string
ModelID() string
MaxBatch() int
Embed(ctx context.Context, c *EmbedCall) (*EmbedResponse, error)
}
EmbeddingModel reports MaxBatch as the largest number of inputs per Embed call; 0 means unlimited.
func WrapEmbeddingModel ¶
func WrapEmbeddingModel(m EmbeddingModel, mw EmbeddingMiddleware) EmbeddingModel
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
base := aitest.NewEmbeddingModel()
m := ai.WrapEmbeddingModel(base, ai.EmbeddingMiddleware{TransformRequest: func(_ context.Context, c *ai.EmbedCall) error {
c.Dimensions = 256
return nil
}})
if _, err := m.Embed(context.Background(), &ai.EmbedCall{Inputs: []ai.Parts{{ai.Text{Text: "hello"}}}}); err != nil {
fmt.Println(err)
return
}
fmt.Println(base.Calls()[0].Dimensions)
}
Output: 256
type File ¶
type File struct {
MediaType string `json:"mediaType,omitzero"`
Filename string `json:"filename,omitzero"`
Data []byte `json:"data,omitzero"`
URL string `json:"url,omitzero"`
Citations bool `json:"citations,omitzero"`
Provider ProviderData `json:"provider,omitzero"`
}
func GetFile ¶
Example ¶
package main
import (
"context"
"fmt"
"strings"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
store := aitest.NewFiles()
ctx := context.Background()
up, err := ai.UploadFile(ctx, store, ai.FileUpload{Name: "a.txt", Data: strings.NewReader("a")})
if err != nil {
fmt.Println(err)
return
}
f, err := ai.GetFile(ctx, store, aitest.FileID(up))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(f.Filename)
}
Output: a.txt
func UploadFile ¶
UploadFile stores a file with the provider behind model, which may be a model or a provider that implements Files; wrappers are searched with As. The returned File holds the provider's file id in Provider and no Data. A failed upload is retried only when Data is an io.Seeker.
Example ¶
package main
import (
"context"
"fmt"
"strings"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
store := aitest.NewFiles()
f, err := ai.UploadFile(context.Background(), store, ai.FileUpload{Name: "notes.txt", MediaType: "text/plain", Data: strings.NewReader("hello")})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(f.Filename, aitest.FileID(f), len(f.Data))
}
Output: notes.txt file_1 0
func (File) MarshalJSON ¶
type FileList ¶
func ListFiles ¶
ListFiles returns one page; pass FileList.Next as After for the next. Next is empty on the last page.
Example ¶
package main
import (
"context"
"fmt"
"strings"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
store := aitest.NewFiles()
ctx := context.Background()
for _, name := range []string{"a", "b", "c"} {
if _, err := ai.UploadFile(ctx, store, ai.FileUpload{Name: name, Data: strings.NewReader(name)}); err != nil {
fmt.Println(err)
return
}
}
after := ""
for {
page, err := ai.ListFiles(ctx, store, ai.FileListRequest{Limit: 2, After: after})
if err != nil {
fmt.Println(err)
return
}
for _, f := range page.Files {
fmt.Println(f.Filename)
}
if after = page.Next; after == "" {
return
}
}
}
Output: a b c
type FileListCall ¶
type FileListRequest ¶
type FileUpload ¶
type FileUploadCall ¶
type Files ¶
type Files interface {
UploadFile(ctx context.Context, c *FileUploadCall) (*File, error)
GetFile(ctx context.Context, id string) (*File, error)
ListFiles(ctx context.Context, c *FileListCall) (*FileList, error)
DeleteFile(ctx context.Context, id string) error
}
Files is the capability of providers that store files. Returned Files carry the provider's file id in Provider and never carry Data.
type FinishReason ¶
type FinishReason string
const ( FinishStop FinishReason = "stop" FinishLength FinishReason = "length" FinishToolCalls FinishReason = "tool-calls" FinishContentFilter FinishReason = "content-filter" FinishRefusal FinishReason = "refusal" FinishStepLimit FinishReason = "step-limit" FinishApprovalPending FinishReason = "approval-pending" FinishError FinishReason = "error" FinishOther FinishReason = "other" FinishPause FinishReason = "pause" )
type ImageCall ¶
type ImageMiddleware ¶
type ImageMiddleware struct {
TransformRequest func(ctx context.Context, c *ImageCall) error
WrapGenerate func(ctx context.Context, c *ImageCall, next func(context.Context, *ImageCall) (*ImageResponse, error)) (*ImageResponse, error)
}
ImageMiddleware hooks run in order: TransformRequest on a clone of the call, then WrapGenerate around the model.
type ImageModel ¶
type ImageModel interface {
Provider() string
ModelID() string
GenerateImage(ctx context.Context, c *ImageCall) (*ImageResponse, error)
}
func WrapImageModel ¶
func WrapImageModel(m ImageModel, mw ImageMiddleware) ImageModel
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
)
type imageStub struct {
calls []ai.ImageCall
}
func (*imageStub) Provider() string { return "stub" }
func (*imageStub) ModelID() string { return "image" }
func (s *imageStub) GenerateImage(_ context.Context, c *ai.ImageCall) (*ai.ImageResponse, error) {
s.calls = append(s.calls, *c)
return &ai.ImageResponse{Images: []ai.File{{MediaType: "image/png", Data: []byte(c.Prompt)}}}, nil
}
func main() {
m := ai.WrapImageModel(&imageStub{}, ai.ImageMiddleware{TransformRequest: func(_ context.Context, c *ai.ImageCall) error {
c.Prompt += ", watercolor"
return nil
}})
res, err := m.GenerateImage(context.Background(), &ai.ImageCall{Prompt: "a lighthouse"})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(res.Images[0].Data))
}
Output: a lighthouse, watercolor
type ImageRequest ¶
type ImageResponse ¶
type ImageResult ¶
func GenerateImage ¶
func GenerateImage(ctx context.Context, m ImageModel, req ImageRequest) (*ImageResult, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
res, err := ai.GenerateImage(context.Background(), aitest.NewImageModel(), ai.ImageRequest{Prompt: "a lighthouse at dusk", N: 2, Size: "1024x1024"})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(res.Images), res.Images[0].MediaType)
}
Output: 2 image/png
type JobError ¶
JobError reports a failed or abandoned asynchronous job. ID is the provider's job id, so the job can still be found after ctx ends.
type LanguageModel ¶
type LanguageModel interface {
Provider() string
ModelID() string
Generate(ctx context.Context, c *Call) (*Response, error)
Stream(ctx context.Context, c *Call) (*StreamResponse, error)
}
LanguageModel implementations must not mutate the Call and must return provider-executed output in Content as ToolCall and ToolResult parts.
func Fallback ¶
func Fallback(models ...LanguageModel) LanguageModel
Fallback tries each model in order and moves on only after a retryable or category error (rate limit, quota, auth, context length) before any output.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
primary := aitest.NewModel(aitest.Turn(aitest.Err(&ai.APIError{StatusCode: http.StatusServiceUnavailable})))
backup := aitest.NewModel(aitest.Turn(aitest.Text("from the backup")))
res, err := ai.GenerateText(context.Background(), ai.Fallback(primary, backup), ai.TextRequest{MaxRetries: new(0)})
fmt.Println(res.Text, err)
}
Output: from the backup <nil>
func WrapModel ¶
func WrapModel(m LanguageModel, mw Middleware) LanguageModel
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
logging := ai.Middleware{TransformRequest: func(_ context.Context, c *ai.Call) error {
c.Instructions = append(c.Instructions, ai.Text{Text: "Answer briefly."})
return nil
}}
inner := aitest.NewModel(aitest.Turn(aitest.Text("ok")))
_, _ = ai.GenerateText(context.Background(), ai.WrapModel(inner, logging), ai.TextRequest{})
fmt.Println(inner.Calls()[0].Instructions[0].Text)
}
Output: Answer briefly.
type Message ¶
type Message struct {
Role Role `json:"role"`
Content Parts `json:"content"`
Provider ProviderData `json:"provider,omitzero"`
}
func Assistant ¶
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
fmt.Println(ai.Assistant("hello").Role)
}
Output: assistant
func User ¶
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
fmt.Println(ai.User("hi").Role, len(ai.User("hi").Content))
}
Output: user 1
func UserParts ¶
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
msg := ai.UserParts(ai.Text{Text: "what is in this image?"}, &ai.File{MediaType: "image/png", Data: []byte{0x89}})
_, isValue := msg.Content[1].(ai.File)
fmt.Println(len(msg.Content), isValue)
}
Output: 2 true
type Middleware ¶
type Middleware struct {
TransformRequest func(ctx context.Context, c *Call) error
WrapGenerate func(ctx context.Context, c *Call, next func(context.Context, *Call) (*Response, error)) (*Response, error)
WrapStream func(ctx context.Context, c *Call, next func(context.Context, *Call) (*StreamResponse, error)) (*StreamResponse, error)
}
Middleware hooks run in order: TransformRequest on a clone of the call, then the Wrap functions around the model.
func DefaultSettings ¶
func DefaultSettings(req TextRequest) Middleware
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
inner := aitest.NewModel(aitest.Turn(aitest.Text("ok")))
model := ai.WrapModel(inner, ai.DefaultSettings(ai.TextRequest{Temperature: new(0.2), MaxOutputTokens: 256}))
_, _ = ai.GenerateText(context.Background(), model, ai.TextRequest{})
call := inner.Calls()[0]
fmt.Println(*call.Temperature, call.MaxOutputTokens)
}
Output: 0.2 256
func ExtractReasoning ¶
func ExtractReasoning(tag string) Middleware
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := ai.WrapModel(
aitest.NewModel(aitest.Turn(aitest.Text("<think>2+2 is 4</think>The answer is 4."))),
ai.ExtractReasoning("think"),
)
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{})
for _, p := range res.Content {
switch p := p.(type) {
case ai.Reasoning:
fmt.Println("reasoning:", p.Text)
case ai.Text:
fmt.Println("text:", p.Text)
}
}
}
Output: reasoning: 2+2 is 4 text: The answer is 4.
type NoSuchModelError ¶
func (*NoSuchModelError) Error ¶
func (e *NoSuchModelError) Error() string
type NoSuchToolError ¶
func (*NoSuchToolError) Error ¶
func (e *NoSuchToolError) Error() string
type ObjectStream ¶
type ObjectStream[T any] struct { // contains filtered or unexported fields }
ObjectStream is single use like TextStream. Partials and Elements are best effort; Result validates the final output.
func StreamObject ¶
func StreamObject[T any](ctx context.Context, m LanguageModel, req TextRequest) *ObjectStream[T]
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type person struct {
Name string `json:"name"`
Age int `json:"age"`
}
model := aitest.NewModel(aitest.Turn(aitest.TextChunks(`{"name":"Al`, `ice","age":3`, `0}`)))
s := ai.StreamObject[person](context.Background(), model, ai.TextRequest{})
for p := range s.Partials() {
fmt.Printf("%+v\n", p)
}
fmt.Println(s.Err())
}
Output: {Name:Al Age:0} {Name:Alice Age:3} {Name:Alice Age:30} <nil>
func (*ObjectStream[T]) Err ¶
func (s *ObjectStream[T]) Err() error
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type person struct {
Name string `json:"name"`
}
model := aitest.NewModel(aitest.Turn(aitest.Text(`not json`)))
s := ai.StreamObject[person](context.Background(), model, ai.TextRequest{})
for range s.Partials() {
}
_, isOutput := errors.AsType[*ai.OutputError](s.Err())
fmt.Println(isOutput)
}
Output: true
func (*ObjectStream[T]) Partials ¶
func (s *ObjectStream[T]) Partials() iter.Seq[T]
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type person struct {
Name string `json:"name"`
}
model := aitest.NewModel(aitest.Turn(aitest.TextChunks(`{"name":"Al`, `ice"}`)))
s := ai.StreamObject[person](context.Background(), model, ai.TextRequest{})
for p := range s.Partials() {
fmt.Println(p.Name)
}
}
Output: Al Alice
func (*ObjectStream[T]) Parts ¶
func (s *ObjectStream[T]) Parts() iter.Seq[StreamPart]
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type person struct {
Name string `json:"name"`
}
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"name":"Alice"}`)))
s := ai.StreamObject[person](context.Background(), model, ai.TextRequest{})
for part := range s.Parts() {
if delta, ok := part.(ai.TextDelta); ok {
fmt.Println(delta.Text)
}
}
}
Output: {"name":"Alice"}
func (*ObjectStream[T]) Result ¶
func (s *ObjectStream[T]) Result() (T, *TextResult, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type person struct {
Name string `json:"name"`
}
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"name":"Alice"}`)))
s := ai.StreamObject[person](context.Background(), model, ai.TextRequest{})
v, res, err := s.Result()
fmt.Println(v.Name, res.Text, err)
}
Output: Alice {"name":"Alice"} <nil>
type Output ¶
type Output interface {
// contains filtered or unexported methods
}
func ChoiceOutput ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"result":"yes"}`)))
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Output: ai.ChoiceOutput("yes", "no")})
answer, err := ai.DecodeChoice[string](res)
fmt.Println(answer, err)
}
Output: yes <nil>
func JSONOutput ¶
func JSONOutput() Output
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.Text(`[1,2,3]`)))
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Output: ai.JSONOutput()})
fmt.Println(res.Text, model.Calls()[0].Output.Name)
}
Output: [1,2,3] response
func ObjectOutput ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type verdict struct {
OK bool `json:"ok"`
}
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"ok":true}`)))
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Output: ai.ObjectOutput[verdict]()})
v, err := ai.DecodeObject[verdict](res)
fmt.Println(v.OK, err)
}
Output: true <nil>
type OutputError ¶
OutputError.Text is the model output that failed to decode or validate.
func (*OutputError) Error ¶
func (e *OutputError) Error() string
func (*OutputError) Unwrap ¶
func (e *OutputError) Unwrap() error
type OutputSpec ¶
type OutputSpec struct {
Name string
Description string
Schema json.RawMessage
}
OutputSpec asks the model for JSON that matches Schema. The model answers with that JSON as Text content; adapters without a native schema mode force a tool call and return its input as Text.
type Parts ¶
type Parts []Part
Parts decodes each element by its "type" field. Part pointers are accepted and normalized to values.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
raw := `[{"type":"text","text":"hi"},{"type":"tool-call","id":"c1","name":"search","input":{"q":"go"}}]`
var parts ai.Parts
if err := json.Unmarshal([]byte(raw), &parts); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%T %T\n", parts[0], parts[1])
}
Output: ai.Text ai.ToolCall
func (*Parts) UnmarshalJSON ¶
type Provider ¶
type Provider interface {
LanguageModel(id string) (LanguageModel, error)
}
type ProviderData ¶
type ProviderData map[string]json.RawMessage
func Providers ¶
func Providers(opts ...ProviderOptions) ProviderData
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
data := ai.Providers(exampleOptions{})
_, ok := ai.ProviderValue[exampleOptions](data, "example")
fmt.Println(ok)
}
type exampleOptions struct {
Tier string `json:"tier"`
}
func (exampleOptions) ProviderName() string { return "example" }
Output: true
func (ProviderData) WithRaw ¶
func (d ProviderData) WithRaw(key string, raw json.RawMessage) ProviderData
WithRaw returns a copy of d with key set to the already encoded JSON raw.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
base := ai.ProviderData{}
derived := base.WithRaw("anthropic", json.RawMessage(`{"container":"c1"}`))
v, _ := ai.ProviderValue[map[string]string](derived, "anthropic")
fmt.Println(len(base), v["container"])
}
Output: 0 c1
func (ProviderData) WithValue ¶
func (d ProviderData) WithValue(key string, v any) (ProviderData, error)
WithValue returns a copy of d with key set to the JSON encoding of v, or the encoding error.
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
derived, err := ai.ProviderData{}.WithValue("anthropic", map[string]string{"container": "c1"})
v, _ := ai.ProviderValue[map[string]string](derived, "anthropic")
fmt.Println(err, v["container"])
}
Output: <nil> c1
type ProviderOptions ¶
type ProviderOptions interface {
ProviderName() string
}
ProviderOptions is implemented by a provider package's option structs; ProviderName is the key they are stored under in ProviderData and must equal the provider's name.
type Reasoning ¶
type Reasoning struct {
Text string `json:"text"`
Provider ProviderData `json:"provider,omitzero"`
}
func (Reasoning) MarshalJSON ¶
type ReasoningDelta ¶
type ReasoningEffort ¶
type ReasoningEffort string
const ( ReasoningNone ReasoningEffort = "none" ReasoningMinimal ReasoningEffort = "minimal" ReasoningLow ReasoningEffort = "low" ReasoningMedium ReasoningEffort = "medium" ReasoningHigh ReasoningEffort = "high" ReasoningMax ReasoningEffort = "max" )
type ReasoningEnd ¶
type ReasoningEnd struct {
ID string
Provider ProviderData
}
type ReasoningStart ¶
type ReasoningStart struct {
ID string
}
type Registry ¶
Registry resolves "provider:model" specs. An alias maps a short name to such a spec.
func (Registry) EmbeddingModel ¶
func (r Registry) EmbeddingModel(spec string) (EmbeddingModel, error)
Example ¶
package main
import (
"errors"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
type exampleProvider struct{ model ai.LanguageModel }
func (p exampleProvider) LanguageModel(string) (ai.LanguageModel, error) { return p.model, nil }
type exampleModelProvider struct {
exampleProvider
embedding ai.EmbeddingModel
rerank ai.RerankModel
}
func (p exampleModelProvider) EmbeddingModel(string) (ai.EmbeddingModel, error) {
return p.embedding, nil
}
func (p exampleModelProvider) RerankModel(string) (ai.RerankModel, error) { return p.rerank, nil }
func exampleRegistry() ai.Registry {
return ai.Registry{
Providers: map[string]ai.Provider{"example": exampleModelProvider{
exampleProvider: exampleProvider{model: aitest.NewModel()},
embedding: aitest.NewEmbeddingModel(),
rerank: aitest.NewRerankModel(),
}},
Aliases: map[string]string{"embedder": "example:embed-1"},
}
}
func main() {
reg := exampleRegistry()
m, err := reg.EmbeddingModel("embedder")
fmt.Println(m.ModelID(), err)
_, err = reg.EmbeddingModel("missing:model")
_, isMissing := errors.AsType[*ai.NoSuchModelError](err)
fmt.Println(isMissing)
}
Output: scripted-embedding <nil> true
func (Registry) LanguageModel ¶
func (r Registry) LanguageModel(spec string) (LanguageModel, error)
Example ¶
package main
import (
"errors"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
type exampleProvider struct{ model ai.LanguageModel }
func (p exampleProvider) LanguageModel(string) (ai.LanguageModel, error) { return p.model, nil }
func main() {
reg := ai.Registry{
Providers: map[string]ai.Provider{"anthropic": exampleProvider{model: aitest.NewModel()}},
Aliases: map[string]string{"smart": "anthropic:claude-opus-5-5"},
}
m, err := reg.LanguageModel("smart")
fmt.Println(m.ModelID(), err)
_, err = reg.LanguageModel("openai:gpt")
_, isMissing := errors.AsType[*ai.NoSuchModelError](err)
fmt.Println(isMissing)
}
Output: scripted <nil> true
func (Registry) RerankModel ¶
func (r Registry) RerankModel(spec string) (RerankModel, error)
Example ¶
package main
import (
"errors"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
type exampleProvider struct{ model ai.LanguageModel }
func (p exampleProvider) LanguageModel(string) (ai.LanguageModel, error) { return p.model, nil }
type exampleModelProvider struct {
exampleProvider
embedding ai.EmbeddingModel
rerank ai.RerankModel
}
func (p exampleModelProvider) EmbeddingModel(string) (ai.EmbeddingModel, error) {
return p.embedding, nil
}
func (p exampleModelProvider) RerankModel(string) (ai.RerankModel, error) { return p.rerank, nil }
func exampleRegistry() ai.Registry {
return ai.Registry{
Providers: map[string]ai.Provider{"example": exampleModelProvider{
exampleProvider: exampleProvider{model: aitest.NewModel()},
embedding: aitest.NewEmbeddingModel(),
rerank: aitest.NewRerankModel(),
}},
Aliases: map[string]string{"embedder": "example:embed-1"},
}
}
func main() {
reg := exampleRegistry()
m, err := reg.RerankModel("example:rerank-1")
fmt.Println(m.ModelID(), err)
_, err = reg.RerankModel("missing:model")
_, isMissing := errors.AsType[*ai.NoSuchModelError](err)
fmt.Println(isMissing)
}
Output: scripted-rerank <nil> true
type RerankCall ¶
type RerankModel ¶
type RerankModel interface {
Provider() string
ModelID() string
Rerank(ctx context.Context, c *RerankCall) (*RerankResponse, error)
}
type RerankRequest ¶
type RerankResponse ¶
type RerankResult ¶
func Rerank ¶
func Rerank(ctx context.Context, m RerankModel, req RerankRequest) (*RerankResult, error)
Rerank returns the ranking sorted by descending score, cut to TopN when TopN is set.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
res, err := ai.Rerank(context.Background(), aitest.NewRerankModel(), ai.RerankRequest{
Query: "go generics",
Documents: []string{"baking bread", "go generics tutorial", "go concurrency"},
TopN: 2,
})
for _, r := range res.Ranking {
fmt.Println(r.Index, r.Score)
}
fmt.Println(err)
}
Output: 1 1 2 0.5 <nil>
type Response ¶
type Response struct {
Content Parts
Usage Usage
FinishReason FinishReason
FinishRaw string
Warnings []Warning
Provider ProviderData
Header http.Header
}
Response.FinishReason may be FinishPause when the provider paused its turn; the core then continues with the response appended.
type RetryError ¶
type RetryError struct {
Errs []error
}
func (*RetryError) Error ¶
func (e *RetryError) Error() string
func (*RetryError) Unwrap ¶
func (e *RetryError) Unwrap() []error
type Segment ¶
type Segment struct {
Text string
Start time.Duration
End time.Duration
Speaker string
Partial bool
}
Segment.Partial marks streaming text that a later segment of the same speech replaces.
type SpeechCall ¶
type SpeechModel ¶
type SpeechModel interface {
Provider() string
ModelID() string
GenerateSpeech(ctx context.Context, c *SpeechCall) (*SpeechResponse, error)
}
type SpeechRequest ¶
type SpeechResponse ¶
type SpeechResult ¶
func GenerateSpeech ¶
func GenerateSpeech(ctx context.Context, m SpeechModel, req SpeechRequest) (*SpeechResult, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
res, err := ai.GenerateSpeech(context.Background(), aitest.NewSpeechModel(), ai.SpeechRequest{Text: "Hello", Voice: "marin", Format: "mp3"})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res.Audio.MediaType, len(res.Audio.Data))
}
Output: audio/mpeg 5
type SpeechStream ¶
type SpeechStream struct {
// contains filtered or unexported fields
}
SpeechStream is lazy and single use: ranging Audio sends the request. Stopping the loop early is not an error. Streams are not retried, because the text iterator cannot be replayed.
func StreamSpeech ¶
func StreamSpeech(ctx context.Context, m SpeechStreamModel, req SpeechStreamRequest) *SpeechStream
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
text := func(yield func(string) bool) {
for _, piece := range []string{"Hello, ", "world."} {
if !yield(piece) {
return
}
}
}
s := ai.StreamSpeech(context.Background(), aitest.NewSpeechModel(), ai.SpeechStreamRequest{Text: text})
total := 0
for chunk := range s.Audio() {
total += len(chunk)
}
if err := s.Err(); err != nil {
fmt.Println(err)
return
}
fmt.Println(total, s.MediaType())
}
Output: 13 audio/mpeg
func (*SpeechStream) Audio ¶
func (s *SpeechStream) Audio() iter.Seq[[]byte]
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
text := func(yield func(string) bool) { yield("one piece") }
s := ai.StreamSpeech(context.Background(), aitest.NewSpeechModel(), ai.SpeechStreamRequest{Text: text})
for range s.Audio() {
}
for range s.Audio() {
}
fmt.Println(s.Err())
}
Output: ai: stream already consumed
func (*SpeechStream) Err ¶
func (s *SpeechStream) Err() error
Err returns the terminal error of a finished stream, or ErrStreamConsumed and ErrStreamActive after a second consumer.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
text := func(yield func(string) bool) { yield("hello") }
s := ai.StreamSpeech(context.Background(), aitest.NewSpeechModel(), ai.SpeechStreamRequest{Text: text})
for range s.Audio() {
}
fmt.Println(s.Err())
}
Output: <nil>
func (*SpeechStream) MediaType ¶
func (s *SpeechStream) MediaType() string
MediaType is known once Audio has started yielding.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
text := func(yield func(string) bool) { yield("hello") }
s := ai.StreamSpeech(context.Background(), aitest.NewSpeechModel(), ai.SpeechStreamRequest{Text: text})
for range s.Audio() {
}
fmt.Println(s.MediaType())
}
Output: audio/mpeg
type SpeechStreamCall ¶
type SpeechStreamModel ¶
type SpeechStreamModel interface {
Provider() string
ModelID() string
StreamSpeech(ctx context.Context, c *SpeechStreamCall) (*SpeechStreamResponse, error)
}
SpeechStreamModel is the capability of speech models that synthesize while text is still arriving.
type SpeechStreamRequest ¶
type SpeechStreamResponse ¶
type SpeechStreamResponse struct {
Audio iter.Seq2[[]byte, error]
MediaType string
Header http.Header
}
SpeechStreamResponse.Audio ends with the first error it yields; MediaType describes every chunk.
type Step ¶
type Step struct {
Number int
Content Parts
ToolCalls []ToolCall
ToolResults []ToolResult
Usage Usage
FinishReason FinishReason
FinishRaw string
Warnings []Warning
Provider ProviderData
Header http.Header
}
type StepEnd ¶
type StepEnd struct {
Usage Usage
FinishReason FinishReason
FinishRaw string
Warnings []Warning
Provider ProviderData
}
StepEnd is the last part of a provider stream. The core re-emits it after the step's tools have run.
type StepInfo ¶
type StepInfo struct {
Provider string
ModelID string
Number int
Request *StepRequest
}
type StepRequest ¶
type StepRequest struct {
Model LanguageModel
Instructions []Text
Messages []Message
Tools []Tool
ToolChoice ToolChoice
MaxOutputTokens int
Temperature *float64
TopP *float64
Reasoning ReasoningEffort
Headers http.Header
Provider ProviderData
}
type StopCondition ¶
func HasToolCall ¶
func HasToolCall(name string) StopCondition
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
stop := ai.HasToolCall("final_answer")
steps := []ai.Step{{ToolCalls: []ai.ToolCall{{Name: "search"}}}, {ToolCalls: []ai.ToolCall{{Name: "final_answer"}}}}
fmt.Println(stop(steps[:1]), stop(steps))
}
Output: false true
func MaxTotalTokens ¶
func MaxTotalTokens(n int) StopCondition
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
stop := ai.MaxTotalTokens(100)
fmt.Println(stop([]ai.Step{{Usage: ai.Usage{Input: 60, Output: 30}}}), stop([]ai.Step{{Usage: ai.Usage{Input: 60, Output: 30}}, {Usage: ai.Usage{Output: 10}}}))
}
Output: false true
type StreamFinish ¶
type StreamFinish struct {
FinishReason FinishReason
}
type StreamPart ¶
type StreamPart interface {
// contains filtered or unexported methods
}
type StreamResponse ¶
StreamResponse.Parts must end with a StepEnd part; an error in the sequence ends it.
type StreamStart ¶
type StreamStart struct{}
type Telemetry ¶
type Telemetry interface {
StartStep(ctx context.Context, info StepInfo) context.Context
FinishStep(ctx context.Context, info StepInfo, step Step, err error)
StartTool(ctx context.Context, call ToolCall) context.Context
FinishTool(ctx context.Context, call ToolCall, result ToolResult, took time.Duration, err error)
}
Telemetry receives metadata by default. The context returned by StartStep and StartTool flows to the model call and the tool. StepInfo.Request and the ToolResult passed to FinishTool are shared with the loop, are read-only, and cost nothing to pass; an implementation decides whether to copy or record them.
type Text ¶
type Text struct {
Text string `json:"text"`
Citations []Citation `json:"citations,omitzero"`
Provider ProviderData `json:"provider,omitzero"`
}
func Texts ¶
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
fmt.Println(len(ai.Texts("rules", "style guide")))
}
Output: 2
func (Text) MarshalJSON ¶
type TextEnd ¶
type TextEnd struct {
ID string
Provider ProviderData
}
type TextRequest ¶
type TextRequest struct {
Instructions []Text
Messages []Message
Tools []Tool
ToolChoice ToolChoice
MaxToolConcurrency int
Output Output
MaxSteps int
StopWhen []StopCondition
PrepareStep func(ctx context.Context, s StepState, step *StepRequest) error
OnStepEnd func(ctx context.Context, s Step) error
MaxOutputTokens int
Temperature *float64
TopP *float64
TopK int
PresencePenalty *float64
FrequencyPenalty *float64
Seed *int
StopSequences []string
Reasoning ReasoningEffort
MaxRetries *int
Timeouts Timeouts
Headers http.Header
Provider ProviderData
Telemetry Telemetry
}
func (TextRequest) Clone ¶
func (r TextRequest) Clone() TextRequest
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
agent := ai.TextRequest{Instructions: ai.Texts("You are a researcher."), Temperature: new(0.2)}
turn := agent.Clone()
turn.Messages = []ai.Message{ai.User("hi")}
fmt.Println(len(agent.Messages), len(turn.Messages))
}
Output: 0 1
func (TextRequest) WithMessages ¶
func (r TextRequest) WithMessages(msgs []Message) TextRequest
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
agent := ai.TextRequest{Instructions: ai.Texts("You are a researcher.")}
turn := agent.WithMessages([]ai.Message{ai.User("q1")})
fmt.Println(len(agent.Messages), len(turn.Messages), turn.Instructions[0].Text)
}
Output: 0 1 You are a researcher.
type TextResult ¶
type TextResult struct {
Text string
Content Parts
Messages []Message
Steps []Step
Usage Usage
FinishReason FinishReason
FinishRaw string
Warnings []Warning
Provider ProviderData
// contains filtered or unexported fields
}
func GenerateChoice ¶
func GenerateChoice[T ~string](ctx context.Context, m LanguageModel, req TextRequest, choices ...T) (T, *TextResult, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type sentiment string
const (
positive sentiment = "positive"
negative sentiment = "negative"
)
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"result":"negative"}`)))
label, _, err := ai.GenerateChoice(context.Background(), model, ai.TextRequest{
Messages: []ai.Message{ai.User("The delivery was late.")},
}, positive, negative)
fmt.Println(label, err)
}
Output: negative <nil>
func GenerateJSON ¶
func GenerateJSON(ctx context.Context, m LanguageModel, req TextRequest) (json.RawMessage, *TextResult, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"any":["json"]}`)))
raw, _, err := ai.GenerateJSON(context.Background(), model, ai.TextRequest{})
fmt.Println(string(raw), err)
}
Output: {"any":["json"]} <nil>
func GenerateObject ¶
func GenerateObject[T any](ctx context.Context, m LanguageModel, req TextRequest) (T, *TextResult, error)
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type person struct {
Name string `json:"name"`
Age int `json:"age"`
}
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"name":"Alice","age":30}`)))
p, _, err := ai.GenerateObject[person](context.Background(), model, ai.TextRequest{
Messages: []ai.Message{ai.User("Extract: Alice is 30.")},
})
fmt.Println(p.Name, p.Age, err)
}
Output: Alice 30 <nil>
Example (Invalid) ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type person struct {
Name string `json:"name"`
}
model := aitest.NewModel(aitest.Turn(aitest.Text(`{"name":42}`)))
_, _, err := ai.GenerateObject[person](context.Background(), model, ai.TextRequest{})
outErr, ok := errors.AsType[*ai.OutputError](err)
fmt.Println(ok, outErr.Text)
}
Output: true {"name":42}
func GenerateText ¶
func GenerateText(ctx context.Context, m LanguageModel, req TextRequest) (*TextResult, error)
GenerateText returns the completed steps together with any error, so callers can append res.Messages and continue.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.Text("Your order ships tomorrow.")))
res, err := ai.GenerateText(context.Background(), model, ai.TextRequest{
Instructions: ai.Texts("You are a support agent."),
Messages: []ai.Message{ai.User("Where is my order?")},
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res.Text)
fmt.Println(res.FinishReason)
}
Output: Your order ships tomorrow. stop
Example (StepLimit) ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
search := ai.NewTool("search", "Search", func(context.Context, struct{}) (string, error) { return "hit", nil })
model := aitest.NewModel(
aitest.Turn(aitest.ToolCall("search", `{}`)),
aitest.Turn(aitest.ToolCall("search", `{}`)),
aitest.Turn(aitest.ToolCall("search", `{}`)),
)
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Tools: []ai.Tool{search}, MaxSteps: 2})
fmt.Println(len(res.Steps), res.FinishReason)
}
Output: 2 step-limit
Example (Tools) ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type orderIn struct {
ID string `json:"id" jsonschema:"order id"`
}
lookup := ai.NewTool("lookup_order", "Look up an order", func(_ context.Context, in orderIn) (string, error) {
return "order " + in.ID + " ships tomorrow", nil
})
model := aitest.NewModel(
aitest.Turn(aitest.ToolCall("lookup_order", `{"id":"42"}`)),
aitest.Turn(aitest.Text("It ships tomorrow.")),
)
res, err := ai.GenerateText(context.Background(), model, ai.TextRequest{
Messages: []ai.Message{ai.User("Where is order 42?")},
Tools: []ai.Tool{lookup},
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(res.Steps), "steps:", res.Text)
}
Output: 2 steps: It ships tomorrow.
type TextStream ¶
type TextStream struct {
// contains filtered or unexported fields
}
TextStream is lazy and single use: the first call to Parts, Text or Result starts it. It is not safe for concurrent use.
func StreamText ¶
func StreamText(ctx context.Context, m LanguageModel, req TextRequest) *TextStream
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.TextChunks("Hel", "lo, ", "world")))
s := ai.StreamText(context.Background(), model, ai.TextRequest{Messages: []ai.Message{ai.User("hi")}})
for text := range s.Text() {
fmt.Print(text)
}
fmt.Println()
if err := s.Err(); err != nil {
fmt.Println(err)
}
}
Output: Hello, world
func (*TextStream) Err ¶
func (s *TextStream) Err() error
Err returns the terminal error of a finished stream, or ErrStreamConsumed and ErrStreamActive after a second consumer.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
s := ai.StreamText(context.Background(), aitest.NewModel(aitest.Turn(aitest.Text("x"))), ai.TextRequest{})
for range s.Parts() {
}
for range s.Parts() {
}
fmt.Println(errors.Is(s.Err(), ai.ErrStreamConsumed))
}
Output: true
func (*TextStream) Parts ¶
func (s *TextStream) Parts() iter.Seq[StreamPart]
Parts stops the stream when the loop breaks; Result then returns context.Canceled with the completed steps.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.Text("done")))
s := ai.StreamText(context.Background(), model, ai.TextRequest{})
for p := range s.Parts() {
switch p := p.(type) {
case ai.TextDelta:
fmt.Println("text:", p.Text)
case ai.StreamFinish:
fmt.Println("finish:", p.FinishReason)
}
}
}
Output: text: done finish: stop
func (*TextStream) Result ¶
func (s *TextStream) Result() (*TextResult, error)
Result drains the stream if nobody has consumed it and returns the completed steps together with the error.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.Text("all at once"), aitest.Usage(5, 2)))
res, err := ai.StreamText(context.Background(), model, ai.TextRequest{}).Result()
fmt.Println(res.Text, res.Usage.Input, res.Usage.Output, err)
}
Output: all at once 5 2 <nil>
func (*TextStream) Text ¶
func (s *TextStream) Text() iter.Seq[string]
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.TextChunks("a", "b")))
for chunk := range ai.StreamText(context.Background(), model, ai.TextRequest{}).Text() {
fmt.Print(chunk, "|")
}
fmt.Println()
}
Output: a|b|
type Tool ¶
type Tool struct {
Name string
Description string
InputSchema json.RawMessage
Strict bool
// Execute is nil for client-side tools; the loop then ends and returns the call.
Execute func(ctx context.Context, input json.RawMessage) (ToolOutput, error)
Approval func(ctx context.Context, in ApprovalInput) Approval
// Untrusted marks tools whose output may carry injected instructions.
Untrusted bool
Timeout time.Duration
Provider ProviderData
}
func NewClientTool ¶
NewClientTool declares a tool the caller executes; the loop ends when the model calls it.
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
type answerIn struct {
Text string `json:"text"`
}
final := ai.NewClientTool[answerIn]("final_answer", "Submit the answer")
model := aitest.NewModel(aitest.Turn(aitest.ToolCall("final_answer", `{"text":"42"}`)))
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Tools: []ai.Tool{final}})
for _, p := range res.Content {
if call, ok := p.(ai.ToolCall); ok {
fmt.Println(call.Name, string(call.Input))
}
}
}
Output: final_answer {"text":"42"}
func NewTool ¶
NewTool panics if In has no JSON schema.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
type weatherIn struct {
City string `json:"city" jsonschema:"city name"`
}
tool := ai.NewTool("weather", "Current weather", func(_ context.Context, in weatherIn) (string, error) {
return "sunny in " + in.City, nil
})
out, err := tool.Execute(context.Background(), json.RawMessage(`{"city":"Daegu"}`))
fmt.Println(string(out.JSON), err)
}
Output: "sunny in Daegu" <nil>
func (Tool) WithApproval ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
remove := ai.NewTool("remove", "Remove a record", func(context.Context, struct{}) (string, error) { return "removed", nil }).
WithApproval(ai.AlwaysAsk)
model := aitest.NewModel(aitest.Turn(aitest.ToolCall("remove", `{}`)))
res, _ := ai.GenerateText(context.Background(), model, ai.TextRequest{Tools: []ai.Tool{remove}})
fmt.Println(res.FinishReason)
}
Output: approval-pending
func (Tool) WithTimeout ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
tool := ai.NewTool("slow", "d", func(context.Context, struct{}) (int, error) { return 1, nil }).WithTimeout(0)
fmt.Println(tool.Timeout)
}
Output: 0s
type ToolApprovalRequest ¶
type ToolApprovalRequest struct {
ApprovalID string `json:"approvalId"`
CallID string `json:"callId"`
Reason string `json:"reason,omitzero"`
InputHash [32]byte `json:"-"`
}
func (ToolApprovalRequest) MarshalJSON ¶
func (r ToolApprovalRequest) MarshalJSON() ([]byte, error)
type ToolApprovalResponse ¶
type ToolApprovalResponse struct {
ApprovalID string `json:"approvalId"`
CallID string `json:"callId"`
Approved bool `json:"approved"`
Reason string `json:"reason,omitzero"`
}
func (ToolApprovalResponse) MarshalJSON ¶
func (r ToolApprovalResponse) MarshalJSON() ([]byte, error)
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input,omitzero"`
ProviderExecuted bool `json:"providerExecuted,omitzero"`
Provider ProviderData `json:"provider,omitzero"`
}
func (ToolCall) MarshalJSON ¶
type ToolChoice ¶
type ToolChoice struct {
// contains filtered or unexported fields
}
ToolChoice zero value means automatic.
func ToolNamed ¶
func ToolNamed(name string) ToolChoice
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.ToolCall("search", `{}`)))
_, err := ai.GenerateText(context.Background(), model, ai.TextRequest{
Messages: []ai.Message{ai.User("Find it.")},
Tools: []ai.Tool{ai.NewClientTool[struct{}]("search", "Search the web")},
ToolChoice: ai.ToolNamed("search"),
})
choice := model.Calls()[0].ToolChoice
fmt.Println(choice.Mode(), choice.Name(), err)
}
Output: named search <nil>
func ToolNone ¶
func ToolNone() ToolChoice
Example ¶
package main
import (
"context"
"fmt"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewModel(aitest.Turn(aitest.Text("no tools needed")))
_, err := ai.GenerateText(context.Background(), model, ai.TextRequest{
Messages: []ai.Message{ai.User("Just answer.")},
Tools: []ai.Tool{ai.NewClientTool[struct{}]("search", "Search the web")},
ToolChoice: ai.ToolNone(),
})
fmt.Println(model.Calls()[0].ToolChoice.Mode(), err)
}
Output: none <nil>
func ToolRequired ¶
func ToolRequired() ToolChoice
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
fmt.Println(ai.ToolRequired().Mode(), ai.ToolNone().Mode(), ai.ToolNamed("search").Name(), ai.ToolChoice{}.Mode())
}
Output: required none search auto
func (ToolChoice) Mode ¶
func (c ToolChoice) Mode() ToolChoiceMode
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
fmt.Println(ai.ToolChoice{}.Mode(), ai.ToolRequired().Mode())
}
Output: auto required
func (ToolChoice) Name ¶
func (c ToolChoice) Name() string
Example ¶
package main
import (
"fmt"
"github.com/minodevss/ai-go"
)
func main() {
fmt.Println(ai.ToolNamed("search").Name())
}
Output: search
type ToolChoiceMode ¶
type ToolChoiceMode string
const ( ToolChoiceAuto ToolChoiceMode = "auto" ToolChoiceRequired ToolChoiceMode = "required" ToolChoiceNone ToolChoiceMode = "none" ToolChoiceNamed ToolChoiceMode = "named" )
type ToolError ¶
ToolError messages are shown to the model; all other tool errors are replaced by a generic message.
type ToolFailed ¶
ToolFailed carries the real tool error for server-side observers; the model and the client only see the generic message.
type ToolInputDelta ¶
type ToolInputEnd ¶
type ToolInputEnd struct {
ID string
}
type ToolInputStart ¶
type ToolOutput ¶
type ToolOutput struct {
Text string `json:"text,omitzero"`
JSON json.RawMessage `json:"json,omitzero"`
Parts Parts `json:"parts,omitzero"`
}
ToolOutput carries exactly one of Text, JSON or Parts.
type ToolResult ¶
type ToolResult struct {
CallID string `json:"callId"`
Name string `json:"name"`
Output ToolOutput `json:"output"`
IsError bool `json:"isError,omitzero"`
ProviderExecuted bool `json:"providerExecuted,omitzero"`
Provider ProviderData `json:"provider,omitzero"`
}
func (ToolResult) MarshalJSON ¶
func (r ToolResult) MarshalJSON() ([]byte, error)
type TranscribeCall ¶
type TranscribeRequest ¶
type TranscribeRequest struct {
Audio io.Reader
MediaType string
Language string
MaxRetries *int
Headers http.Header
Provider ProviderData
Telemetry Telemetry
}
TranscribeRequest.Audio is read once per attempt; a failed attempt is retried only when Audio is an io.Seeker.
type TranscribeResponse ¶
type TranscribeResult ¶
func Transcribe ¶
func Transcribe(ctx context.Context, m TranscriptionModel, req TranscribeRequest) (*TranscribeResult, error)
Example ¶
package main
import (
"context"
"fmt"
"strings"
"time"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewTranscriptionModel(aitest.Segments(ai.Segment{Text: "Hello", End: time.Second}, ai.Segment{Text: "world", Start: time.Second, End: 2 * time.Second}))
res, err := ai.Transcribe(context.Background(), model, ai.TranscribeRequest{Audio: strings.NewReader("audio"), MediaType: "audio/wav"})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res.Text, len(res.Segments))
}
Output: Hello world 2
type TranscribeStream ¶
type TranscribeStream struct {
// contains filtered or unexported fields
}
TranscribeStream is lazy and single use: ranging Segments sends the request. Partial segments are replaced by later ones.
func StreamTranscribe ¶
func StreamTranscribe(ctx context.Context, m TranscriptionStreamModel, req TranscribeStreamRequest) *TranscribeStream
Example ¶
package main
import (
"context"
"fmt"
"strings"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewTranscriptionModel(aitest.Segments(ai.Segment{Text: "Hel", Partial: true}, ai.Segment{Text: "Hello"}))
s := ai.StreamTranscribe(context.Background(), model, ai.TranscribeStreamRequest{Audio: strings.NewReader("audio")})
for seg := range s.Segments() {
fmt.Println(seg.Text, seg.Partial)
}
if err := s.Err(); err != nil {
fmt.Println(err)
}
}
Output: Hel true Hello false
func (*TranscribeStream) Err ¶
func (s *TranscribeStream) Err() error
Example ¶
package main
import (
"context"
"fmt"
"strings"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewTranscriptionModel(aitest.Segments(ai.Segment{Text: "Hello"}))
s := ai.StreamTranscribe(context.Background(), model, ai.TranscribeStreamRequest{Audio: strings.NewReader("audio")})
for range s.Segments() {
}
fmt.Println(s.Err())
}
Output: <nil>
func (*TranscribeStream) Segments ¶
func (s *TranscribeStream) Segments() iter.Seq[Segment]
Example ¶
package main
import (
"context"
"fmt"
"strings"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
model := aitest.NewTranscriptionModel(aitest.Segments(ai.Segment{Text: "Hello"}))
s := ai.StreamTranscribe(context.Background(), model, ai.TranscribeStreamRequest{Audio: strings.NewReader("audio")})
for seg := range s.Segments() {
fmt.Println(seg.Text)
}
}
Output: Hello
type TranscribeStreamRequest ¶
type TranscriptionModel ¶
type TranscriptionModel interface {
Provider() string
ModelID() string
Transcribe(ctx context.Context, c *TranscribeCall) (*TranscribeResponse, error)
}
type TranscriptionStreamModel ¶
type TranscriptionStreamModel interface {
Provider() string
ModelID() string
StreamTranscribe(ctx context.Context, c *TranscribeCall) (*TranscribeStreamResponse, error)
}
TranscriptionStreamModel is the capability of transcription models that return text while audio is still being read.
type VideoModel ¶
type VideoModel interface {
Provider() string
ModelID() string
StartVideo(ctx context.Context, c *VideoCall) (*VideoJob, error)
PollVideo(ctx context.Context, job *VideoJob) (*VideoPoll, error)
}
VideoModel generates videos as asynchronous jobs: StartVideo submits one and PollVideo reports its progress until it is done.
type VideoPoll ¶
type VideoPoll struct {
Done bool
Progress int
Videos []File
Failure error
Interval time.Duration
Warnings []Warning
Header http.Header
}
VideoPoll reports a job that is still running while Done and Failure are both unset. Interval, when set, overrides the core's poll interval for the next poll.
type VideoRequest ¶
type VideoRequest struct {
Prompt string
Duration time.Duration
AspectRatio string
Seed *int
Files []File
PollInterval time.Duration
MaxRetries *int
Headers http.Header
Provider ProviderData
Telemetry Telemetry
}
VideoRequest.PollInterval is the first wait between polls (0 = 5s); it grows by half each poll up to 30s unless the provider names an interval.
type VideoResult ¶
func GenerateVideo ¶
func GenerateVideo(ctx context.Context, m VideoModel, req VideoRequest) (*VideoResult, error)
GenerateVideo submits the job and polls it until it finishes. ctx bounds the whole wait; when it ends first, the returned *JobError carries the job id.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/minodevss/ai-go"
"github.com/minodevss/ai-go/aitest"
)
func main() {
clip := ai.File{MediaType: "video/mp4", Data: []byte("mp4")}
model := aitest.NewVideoModel(aitest.VideoProgress(30), aitest.VideoDone(clip))
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
res, err := ai.GenerateVideo(ctx, model, ai.VideoRequest{Prompt: "waves on a beach", Duration: 8 * time.Second, PollInterval: time.Millisecond})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res.ID, res.Videos[0].MediaType)
}
Output: video_1 video/mp4
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package aitest provides scripted models for testing code built on ai without a network.
|
Package aitest provides scripted models for testing code built on ai without a network. |
|
record
Package record is an http.RoundTripper that records exchanges to JSON files under testdata and replays them offline.
|
Package record is an http.RoundTripper that records exchanges to JSON files under testdata and replays them offline. |
|
Package anthropic adapts the Anthropic Messages API to package ai.
|
Package anthropic adapts the Anthropic Messages API to package ai. |
|
Package assemblyai adapts the AssemblyAI transcription and Universal-Streaming APIs to package ai.
|
Package assemblyai adapts the AssemblyAI transcription and Universal-Streaming APIs to package ai. |
|
Package bedrock adapts the Amazon Bedrock Converse and InvokeModel APIs to package ai.
|
Package bedrock adapts the Amazon Bedrock Converse and InvokeModel APIs to package ai. |
|
Package bfl adapts the Black Forest Labs FLUX API to the image model kind of package ai.
|
Package bfl adapts the Black Forest Labs FLUX API to the image model kind of package ai. |
|
Package cohere adapts the Cohere Chat, Embed and Rerank v2 APIs to package ai.
|
Package cohere adapts the Cohere Chat, Embed and Rerank v2 APIs to package ai. |
|
Package deepgram adapts the Deepgram speech-to-text and Aura text-to-speech APIs to package ai.
|
Package deepgram adapts the Deepgram speech-to-text and Aura text-to-speech APIs to package ai. |
|
Package elevenlabs adapts the ElevenLabs text-to-speech and Scribe speech-to-text APIs to package ai.
|
Package elevenlabs adapts the ElevenLabs text-to-speech and Scribe speech-to-text APIs to package ai. |
|
Package fal adapts the fal.ai queue and synchronous inference APIs to package ai.
|
Package fal adapts the fal.ai queue and synchronous inference APIs to package ai. |
|
Package google adapts the Gemini API (AI Studio) and Vertex AI generateContent and embedding endpoints to package ai.
|
Package google adapts the Gemini API (AI Studio) and Vertex AI generateContent and embedding endpoints to package ai. |
|
internal
|
|
|
chatcompletions
Package chatcompletions implements the Chat Completions wire format for OpenAI and compatible providers.
|
Package chatcompletions implements the Chat Completions wire format for OpenAI and compatible providers. |
|
claudewire
Package claudewire holds the turn and tool-call bookkeeping that the Anthropic Messages and Bedrock Converse wire formats share.
|
Package claudewire holds the turn and tool-call bookkeeping that the Anthropic Messages and Bedrock Converse wire formats share. |
|
embeddings
Package embeddings implements the OpenAI-style /embeddings endpoint for OpenAI and compatible providers.
|
Package embeddings implements the OpenAI-style /embeddings endpoint for OpenAI and compatible providers. |
|
emit
Package emit wraps a provider-boundary yield function so that it is never called again after it reports false.
|
Package emit wraps a provider-boundary yield function so that it is never called again after it reports false. |
|
eventstream
Package eventstream reads and writes the application/vnd.amazon.eventstream binary framing used by AWS streaming APIs.
|
Package eventstream reads and writes the application/vnd.amazon.eventstream binary framing used by AWS streaming APIs. |
|
form
Package form builds multipart/form-data request bodies for provider adapters.
|
Package form builds multipart/form-data request bodies for provider adapters. |
|
mediaio
Package mediaio downloads generated media and encodes input media for the hosted generation providers.
|
Package mediaio downloads generated media and encodes input media for the hosted generation providers. |
|
openaiwire
Package openaiwire holds the JSON helpers shared by the OpenAI-style Responses, Chat Completions and Embeddings adapters.
|
Package openaiwire holds the JSON helpers shared by the OpenAI-style Responses, Chat Completions and Embeddings adapters. |
|
pdata
Package pdata encodes and decodes the per-provider entries of ai.ProviderData.
|
Package pdata encodes and decodes the per-provider entries of ai.ProviderData. |
|
schemafit
Package schemafit rewrites JSON Schemas for providers that accept only a subset and reports every change as a warning.
|
Package schemafit rewrites JSON Schemas for providers that accept only a subset and reports every change as a warning. |
|
sigv4
Package sigv4 signs HTTP requests with AWS Signature Version 4 using only the standard library.
|
Package sigv4 signs HTTP requests with AWS Signature Version 4 using only the standard library. |
|
sse
Package sse reads Server-Sent Events streams as defined by the WHATWG HTML standard.
|
Package sse reads Server-Sent Events streams as defined by the WHATWG HTML standard. |
|
toolmsg
Package toolmsg holds the tool-call texts and input handling shared by the core loop and realtime sessions.
|
Package toolmsg holds the tool-call texts and input handling shared by the core loop and realtime sessions. |
|
transport
Package transport is the shared HTTP layer of provider adapters: JSON requests, limiter hook and API error mapping.
|
Package transport is the shared HTTP layer of provider adapters: JSON requests, limiter hook and API error mapping. |
|
Package jina adapts the Jina embeddings and rerank APIs to package ai.
|
Package jina adapts the Jina embeddings and rerank APIs to package ai. |
|
Package luma adapts the Luma Dream Machine API to the image and video model kinds of package ai.
|
Package luma adapts the Luma Dream Machine API to the image and video model kinds of package ai. |
|
Package ollama adapts the native Ollama chat and embed APIs to package ai.
|
Package ollama adapts the native Ollama chat and embed APIs to package ai. |
|
Package openai adapts the OpenAI Responses, Chat Completions and Embeddings APIs to package ai.
|
Package openai adapts the OpenAI Responses, Chat Completions and Embeddings APIs to package ai. |
|
Package openaicompat adapts OpenAI-compatible Chat Completions and Embeddings endpoints, with presets for providers that document their own differences.
|
Package openaicompat adapts OpenAI-compatible Chat Completions and Embeddings endpoints, with presets for providers that document their own differences. |
|
Package providertest is the contract suite every language model adapter runs against recorded fixtures.
|
Package providertest is the contract suite every language model adapter runs against recorded fixtures. |
|
Package realtime runs low-latency voice and text sessions with models that stream audio both ways, and executes their tool calls on the server.
|
Package realtime runs low-latency voice and text sessions with models that stream audio both ways, and executes their tool calls on the server. |
|
Package replicate adapts the Replicate predictions API to the image and video model kinds of package ai.
|
Package replicate adapts the Replicate predictions API to the image and video model kinds of package ai. |
|
Package ui serves the Vercel AI SDK UI message stream protocol v1 (useChat) from Go.
|
Package ui serves the Vercel AI SDK UI message stream protocol v1 (useChat) from Go. |
|
Package voyage adapts the Voyage AI embeddings, multimodal embeddings and rerank APIs to package ai.
|
Package voyage adapts the Voyage AI embeddings, multimodal embeddings and rerank APIs to package ai. |