A small, provider-agnostic Go library for calling language models, running tools, generating images and speech, and transcribing audio.
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Rafael G. Martins e4cf4a99d3
All checks were successful
main / test (push) Successful in 16s
expand json schema generator capabilities
2026-11-22 10:01:06 +01:00
.forgejo/workflows initial codebase 2026-11-22 03:49:41 +01:00
examples implement a decimal type for costs 2026-11-22 09:54:29 +01:00
providers implement a decimal type for costs 2026-11-22 09:54:29 +01:00
agent.go initial codebase 2026-11-22 03:49:41 +01:00
agent_test.go fix error handling 2026-11-22 09:10:44 +01:00
decimal.go implement a decimal type for costs 2026-11-22 09:54:29 +01:00
decimal_test.go implement a decimal type for costs 2026-11-22 09:54:29 +01:00
doc.go initial codebase 2026-11-22 03:49:41 +01:00
go.mod initial codebase 2026-11-22 03:49:41 +01:00
image.go initial codebase 2026-11-22 03:49:41 +01:00
LICENSE Initial commit 2026-10-31 00:47:21 +00:00
message.go initial codebase 2026-11-22 03:49:41 +01:00
message_test.go initial codebase 2026-11-22 03:49:41 +01:00
model.go initial codebase 2026-11-22 03:49:41 +01:00
README.md expand json schema generator capabilities 2026-11-22 10:01:06 +01:00
schema.go expand json schema generator capabilities 2026-11-22 10:01:06 +01:00
schema_test.go expand json schema generator capabilities 2026-11-22 10:01:06 +01:00
speech.go initial codebase 2026-11-22 03:49:41 +01:00
tool.go initial codebase 2026-11-22 03:49:41 +01:00
trace.go initial codebase 2026-11-22 03:49:41 +01:00
trace_test.go initial codebase 2026-11-22 03:49:41 +01:00

agents

A small, provider-agnostic Go library for calling language models, running tools, generating images and speech, and transcribing audio.

agents provides common interfaces for language, image, speech and transcription models, and an agent that executes tool calls in a model loop. It includes providers for OpenRouter and Venice and depends only on the Go standard library. Model calls are non-streaming; each returns a complete response.

go get git.rafaelmartins.com/ai/agents

Requires Go 1.27 or later.

Quick start

type weatherInput struct {
	City string `json:"city" description:"The city to get the weather for"`
}

ctx := context.Background()
model, err := openrouter.New(os.Getenv("OPENROUTER_API_KEY")).
	LanguageModel(ctx, "moonshotai/kimi-k2.6")
if err != nil {
	log.Fatal(err)
}

weather := agents.NewAgentTool("get_weather", "Get the current weather for a city.",
	func(_ context.Context, in weatherInput) (string, error) {
		return fmt.Sprintf("It is 22 degrees Celsius and sunny in %s.", in.City), nil
	},
)

agent := agents.NewAgent(model,
	agents.WithTools(weather),
	agents.WithStopConditions(agents.StepCountIs(5)),
)

result, err := agent.Generate(ctx,
	agents.NewSystemMessage("You are a concise assistant."),
	agents.NewUserMessage("What's the weather like in Lisbon?"),
)
if err != nil {
	log.Fatal(err)
}
fmt.Println(result.Text())

The complete program is in examples/simple.

Concepts

Models

A Provider returns LanguageModel, ImageModel, SpeechModel and TranscriptionModel values by model ID. A language model accepts a Call containing the conversation, sampling settings and tool definitions, and returns a Response holding the assistant message. Calling the model directly makes one request, without tool execution:

resp, err := model.Generate(ctx, agents.Call{
	Messages:        []agents.Message{agents.NewUserMessage("Say hello.")},
	MaxOutputTokens: new(int64(1000)),
})

Attach files with agents.NewUserMessage(text, file). Each file is a File containing its bytes and media type; supported types depend on the provider and model.

Messages

A Message has the shape of a chat completions message: a role, Content items, which are text or files, the ToolCalls of an assistant message, the ToolCallID of a tool message, and the reasoning fields that providers need back on later turns. A tool message holds the result of one tool call. Messages are sent to the providers as they are, so keep all their fields when storing them.

Agents

An Agent calls the model, executes its tool calls, and sends the results back in the next model call. Each step consists of one successful model call and any tools run in response. The run ends when there are no tool calls to execute or a stop condition matches.

Stop conditions are checked after the step's tools finish. StepCountIs(n) limits the number of steps, and a custom StopCondition can check the tool calls and results of the steps. There is no step limit by default. A stop condition or a context deadline bounds a run.

The agent does not remember conversations. Each run takes the messages to send, including the system prompt as a system message, and returns the ones it produced. The application stores and trims the history:

history := []agents.Message{agents.NewSystemMessage("You are a concise assistant.")}
history = append(history, agents.NewUserMessage(text))
result, err := agent.Generate(ctx, history...)
if err != nil {
	log.Fatal(err)
}
history = append(history, result.Messages...)

