toolkit

package
v1.6.5 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 29 Imported by: 1 module, 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.

Documentation

Index

Constants

View Source
const (
	// RespondName is the name of the tool a model calls to reply with JSON
	RespondName = "respond"

	// RespondPrompt is added to the system prompt when the reply has a schema
	RespondPrompt = "Reply in JSON, by calling the " + RespondName + " tool with your final answer as its result, which must match the tool's schema. Don't reply with text instead."

	// RespondNudge is the message sent when the model replies with text, when
	// the reply has a schema
	RespondNudge = "Reply by calling the " + RespondName + " tool with your answer as its result, which must match the tool's schema."
)
View Source
const (
	// EventSchema is the schema of the toolkit's events, which is the
	// registry's
	EventSchema = "llm"

	// ToolTable is the table of the events of tools, whose rows are their
	// canonical names, such as agent:segment
	ToolTable = "tool"
)
View Source
const AgentCall = "Each call is new: it doesn't see this conversation, or earlier calls, so give it what it needs in its input."

AgentCall is what a model which calls an agent is told, so it gives the agent what it needs, as an agent doesn't see the conversation

Variables

This section is empty.

Functions

func Logf added in v0.6.0

func Logf(ctx context.Context, format string, args ...any)

Logf logs what the tool run in the context is doing, as a sentence in plain English, such as "Getting the current weather for Berlin", which is shown to the user, to its session's logger, at the info level

func Progressf added in v0.6.0

func Progressf(ctx context.Context, format string, args ...any)

Progressf says how the tool run in the context is getting on, as a sentence in plain English, such as "Segmenting the transcript", which is shown to the user, in place of what it said before

func Resource added in v1.3.0

func Resource(ctx context.Context, uri string) (llm.Resource, error)

Resource returns the resource with the URI, such as resource:///<hash>, which the tool running in the context is given, with the context's resolve function. Returns ErrNotImplemented when there's none, such as when a tool is called without a session, or the registry's resources, and the resolve function's errors, such as ErrNotFound.

func Resources added in v1.4.0

func Resources(ctx context.Context, uris ...string) ([]llm.Resource, error)

Resources returns the resources with the URIs, which the tool running in the context is given, with the context's resolve function, as they're kept, without reading them, so a tool which reads all of them limits what it reads itself, as ResolveFunc says. Returns errors as Resource does.

func RunTools added in v0.6.0

func RunTools(ctx context.Context, tools []llm.Tool, calls []llm.ToolCall, timeout time.Duration, session func(llm.ToolCall) Session) ([]providerschema.ContentBlock, error)

RunTools runs the tools a model called, which are found in the tools by the name the model called them by, in parallel, each in the session the function returns for its call, unless the function is nil, and returns their results, in the order of the calls, as content blocks of a message of the results. A call of a tool which isn't one of the tools, or which fails, has its error as its result, which the model can correct. Each tool has its own timeout to return, or else the timeout, unless it's zero, after which its context is done, and its result is that it timed out, without waiting for it to return, so a tool which doesn't return when its context is done can't keep the others waiting. Returns the context's error, when it's done, without waiting for the tools to return.

func TruncateResult added in v0.6.0

func TruncateResult(ctx context.Context, result json.RawMessage, limit uint, measure MeasureFn) (json.RawMessage, error)

TruncateResult returns the result of a tool, as JSON, so it's at most the limit of tokens, as the function measures them, so a model is sent no more of a tool's result than fits in its context. A result which fits, or when the limit is zero, is returned as it is. Otherwise, its longest strings, arrays and objects are shortened, as little as fits, with notes of what was left out of each, so the result is valid JSON of the same shape, or, when that doesn't fit, or it isn't JSON, it's the start of the result as text, as a JSON string, with a note of what was left out of it, or, when even that doesn't fit, a note that it was left out. Returns the function's error, when it fails.

func Unexpanded added in v1.6.4

func Unexpanded(name string) bool

Unexpanded returns true when "*", and its namespace's "*", don't include the tool with the canonical name, as only the server runs it, such as "builtin:event"

func WithPromptSession added in v1.5.1

