Documentation
¶
Overview ¶
Package harness runs typed, tool-using agents. An Agent can serve concurrent conversations. Capabilities install their tools and hooks separately for each run.
Index ¶
- Variables
- func AccountModelRequest(ctx context.Context, op func(context.Context) (Usage, error)) error
- func BindState[T any](r *Run, name string, state *T) error
- func Retry(err error) error
- type Agent
- type Call
- type Capability
- type Decision
- type Definition
- type Event
- type Image
- type Limits
- type Message
- type Model
- type ModelFunc
- type NamedModel
- type NativeContext
- type Options
- type Output
- type ReasoningItem
- type Request
- type Response
- type Result
- type Role
- type Run
- func (r *Run) ChildOptions(ctx context.Context, name string, shareUsage, forwardEvents bool) (Options, error)
- func (r *Run) EditAnsweredToolResult(ctx context.Context, id string, edit func(Call, string) (string, error)) error
- func (r *Run) FilterPrompt(f func(string) (string, error)) error
- func (r *Run) InvokeTool(ctx context.Context, t Tool, c Call) (string, error)
- func (r *Run) Register(tools ...Tool) error
- func (r *Run) SelfAgent() Agent[string]
- type Snapshot
- type StreamingModel
- type Tool
- type ToolHandler
- type ToolMiddleware
- type Usage
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrLimit = errors.New("run limit reached") ErrRetries = errors.New("model correction limit reached") )
var ErrDeferred = errors.New("tool call awaits approval")
Functions ¶
func AccountModelRequest ¶
AccountModelRequest records a helper model request made by a history processor. The operation returns the provider's input and output usage. Outside a run it executes directly. Within a run, helper requests share the normal request and token limits, including the enclosing delegation budget.
Types ¶
type Agent ¶
type Agent[T any] struct { Model Model Output Output[T] Instructions string Capabilities []Capability Limits Limits // MaxRetries defaults to one model correction. Set a negative value for none. MaxRetries int }
Example ¶
package main
import (
"context"
"fmt"
h "github.com/natexcvi/go-llm"
)
func main() {
type Answer struct {
City string `json:"city"`
}
model := h.ModelFunc(func(context.Context, h.Request) (h.Response, error) {
return h.Response{Text: `{"city":"Lisbon"}`}, nil
})
agent := h.Agent[Answer]{Model: model, Output: h.JSON[Answer]()}
result, err := agent.Run(context.Background(), "What is the capital of Portugal?", h.Options{})
if err != nil {
panic(err)
}
fmt.Println(result.Output.City)
}
Output: Lisbon
func (Agent[T]) Advance ¶
Advance runs at most one model request or one pending tool call. Persist the returned snapshot before invoking it again. Like Resume, it reinstalls capabilities from saved state and closes run resources before returning.
type Call ¶
type Call struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
}
Arguments retains the model's original text, including malformed JSON that a tool may ask the model to correct.
type Capability ¶
func Combine ¶
func Combine(caps ...Capability) Capability
func ToolBridge ¶
func ToolBridge(wrapped ...Capability) Capability
ToolBridge publishes a fixed search/describe/call interface for the tools in wrapped. Authorization and execution middleware receive the underlying call.
func Tools ¶
func Tools(tools ...Tool) Capability
type Definition ¶
type Definition struct {
Name string `json:"name"`
Description string `json:"description"`
Schema json.RawMessage `json:"parameters_json_schema"`
}
type Image ¶
type Image struct {
URL string `json:"url,omitempty"`
MediaType string `json:"media_type,omitempty"`
Data []byte `json:"data,omitempty"`
}
Image is an image input for a user turn. Supply an HTTP(S) URL or the raw image bytes and their media type. Binary data is base64-encoded in snapshots.
type Limits ¶
type Limits struct {
// Zero uses 50 requests. Other zero limits are disabled.
Requests, ToolCalls, InputTokens, OutputTokens, TotalTokens int
}
type Message ¶
type Message struct {
Reasoning []ReasoningItem `json:"reasoning,omitempty"`
Native *NativeContext `json:"native_context,omitempty"`
// Pinned messages (and their tool exchange) survive local history compaction.
Pinned bool `json:"pinned,omitempty"`
// ContextTokens is the provider's input plus output usage through this
// message, or an adjusted estimate after a history rewrite. Zero is unknown.
ContextTokens int `json:"context_tokens,omitempty"`
// ContextKind identifies framework-generated user-role context in snapshots.
ContextKind string `json:"context_kind,omitempty"`
Images []Image `json:"images,omitempty"`
Model string `json:"model,omitempty"`
Role Role `json:"role"`
Text string `json:"text,omitempty"`
Calls []Call `json:"calls,omitempty"`
CallID string `json:"call_id,omitempty"`
}
type NamedModel ¶
type NamedModel interface{ ModelName() string }
NamedModel identifies the model used for cross-model history and cache telemetry.
type NativeContext ¶
type NativeContext struct {
// Boundary marks server-side compaction of everything before this response.
Boundary bool `json:"boundary,omitempty"`
Transport string `json:"transport"`
Endpoint string `json:"endpoint"`
Content string `json:"content,omitempty"`
ID string `json:"id,omitempty"`
Signature string `json:"signature,omitempty"`
Encrypted string `json:"encrypted,omitempty"`
Tokens int `json:"tokens,omitempty"`
}
NativeContext is a provider-issued compaction item. Replay requires the issuing transport and endpoint. Keep its contents intact across checkpoints.
type Options ¶
type Options struct {
// Images accompany the new user prompt passed to Run. Resume uses the saved history.
Images []Image
Authorize func(context.Context, Call) (Decision, error)
History []Message
Observe func(context.Context, Event) error
// Checkpoint receives a complete turn before the next model request.
Checkpoint func(context.Context, Snapshot) error
// contains filtered or unexported fields
}
type Output ¶
type Output[T any] struct { Schema json.RawMessage Decode func(string) (T, error) }
Output defines how a final response becomes an application value.
type ReasoningItem ¶
type ReasoningItem struct {
BeforeCall int `json:"before_call,omitempty"`
Endpoint string `json:"endpoint"`
ID string `json:"id,omitempty"`
Encrypted string `json:"encrypted_content"`
Summary json.RawMessage `json:"summary,omitempty"`
}
ReasoningItem stores stateless Responses reasoning needed by later tool turns.
type Request ¶
type Request struct {
Messages []Message
Tools []Definition
OutputSchema json.RawMessage
}
type Response ¶
type Response struct {
Native *NativeContext
ContextTokens int
Reasoning []ReasoningItem
Model string
CacheReadTokens, CacheWriteTokens int
Text string
Calls []Call
InputTokens, OutputTokens int
}
type Run ¶
type Run struct {
// FirstRequest is true during preparation of the first top-level model request.
FirstRequest bool
// Authorize is the application policy inherited by delegated agents.
Authorize func(context.Context, Call) (Decision, error)
Step int
Prompt string
Model Model
Instructions []string
Limits Limits
PrepareCall []func(Call) (Call, error)
AfterResponse []func(context.Context, Response) error
// TransformText sanitizes assistant text before history, output decoding and
// observer delivery. Streaming deltas are held until transforms finish.
TransformText []func(context.Context, string) (string, error)
ReviewOutput []func(context.Context, string) (string, error)
CheckDelta []func(context.Context, string) error
// RewriteHistory processes durable conversation history before request-only hooks.
// Return nil for no change. Processors receive an isolated copy.
RewriteHistory []func(context.Context, Request, Usage) ([]Message, error)
BeforeRequest []func(context.Context, *Request, Usage) error
AroundTool []ToolMiddleware
CheckOutput []func(context.Context, string) error
OnClose []func() error
// contains filtered or unexported fields
}
Run is the per-invocation configuration. Hooks run in registration order. Tools execute sequentially in model order so later calls observe prior writes.
func (*Run) ChildOptions ¶
func (r *Run) ChildOptions(ctx context.Context, name string, shareUsage, forwardEvents bool) (Options, error)
ChildOptions inherits authorization and optionally forwards events and usage. Use synchronously inside a delegated tool. A shared account charges each operation as it occurs, including work done before a child suspends.
func (*Run) EditAnsweredToolResult ¶
func (r *Run) EditAnsweredToolResult(ctx context.Context, id string, edit func(Call, string) (string, error)) error
EditAnsweredToolResult replaces one result from the tool batch seen by the latest model response. It is available during tool execution. The change is persisted with the executing tool's checkpoint.
func (*Run) FilterPrompt ¶
FilterPrompt applies a prompt filter during capability installation. A restored checkpoint already contains the filtered prompt. Multiple filters on a fresh run see the previous filter's result.
func (*Run) InvokeTool ¶
InvokeTool calls an explicitly supplied nested tool from inside a tool handler. Invoke synchronously in the handler's goroutine. The application authorizes the nested call, and run middleware, limits and events see it.
type Snapshot ¶
type Snapshot struct {
PromptFiltered bool `json:"prompt_filtered,omitempty"`
// RequestStep identifies the parent request that produced the pending calls.
RequestStep int `json:"request_step,omitempty"`
Offered []string `json:"offered,omitempty"`
Pending []Call `json:"pending,omitempty"`
AwaitingApproval bool `json:"awaiting_approval,omitempty"`
Correction string `json:"correction,omitempty"`
Complete bool `json:"complete,omitempty"`
Prompt string `json:"prompt"`
State map[string]json.RawMessage `json:"state,omitempty"`
History []Message `json:"history"`
Usage Usage `json:"usage"`
Retries int `json:"retries"`
}
type StreamingModel ¶
type StreamingModel interface {
Model
Stream(context.Context, Request, func(string) error) (Response, error)
}
StreamingModel emits incremental text and returns the assembled response. A callback error terminates the stream and must be propagated.
type Tool ¶
type ToolMiddleware ¶
type ToolMiddleware func(ToolHandler) ToolHandler
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package browser drives Chromium through the Chrome DevTools Protocol.
|
Package browser drives Chromium through the Chrome DevTools Protocol. |
|
Package capabilities provides composable run policies and tools.
|
Package capabilities provides composable run policies and tools. |
|
Package codemode runs small tool-using Starlark programs in isolated WebAssembly instances.
|
Package codemode runs small tool-using Starlark programs in isolated WebAssembly instances. |
|
cmd/harness-code
command
Command harness-code is the isolated guest interpreter for package codemode.
|
Command harness-code is the isolated guest interpreter for package codemode. |
|
internal/wire
Package wire defines the request exchanged with the isolated interpreter.
|
Package wire defines the request exchanged with the isolated interpreter. |
|
Package durable defines the serializable activity boundary used by workflow backends.
|
Package durable defines the serializable activity boundary used by workflow backends. |
|
absurd
Package absurd records agent steps within a registered Absurd task handler.
|
Package absurd records agent steps within a registered Absurd task handler. |
|
azure
Package azure integrates the harness with the Microsoft Durable Task Go SDK.
|
Package azure integrates the harness with the Microsoft Durable Task Go SDK. |
|
lambda
Package lambda runs a Go agent inside an AWS Lambda durable function.
|
Package lambda runs a Go agent inside an AWS Lambda durable function. |
|
pgtask
Package pgtask journals agent steps with the pgtask PostgreSQL protocol.
|
Package pgtask journals agent steps with the pgtask PostgreSQL protocol. |
|
mocks
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |
|
Package integrations connects native Go agents to hosted and local MCP servers.
|
Package integrations connects native Go agents to hosted and local MCP servers. |
|
mocks
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |
|
Package models contains model transports for the harness.
|
Package models contains model transports for the harness. |
|
Package storage saves named JSON checkpoints and agent memory documents.
|
Package storage saves named JSON checkpoints and agent memory documents. |
|
mocks
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |
|
Package workspace provides the file and command backends used by capabilities.
|
Package workspace provides the file and command backends used by capabilities. |
|
opensandbox
Package opensandbox adapts an existing OpenSandbox instance to the harness.
|
Package opensandbox adapts an existing OpenSandbox instance to the harness. |
|
sprite
Package sprite adapts a Fly.io Sprite to the harness workspace interfaces.
|
Package sprite adapts a Fly.io Sprite to the harness workspace interfaces. |