result.Steps contains the completed steps, and result.Usage sums their token usage. result.Text() returns the text of the last step.

On a model-call error, Generate returns the error and the result accumulated so far.

Tools

NewAgentTool wraps a function whose input is a Go struct. It generates a JSON schema for that type and decodes tool arguments into it with encoding/json. SchemaFor[T]() generates the schema independently:

  • The properties of a struct are its exported fields, named by their json tag. A field is required unless its tag includes omitempty or omitzero.
  • A description tag describes the property, and the string option of the json tag makes a number or a boolean a string.
  • The properties of an embedded struct without a json name belong to the struct that embeds it, unless that struct, or a struct embedded before, has a property of the same name. Those of an embedded pointer to an unexported struct type, which encoding/json cannot set, are left out.
  • A pointer is described as the type it points to. Integers smaller than 64 bits are limited to the range of their type, and unsigned ones to values of at least 0.
  • A byte slice is a base64 string, and an array has a fixed number of items.
  • time.Time is a date-time string, and agents.Decimal and json.Number are numbers. Other types that implement json.Unmarshaler take any value, and types that implement encoding.TextUnmarshaler are strings.
  • A struct nested in itself is an object without properties at the nested occurrence.
  • Fields that encoding/json cannot decode, such as functions, channels and complex numbers, are left out.

Tools that need another schema, or one built at run time, can implement AgentTool directly, as searchTool does in examples/tools.

The tool calls of a step run one after another, in order. A tool error, unknown tool or invalid input becomes a tool message that starts with Error: , rather than an error from Generate. A stop condition can still end the run before the model sees it.

Provider options and metadata

ProviderOptions carries provider-specific request settings, in a map keyed by provider name. Each provider reads only its own options, and one map holds the settings of several providers. Each provider takes a pointer to its options type for the call, and fails the call for any other value under its name. The ProviderMetadata of a response holds the provider's own data on it:

agent := agents.NewAgent(model,
	agents.WithProviderOptions(agents.ProviderOptions{
		openrouter.Name: &openrouter.ProviderOptions{
			Reasoning: &openrouter.ReasoningOptions{Effort: openrouter.ReasoningEffortLow},
		},
		venice.Name: &venice.ProviderOptions{
			Reasoning: &venice.ReasoningOptions{Effort: venice.ReasoningEffortLow},
		},
	}),
)

result, err := agent.Generate(ctx, agents.NewUserMessage("Say hello."))
if err != nil {
	log.Fatal(err)
}
for _, step := range result.Steps {
	if md, ok := step.ProviderMetadata.(*openrouter.ResponseMetadata); ok {
		log.Printf("served by %s, $%s", md.Provider, md.Cost)
	}
}

Images

An ImageModel accepts an ImageCall and returns an ImageResponse. Its images are File values that can be used as reference images in another call, here to an OpenRouter editing model:

imageModel, err := provider.ImageModel(ctx, "krea/krea-2-medium-turbo")
if err != nil {
	log.Fatal(err)
}
editModel, err := provider.ImageModel(ctx, "krea/k3-edit")
if err != nil {
	log.Fatal(err)
}

resp, err := imageModel.Generate(ctx, agents.ImageCall{
	Prompt:      "A red panda reading a book under a tree, watercolor.",
	AspectRatio: "1:1",
})
if err != nil {
	log.Fatal(err)
}

edited, err := editModel.Generate(ctx, agents.ImageCall{
	Prompt: "Make it snow, keeping everything else the same.",
	Images: resp.Images[:1],
})

Speech

A SpeechModel accepts a SpeechCall with the text and returns a SpeechResponse, whose audio is a File. Voices returns the voices of the model, which are the values of SpeechCall.Voice. A TranscriptionModel accepts a TranscriptionCall with the audio, also a File, and returns a TranscriptionResponse with its text:

speechModel, err := provider.SpeechModel(ctx, "elevenlabs/eleven-flash-v2.5")
if err != nil {
	log.Fatal(err)
}
voices, err := speechModel.Voices(ctx)
if err != nil {
	log.Fatal(err)
}

spoken, err := speechModel.Generate(ctx, agents.SpeechCall{
	Text:   "The quick brown fox jumps over the lazy dog.",
	Voice:  voices[0],
	Format: "mp3",
})
if err != nil {
	log.Fatal(err)
}

