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_engine_016, spec_models_015).
Index ¶
- Constants
- Variables
- func Ask(ctx context.Context, llm model.LLM, instruction, prompt string) (text, served string, usage *genai.GenerateContentResponseUsageMetadata, ...)
- func CarryOutPrompt(planFile string) string
- func ConfiguredProviders(cfg *config.Config) []string
- func NewGeminiUploader(ctx context.Context, cfg *config.Config) (images.Uploader, error)
- func NewModel(ctx context.Context, cfg *config.Config, overrideModel string) (model.LLM, error)
- func NewModelRef(ctx context.Context, cfg *config.Config, ref string) (model.LLM, error)
- func NewSpeaker(ctx context.Context, cfg *config.Config) (tools.Speaker, error)
- func NewUnavailableModel(name, why string) model.LLM
- func ParseModelRef(ref, defaultProvider string) (provider, name string)
- func PlanAllows(toolName string) bool
- func PlanPrompt(goal string) string
- func SessionSearchPrompt(terms string, matches []session.Match, total int) string
- func SettingApplies(provider, modelName, key string, s config.ModelSettings) bool
- func SettingSupported(provider, modelName, key string) bool
- func SupportsDocuments(provider, modelName string) bool
- func TaskNote(t api.TaskInfo) string
- func WebSearchPrompt(terms string, links []tools.SearchResult, answer string) string
- func WithTurnNotices(ctx context.Context, f func(string)) context.Context
- type Accept
- type CompactResult
- type Embedder
- type Engine
- func (e *Engine) AcceptedMedia(agent string) []Accept
- func (e *Engine) ActiveAgent() string
- func (e *Engine) AgentModel(agent string) (name string, pinned bool)
- func (e *Engine) AllModelSettings() map[string]config.ModelSettings
- func (e *Engine) AnswerRequest(sessions []string, id string, decision api.Decision, text string) error
- func (e *Engine) Aside(ctx context.Context, sessionID, prompt string, handler EventHandler) error
- func (e *Engine) CloseSteers(sessionID string) []string
- func (e *Engine) Compact(ctx context.Context, sessionID, focus string, keepTurns int) (CompactResult, error)
- func (e *Engine) CompactAt(ctx context.Context, sessionID, focus string, at int, upTo bool) (CompactResult, error)
- func (e *Engine) ContextParts(ctx context.Context, sessionID string, total int64) []api.ContextPart
- func (e *Engine) Effort() string
- func (e *Engine) EventCount(ctx context.Context, sessionID string) int
- func (e *Engine) Execute(ctx context.Context, sessionID, prompt string, handler EventHandler, ...) error
- func (e *Engine) ForgetSession(ctx context.Context, sessionID string)
- func (e *Engine) InvokeSubagent(ctx context.Context, agentName, prompt string) (_ string, err error)
- func (e *Engine) JudgeGoal(ctx context.Context, sessionID, condition string) (GoalVerdict, error)
- func (e *Engine) ListTasks(sessions []string) []api.TaskInfo
- func (e *Engine) ModelName() string
- func (e *Engine) ModelSettings(model string) config.ModelSettings
- func (e *Engine) OpenSteers(sessionID string)
- func (e *Engine) PendingRequests(sessions []string) []api.TaskRequest
- func (e *Engine) PinModel(ctx context.Context, agent string, llm model.LLM) error
- func (e *Engine) Rebuild(ctx context.Context) error
- func (e *Engine) RecordSearch(ctx context.Context, sessionID string, queries int, costUSD float64)
- func (e *Engine) RecordSpeech(ctx context.Context, sessionID, model string, ...)
- func (e *Engine) SetActiveAgent(ctx context.Context, agentName string) error
- func (e *Engine) SetEffort(effort string)
- func (e *Engine) SetInstructions(ctx context.Context, text string) error
- func (e *Engine) SetModel(ctx context.Context, llm model.LLM) error
- func (e *Engine) SetModelSettings(model string, s config.ModelSettings)
- func (e *Engine) SetScopedRules(rules []memory.Rule)
- func (e *Engine) SetUploader(up images.Uploader)
- func (e *Engine) StartTask(ctx context.Context, agentName, prompt, isolation string) (api.TaskInfo, error)
- func (e *Engine) Steer(sessionID, text string) error
- func (e *Engine) StopTask(sessions []string, id string) (api.TaskInfo, error)
- func (e *Engine) StopTasks()
- func (e *Engine) TakeSteers(sessionID string) []string
- func (e *Engine) TakeTaskNotes(sessionID string) []string
- func (e *Engine) TruncateSession(ctx context.Context, sessionID string, keep int) error
- func (e *Engine) Unpin(ctx context.Context, agent string) error
- func (e *Engine) Usage(sessionID string) api.Usage
- func (e *Engine) WaitTask(ctx context.Context, sessions []string, id string, wait time.Duration) (api.TaskInfo, []string, error)
- func (e *Engine) Watch(ctx context.Context, sessions []string) <-chan api.SessionEvent
- type EventHandler
- type ExecOption
- type GoalVerdict
- type ListedModel
- type MockLLM
- type Option
- func WithAgentModel(agent string, llm model.LLM) Option
- func WithHookModel(ref string, llm model.LLM) Option
- func WithInstructions(text string) Option
- func WithNotice(f func(string)) Option
- func WithProjectTrusted(trusted bool) Option
- func WithReviewModel(llm model.LLM) Option
- func WithScopedRules(rules []memory.Rule) Option
- func WithSessionService(s session.Service) Option
- func WithStreaming(on bool) Option
- func WithTaskDone(f func(api.TaskInfo)) Option
- func WithTurnStore(s TurnStore) Option
- func WithUsageStore(s UsageStore) Option
- type ProviderModels
- type QuotaError
- type TurnStore
- type UsageStore
- type UsageTracker
- func (t *UsageTracker) Estimate(model string, m *genai.GenerateContentResponseUsageMetadata, cacheWrites int64) api.Usage
- func (t *UsageTracker) Has(session string) bool
- func (t *UsageTracker) HasPrice(model string) bool
- func (t *UsageTracker) Record(session, model string, m *genai.GenerateContentResponseUsageMetadata) api.Usage
- func (t *UsageTracker) RecordSearch(session string, queries int, costUSD float64)
- func (t *UsageTracker) RecordSpeech(session, model string, m *genai.GenerateContentResponseUsageMetadata)
- func (t *UsageTracker) RecordWrites(session, model string, m *genai.GenerateContentResponseUsageMetadata, ...) api.Usage
- func (t *UsageTracker) Seed(session string, u api.Usage) bool
- func (t *UsageTracker) Session(session string) api.Usage
Constants ¶
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).
const DefaultAnthropicModel = "claude-opus-5"
DefaultAnthropicModel is used when no model is configured for the provider.
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.
const MaxSubagentDepth = 3
MaxSubagentDepth bounds nested invoke_agent calls so agents cannot recurse forever.
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.
const SteerKey = "message_from_user"
SteerKey is the tool-result field that carries messages the user sent while the turn was running.
const TaskUpdatesKey = "task_updates"
TaskUpdatesKey is the tool-result field that carries notes about background tasks that have ended.
Variables ¶
ErrModelUnavailable is the error of every call to a model that couldn't be built.
var ErrStalled = errors.New("model API stopped responding")
ErrStalled is returned when a model API stops sending data.
var ( // ErrSubagentDepth is returned when invoke_agent nesting exceeds MaxSubagentDepth. ErrSubagentDepth = errors.New("maximum sub-agent nesting depth exceeded") )
Functions ¶
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 ¶
CarryOutPrompt asks the agent to carry out the plan the user approved.
func ConfiguredProviders ¶
ConfiguredProviders are the providers cfg has credentials (or, for Ollama, a choice) for.
func NewGeminiUploader ¶ added in v0.2.1
NewGeminiUploader sends attachments too large to go inline through Gemini's Files API, signed in as [llm.gemini] (spec_images_011): nil without a Gemini API key or key command (Vertex AI has no Files API).
func NewModel ¶
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 ¶
NewModelRef builds the single model a fallback reference names (no chain), e.g. for `doctor` to check each fallback on its own.
func NewSpeaker ¶ added in v0.2.1
NewSpeaker builds the [audio] model's speaker (spec_models_015): 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 ¶
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 ParseModelRef ¶
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 PlanAllows ¶
PlanAllows reports whether a tool may run in plan mode.
func PlanPrompt ¶
PlanPrompt wraps a goal in the instructions for plan mode.
func SessionSearchPrompt ¶
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 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 ¶
SettingSupported reports whether a model of provider accepts a [model_settings] key. Unsupported settings are left out of requests.
func SupportsDocuments ¶ added in v0.2.1
SupportsDocuments reports whether a model reads a PDF as it is, pages, figures and all, rather than as its text.
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.
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
AcceptedMedia is what a model of provider takes (spec_images_011):
- 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): pictures, PDFs and text.
- Others: pictures, text, and PDFs as their text.
type CompactResult ¶
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_search_035 SRCH-50).
func NewEmbedder ¶ added in v0.3.0
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.
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
AcceptedMedia is what agent's model takes as attachments ("": the active agent's), for refusing others at upload (spec_images_011).
func (*Engine) ActiveAgent ¶
ActiveAgent returns the name of the currently active agent persona.
func (*Engine) AgentModel ¶
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 ¶
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 ¶
CloseSteers stops sessionID taking steer messages and returns those no tool result carried (the turn's leftovers).
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) ContextParts ¶
ContextParts estimates what a session's next prompt is made of (spec_parity_027 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) EventCount ¶
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 ¶
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) 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 ¶
JudgeGoal has a model (the auto reviewer's, else the session's) decide whether the session's conversation shows condition holds (spec_parity_027 PAR-SES-30).
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 ¶
OpenSteers makes sessionID take steer messages: its turn has started.
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) RecordSearch ¶
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 ¶
SetActiveAgent switches the primary active agent persona and rebuilds the agent tree.
func (*Engine) SetEffort ¶
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 ¶
SetInstructions replaces the extra instructions (project memory) and rebuilds.
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) SetScopedRules ¶
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
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 ¶
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) StopTasks ¶
func (e *Engine) StopTasks()
StopTasks stops every running task and waits for them (the workspace is closing).
func (*Engine) TakeSteers ¶
TakeSteers removes and returns the messages queued for sessionID that no tool result has carried yet.
func (*Engine) TakeTaskNotes ¶
TakeTaskNotes removes and returns the notes about ended tasks waiting for sessionID's main agent.
func (*Engine) TruncateSession ¶
TruncateSession keeps the first keep events of a session's log and drops the rest, rewinding the conversation to before them.
type EventHandler ¶
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. Empty means no limit.
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 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 ¶
GoalVerdict is the judge's answer about a goal.
type ListedModel ¶
type ListedModel struct {
ID string
Price *config.ModelPrice
}
ListedModel is one of them, with the price Blitz knows for it.
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
// 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 ¶
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) 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.
type Option ¶
type Option func(*Engine)
Option configures an Engine.
func WithAgentModel ¶
WithAgentModel runs agent on llm instead of the engine's model (a pin from [agent_models] or the agent's own default_model).
func WithHookModel ¶
WithHookModel makes llm the model of prompt hooks naming ref.
func WithInstructions ¶
WithInstructions appends text (e.g. project memory) to every agent's instructions.
func WithNotice ¶
WithNotice sets where the engine reports events the user should know about, such as a fallback model taking over (default: nowhere).
func WithProjectTrusted ¶
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_background_agents_032 BGA-50).
func WithReviewModel ¶
WithReviewModel makes llm the auto mode's reviewer ([permissions.auto] model); without it the session's model reviews.
func WithScopedRules ¶
WithScopedRules hands rules scoped to paths to agents as they touch matching files (see memory.Rule).
func WithSessionService ¶
WithSessionService replaces the default in-memory session store (e.g. with a persistent one so conversations can be resumed).
func WithStreaming ¶
WithStreaming makes Execute deliver partial text events as the model generates them (followed by the usual final events).
func WithTaskDone ¶
WithTaskDone calls f when a background task ends (the workspace records it in the session's transcript).
func WithTurnStore ¶
WithTurnStore chains turn spans per session through s.
func WithUsageStore ¶
func WithUsageStore(s UsageStore) Option
WithUsageStore keeps sessions' usage in s.
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_parity_027 PAR-MOD-03), or why they couldn't be listed.
func ListModels ¶
ListModels asks each provider (all configured ones when none are named) for its models, in parallel.
type QuotaError ¶
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.
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.
func NewUsageTracker ¶
func NewUsageTracker(pricing map[string]config.ModelPrice) *UsageTracker
NewUsageTracker creates a tracker with the given price table.
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.
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 ¶
func (t *UsageTracker) Record(session, model string, m *genai.GenerateContentResponseUsageMetadata) api.Usage
Record adds one model call's usage to session.
func (*UsageTracker) RecordSearch ¶
func (t *UsageTracker) RecordSearch(session string, queries int, costUSD float64)
RecordSearch adds web search queries, and what they cost, to session.
func (*UsageTracker) RecordSpeech ¶ added in v0.2.1
func (t *UsageTracker) RecordSpeech(session, model string, m *genai.GenerateContentResponseUsageMetadata)
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.
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.
Source Files
¶
- agentrun.go
- anthropic.go
- aside.go
- cloud.go
- compact.go
- contextparts.go
- embed.go
- engine.go
- fallback.go
- geminifiles.go
- httpclient.go
- images.go
- keycommand.go
- listmodels.go
- media.go
- model_factory.go
- openai_images.go
- outputcap.go
- plan.go
- quota.go
- review.go
- rules.go
- search.go
- settings.go
- signatures.go
- speech.go
- steer.go
- tasks.go
- unavailable.go
- usage.go