func WithPromptSession(ctx context.Context, session uuid.UUID) context.Context

WithPromptSession returns the context, in which the system prompts of namespaces are for the session with the identifier, such as the conversation a model is asked in, which SessionPrompter namespaces add to

func WithResolver added in v1.3.0

func WithResolver(ctx context.Context, fn ResolveFunc) context.Context

WithResolver returns the context, with the function which returns the resources which the tools run in it are given, by their URIs

func WithSession

func WithSession(ctx context.Context, session Session) context.Context

WithSession returns the context with the session, which the tools run in the context get with SessionFromContext

func WithStore added in v1.3.0

func WithStore(ctx context.Context, fn StoreFunc) context.Context

WithStore returns the context, with the function which keeps the resources which the tools run in it return, so their results have links to them, rather than their content. Without one, a resource's content is in the result, encoded as base64.

Types

type AgentTool added in v1.6.4

type AgentTool interface {
	IsAgent() bool
}

AgentTool is a tool which can say it's an agent, which asks a model to do what it does, rather than doing it itself, such as the registry's agents, whatever namespace it's in

type Base added in v0.5.0

type Base struct{}

Base provides default implementations of the optional llm.Tool methods. Embed Base in a tool to avoid boilerplate, and override the methods the tool needs.

func (Base) OutputSchema added in v0.5.0

func (Base) OutputSchema() *jsonschema.Schema

OutputSchema returns nil, as the tool has no structured output schema

func (Base) Timeout added in v1.4.1

func (Base) Timeout() time.Duration

Timeout returns zero, as the tool has the time a tool has by default

func (Base) Title added in v1.6.0

func (Base) Title() string

Title returns nothing, as the tool has no title

type CredentialsProvider added in v0.5.0

type CredentialsProvider = credentials.Provider

CredentialsProvider expands credentials, such as a tool's API key, whose placeholders, such as ${OPENAI_KEY}, are replaced with the credentials they name. It's the credentials package's Provider, so one provider is shared by the registry, the toolkit and the connectors.

type MeasureFn added in v0.6.0

type MeasureFn func(ctx context.Context, text string) (uint, error)

MeasureFn returns how many tokens the text is, for the model a tool's result is sent to

type Namespace added in v0.6.0

type Namespace interface {
	Name() string

	// Type returns where the namespace's tools are from: schema.NamespaceBuiltin,
	// for the server's own, schema.NamespaceMCP, for an MCP server's, or
	// schema.NamespaceAgent, for the agents'
	Type() string

	Description() string
	SystemPrompt() string
	Tools() []llm.Tool

	// Notify sets the function which the namespace calls, once it's added to
	// a toolkit, when one of its tools is created, updated, or deleted, with
	// the action, and the tool's name, after Tools returns it as it is. A
	// namespace whose tools don't change, once it's added, doesn't call it.
	// It's called without the namespace's lock held, as Tools is called.
	Notify(func(action eventschema.EventAction, name string))
}

Namespace is a namespace of tools: its name, which is an identifier, a line which describes it, such as for a person choosing its tools, which can be empty, its system prompt, which says how to use its tools, and is added to the system prompt of a model which can call any of them, or is empty, and its tools

func NewNamespace added in v0.6.0

func NewNamespace(name, prompt string, tools ...llm.Tool) Namespace

NewNamespace returns a namespace with the name, the system prompt, which can be empty, and the tools

type Opt added in v0.5.0

type Opt func(*opt) error

Opt is a functional option for toolkit configuration.

func WithBroadcaster added in v0.6.0

func WithBroadcaster(b *broadcaster.Broadcaster) Opt

WithBroadcaster sets the broadcaster which the toolkit publishes the changes to its tools to, as they're added, and as a namespace's tools are created, updated or deleted, whose table is ToolTable, and whose rows are the tools' canonical names

func WithClientOpts added in v0.5.0

func WithClientOpts(clientopts ...client.ClientOpt) Opt

WithClientOpts sets the client options for the HTTP clients of tools which call APIs, e.g. for timeouts.

func WithCredentialsProvider added in v0.5.0

func WithCredentialsProvider(provider CredentialsProvider) Opt

