ai

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ai

A small Go library for building LLM agents: messages and tools, clients for the common providers, a tool-calling loop, and context compaction. The root package is the shared vocabulary; everything else is optional and builds on it.

go get github.com/7ar-chat/harness/ai
  • Few dependencies. The standard library and one JSON-schema reflector. No framework, no code generation.
  • Streaming is the default. Every client streams; Generate is a stream joined into one message.
  • Failures are data. Provider errors carry a status and a code; llm.Classify turns them into "retry", "shrink the request" or "give up".
  • Testable without a network. ai/llm/llmtest scripts a model, its failures and its stalls.

A complete agent

weather, _ := ai.InferTool("weather", "Current weather of a city.",
    func(ctx context.Context, in struct {
        City string `json:"city" jsonschema_description:"the city"`
    }) (string, error) {
        return in.City + ": 18C, clear", nil
    })
info, _ := weather.Info(ctx)

base, _ := openai.New(openai.Config{BaseURL: "https://api.openai.com/v1", APIKey: key, Model: "gpt-4o-mini"})
model, _ := base.WithTools([]*ai.ToolInfo{info})

res, err := agent.Run(ctx, agent.Config{
    Model:  model,
    Tools:  []ai.InvokableTool{weather},
    Caller: &agent.Caller{Retries: 2}, // stream, cut a silent call, retry transient failures
}, []*ai.Message{ai.UserMessage("Weather in Lyon?")})

fmt.Println(res.Reply.Content)

Packages

Package What it is
ai Message, ToolCall, ToolInfo, Model, call options, streams, InferTool, ConcatMessages
ai/openai Chat Completions client for OpenAI and compatible servers (Azure, OpenRouter, vLLM, Ollama, gateways)
ai/llm provider factory, error classification, retry delays
ai/llm/anthropic Anthropic Messages client with prompt-cache breakpoints
ai/llm/responses OpenAI Responses client with encrypted reasoning carried between calls
ai/agent the loop, streaming under a watchdog, retries, parallel tool scheduling
ai/compaction token estimates and keeping a conversation inside a context window
ai/llm/llmtest a scripted fake model for tests

The model contract

type ChatModel interface {
    Generate(ctx context.Context, msgs []*Message, opts ...Option) (*Message, error)
    Stream(ctx context.Context, msgs []*Message, opts ...Option) (*StreamReader[*Message], error)
}

type Model interface {
    ChatModel
    WithTools(tools []*ToolInfo) (Model, error) // returns a copy that offers the tools
}

Anything that implements Model works with ai/agent. A new provider is one type with these three methods.

Tools

A tool is an InvokableTool: it describes itself (Info) and runs on a JSON arguments object (InvokableRun), returning the text the model reads. InferTool builds one from a Go function, deriving the schema from the input struct. Mark a tool read-only (ReadOnly() bool) and the loop can run several of its calls in one step at the same time.

Stability

Version 0.x: the vocabulary (Message, Model, tools) is settled; agent.Policy, agent.Caller's Attempt and the Extra keys some packages use may still change. Pin a version.

License

MIT. See LICENSE.

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

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 BaseTool

type BaseTool interface {
	Info(ctx context.Context) (*ToolInfo, error)
}

BaseTool is a tool the model can be told about.

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.

func Apply

func Apply(opts ...Option) CallOptions

Apply returns the options o configure.

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

func AssistantMessage(content string, toolCalls []ToolCall) *Message

AssistantMessage is an assistant message with its tool calls.

func ConcatMessages

func ConcatMessages(msgs []*Message) (*Message, error)

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 SystemMessage

func SystemMessage(content string) *Message

SystemMessage is a system message.

func ToolMessage

func ToolMessage(content, toolCallID string, opts ...ToolMessageOption) *Message

ToolMessage is the result of the tool call toolCallID.

func UserMessage

func UserMessage(content string) *Message

UserMessage is a user message.

type Model

type Model interface {
	ChatModel
	WithTools(tools []*ToolInfo) (Model, error)
}

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 WithMaxTokens

func WithMaxTokens(n int) Option

WithMaxTokens caps the completion.

func WithPromptCacheKey

func WithPromptCacheKey(key string) Option

WithPromptCacheKey makes calls with the same key share a prompt cache.

func WithReasoningEffort

func WithReasoningEffort(effort string) Option

WithReasoningEffort sets the reasoning effort of a reasoning model.

func WithTemperature

func WithTemperature(t float32) Option

WithTemperature sets the sampling temperature.

func WithToolChoice

func WithToolChoice(choice ToolChoice, allowedToolNames ...string) Option

WithToolChoice sets how the model may use its tools.

func WithTopP

func WithTopP(p float32) Option

WithTopP sets nucleus sampling.

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 PartType

type PartType string

PartType is the kind of a Part.

const (
	PartText  PartType = "text"
	PartImage PartType = "image"
)

Part types.

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 Role

type Role string

Role is who wrote a Message.

const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

Roles.

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.
llm
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL