runtime

package
v1.3.6 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 101 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

Overview

Package runtime runs the agent: it wraps Google's ADK runner, builds the agent tree with its tools and sub-agents, runs a prompt as a turn within its limits, delivers steering mid-turn, answers side questions without touching history, compacts history, and records usage and traces. It also makes the models (Gemini, Anthropic, OpenAI, Ollama) and falls back between them (spec_016_engine, spec_015_models).

Index

Constants

View Source
const (
	// HearBegin and HearEnd are the person starting and stopping speaking.
	HearBegin = "begin"
	HearEnd   = "end"
	// HearInterim is the words so far of what's being said, which may
	// still change; HearFinal is them settled.
	HearInterim = "interim"
	HearFinal   = "final"
	// HearError is the listener giving up (Err).
	HearError = "error"
)

What a Listener hears.

View Source
const (
	// CitationsKey (CustomMetadata) holds the answer's citations: a list
	// of {"title", "url", "text"} (CA-84).
	CitationsKey = "blitz_citations"
	// ProviderToolRequestsKey (CustomMetadata) counts the provider tool
	// requests the answer made, by purpose ({"web_search": 2}), for
	// pricing (CA-83).
	ProviderToolRequestsKey = "blitz_provider_tool_requests"
)

Keys a model's answer carries for its provider tools.

View Source
const CacheWriteTokensKey = "cache_creation_input_tokens"

CacheWriteTokensKey is the LLMResponse.CustomMetadata key a model uses to report prompt tokens written to the cache (genai usage has no such field).

View Source
const DefaultAnthropicModel = "claude-opus-5"

DefaultAnthropicModel is used when no model is configured for the provider.

View Source
const FallbackFromKey = "blitz_fallback_from"

FallbackFromKey is set in a response's CustomMetadata when a fallback model answered; its value is the name of the model that failed first.

View Source
const FallbackReasonKey = "blitz_fallback_reason"

FallbackReasonKey is set beside FallbackFromKey: the primary's error that made the chain move on (this call's, or the one that opened its breaker), so a broken key or a bad model name isn't hidden behind the fallback.

View Source
const HeldTextKey = "blitz_held_text"

HeldTextKey is the CustomMetadata key of the end of a streamed answer that was held back (see guardOutput) and is sent with its final response: front ends showing the streamed pieces get it as the last piece, before the final text that repeats them.

View Source
const LearnedKey = "blitz_learned"

LearnedKey is the CustomMetadata key of what a call learned about its model, as lines for the person ([]string).

View Source
const MaxSubagentDepth = 3

MaxSubagentDepth bounds nested invoke_agent calls so agents cannot recurse forever.

View Source
const OriginKey = "blitz_origin"

OriginKey is the CustomMetadata key of the origin a model's answer records (CA-02).

View Source
const RulesKey = "project_rules"

RulesKey is the tool-result field that carries path-scoped rules the first time a tool touches a file they apply to.

View Source
const SteerKey = "message_from_user"

SteerKey is the tool-result field that carries messages the user sent while the turn was running.

View Source
const TaskUpdatesKey = "task_updates"

TaskUpdatesKey is the tool-result field that carries notes about background tasks that have ended.

View Source
const UnshownKey = "blitz_unshown"

UnshownKey is the CustomMetadata key of the parts of an answer Blitz doesn't show yet (a provider's server tool blocks, output it has no form for): each {"type", "raw"}, kept with the answer, noted to the person (CA-30).

Variables

View Source
var ErrModelNotAllowed = errors.New("your organization doesn't allow that model")

ErrModelNotAllowed is a model of the person's own provider the organization's policy doesn't allow (EN-35).

View Source
var ErrModelUnavailable = errors.New("the model isn't available")

ErrModelUnavailable is the error of every call to a model that couldn't be built.

View Source
var ErrNoLiveModel = errors.New("no Gemini Live model answers for this Gemini key or Vertex AI project")

ErrNoLiveModel is a provider none of whose live models answers for this key or project (VOX-06a).

View Source
var ErrOrgLimit = errors.New("your organization's limit is reached")

ErrOrgLimit is a request the organization's gateway refused for a budget or quota (spec_053 EN-24).

View Source
var ErrOwnProviderOff = errors.New("your organization is your provider")

ErrOwnProviderOff is a provider of the person's own while they're connected to an organization, which is their provider then (EN-35a): only the local one (Ollama) stays theirs.

View Source
var ErrStalled = errors.New("model API stopped responding")

ErrStalled is returned when a model API stops sending data.

View Source
var (
	// ErrSubagentDepth is returned when invoke_agent nesting exceeds MaxSubagentDepth.
	ErrSubagentDepth = errors.New("maximum sub-agent nesting depth exceeded")
)
View Source
var ErrVoiceModel = errors.New("[voice] model isn't a Gemini Live model")

ErrVoiceModel is a [voice] model that isn't a Gemini Live model.

View Source
var ErrVoiceNotSetUp = errors.New("voice needs Google's Gemini: set up Gemini in Settings › Providers (an API key, or Vertex AI)")

ErrVoiceNotSetUp is voice with no Google provider to use (VOX-03).

Functions

func AntigravityAnswers added in v1.3.6

func AntigravityAnswers(cfg *config.Config) bool

AntigravityAnswers reports whether Google Antigravity is available on this machine.

func Ask

func Ask(ctx context.Context, llm model.LLM, instruction, prompt string) (text, served string, usage *genai.GenerateContentResponseUsageMetadata, err error)

Ask has llm answer prompt under instruction, outside any session (no tools, no history): its text without thoughts, the model that served it, and the tokens it took.

func CarryOutPrompt

func CarryOutPrompt(planFile string) string

CarryOutPrompt asks the agent to carry out the plan the user approved.

func ChatModel added in v0.9.6

func ChatModel(id string) bool

ChatModel reports whether id is a model that holds a conversation; a name Blitz doesn't know is kept, since it may be new.

func ChirpVoice added in v1.3.3

func ChirpVoice(locale, voice string) string

ChirpVoice is the Text-to-Speech name of voice in locale: "en-GB-Chirp3-HD-Aoede".

func CloudNotSetUp added in v1.3.3

func CloudNotSetUp(why string) error

CloudNotSetUp is the cloud voice engine not being set up, for why (VOX-74): errors.Is finds ErrVoiceNotSetUp in it.

func CloudVoiceProblem added in v1.3.3

func CloudVoiceProblem(err error, project string) string

CloudVoiceProblem is err from Google Cloud's speech APIs as the person is told it (VOX-74): what to do about a sign-in that has run out, an API that's off, a model or voice that isn't there; "" for an error that says nothing of the kind.

func CloudVoiceProject added in v1.3.3

func CloudVoiceProject(ctx context.Context, cfg *config.Config, signIn bool) (string, error)

CloudVoiceProject is the Google Cloud project the cloud engine would work in, or why it can't be used (ErrVoiceNotSetUp, VOX-74); with signIn it tries the credentials, which asks Google.

func ConfiguredProviders

func ConfiguredProviders(cfg *config.Config) []string