WithCredentialsProvider sets the provider of credentials, such as API keys, for tools which need them, which are environment variables, without one, or with a nil provider

func WithTracer

func WithTracer(tracer trace.Tracer) Opt

WithTracer sets the tracer used for tracing operations.

type ResolveFunc added in v1.3.0

type ResolveFunc func(ctx context.Context, uris ...string) ([]llm.Resource, error)

ResolveFunc returns the resources with the URIs, such as resource:///<hash>, which a tool is given, in the session the tool runs in, or on their own, in the same order, as they're kept, without reading them: a resource's content is read from where it's kept as it's read, so it can be streamed, such as to a provider which uploads it, and isn't limited, so a tool which reads all of it, with llm.ReadAll, limits it itself, such as by its length, with llm.ContentLength. What the registry reads in memory, such as a document which is recognized, or images which are changed, it reads within a limit.

type Respond added in v0.5.0

type Respond struct {
	Base
	// contains filtered or unexported fields
}

Respond is the tool a model calls to reply with JSON which conforms to a schema. The tool's input is an object, as the input of a tool must be, whose result is the reply, so the reply can be any JSON. The tool's result is the reply, when it conforms, or an error the model can correct.

func NewRespond added in v0.5.0

func NewRespond(schema json.RawMessage) (*Respond, error)

NewRespond returns the tool a model calls to reply with JSON which conforms to the schema. Returns an error if the schema isn't a JSON schema.

func (*Respond) Description added in v0.5.0

func (t *Respond) Description() string

func (*Respond) InputSchema added in v0.5.0

func (t *Respond) InputSchema() *jsonschema.Schema

func (*Respond) Name added in v0.5.0

func (t *Respond) Name() string

func (*Respond) Run added in v0.5.0

func (t *Respond) Run(_ context.Context, input json.RawMessage) (any, error)

Run returns the reply, which is the input's result, as JSON, when the input conforms to the schema, or an error which says how it doesn't

type Result added in v1.3.0

type Result struct {
	// Value is what the tool returns with the resources, which is encoded as
	// JSON, or nil, for none
	Value any

	// Resources are the resources the tool returns
	Resources []llm.Resource
}

Result is a tool's result with resources, such as images, or audio, which it returns, with a value, or without one, as MCP's tools return content and structured content. A tool can also return a resource, or resources, on their own.

type Session

type Session interface {
	// ID returns the identifier of the session the tool runs in, such as
	// the conversation whose model called it, or the nil UUID when it
	// isn't run in one, so a tool which asks a model, such as an agent, can
	// continue from it
	ID() uuid.UUID

	// Logger returns the logger the tool logs to as it runs, such as to say
	// what it's doing, which what runs it can show, such as by streaming it
	Logger() *slog.Logger

	// Progress says how the tool is getting on, as it runs, as MCP's
	// progress notification does: how far it's got, which increases each
	// time, out of the total, when it's known, or zero, and a message, such
	// as that an agent it runs is replying, which what runs it can show, in
	// place of its progress before, rather than keeping it, as a line it
	// logs is
	Progress(progress, total float64, message string)

	// Usage adds the tokens the tool used, such as when it asks a model, as
	// an agent does, to those of its result, so what runs it counts them
	Usage(llm.Usage)
}

Session is what a tool can use as it runs, from what runs it, such as an agent loop, which a tool gets from its context with SessionFromContext

func NewSession added in v0.6.0

func NewSession(name string, id uuid.UUID, stream llm.GeneratorStreamFn, span trace.Span) Session

NewSession returns the session of the tool with the name, such as the name the model called it by, in the session with the identifier, or the nil UUID, when it isn't run in one. Its logger streams what the tool logs, at the info level or above, to the function, as log lines of the level, when it isn't info, the message, and its attributes, as key=value, which are shown to the user, so needn't say which tool it is, and its progress is streamed to the function too, unless it's nil. What it logs, at every level, and its progress, are added to the span, as events, with the tool's name, unless the span is nil. The function is called from each goroutine the tool, or tools run in parallel, stream from, so must be safe to call at once.

func SessionFromContext

