Documentation
¶
Overview ¶
Package ai is the vocabulary an agent speaks with language models and tools: messages, tool descriptions, call options, streams and the helpers to build tools from Go functions.
It depends on nothing outside the standard library and one JSON-schema reflector, so a provider client or a tool set can be written against it alone. The sub-packages build on it:
ai/openai OpenAI Chat Completions client (and compatible gateways) ai/llm provider factory, error classification, retry delays; llm/anthropic, llm/responses clients ai/agent the tool-calling loop, streaming under a watchdog, parallel tool scheduling ai/compaction keeping a conversation inside a context window ai/llm/llmtest a scripted fake model for tests
Index ¶
- func Pipe[T any](capacity int) (*StreamReader[T], *StreamWriter[T])
- type BaseTool
- type CallOptions
- type ChatModel
- type CompletionTokenDetails
- type FunctionCall
- type Image
- type ImageDetail
- type InvokableTool
- type Message
- type Model
- type Option
- type Part
- type PartType
- type PromptTokenDetails
- type ResponseMeta
- type Role
- type StreamReader
- type StreamWriter
- type TokenUsage
- type ToolCall
- type ToolChoice
- type ToolInfo
- type ToolMessageOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Pipe ¶
func Pipe[T any](capacity int) (*StreamReader[T], *StreamWriter[T])
Pipe returns the two ends of a stream that buffers up to capacity chunks.
Example ¶
Pipe connects a producer to a consumer. The consumer reads until io.EOF; closing the reader tells the producer to stop.
package main
import (
"fmt"
"io"
"github.com/7ar-chat/harness/ai"
)
func main() {
sr, sw := ai.Pipe[string](2)
go func() {
defer sw.Close()
sw.Send("hello", nil)
sw.Send("world", nil)
}()
defer sr.Close()
for {
chunk, err := sr.Recv()
if err == io.EOF {
break
}
fmt.Println(chunk)
}
}
Output: hello world
Types ¶
type CallOptions ¶
type CallOptions struct {
Temperature *float32
TopP *float32
MaxTokens *int
// ToolChoice constrains tool use; AllowedToolNames narrows a forced choice to those tools.
ToolChoice *ToolChoice
AllowedToolNames []string
// ReasoningEffort is the reasoning effort requested of a reasoning model ("": its default).
ReasoningEffort string
// PromptCacheKey groups calls that share a prompt cache.
PromptCacheKey string
}
CallOptions are the settings of one model call.
type ChatModel ¶
type ChatModel interface {
Generate(ctx context.Context, msgs []*Message, opts ...Option) (*Message, error)
Stream(ctx context.Context, msgs []*Message, opts ...Option) (*StreamReader[*Message], error)
}
ChatModel answers a conversation, whole or as a stream of chunks that ConcatMessages merges.
type CompletionTokenDetails ¶
type CompletionTokenDetails struct {
ReasoningTokens int `json:"reasoning_tokens,omitempty"`
}
CompletionTokenDetails breaks the completion tokens down.
type FunctionCall ¶
type FunctionCall struct {
Name string `json:"name,omitempty"`
Arguments string `json:"arguments,omitempty"`
}
FunctionCall is the function a ToolCall invokes; Arguments is a JSON object (possibly a fragment while a stream is in flight).
type Image ¶
type Image struct {
URL string `json:"url,omitempty"`
Base64Data string `json:"base64data,omitempty"`
MIMEType string `json:"mime_type,omitempty"`
Detail ImageDetail `json:"detail,omitempty"`
}
Image is an image given to the model: a URL or base64 data with its media type.
type ImageDetail ¶
type ImageDetail string
ImageDetail is the fidelity an image is read at ("" is auto).
type InvokableTool ¶
type InvokableTool interface {
BaseTool
InvokableRun(ctx context.Context, arguments string) (string, error)
}
InvokableTool is a BaseTool the agent can run: arguments in as a JSON object, a text result out.
func InferTool ¶
func InferTool[T, D any](name, desc string, fn func(ctx context.Context, input T) (D, error)) (InvokableTool, error)
InferTool builds a tool whose parameters schema is reflected from T (json and jsonschema struct tags) and whose result is D rendered as JSON (a string is returned as is).
Example ¶
A tool is a Go function: InferTool derives the arguments schema the model sees from the input struct, decodes the model's JSON arguments into it and renders the result as the text the model reads.
package main
import (
"context"
"fmt"
"github.com/7ar-chat/harness/ai"
)
type weatherArgs struct {
City string `json:"city" jsonschema_description:"the city to look up"`
}
func main() {
weather, _ := ai.InferTool("weather", "Current weather of a city.",
func(_ context.Context, in weatherArgs) (map[string]any, error) {
return map[string]any{"city": in.City, "temp_c": 18}, nil
})
info, _ := weather.Info(context.Background())
out, _ := weather.InvokableRun(context.Background(), `{"city":"Lyon"}`)
fmt.Println(info.Name, "-", info.Desc)
fmt.Println(info.Parameters["required"])
fmt.Println(out)
}
Output: weather - Current weather of a city. [city] {"city":"Lyon","temp_c":18}
type Message ¶
type Message struct {
Role Role `json:"role"`
// Content is the text of the message.
Content string `json:"content"`
// Parts, when not empty, replace Content for a user message with images.
Parts []Part `json:"parts,omitempty"`
Name string `json:"name,omitempty"`
// ToolCalls are the calls an assistant message asks for.
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
// ToolCallID and ToolName say which call a tool message answers.
ToolCallID string `json:"tool_call_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
// ResponseMeta is set on answers.
ResponseMeta *ResponseMeta `json:"response_meta,omitempty"`
// ReasoningContent is the thinking the model returned.
ReasoningContent string `json:"reasoning_content,omitempty"`
// Extra carries provider-specific and harness-specific values with the message.
Extra map[string]any `json:"extra,omitempty"`
}
Message is one turn of a conversation, or a chunk of one while it streams.
func AssistantMessage ¶
AssistantMessage is an assistant message with its tool calls.
func ConcatMessages ¶
ConcatMessages merges the chunks of one streamed answer into a message: text and reasoning are appended, tool-call fragments with the same Index are joined (arguments concatenated), token usage keeps the largest figure of each counter and the last finish reason wins. Chunks must agree on role, name and tool-call id; Extra values merge key by key (strings append, a single value is kept).
Example ¶
A streamed answer arrives as chunks; ConcatMessages merges them into the message a non-streamed call returns. Tool call fragments that share an Index are joined, their arguments concatenated.
package main
import (
"fmt"
"github.com/7ar-chat/harness/ai"
)
func main() {
zero := 0
msg, _ := ai.ConcatMessages([]*ai.Message{
{Role: ai.RoleAssistant, Content: "Let me "},
{Content: "look."},
{ToolCalls: []ai.ToolCall{{Index: &zero, ID: "call_1", Type: "function", Function: ai.FunctionCall{Name: "weather", Arguments: `{"city":`}}}},
{ToolCalls: []ai.ToolCall{{Index: &zero, Function: ai.FunctionCall{Arguments: `"Lyon"}`}}}},
})
fmt.Println(msg.Content)
fmt.Println(msg.ToolCalls[0].Function.Name, msg.ToolCalls[0].Function.Arguments)
}
Output: Let me look. weather {"city":"Lyon"}
func ToolMessage ¶
func ToolMessage(content, toolCallID string, opts ...ToolMessageOption) *Message
ToolMessage is the result of the tool call toolCallID.
type Model ¶
Model is a ChatModel that can be offered tools. WithTools returns a copy; the receiver is unchanged.
type Option ¶
type Option func(*CallOptions)
Option changes the CallOptions of one call.
func WithPromptCacheKey ¶
WithPromptCacheKey makes calls with the same key share a prompt cache.
func WithReasoningEffort ¶
WithReasoningEffort sets the reasoning effort of a reasoning model.
func WithTemperature ¶
WithTemperature sets the sampling temperature.
func WithToolChoice ¶
func WithToolChoice(choice ToolChoice, allowedToolNames ...string) Option
WithToolChoice sets how the model may use its tools.
type Part ¶
type Part struct {
Type PartType `json:"type"`
Text string `json:"text,omitempty"`
Image *Image `json:"image,omitempty"`
Extra map[string]any `json:"extra,omitempty"`
}
Part is one element of a multimodal user message.
type PromptTokenDetails ¶
type PromptTokenDetails struct {
// CachedTokens were read from the provider's prompt cache.
CachedTokens int `json:"cached_tokens"`
// CacheWriteTokens were written to it.
CacheWriteTokens int `json:"cache_write_tokens"`
}
PromptTokenDetails breaks the prompt tokens down.
type ResponseMeta ¶
type ResponseMeta struct {
FinishReason string `json:"finish_reason,omitempty"`
Usage *TokenUsage `json:"usage,omitempty"`
}
ResponseMeta is what the provider reported about an answer.
type StreamReader ¶
type StreamReader[T any] struct { // contains filtered or unexported fields }
StreamReader is the consuming end of a stream: Recv until io.EOF or an error, then Close. One goroutine reads.
func (*StreamReader[T]) Close ¶
func (r *StreamReader[T]) Close()
Close releases the stream; the writer's Send then reports it closed. Safe to call more than once.
func (*StreamReader[T]) Recv ¶
func (r *StreamReader[T]) Recv() (T, error)
Recv returns the next chunk, io.EOF once the writer closed the stream, or the error it sent.
type StreamWriter ¶
type StreamWriter[T any] struct { // contains filtered or unexported fields }
StreamWriter is the producing end: Send the chunks, then Close.
func (*StreamWriter[T]) Close ¶
func (w *StreamWriter[T]) Close()
Close tells the reader no more chunks come: its Recv then returns io.EOF.
func (*StreamWriter[T]) Send ¶
func (w *StreamWriter[T]) Send(chunk T, err error) (closed bool)
Send delivers a chunk, or an error that ends the stream for the reader. It reports whether the reader has closed the stream (stop producing).
type TokenUsage ¶
type TokenUsage struct {
PromptTokens int `json:"prompt_tokens"`
PromptTokenDetails PromptTokenDetails `json:"prompt_token_details"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
// CompletionTokenDetails breaks the completion tokens down.
CompletionTokenDetails CompletionTokenDetails `json:"completion_token_details"`
}
TokenUsage is what a call cost in tokens.
type ToolCall ¶
type ToolCall struct {
// Index orders the fragments of one call in a stream (nil: the chunk is a whole call).
Index *int `json:"index,omitempty"`
ID string `json:"id"`
Type string `json:"type"`
Function FunctionCall `json:"function"`
}
ToolCall is a request of the model to run a tool.
type ToolChoice ¶
type ToolChoice string
ToolChoice says whether the model may, must or must not call tools.
const ( ToolChoiceForbidden ToolChoice = "forbidden" ToolChoiceAllowed ToolChoice = "allowed" ToolChoiceForced ToolChoice = "forced" )
Tool choices.
type ToolInfo ¶
type ToolInfo struct {
Name string `json:"name"`
Desc string `json:"desc"`
// Parameters is the JSON schema of the arguments object (nil: no parameters).
Parameters map[string]any `json:"parameters,omitempty"`
}
ToolInfo describes a tool to the model.
type ToolMessageOption ¶
type ToolMessageOption func(*Message)
ToolMessageOption customises ToolMessage.
func WithToolName ¶
func WithToolName(name string) ToolMessageOption
WithToolName records the name of the tool a result answers.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agent is the tool-calling loop: ask the model, run the tools it calls, feed the results back, until it answers without a tool call or the step budget ends.
|
Package agent is the tool-calling loop: ask the model, run the tools it calls, feed the results back, until it answers without a tool call or the step budget ends. |
|
Package compaction keeps an agent's prompt inside the model's context window.
|
Package compaction keeps an agent's prompt inside the model's context window. |
|
Package llm builds chat models for a provider and classifies their failures.
|
Package llm builds chat models for a provider and classifies their failures. |
|
anthropic
Package anthropic is an ai.Model over the Anthropic Messages API (POST /v1/messages, streamed).
|
Package anthropic is an ai.Model over the Anthropic Messages API (POST /v1/messages, streamed). |
|
llmtest
Package llmtest provides a scripted fake chat model for tests of code that talks to an ai.Model.
|
Package llmtest provides a scripted fake chat model for tests of code that talks to an ai.Model. |
|
responses
Package responses is an ai.Model over the OpenAI Responses API (POST …/responses, streamed), as served by the OpenAI-compatible endpoint Calls are stateless (store:false) and ask for the encrypted reasoning (include reasoning.encrypted_content): the reasoning items of an answer travel on its ai.Message (ExtraReasoningItems) and are sent back, in order, before the answer's own items, so the model keeps its reasoning across tool steps and runs.
|
Package responses is an ai.Model over the OpenAI Responses API (POST …/responses, streamed), as served by the OpenAI-compatible endpoint Calls are stateless (store:false) and ask for the encrypted reasoning (include reasoning.encrypted_content): the reasoning items of an answer travel on its ai.Message (ExtraReasoningItems) and are sent back, in order, before the answer's own items, so the model keeps its reasoning across tool steps and runs. |
|
Package openai is an ai.Model over the OpenAI Chat Completions API (POST {BaseURL}/chat/completions), as served by OpenAI and the many gateways that copy it.
|
Package openai is an ai.Model over the OpenAI Chat Completions API (POST {BaseURL}/chat/completions), as served by OpenAI and the many gateways that copy it. |