ConfiguredProviders are the providers cfg has credentials (or, for Ollama, a choice) for. Connected to an organization, its service first, alone unless its policy allows the person's own beside it (spec_053_enterprise EN-20, EN-35).

func NewGeminiUploader added in v0.2.1

func NewGeminiUploader(ctx context.Context, cfg *config.Config) (images.Uploader, error)

NewGeminiUploader sends attachments too large to go inline through Gemini's Files API, signed in as [llm.gemini] (spec_011_images): nil without a Gemini API key or key command (Vertex AI has no Files API).

func NewModel

func NewModel(ctx context.Context, cfg *config.Config, overrideModel string) (model.LLM, error)

NewModel builds an ADK model.LLM based on configuration.

The model (overrideModel, else the configured one) may name its provider, "anthropic/claude-sonnet-5", to use a provider other than llm.provider. Bare fallback names use llm.provider.

func NewModelRef

func NewModelRef(ctx context.Context, cfg *config.Config, ref string) (model.LLM, error)

NewModelRef builds the single model a fallback reference names (no chain), e.g. for `doctor` to check each fallback on its own.

func NewPainter added in v0.9.3

func NewPainter(ctx context.Context, cfg *config.Config) (tools.Painter, error)

NewPainter builds the images model's painter (spec_006_filetools FS-80): a Gemini image model, through the Gemini API or Vertex AI as [llm.gemini] signs in, or one of the organization's image models through its service (MDL-95a). nil without a model; an error for a provider that can't draw or credentials that don't work.

func NewSpeaker added in v0.2.1

func NewSpeaker(ctx context.Context, cfg *config.Config) (tools.Speaker, error)

NewSpeaker builds the [audio] model's speaker (spec_015_models): a Gemini speech model (through the Gemini API or Vertex AI, as [llm.gemini] signs in) or an OpenAI one. nil without a model; an error for a provider that can't speak or credentials that don't work.

func NewUnavailableModel

func NewUnavailableModel(name, why string) model.LLM