func SessionFromContext(ctx context.Context) Session

SessionFromContext returns the session of the tool run in the context, or, when it isn't run in one, a session whose logger discards what's logged, so it's never nil

type SessionPrompter added in v1.5.1

type SessionPrompter interface {
	// SessionPrompt returns what's added to the namespace's system prompt,
	// for the session with the identifier, or nothing
	SessionPrompt(ctx context.Context, session uuid.UUID) string
}

SessionPrompter is a namespace whose system prompt says more, for a session, such as how to use what's connected to it, which is added to its system prompt, when a model is asked in the session

type StoreFunc added in v1.3.0

type StoreFunc func(context.Context, llm.Resource) (schema.ResourceLink, error)

StoreFunc keeps a resource which a tool returned, such as in the session the tool runs in, and returns a link to it, which the tool's result has, rather than its content

type ToolPrompter added in v1.0.0

type ToolPrompter interface {
	// SystemPromptFor returns the system prompt, when the model can call
	// the tools, by their names in the namespace, or all of them, when
	// they're nil
	SystemPromptFor(tools []string) string
}

ToolPrompter is a namespace whose system prompt depends on which of its tools a model can call, so it says nothing of those it can't

type Toolkit

type Toolkit struct {
	// contains filtered or unexported fields
}

Toolkit is a set of tools, by name, which models can call

func New

func New(ctx context.Context, opts ...Opt) (_ *Toolkit, err error)

New returns a toolkit with the options

func (*Toolkit) Add added in v0.5.0

func (self *Toolkit) Add(ns Namespace) error

Add adds the namespace, and its tools, to the toolkit, by their canonical name, which is the namespace's name and the tool's name separated by a colon, such as "weatherapi:current". The namespace's name must be an identifier. Returns an error, and adds none of the tools, if the namespace is nil, isn't valid or has already been added, or a tool is nil, its name isn't valid, or two tools have the same name.

func (*Toolkit) AvailableTools added in v0.5.0

func (self *Toolkit) AvailableTools(ctx context.Context, names ...string) (_ []llm.Tool, skipped []string, err error)

AvailableTools returns the tools with the names, as with Tools, except a name which isn't a tool, or a namespace which doesn't exist, is skipped, rather than an error, as when the tools of a namespace aren't available. Returns the names which were skipped, and the same errors as Tools otherwise.

func (*Toolkit) CallTool added in v0.5.0

func (self *Toolkit) CallTool(ctx context.Context, name string, input json.RawMessage) (_ json.RawMessage, err error)

CallTool runs the tool with the name, which is its canonical name, such as "weatherapi:current", or its name without a namespace, such as "current", with the input, which may be empty, and returns its result as JSON, or nil when the tool has no result. Returns ErrNotFound if there is no tool with the name, ErrConflict if the name has no namespace, and more than one namespace has a tool with the name, or ErrBadParameter if the input isn't valid JSON, or doesn't match the tool's input schema. The tool is run without holding the toolkit's lock, so tools can be added and removed while it runs.

func (*Toolkit) ClientOpts added in v0.5.0

func (self *Toolkit) ClientOpts() []client.ClientOpt

ClientOpts returns the client options for the HTTP clients of tools which call APIs

func (*Toolkit) Credential added in v0.5.0

func (self *Toolkit) Credential(ctx context.Context, key string) (_ string, err error)

Credential returns the value of the credential with the key, such as a tool's API key, from the toolkit's credential provider. Returns ErrNotFound when the credential doesn't exist, or is empty, as when its environment variable is set to nothing, so it's as if it isn't set.

func (*Toolkit) GetTool added in v0.5.0

func (self *Toolkit) GetTool(ctx context.Context, name string) (_ *schema.Tool, err error)

GetTool returns the tool with the name, which is its canonical name, such as "weatherapi:current", or its name without a namespace, such as "current". Returns ErrNotFound if there is no tool with the name, or ErrConflict if the name has no namespace, and more than one namespace has a tool with the name.

func (*Toolkit) HasNamespace added in v1.6.0

func (self *Toolkit) HasNamespace(name string) bool