transcriptionModel, err := provider.TranscriptionModel(ctx, "elevenlabs/scribe-v2")
if err != nil {
	log.Fatal(err)
}
transcript, err := transcriptionModel.Transcribe(ctx, agents.TranscriptionCall{
	Audio:    spoken.Audio,
	Language: "en",
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(transcript.Text)

Tracing

WithTrace attaches callbacks to a context. Providers report each language, image, speech and transcription model call, and agents report each tool call.

Traces are for debugging. They must not be used as infrastructure, such as recording or delivering messages.

ctx = agents.WithTrace(ctx, &agents.Trace{
	ModelCall: func(_ context.Context, info *agents.ModelCallInfo) {
		log.Printf("step %d, took %s, error: %v", info.Step, info.Duration, info.Err)
	},
	ToolCall: func(_ context.Context, info *agents.ToolCallInfo) {
		log.Printf("step %d: %s %s", info.Step, info.Call.Function.Name, info.Call.Function.Arguments)
	},
})

Callbacks run synchronously when an operation ends, before the corresponding call returns. They should be fast, safe for concurrent use and must not modify the supplied data. Direct model calls have step 0; agent steps are numbered from 1.

ModelCallInfo.InputMessages contains the messages supplied to Agent.Generate, without the messages produced during the run. Direct model calls have nil InputMessages.

The infos of model calls have RequestBody, the body of the HTTP request as the provider sent it, and ResponseBody, the body of the HTTP response as the provider received it, whatever its status.

Providers

openrouter venice
Package git.rafaelmartins.com/ai/agents/providers/openrouter git.rafaelmartins.com/ai/agents/providers/venice
Attachments Images, PDF documents, wav and mp3 audio Images, audio, video and documents
Image editing On the models that take reference images On separate editing models
Cache breakpoints anthropic/ and qwen/ models, and their ~ aliases claude- models
Reasoning Effort or token budget Effort
Speech format Raw PCM, unless the call sets one The default of the model, unless the call sets one
Transcription audio wav, mp3, aiff, aac, ogg, flac, m4a, webm and opus, as each model supports wav, mp3, aac, ogg, flac, m4a, webm and opus, as each model supports
Cost In USD, from listed prices for speech In USD and DIEM for chat, in USD from listed prices for images, speech and transcription
Extras Upstream provider routing Web search and scraping, characters

Costs are agents.Decimal values, exact decimal numbers. The costs and prices the APIs report are read from their decimal text, and the costs worked out from listed prices are computed without rounding. Add, Mul and Cmp add, multiply and compare decimals, String formats them, and they encode to and from JSON numbers. ParseDecimal and NewDecimal make them.

Both providers send a last system message as a user message. An API error is returned with its HTTP status and response body.

The costs worked out from listed prices come from the models API, which the provider reads before each call; the call fails when it cannot be read, and the cost is zero for a model it does not list. A Venice image call without a resolution, on a model without a default one, asks for the smallest resolution of the model, so that its price is known.

Speech and transcription have these limits:

  • Neither provider transcribes raw PCM audio, which is what OpenRouter speech returns when the call sets no format.
  • The cost of speech is worked out from the number of characters of the text and the price that the models API lists for them. On OpenRouter it is zero for the models that also list a price for their output, such as bytedance-seed/seed-audio-1-0 and the Gemini models.
  • The cost of a Venice transcription is worked out from the listed price of a second of audio. It is zero for the models that report no audio length, such as nvidia/parakeet-tdt-0.6b-v3.
  • Venice transcription has no provider options, and fails with any value under its name.

Both providers have New(apiKey) constructors. Requests use http.DefaultClient, with no client timeout; a context deadline limits their duration.

Prompt caching depends on the model family and upstream server. CacheOptions controls explicit breakpoints and cache-routing hints; it does not guarantee a cache hit. See the family-specific documentation in OpenRouter's options.go and Venice's options.go.

Custom providers

Implement LanguageModel to use another service with an agent. Return only complete tool calls and set FinishReasonToolCalls when they are present. Report each Generate call with TraceModelCall, including failures, with the bodies of its HTTP request and response.

Image integrations implement ImageModel and report calls with TraceImageCall. Speech and transcription integrations implement SpeechModel and TranscriptionModel, and report calls with TraceSpeechCall and TraceTranscriptionCall. Implement Provider to expose the models through a common factory.

Examples

Run them from the repository root, with OPENROUTER_API_KEY or, for Venice, VENICE_API_KEY set. All but simple take -provider openrouter or -provider venice, and -model.

Example What it does
simple An agent with one tool, reporting tokens and cost
chat A terminal chat that keeps the conversation and reports tokens read from the prompt cache
tools A shopping assistant with its own AgentTool, shared state and a stop condition once the order is placed
image Generates an image, then edits it
describe Asks a model about a file, calling it directly
speech Speaks a text with a voice of the model, then transcribes the audio
OPENROUTER_API_KEY=... go run ./examples/tools "Two mugs of different colors."
VENICE_API_KEY=... go run ./examples/describe -provider venice photo.jpg

Tests

go test ./... needs no network or credentials. Live tests require API keys and make billable requests, including image generation and editing, speech and transcription:

OPENROUTER_API_KEY=... go test -tags live -v ./providers/openrouter
VENICE_API_KEY=... go test -tags live -v ./providers/venice

License

Apache 2.0. See LICENSE.