NewUnavailableModel is a model named name whose every call fails with ErrModelUnavailable and why (which must hold no secrets: it reaches the user as the turn's error).

func NotSetUp added in v0.9.6

func NotSetUp(cfg *config.Config, listed []ProviderModels) []string

NotSetUp are the providers the person could set up and hasn't, given those listed (spec_061_models MOD-06); under an organization, only those its policy allows.

func OllamaAnswers added in v0.9.6

func OllamaAnswers(ctx context.Context) bool

OllamaAnswers reports whether Ollama answers on this machine (MOD-03; doctor's check, spec_060 DRV-81).

func ParseModelRef

func ParseModelRef(ref, defaultProvider string) (provider, name string)

ParseModelRef splits "provider/model" into its parts. Without a known provider prefix the whole reference is a model of defaultProvider, so OpenRouter-style names ("anthropic/claude-…" on the openai provider) need the provider spelled out: "openai/anthropic/claude-…".

func ParseProviderToolsOff added in v0.9.2

func ParseProviderToolsOff(names []string, prefix string) (all bool, off map[string]bool)

ParseProviderToolsOff reads the provider tools a list of tool names turns off: "-provider:<kind>" (an agent's tools), "provider:<kind>" (the organization's tools.off), "*" for all of them.

func PlanAllows

func PlanAllows(toolName string) bool

PlanAllows reports whether a tool may run in plan mode.

func PlanPrompt

func PlanPrompt(goal string) string

PlanPrompt wraps a goal in the instructions for plan mode.

func ProviderToolPart added in v0.9.2

func ProviderToolPart(p *genai.Part) (name, id string, args map[string]any, call, ok bool)

ProviderToolPart reads a stored part as a provider tool's call (call true) or result, as the client tool it stands for, for showing it as that tool's call and result; ok is false for any other part.

func SessionSearchPrompt

func SessionSearchPrompt(terms string, matches []session.Match, total int) string

SessionSearchPrompt asks the agent what this conversation said about terms, with the transcript passages that mention them (total is how many messages matched, of which matches are the ones sent).

func SetLearnedStore added in v0.9.2

func SetLearnedStore(s *modelfacts.Store)

SetLearnedStore is where learned facts are kept (the engine sets ~/.blitz/models.learned.toml; nil keeps none).

func SettingApplies

func SettingApplies(provider, modelName, key string, s config.ModelSettings) bool

SettingApplies reports whether a model accepts a setting with the value s gives it: SettingSupported, and for thinking_budget 0 (thinking off), a model that lets thinking be turned off.

func SettingSupported

func SettingSupported(provider, modelName, key string) bool

SettingSupported reports whether a model of provider accepts a [model_settings] key. Unsupported settings are left out of requests.

func TaskNote

func TaskNote(t api.TaskInfo) string

TaskNote is what the main agent is told when task t has ended.

func UseLiveProbe added in v1.3.0

func UseLiveProbe(answers func(model string) error) (restore func())

UseLiveProbe replaces the live models' check with answers (nil: the model answers) and forgets what was kept, for other packages' tests; the func returned puts both back.

func VoiceBackend added in v1.0.0

func VoiceBackend(ctx context.Context, cfg *config.Config) (string, error)

VoiceBackend is how voice would reach Gemini ("gemini" for the Gemini API, "vertex" for Vertex AI), or why it can't (ErrVoiceNotSetUp, VOX-03). It asks nothing of Google.

func VoiceLiveConfig added in v1.0.0

func VoiceLiveConfig(voice string, vc config.VoiceConfig) agent.LiveRunConfig

VoiceLiveConfig is the live connection's settings (VOX-07, VOX-08): audio answers in voice, both sides transcribed, resumption, so a connection the server cycles carries on; and how Gemini hears the person: hold to talk turns its activity detection off (the page says when the person speaks); otherwise noise, pause_ms and start_ms tune it.

func VoiceModels added in v1.0.0

func VoiceModels(ctx context.Context, cfg *config.Config) ([]string, string, error)

VoiceModels are the live models that answer for this key or project, best first (VOX-41, VOX-06a), and the one a conversation would use; none answering is ErrNoLiveModel, with the provider's reason.

func WebSearchPrompt

func WebSearchPrompt(terms string, links []tools.SearchResult, answer string) string

WebSearchPrompt hands the links the user's /search web picked to the agent to read. They are approved for the turn (tools.WithFetchGrants); answer is the search engine's own summary, if it gave one.

func WithProviderToolPolicy added in v0.9.2

func WithProviderToolPolicy(ctx context.Context, p ProviderToolPolicy) context.Context

WithProviderToolPolicy puts p in ctx for the model calls made with it.

func WithSubagentEvents added in v0.8.10

func WithSubagentEvents(ctx context.Context, fn func(*session.Event)) context.Context

WithSubagentEvents passes fn the events of the sub-agents a turn runs in the foreground (invoke_agent without background), as they happen, so the conversation can show their work; a background task's go to the task instead. fn may be called from several goroutines at once, as sub-agents run in parallel.

func WithTurnNotices

func WithTurnNotices(ctx context.Context, f func(string)) context.Context

WithTurnNotices sends the engine's notices during runs under ctx to f (the turn's own events, so the conversation shows them) rather than to the engine's WithNotice, which gets them outside a turn.

func WithTurnStatus added in v0.6.4

func WithTurnStatus(ctx context.Context, f func(string)) context.Context

WithTurnStatus sends passing statuses raised during runs under ctx to f: a model request whose connection failed and is being retried. Unlike notices, they aren't kept in the conversation.

Types

type Accept added in v0.2.1

type Accept struct {
	Kind     images.Kind
	MIMEs    []string
	MaxBytes int64
	Inline   int64
	Pages    int
	Upload   bool
	AsText   bool
}

Accept is a kind of attachment a model takes: the media types, the largest file, and how: inline up to Inline bytes (and Pages pages, for PDFs), uploaded above it (Upload), else as text (AsText: a PDF's text, for a model that can't read PDFs).

func AcceptedMedia added in v0.2.1

func AcceptedMedia(provider, modelName string, upload bool) []Accept

AcceptedMedia is what a model of provider takes (spec_011_images), as its record says (spec_056 CA-10, ModelInfo.Accepts):

  • Gemini: pictures (HEIC too), PDFs, text, audio and video; audio and video over 14 MB through the Files API when upload is possible (the Gemini API, not Vertex AI), else no larger than that.
  • Claude (Anthropic's API, Vertex AI, Bedrock): pictures, PDFs and text.
  • Others: pictures, text, and PDFs as their text.

A model that doesn't read images takes none (CA-64).

type Budget added in v0.9.1

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

Budget is a model-call budget several Execute calls share: the runs of one turn (its first, an approved plan's, a stop hook's, a goal's or a rule's continuation), or a job's workflow steps.

func NewBudget added in v0.9.1

func NewBudget(max int, within *Budget) *Budget

NewBudget is a budget of max model calls (0: no limit of its own) whose calls count toward within too (nil: none).

func (*Budget) Exhausted added in v0.9.1

func (b *Budget) Exhausted() bool

Exhausted reports whether a run was stopped at this budget's own limit (not one it counts toward).

type Charge added in v0.9.2

type Charge struct {
	Session string
	// Task is the background task it ran for, if any; its own total is
	// kept too, for its cost cap.
	Task    string
	Purpose string
	// Model is the model the call is priced as (the one that answered).
	Model       string
	Origin      Origin
	Usage       *genai.GenerateContentResponseUsageMetadata
	CacheWrites int64
}

Charge is a model call to record: whose session it's charged to, what it was for, who answered and what it used.

type Citation added in v0.9.2

type Citation struct {
	Title string `json:"title,omitempty"`
	URL   string `json:"url"`
	Text  string `json:"text,omitempty"`
}

Citation is one source an answer cites (CA-84).

func Citations added in v0.9.2

func Citations(resp *model.LLMResponse) []Citation

Citations is what resp cites.

type CloudVoice added in v1.3.3

type CloudVoice struct {
	// Project is the Google Cloud project they're used in.
	Project string
	// contains filtered or unexported fields
}

CloudVoice is the cloud engine's Speech-to-Text and Text-to-Speech.

func NewCloudVoice added in v1.3.3

func NewCloudVoice(ctx context.Context, cfg *config.Config) (*CloudVoice, error)

NewCloudVoice builds the cloud engine's Speech-to-Text and Text-to-Speech from cfg (VOX-70): ErrVoiceNotSetUp, saying what's missing, without Google Cloud credentials that still sign in, or without a project.

func NewCloudVoiceWith added in v1.3.3

func NewCloudVoiceWith(speak func(ctx context.Context, voice string, t config.VoiceTuning) (SpeechStream, error), listen func(ctx context.Context, language string) (Listener, error)) *CloudVoice

NewCloudVoiceWith is a CloudVoice that speaks and listens with these (tests' own, in place of Google's).

func (*CloudVoice) Close added in v1.3.3

func (c *CloudVoice) Close()

Close lets go of its connections.

func (*CloudVoice) Listen added in v1.3.3

func (c *CloudVoice) Listen(ctx context.Context, language string) (Listener, error)

Listen starts hearing someone who speaks language (BCP-47).

func (*CloudVoice) Speak added in v1.3.3

func (c *CloudVoice) Speak(ctx context.Context, voice string, t config.VoiceTuning) (SpeechStream, error)

Speak starts saying something in voice (one of config.GeminiVoices, which Chirp 3: HD's are named as), tuned by t.

type CompactResult

type CompactResult struct {
	EventsCompacted int
	TurnsKept       int
	SummaryChars    int
}

CompactResult describes a manual compaction.

type Embedder added in v0.3.0

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

Embedder turns texts into vectors with a provider's embedding model: the semantic half of workspace search (spec_035_search SRCH-50).

func NewEmbedder added in v0.3.0

func NewEmbedder(ctx context.Context, cfg *config.Config, ref string) (*Embedder, error)

NewEmbedder builds the embedder for ref ("provider/model", the search.embedding_model setting): Gemini (the Gemini API or Vertex AI, as [llm.gemini] signs in), OpenAI, or an OpenAI-compatible server such as Ollama. nil without a model.

func (*Embedder) Embed added in v0.3.0

func (e *Embedder) Embed(ctx context.Context, texts []string) ([][]float32, error)

Embed embeds texts, in batches, in order.

func (*Embedder) Model added in v0.3.0

func (e *Embedder) Model() string

Model is the embedding model, as "provider/model".

type Engine

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

Engine orchestrates the Google ADK execution lifecycle for Blitz. It is safe for concurrent use.

func NewEngine

func NewEngine(
	ctx context.Context,
	cfg *config.Config,
	agentReg *agents.Registry,
	skillProv *skills.Provider,
	toolReg *tools.Registry,
	llm model.LLM,
	opts ...Option,
) (*Engine, error)

NewEngine creates and wires the ADK runtime engine, registering itself as the sub-agent invoker for the invoke_agent tool.

func (*Engine) AcceptedMedia added in v0.2.1

func (e *Engine) AcceptedMedia(agent string) []Accept

AcceptedMedia is what agent's model takes as attachments ("": the active agent's), for refusing others at upload (spec_011_images).

func (*Engine) ActiveAgent

func (e *Engine) ActiveAgent() string

ActiveAgent returns the name of the currently active agent persona.

func (*Engine) AgentModel

func (e *Engine) AgentModel(agent string) (name string, pinned bool)

AgentModel returns the model agent runs on and whether it is pinned.

func (*Engine) AllModelSettings

func (e *Engine) AllModelSettings() map[string]config.ModelSettings

AllModelSettings returns every model's settings, by model name.

func (*Engine) AnswerRequest

func (e *Engine) AnswerRequest(sessions []string, id string, decision api.Decision, text string) error

AnswerRequest answers request id of one of sessions' tasks (nil: any): decision for an approval, text for a question.

func (*Engine) Aside

func (e *Engine) Aside(ctx context.Context, sessionID, prompt string, handler EventHandler) error

Aside answers prompt with everything session sessionID knows, without adding to it (/btw). The session's events are copied into a throwaway in-memory session that the question runs in; it is discarded afterwards, so neither the question nor the answer reaches the history, the saved event log or later prompts. The turn is read-only, and its tokens count towards sessionID's usage because they were spent there.

func (*Engine) CloseSteers

func (e *Engine) CloseSteers(sessionID string) []string

CloseSteers ends one run's taking steer messages for sessionID; the last to end stops the session taking them and gets those no tool result carried (the turn's leftovers). Runs still going (parallel workflow steps) keep taking them (N26 engine-top-2#10: the first step to end closed steering for the rest, and took their messages).

func (*Engine) Compact

func (e *Engine) Compact(ctx context.Context, sessionID, focus string, keepTurns int) (CompactResult, error)

Compact summarises a session's history except its last keepTurns user turns and records the summary as a compaction event, so later prompts carry the summary instead of the covered events. focus, if set, tells the summarizer what to emphasise. The cut is always made at the start of a user turn so a tool call is never separated from its result.

func (*Engine) CompactAt

func (e *Engine) CompactAt(ctx context.Context, sessionID, focus string, at int, upTo bool) (CompactResult, error)

CompactAt summarises a session's history on one side of the user turn that starts at event index at: the turns before it (upTo) or it and every turn after (from here). The rest stays as it was.

func (*Engine) CompactionThreshold added in v0.9.2

func (e *Engine) CompactionThreshold() int

CompactionThreshold is where the active model's conversations are compacted (spec_056 CA-110), for the context meter.

func (*Engine) ContextParts

func (e *Engine) ContextParts(ctx context.Context, sessionID string, total int64) []api.ContextPart

ContextParts estimates what a session's next prompt is made of (spec_027_parity PAR-UI-06): the active agent's system prompt, the project instructions and notes, the tool declarations, the prompts, replies, tool calls and results, images, PDFs and summaries of earlier conversation. Each is its text's length / 4 (images a flat amount, PDFs an amount a page), scaled so they add up to total when the model reported one.

func (*Engine) Effort

func (e *Engine) Effort() string

Effort returns the session's reasoning effort ("" when unset).

func (*Engine) EstimateCostUSD added in v0.7.1

func (e *Engine) EstimateCostUSD(model string, usage *genai.GenerateContentResponseUsageMetadata) float64

EstimateCostUSD is what a model call outside a session cost (an eval's judge), by the configured prices; 0 for a model without one.

func (*Engine) EstimateUsage added in v0.7.1

func (e *Engine) EstimateUsage(model string, usage *genai.GenerateContentResponseUsageMetadata) api.Usage

EstimateUsage is a model call outside a session's usage (a rule's judge, a workflow's extract step), priced by the configured prices; a call that reported no tokens is unpriced.

func (*Engine) EventCount

func (e *Engine) EventCount(ctx context.Context, sessionID string) int

EventCount is how many events a session's log holds (0 for a new one).

func (*Engine) Execute

func (e *Engine) Execute(ctx context.Context, sessionID, prompt string, handler EventHandler, opts ...ExecOption) error

Execute runs a prompt within a session and streams ADK events to the handler.

func (*Engine) ForgetSession

func (e *Engine) ForgetSession(ctx context.Context, sessionID string)

ForgetSession drops a session's event log, in memory and on disk, once the session is deleted. A session this process never loaded is fine.

func (*Engine) HasPrice added in v0.9.2

func (e *Engine) HasPrice(model string) bool

HasPrice reports whether model ("provider/" prefix optional) has a price, so its calls count toward cost limits.

func (*Engine) InvokeSubagent

func (e *Engine) InvokeSubagent(ctx context.Context, agentName, prompt string) (_ string, err error)

InvokeSubagent runs a single registered agent on prompt in a fresh, isolated session and returns the text it produced. Nesting is limited to MaxSubagentDepth to stop agents delegating to each other indefinitely. Usage and turn limits of the calling run still apply.

func (*Engine) JudgeGoal

func (e *Engine) JudgeGoal(ctx context.Context, sessionID, condition string) (GoalVerdict, error)

JudgeGoal has a model (the auto reviewer's, else the session's) decide whether the session's conversation shows condition holds (spec_027_parity PAR-SES-30).

func (*Engine) Ledger added in v0.9.2

func (e *Engine) Ledger(sessionID string) ([]api.Call, api.Totals, error)

Ledger is sessionID's calls, oldest first, with what was spent before its ledger was kept as one call at the head (spec_056 CA-126), and their totals by model and purpose (CA-121).

func (*Engine) ListTasks

func (e *Engine) ListTasks(sessions []string) []api.TaskInfo

ListTasks are the tasks of sessions (nil: every session), oldest first.

func (*Engine) ModelName

func (e *Engine) ModelName() string

ModelName returns the name of the model the active agent runs on.

func (*Engine) ModelSettings

func (e *Engine) ModelSettings(model string) config.ModelSettings

ModelSettings returns the generation settings for model ("provider/" prefix optional); the zero value when it has none.

func (*Engine) OpenSteers

func (e *Engine) OpenSteers(sessionID string) func() []string

OpenSteers makes sessionID take steer messages: a run of it has started. It returns the run's close, which acts once however often it's called (CloseSteers).

func (*Engine) PendingRequests

func (e *Engine) PendingRequests(sessions []string) []api.TaskRequest

PendingRequests are the requests of sessions' tasks (nil: every session's) waiting for an answer, oldest first.

func (*Engine) PinModel

func (e *Engine) PinModel(ctx context.Context, agent string, llm model.LLM) error

PinModel runs agent on llm from now on (other agents are unaffected).

func (*Engine) PriceOf added in v0.9.2

func (e *Engine) PriceOf(model string) (config.ModelPrice, bool)

PriceOf is model's price as the ledger charges it: the price table, then the organization's catalog (spec_056 CA-123).

func (*Engine) Rebuild

func (e *Engine) Rebuild(ctx context.Context) error

Rebuild regenerates agent instructions, e.g. after settings change.

func (*Engine) RecordImage added in v0.9.3

func (e *Engine) RecordImage(ctx context.Context, sessionID, model string, usage *genai.GenerateContentResponseUsageMetadata)

RecordImage adds an image model's usage (generate_image) to sessionID's usage, as RecordSpeech does a speech model's.

func (*Engine) RecordSearch

func (e *Engine) RecordSearch(ctx context.Context, sessionID string, queries int, costUSD float64)

RecordSearch adds a web search's billed queries, and their cost, to sessionID's usage, and saves it (BL-WEB-01).

func (*Engine) RecordSpeech added in v0.2.1

func (e *Engine) RecordSpeech(ctx context.Context, sessionID, model string, usage *genai.GenerateContentResponseUsageMetadata)

RecordSpeech adds a speech model's usage (generate_audio) to sessionID's usage, priced by [pricing] like any model's, and saves it. A provider that reports no usage leaves the cost unknown.

func (*Engine) SetActiveAgent

func (e *Engine) SetActiveAgent(ctx context.Context, agentName string) error

SetActiveAgent switches the primary active agent persona and rebuilds the agent tree.

func (*Engine) SetAgency added in v0.8.0

func (e *Engine) SetAgency(level string)

SetAgency sets the agency level the root agent's prompt names, from the next rebuild (the settings it was built with aren't written once open).

func (*Engine) SetEffort

func (e *Engine) SetEffort(effort string)

SetEffort sets the reasoning effort for every model call from now on ("" returns each model to its own reasoning_effort, or the default).

func (*Engine) SetInstructions

func (e *Engine) SetInstructions(ctx context.Context, text string) error

SetInstructions replaces the extra instructions (project memory) and rebuilds.

func (*Engine) SetModel

func (e *Engine) SetModel(ctx context.Context, llm model.LLM) error

SetModel swaps the LLM used by all agents.

func (*Engine) SetModelSettings

func (e *Engine) SetModelSettings(model string, s config.ModelSettings)

SetModelSettings replaces model's settings (the zero value removes them). They apply from the next model call, also to calls already running.

func (*Engine) SetPersonality added in v1.0.0

func (e *Engine) SetPersonality(ctx context.Context, text string) error

SetPersonality replaces the root agent's personality (WithPersonality) from the next turn; "" removes it.

func (*Engine) SetScopedRules

func (e *Engine) SetScopedRules(rules []memory.Rule)

SetScopedRules replaces the path-scoped rules (after /memory reload). Rules already handed out in a session aren't handed out again.

func (*Engine) SetUploader added in v0.2.1

func (e *Engine) SetUploader(up images.Uploader)

SetUploader gives the models a way to send files too large to go inline (Gemini's Files API); nil for none.

func (*Engine) StartTask

func (e *Engine) StartTask(ctx context.Context, agentName, prompt, isolation string) (api.TaskInfo, error)

StartTask starts agentName on prompt in the background, for the session whose run ctx is, and returns at once.

func (*Engine) Steer

func (e *Engine) Steer(sessionID, text string) error

Steer queues a message for the turn running in sessionID. It is attached to the next tool result of that turn, so the model reads it before its next step without anything being interrupted, and it is kept in the session history in the place it arrived. Messages still queued when the turn ends (the model made no further tool calls) are returned by TakeSteers for the caller to send as the next prompt.

A session takes messages only while its turn runs (OpenSteers until CloseSteers); otherwise the message would wait for a turn nobody starts, so Steer refuses it with api.ErrSteerTooLate and the caller sends it as the next prompt.

func (*Engine) StopTask

func (e *Engine) StopTask(sessions []string, id string) (api.TaskInfo, error)

StopTask stops task id and waits up to stopWait for it to end.

func (*Engine) StopTasks

func (e *Engine) StopTasks()

StopTasks stops every running task and waits for them (the workspace is closing).

func (*Engine) SwitchFacts added in v0.9.2

func (e *Engine) SwitchFacts(ctx context.Context, sessionID string, llm model.LLM) SwitchFacts

SwitchFacts says what moving sessionID to llm means.

func (*Engine) TakeSteers

func (e *Engine) TakeSteers(sessionID string) []string

TakeSteers removes and returns the messages queued for sessionID that no tool result has carried yet.

func (*Engine) TakeTaskNotes

func (e *Engine) TakeTaskNotes(sessionID string) []string

TakeTaskNotes removes and returns the notes about ended tasks waiting for sessionID's main agent.

func (*Engine) TruncateSession

func (e *Engine) TruncateSession(ctx context.Context, sessionID string, keep int) error

TruncateSession keeps the first keep events of a session's log and drops the rest, rewinding the conversation to before them.

func (*Engine) Unpin

func (e *Engine) Unpin(ctx context.Context, agent string) error

Unpin returns agent to the engine's model.

func (*Engine) UnpricedModels added in v0.9.2

func (e *Engine) UnpricedModels(sessionID string) []string

UnpricedModels are the models sessionID called that have no price.

func (*Engine) Usage

func (e *Engine) Usage(sessionID string) api.Usage

Usage returns the token usage and estimated cost recorded for a session.

func (*Engine) WaitTask

func (e *Engine) WaitTask(ctx context.Context, sessions []string, id string, wait time.Duration) (api.TaskInfo, []string, error)

WaitTask is task id with its latest events, once it has ended or wait has passed.

func (*Engine) Watch

func (e *Engine) Watch(ctx context.Context, sessions []string) <-chan api.SessionEvent

Watch sends the events of sessions' tasks until ctx ends: tasks starting, waiting, running again and ending, requests waiting for an answer, and requests no longer waiting.

type EventHandler

type EventHandler func(ev *session.Event) error

EventHandler receives events (text tokens, function calls, function responses) from the runner.

type ExecOption

type ExecOption func(*runState)

ExecOption configures one Execute call.

func WithAgent

func WithAgent(name string) ExecOption

WithAgent runs the prompt with name as the root agent instead of the active one, for this run only (e.g. a worker's agent).

func WithAllowedTools

func WithAllowedTools(names []string) ExecOption

WithAllowedTools limits the run to the named tools (Blitz's names, or Claude Code's such as Bash or Read; "Bash(git *)" counts as Bash): any other tool is refused. Nil means no limit; empty, no tools.

func WithAttachments

func WithAttachments(parts ...*genai.Part) ExecOption

WithAttachments adds parts (usually images.Part references) to the prompt, ahead of its text as providers recommend.

func WithBudget added in v0.9.1

func WithBudget(b *Budget) ExecOption

WithBudget counts the run's model calls toward b (nil: none).

func WithConversationModel added in v0.9.2

func WithConversationModel(llm model.LLM) ExecOption

WithConversationModel runs the prompt on its conversation's own model (spec_056 CA-100): every agent without a pin runs on it, a pinned one on its pin. A run's own model (WithModel) wins over it.

func WithMaxTurns

func WithMaxTurns(n int) ExecOption

WithMaxTurns limits the number of model calls in the run (0 = unlimited).

func WithModel

func WithModel(llm model.LLM) ExecOption

WithModel runs the prompt on llm instead of the configured model, for this run only: the root agent runs on it even if pinned, and so does every unpinned agent (e.g. a worker's model).

func WithPlanOnly

func WithPlanOnly() ExecOption

WithPlanOnly runs the prompt in plan mode: the agent may read and search but every tool that could change something is refused, so the answer is a plan grounded in the code rather than an edit.

func WithReadOnly

func WithReadOnly(mode string) ExecOption

WithReadOnly refuses the same tools as plan mode, for a prompt that only looks things up (e.g. /search). mode names it in the refusal.

type GoalVerdict

type GoalVerdict struct {
	Met, Impossible bool
	Reason, Next    string
}

GoalVerdict is the judge's answer about a goal.

type Guard added in v0.7.1

type Guard interface {
	// ToolCall decides a call before it runs.
	ToolCall(ctx context.Context, c GuardCall) GuardVerdict
	// ToolResult checks a tool's result.
	ToolResult(ctx context.Context, c GuardCall, result map[string]any) GuardVerdict
	// Output checks a piece of the model's answer; final is the whole
	// answer, after the pieces streamed.
	Output(ctx context.Context, c GuardCall, text string, final bool) GuardVerdict
}

Guard checks what a turn reads, says and does, at every step (guardrails, spec_041_gates): a tool call before it runs, a tool's result before the model reads it, and the model's answers.

type GuardCall added in v0.7.1

type GuardCall struct {
	Session, Agent, Tool string
	Args                 map[string]any
}

GuardCall is what a guard is asked about: the session and agent, and for a tool call or result, the tool and its arguments.

type GuardVerdict added in v0.7.1

type GuardVerdict struct {
	// Refusal stops a tool call: the model gets it as the call's error.
	Refusal string
	// Result replaces a tool's result (withheld, or with a warning).
	Result map[string]any
	// Text replaces a piece of the answer (masked, or withheld).
	Text *string
	// Notices are said in the conversation.
	Notices []string
	// Withheld ends a streamed answer: the rest of it isn't sent (Text is
	// the last of it).
	Withheld bool
}

GuardVerdict is a guard's answer; the zero value lets things be.

type HearEvent added in v1.3.3

type HearEvent struct {
	Kind string
	Text string
	Err  error
}

HearEvent is one thing heard.

type LedgerStore added in v0.9.2

type LedgerStore interface {
	AppendCall(sessionID string, c api.Call) error
	Calls(sessionID string) ([]api.Call, error)
}

LedgerStore is a UsageStore that also keeps each session's ledger: its calls one by one (spec_056_conversation_adapters CA-120).

type ListedModel

type ListedModel struct {
	ID    string
	Price *config.ModelPrice
	// DisplayName and Default are the organization's, for its models.
	DisplayName string
	Default     bool
	// Caps are what the model can do: what the organization says of its
	// model (EN-21), else Blitz's facts for the name (spec_061_models
	// MOD-01); nil when the organization says nothing.
	Caps *enterprise.Capabilities
}

ListedModel is one of them, with the price Blitz knows for it.

func LatestModels added in v0.9.6

func LatestModels(models []ListedModel) []ListedModel

LatestModels are a provider's latest models (spec_061_models MOD-43): of each family its newest version, a stable one over a preview or snapshot of the same version, of the families whose newest is within one major version of the provider's newest; in the order given.

type Listener added in v1.3.3

type Listener interface {
	// Send adds audio; it never waits.
	Send(pcm []byte)
	// Flush settles what's been heard without waiting for a pause (hold
	// to talk's release).
	Flush()
	// Events are what's heard, in order; closed when the listener ends.
	Events() <-chan HearEvent
	Close()
}

Listener hears the person: 16 kHz 16-bit mono PCM in, words out.

type MockLLM

type MockLLM struct {
	ModelName string
	Responses []*genai.Content
	CallCount int

	Requests []*model.LLMRequest
	// Usage, if set, is attached to every response.
	Usage *genai.GenerateContentResponseUsageMetadata
	// ServedBy and Metadata, if set, become each response's ModelVersion and
	// CustomMetadata.
	ServedBy string
	Metadata map[string]any
	// FinishReasons, if set, are the responses' finish reasons, in order
	// (MAX_TOKENS: a reply cut off at the output limit).
	FinishReasons []genai.FinishReason
	// Chunk, if set, streams a reply that's only text when streaming is
	// asked for, as a streaming API does: pieces of Chunk bytes as
	// partial responses, then the whole text as the final one.
	Chunk int
	// contains filtered or unexported fields
}

MockLLM provides an in-memory LLM implementation for tests and offline validation. It is safe for concurrent use; read CallCount via Calls() while runs are in flight.

func NewMockLLM

func NewMockLLM(name string, responses ...*genai.Content) *MockLLM

NewMockLLM returns a scripted model for tests: it answers each call with the next of responses, then "Done.", and is named name ("mock-llm" if empty).

func (*MockLLM) Calls

func (m *MockLLM) Calls() int

Calls returns the number of GenerateContent calls so far.

func (*MockLLM) GenerateContent

func (m *MockLLM) GenerateContent(ctx context.Context, req *model.LLMRequest, stream bool) iter.Seq2[*model.LLMResponse, error]

GenerateContent records the request and answers with the next scripted response ("Done." once they run out), as one final response whether or not streaming was asked for. As strict as the APIs it stands for: a call whose context is done fails with its error, and a request with a tool result whose call isn't before it is refused.

func (*MockLLM) Name

func (m *MockLLM) Name() string

Name is the model's name.

type ModelInfo added in v0.9.2

type ModelInfo struct {
	// API is the wire API (gemini, anthropic, openai), Provider the
	// provider as configured, Name the model's canonical name.
	API, Provider, Name string
	// ContextWindow and MaxOutput are in tokens.
	ContextWindow, MaxOutput int
	// Tools is how it calls tools.
	Tools ToolMode
	// Vision is whether it reads images.
	Vision bool
	// Thinking is how it reasons; Effort whether it takes an effort level;
	// Sampling whether it takes temperature and top_p.
	Thinking ThinkingMode
	Effort   bool
	Sampling bool
	// Streams is whether it streams.
	Streams bool
	// Price is what it costs; nil when Blitz has no price for it.
	Price *config.ModelPrice
	// Refused are the settings it refuses (learned, CA-13).
	Refused []string
	// Guesses are the facts above that are guesses, not known (CA-11).
	Guesses []string
	// Learned is what Blitz learned from its refusals (CA-13).
	Learned []modelfacts.Fact
	// contains filtered or unexported fields
}

ModelInfo is what Blitz knows of one model (CA-10).

func Info added in v0.9.2

func Info(api, provider, model string) ModelInfo

Info is what's known of provider's model now, reached through api (the wire API: gemini, anthropic, openai; "" for provider's usual) (CA-10, CA-11): Blitz's table, then the provider's listing, what was learned, the organization's catalog (for its models), and the settings' price, each later one winning.

func (ModelInfo) Accepts added in v0.9.2

func (m ModelInfo) Accepts(upload bool) []Accept

Accepts is what the model takes as attachments (CA-60, CA-61), upload saying whether files can go through the provider's Files API; a model that doesn't read images gets each as a note (CA-64).

func (ModelInfo) CompactionPoint added in v0.9.2

func (m ModelInfo) CompactionPoint(configured int) int

CompactionPoint is where a conversation on the model is compacted (CA-110): token_threshold when it's set to other than its default, else the model's context window less its maximum output, less 10%. A model whose window is a guess keeps the setting.

func (ModelInfo) Guess added in v0.9.2

func (m ModelInfo) Guess(fact string) bool

Guess reports whether fact is a guess.

type Option

type Option func(*Engine)

Option configures an Engine.

func WithAgentModel

func WithAgentModel(agent string, llm model.LLM) Option

WithAgentModel runs agent on llm instead of the engine's model (a pin from [agent_models] or the agent's own default_model).

func WithGuard added in v0.7.1

func WithGuard(g Guard) Option

WithGuard has the engine ask g at every step.

func WithHookModel

func WithHookModel(ref string, llm model.LLM) Option

WithHookModel makes llm the model of prompt hooks naming ref.

func WithInstructions

func WithInstructions(text string) Option

WithInstructions appends text (e.g. project memory) to every agent's instructions.

func WithNotice

func WithNotice(f func(string)) Option

WithNotice sets where the engine reports events the user should know about, such as a fallback model taking over (default: nowhere).

func WithPersonality added in v1.0.0

func WithPersonality(text string) Option

WithPersonality gives the root agent of attended runs text after its instructions (spec_064_personality PER-02): how it sounds to the person.

func WithProjectTrusted

func WithProjectTrusted(trusted bool) Option

WithProjectTrusted says whether the workspace's project settings are trusted: until they are, the project's own agents may only tighten the permission mode (spec_032_background_agents BGA-50).

func WithReviewModel

func WithReviewModel(llm model.LLM) Option

WithReviewModel makes llm the auto mode's reviewer ([permissions.auto] model); without it the session's model reviews.

func WithScopedRules

func WithScopedRules(rules []memory.Rule) Option

WithScopedRules hands rules scoped to paths to agents as they touch matching files (see memory.Rule).

func WithSecrets added in v0.7.1

func WithSecrets(expand func(text string) (string, []string)) Option

WithSecrets gives the engine {secrets:key} values (spec_039_secrets): expand puts them in text's place and returns those used. They're put in only as the model is called, never in the session, the transcript or the hooks' view.

func WithSessionService

func WithSessionService(s session.Service) Option

WithSessionService replaces the default in-memory session store (e.g. with a persistent one so conversations can be resumed).

func WithStreaming

func WithStreaming(on bool) Option

WithStreaming makes Execute deliver partial text events as the model generates them (followed by the usual final events).

func WithTaskDone

func WithTaskDone(f func(api.TaskInfo)) Option

WithTaskDone calls f when a background task ends (the workspace records it in the session's transcript).

func WithTurnStore

func WithTurnStore(s TurnStore) Option

WithTurnStore chains turn spans per session through s.

func WithUsageStore

func WithUsageStore(s UsageStore) Option

WithUsageStore keeps sessions' usage in s (and their ledgers, when s is a LedgerStore too).

type Origin added in v0.9.2

type Origin struct {
	API, Provider, Model string
}

Origin is the model a part came from: the wire API it speaks, the provider as configured, and the model.

type PictureAnswer added in v0.9.4

type PictureAnswer struct {
	Pictures []tools.Picture
	Text     string
	Thoughts string
	Sources  []PictureSource
	// Searches counts the grounding searches the model made.
	Searches int
	Content  *genai.Content
	Usage    *genai.GenerateContentResponseUsageMetadata
}

PictureAnswer is what a model made: its pictures, what it said and thought, the pages it grounded on, its turn as it answered (with thought signatures, for the conversation), and its usage.

type PictureCall added in v0.9.4

type PictureCall struct {
	History    []*genai.Content
	User       *genai.Content
	Prompt     string
	References []tools.Reference

	Count        int
	AspectRatio  string
	Size         string
	Thinking     string
	Search       bool
	SearchImages bool
	Avoid        string
	People       string
	Seed         *int32
	Enhance      bool
	Format       string
	Quality      int
}

PictureCall is one Pictures turn (spec_058_pictures §8): for a Gemini model, the conversation so far and the user's turn (its text and references, labelled by role); for Imagen and an organization's model, the prompt and references alone; and the settings, checked against the catalog before.

type PictureMaker added in v0.9.4

type PictureMaker interface {
	// Model names the model, "provider/model"; Info is what it can do.
	Model() string
	Info() images.Model
	// Host is the API's host.
	Host() string
	// Make makes what call asks for. A turn without a picture is an error
	// saying why, with what came (its text, its usage) in the answer.
	Make(ctx context.Context, call PictureCall) (*PictureAnswer, error)
}

PictureMaker makes pictures for Pictures (spec_058).

func NewPictureMaker added in v0.9.4

func NewPictureMaker(ctx context.Context, cfg *config.Config, ref string) (PictureMaker, error)

NewPictureMaker is the picture maker for ref ("provider/model"): a Gemini image model or Imagen with the Gemini provider's credentials, or one of the organization's image models (one turn at a time, its ratio and size: GW-04b).

type PictureSource added in v0.9.4

type PictureSource struct {
	Title string
	URL   string
}

PictureSource is a page a grounded turn used.

type ProviderModels

type ProviderModels struct {
	Provider string
	Models   []ListedModel
	Err      error
	// Note says what the list is when it isn't the provider's own.
	Note string
}

ProviderModels are the models a configured provider offers (spec_027_parity PAR-MOD-03), or why they couldn't be listed.

func ChatModels added in v0.9.6

func ChatModels(pms []ProviderModels) []ProviderModels

ChatModels is pms with only their chat models (ChatModel), each provider's newest family first, then by name (spec_061_models MOD-01, MOD-02).

func ListModels

func ListModels(ctx context.Context, cfg *config.Config, providers ...string) []ProviderModels

ListModels asks each provider (all configured ones when none are named) for its models, in parallel.

func MenuModels(cfg *config.Config, pms []ProviderModels, current string) []ProviderModels

MenuModels are what the model menus list for each provider of pms (MOD-44): the person's chosen models (MOD-42), else its latest (MOD-43) for the major providers and all of them for the rest; and always the model in use, current ("provider/name" or a name of cfg's provider).

type ProviderToolPolicy added in v0.9.2

type ProviderToolPolicy struct {
	Off      bool
	Disabled map[string]bool
	// Wants is the client tools the calling agent's tools list: its
	// web_search lets the model search with no search provider set.
	Wants map[string]bool
}

ProviderToolPolicy is what Blitz's rules say about provider tools beyond the client tools a request offers (CA-81): all off (tools provider = false), or some off (an agent's -provider:<kind>, the organization's tools.off).

type QuotaError

type QuotaError struct {
	Message string
	Err     error
}

QuotaError is a request refused because a quota is used up: Google's RESOURCE_EXHAUSTED (Vertex AI, the Gemini API), which also comes as a 429 but, unlike a rate limit, waiting a moment rarely helps. Message is Google's, which names the quota.

func (*QuotaError) Error

func (e *QuotaError) Error() string

Error says it's a quota, what Google said, and where to raise it.

func (*QuotaError) Unwrap

func (e *QuotaError) Unwrap() error

Unwrap is the provider's error.

type SpeechStream added in v1.3.3

type SpeechStream interface {
	// Say adds text to say; whole sentences sound best.
	Say(text string) error
	// Finish says no more text is coming: Recv ends once it's all said.
	Finish() error
	// Recv is the next audio, io.EOF after the last.
	Recv() ([]byte, error)
	// Close gives it up, said or not.
	Close()
}

SpeechStream is one thing being said: text in, a sentence or more at a time, 24 kHz 16-bit mono PCM out as it's made.

type SwitchFacts added in v0.9.2

type SwitchFacts struct {
	// CompactAt is where the model's conversations are compacted (CA-110):
	// past it, the conversation is compacted before the move.
	CompactAt int
	// Unseen names the conversation's attachments the model won't see as
	// they are (CA-63).
	Unseen []string
	// NoTools is set for a model that can't call tools (CA-103).
	NoTools bool
}

SwitchFacts is what the engine can tell of moving a conversation to a model, for the switch's preview (spec_056 CA-101).

type ThinkingMode added in v0.9.2

type ThinkingMode int

ThinkingMode is how a model reasons.

const (
	// ThinkingNone: no reasoning setting applies.
	ThinkingNone ThinkingMode = iota
	// ThinkingBudget: a token budget turns reasoning on and sizes it.
	ThinkingBudget
	// ThinkingAdaptive: the model decides, at an effort; a budget is refused.
	ThinkingAdaptive
	// ThinkingAlways: adaptive, and it can't be turned off.
	ThinkingAlways
)

type ToolMode added in v0.9.2

type ToolMode int

ToolMode is how a model calls tools.

const (
	// ToolsNative: the API's own function calls.
	ToolsNative ToolMode = iota
	// ToolsNone: the model doesn't call tools; its agent runs without
	// them (CA-103).
	ToolsNone
)

type TurnStore

type TurnStore interface {
	LastTurn(sessionID string) (traceparent string, index int)
	SetLastTurn(sessionID, traceparent string, index int) error
}

TurnStore remembers each session's latest turn so the next turn's span can link to it, across processes when the store is persistent. session.Storage implements it.

type UsageStore

type UsageStore interface {
	Usage(sessionID string) (api.Usage, bool)
	SetUsage(sessionID string, u api.Usage) error
}

UsageStore keeps each session's usage between processes: the engine saves it after every model call and restores it the first time a session's usage is asked for. session.Storage implements it.

type UsageTracker

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

UsageTracker records usage per session: its totals in memory, and each call for its ledger (spec_056_conversation_adapters CA-120).

func NewUsageTracker

func NewUsageTracker(pricing map[string]config.ModelPrice) *UsageTracker

NewUsageTracker creates a tracker with the given price table.

func (*UsageTracker) Charge added in v0.9.2

func (t *UsageTracker) Charge(ctx context.Context, c Charge) api.Call

Charge records one model call: in the session's totals (and its task's) and as the ledger entry it returns, for the session's store to keep.

func (*UsageTracker) Estimate

func (t *UsageTracker) Estimate(model string, m *genai.GenerateContentResponseUsageMetadata, cacheWrites int64) api.Usage

Estimate converts token counts to USD for model. cacheWrites are prompt tokens (already counted in the prompt total) written to the cache. A call that reported no usage is one call of unknown cost (unpriced).

func (*UsageTracker) Forget added in v0.3.4

func (t *UsageTracker) Forget(ids ...string)

Forget drops sessions' (or tasks') usage: deleted, or gone for good.

func (*UsageTracker) Has

func (t *UsageTracker) Has(session string) bool

Has reports whether session has usage in the tracker.

func (*UsageTracker) HasPrice

func (t *UsageTracker) HasPrice(model string) bool

HasPrice reports whether a price is configured for model.

func (*UsageTracker) Record

Record adds one model call's usage to session.

func (*UsageTracker) RecordCall added in v0.9.1

func (t *UsageTracker) RecordCall(ctx context.Context, session, model string, m *genai.GenerateContentResponseUsageMetadata, cacheWrites int64) api.Usage

RecordCall is RecordWrites for a call made under ctx, whose trace the token metrics keep.

func (*UsageTracker) RecordMedia added in v0.9.3

func (t *UsageTracker) RecordMedia(ctx context.Context, session, purpose, model string, m *genai.GenerateContentResponseUsageMetadata) api.Call

RecordMedia adds a call made for purpose by a model that makes media (speech, pictures) to session, as RecordSpeech describes.

func (*UsageTracker) RecordSearch

func (t *UsageTracker) RecordSearch(session string, queries int, costUSD float64) api.Call

RecordSearch adds web search queries, and what they cost, to session, and returns them as a call for its ledger.

func (*UsageTracker) RecordSpeech added in v0.2.1

func (t *UsageTracker) RecordSpeech(ctx context.Context, session, model string, m *genai.GenerateContentResponseUsageMetadata) api.Call

RecordSpeech adds a speech model's call (generate_audio) to session: its tokens and cost, but not as a prompt, so the context's size stays the conversation's. Without usage (a provider that reports none) the cost is unknown. It returns the call for the session's ledger.

func (*UsageTracker) RecordWrites

func (t *UsageTracker) RecordWrites(session, model string, m *genai.GenerateContentResponseUsageMetadata, cacheWrites int64) api.Usage

RecordWrites is Record with a count of cache-write tokens.

func (*UsageTracker) Seed

func (t *UsageTracker) Seed(session string, u api.Usage) bool

Seed sets session's usage to u when it has none yet (usage saved before a restart); it reports whether it did.

func (*UsageTracker) Session

func (t *UsageTracker) Session(session string) api.Usage

Session returns the usage recorded for session.

func (*UsageTracker) SetCatalogPrices added in v0.9.2

func (t *UsageTracker) SetCatalogPrices(f func(model string) (config.ModelPrice, bool))

SetCatalogPrices has the tracker price the organization's models by f where its price table has no price.

func (*UsageTracker) UnpricedModels added in v0.9.2

func (t *UsageTracker) UnpricedModels(session string) []string

UnpricedModels are the models session called that have no price, so cost limits can't count their calls (spec_056 CA-124).

type VoiceModel added in v1.0.0

type VoiceModel struct {
	model.LLM
	// ID is the model's name ("gemini-…"), Backend the API it's on.
	ID      string
	Backend genai.Backend
	// Project is the Google Cloud project the cloud engine's speech is
	// made in ("" for a live model).
	Project string
}

VoiceModel is the voice's model and how it's reached.

func NewVoiceModel added in v1.0.0

func NewVoiceModel(ctx context.Context, cfg *config.Config) (*VoiceModel, error)

NewVoiceModel builds the voice's model from cfg (VOX-05, VOX-06, VOX-06a): [voice] model ("gemini/<model>"), checked to answer, else the best live model that answers for this key or project (ErrNoLiveModel when none does). ErrVoiceNotSetUp when Gemini can't sign in.

Directories

Path Synopsis
Package wirefake has fakes of the model APIs Blitz speaks (Anthropic's Messages API, the Gemini API and OpenAI's Responses API) that are as strict as the real ones (spec_056_conversation_adapters CA-150): each refuses, with the real API's status and words, what its documentation says it refuses.
Package wirefake has fakes of the model APIs Blitz speaks (Anthropic's Messages API, the Gemini API and OpenAI's Responses API) that are as strict as the real ones (spec_056_conversation_adapters CA-150): each refuses, with the real API's status and words, what its documentation says it refuses.

Jump to

Keyboard shortcuts

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