HasNamespace returns true when the toolkit has a namespace with the name

func (*Toolkit) ListNamespaces added in v1.0.0

func (self *Toolkit) ListNamespaces(ctx context.Context) (_ *schema.NamespaceList, err error)

ListNamespaces returns the namespaces in the toolkit, in order of name, with their descriptions, and how many tools each has, and their number

func (*Toolkit) ListTools added in v0.5.0

func (self *Toolkit) ListTools(ctx context.Context, req schema.ToolListRequest) (_ *schema.ToolList, err error)

ListTools returns the tools in the toolkit, or the tools in the namespace in the request, in order of canonical name, with their number

func (*Toolkit) Remove added in v1.6.0

func (self *Toolkit) Remove(ns Namespace) error

Remove removes the namespace, and its tools, from the toolkit, which publishes that each of its tools was deleted, when it's the namespace with its name, rather than one which replaced it. Returns ErrNotFound when it isn't.

func (*Toolkit) SystemPrompts added in v0.6.0

func (self *Toolkit) SystemPrompts(ctx context.Context, names ...string) (_ []string, err error)

SystemPrompts returns the system prompts of the namespaces of the tools with the names, as Tools returns them, to add to the system prompt of a model which can call them, in the order of the names, once each, without those which are empty, or the same as one before. Each namespace's system prompt is read once, as it can change, such as one which has the time, with what a SessionPrompter says of the session the context is for, which WithPromptSession sets. A namespace named by its name and "*", such as "memory:*", or by "*", has its system prompt, even when it has no tools. Returns the same errors as Tools.

func (*Toolkit) ToolNames added in v0.5.0

func (self *Toolkit) ToolNames(ctx context.Context, names ...string) (_ []string, err error)

ToolNames returns the names, as with Tools, as canonical names, such as "weatherapi:current" for "current". A namespace and "*", such as "ollama:*", or "*", is returned as it is, so it includes tools added to the namespace, or the toolkit, later. Returns the same errors as Tools.

func (*Toolkit) Tools added in v0.5.0

func (self *Toolkit) Tools(ctx context.Context, names ...string) (_ []llm.Tool, err error)

Tools returns the tools with the names, which are their canonical names, their names without a namespace, a namespace and "*", such as "ollama:*", for all the tools in the namespace, or "*" for all the tools. No names are no tools. Each tool is wrapped with a new name, which is its namespace and name separated by two underscores, such as "weatherapi__current". Returns ErrNotFound if there is no tool with a name, or no namespace for "*", ErrConflict if a name without a namespace is ambiguous, or two tools have the same new name, or ErrBadParameter if a tool is named more than once, including by a "*", or its new name isn't a valid tool name, such as when it's too long.

Directories

Path Synopsis
httpclient
httpclient implements an API client for DeepSeek's web search and fetch https://api-docs.deepseek.com/guides/search/
httpclient implements an API client for DeepSeek's web search and fetch https://api-docs.deepseek.com/guides/search/
httpclient
httpclient implements an API client for the Home Assistant REST API https://developers.home-assistant.io/docs/api/rest/
httpclient implements an API client for the Home Assistant REST API https://developers.home-assistant.io/docs/api/rest/
Package llm has the llm namespace of tools, which ask the registry's models to do what a model which calls them can't, such as speak text, whose results, such as audio, are resources, which are kept, as resources of the session the tools run in
Package llm has the llm namespace of tools, which ask the registry's models to do what a model which calls them can't, such as speak text, whose results, such as audio, are resources, which are kept, as resources of the session the tools run in
httpclient
httpclient implements an API client for NewsAPI https://newsapi.org/docs
httpclient implements an API client for NewsAPI https://newsapi.org/docs
httpclient
httpclient implements an API client for Ollama's web search and web fetch https://docs.ollama.com/capabilities/web-search
httpclient implements an API client for Ollama's web search and web fetch https://docs.ollama.com/capabilities/web-search
httpclient
httpclient implements an API client for WeatherAPI https://www.weatherapi.com/docs/
httpclient implements an API client for WeatherAPI https://www.weatherapi.com/docs/

Jump to

Keyboard shortcuts

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