Documentation
¶
Overview ¶
Package chat is the chassis-owned `ai://chat` exec dispatch surface.
Like chassis/compute and chassis/egress, it is a thin registry: backends (OpenRouter, future OpenAI-direct, Anthropic-direct, local-vllm) self- register via init() in their subpackages; the chassis activates one with a blank import. Per-call selection is handled by Resolve.
**Boundary of trust.** The chassis owns three concerns that raw HTTP wouldn't enforce:
- Secret materialization. RequiredSecrets() declares which standardized names (OPENROUTER_KEY, OPENAI_KEY, …) a backend needs; the ExecAI handler materializes them through the same per-tenant store + audit counter every other op uses (with an optional env-var fallback gated by AIChatEnvFallback for developer-machine convenience).
- Cleartext containment. Cleartext rides only in the *secrets.SecretBag passed to Run; the bag panics on every standard encoder, so it cannot reach trace, log, mock, or continuation by construction.
- Fuel + trace. Chat ops pay the standard 25-fuel EXEC + 100-fuel per-secret charge — chassis-owned infrastructure cost. Token counts are recorded in the trace event and `_txc.chat.tokens` envelope metadata, NOT charged to fuel: tokens are provider compute, and conflating them with the chassis's per-request meter would distort the bound. USD-denominated cost reporting (deferred) sources from token counts × per-model pricing, not from fuel.
**Tools, without a loop.** A request may offer tool definitions (tools.go) and a response carries the calls the model made; a backend that takes them implements ToolCapable. The chassis never runs a call: the stack that made the request dispatches each one (`cap://`, usually) and sends the results back as `tool` messages on its next request. That keeps every call decided at the gateway, visible as its own step, and able to end a run (a hold). The dialect a backend speaks lives beside it (chat/openaicompat for the OpenAI-compatible endpoints).
**Still deliberately absent.** Capability-matched routing across several backends (Resolve is provider-override-or-first-registered); a sophisticated retry policy (one retry on 5xx + network); raw `{{!@field}}` template insertion (rejected with a clear error). Each belongs to its own focused change.
Index ¶
- Constants
- Variables
- func MakeStrict(schema json.RawMessage) (out json.RawMessage, wrapped []string, err error)
- func Qualifies(schema json.RawMessage) (ok bool, reason string)
- func Register(name string, c Constructor)
- func Registered() []string
- func Render(template string, envelope []byte, logger *zap.Logger) (string, error)
- func StripWrappedNulls(doc json.RawMessage, wrapped []string) json.RawMessage
- func ValidToolName(s string) bool
- func ValidateTools(tools []Tool) error
- type Backend
- type CodedError
- type Config
- type Constructor
- type DetailedError
- type InvalidWithError
- type Limits
- type Message
- type MissingSecretError
- type NoBackendError
- type ProviderHTTPError
- type ProviderNetError
- type ProviderParseError
- type Request
- type Response
- type SchemaFailedError
- type Tool
- type ToolCall
- type ToolCapable
- type ToolFeatures
- type ToolProblem
- type ToolRequestError
- type UnsupportedSubOpError
Constants ¶
const ( CodeMissingSecret = "txco_chat_missing_secret" CodeNoBackend = "txco_chat_no_backend" CodeInvalidWith = "txco_chat_invalid_with" CodeAuthFailed = "txco_chat_auth_failed" CodeProviderHTTP = "txco_chat_provider_http" CodeProviderNet = "txco_chat_provider_net" CodeProviderParse = "txco_chat_provider_parse" CodeSchemaFailed = "txco_chat_schema_failed" CodeUnsupportedSub = "txco_chat_unsupported_sub_op" // CodeUnknown is what an error without a code of its own reports. CodeUnknown = "txco_chat_unknown" // The tool-related codes are `txco_chat_<kind>` for the kinds in // tools.go: tool_invalid, tool_names, tools_unsupported, // strict_unsupported, pending_tool_result. CodeToolInvalid = "txco_chat_" + KindToolInvalid CodeToolNames = "txco_chat_" + KindToolNames CodeToolsUnsupported = "txco_chat_" + KindToolsUnsupported CodeStrictUnsupported = "txco_chat_" + KindStrictUnsupported CodePendingToolResult = "txco_chat_" + KindPendingToolResult )
Error codes surfaced to operators via response envelope's `chat.error` field and trace events. The `txco_chat_*` prefix mirrors the budget-exhaustion codes (`txco_fuel_exhausted`, `txcl_scope_ttl_exhausted`) so they all sort together in logs and dashboards.
const ( // ProblemNotOffered: the call names a tool this request did not offer. ProblemNotOffered = "not_offered" // ProblemNotJSON: the arguments are not a JSON object; Raw has them. ProblemNotJSON = "not_json" // ProblemTruncated: the answer hit the output limit, so the arguments // of every call in it may be cut off. ProblemTruncated = "truncated" // ProblemDuplicateID: the id repeats one earlier in the same answer. ProblemDuplicateID = "duplicate_id" )
The codes a ToolProblem carries.
const ( FinishStop = "stop" FinishLength = "length" FinishToolCalls = "tool_calls" FinishFiltered = "filtered" FinishOther = "other" )
How an answer ended, in the neutral vocabulary. A backend maps its provider's words onto these; an empty Finish means the provider said nothing.
const ( ToolChoiceAuto = "auto" ToolChoiceNone = "none" ToolChoiceRequired = "required" )
The tool_choice values a request may carry; any other value names one offered tool to force.
const ( StrictOff = "off" StrictPrefer = "prefer" StrictRequire = "require" )
The strict modes a request may carry.
const ( KindToolInvalid = "tool_invalid" KindToolNames = "tool_names" KindToolsUnsupported = "tools_unsupported" KindStrictUnsupported = "strict_unsupported" KindPendingToolResult = "pending_tool_result" )
The kinds of ToolRequestError; each is the suffix of its code.
Variables ¶
var ErrAuthFailed = &authFailedError{}
ErrAuthFailed is the sanitized auth-failed error returned by backends after a 401. The provider's body — which may quote a prefix of the submitted API key — is discarded BEFORE this error is constructed. Surfaced to operators as a fixed generic; the real diagnosis happens from the trace event's `retries` and `latency_ms` fields plus the inbound `_txc.chat.error` projection.
var ErrNotStrict = errors.New("schema does not qualify for strict decoding")
ErrNotStrict is wrapped by Qualifies's reason when a schema cannot be decoded strictly.
var ToolNameRE = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
ToolNameRE is the grammar of a tool's name: what OpenAI and Anthropic both accept.
Functions ¶
func MakeStrict ¶ added in v0.2.59
func MakeStrict(schema json.RawMessage) (out json.RawMessage, wrapped []string, err error)
MakeStrict rewrites a qualifying schema into the strict form: every property required, each optional one wrapped as `anyOf: [<schema>, {type: null}]`, `additionalProperties: false` on every object, applied through nested objects and array items. `default` and `description` stay as annotations. wrapped lists the instance pointers of the fields made nullable, for StripWrappedNulls.
func Qualifies ¶ added in v0.2.59
func Qualifies(schema json.RawMessage) (ok bool, reason string)
Qualifies reports whether schema can be sent for strict decoding: an object schema whose every property is typed, with no open additionalProperties, no optional property that already allows null (its absence could not be told from a null), no references and no keywords the strict grammar refuses. The reason says which rule failed.
func Register ¶
func Register(name string, c Constructor)
Register adds a backend constructor. Called from a backend package's init(); the chassis activates a backend with a blank import.
Re-registering an existing name overwrites the constructor (test support); the registration order is preserved on first-registration only, so a re-registered backend keeps its original priority slot.
func Registered ¶
func Registered() []string
Registered returns the names of currently registered backends, sorted for deterministic display. Used by error messages and observability.
func Render ¶
Render substitutes `{{@field.path}}` markers in template with values from the envelope. The `@`-prefix follows the **chassis-wide txcl convention**: it addresses paths under the envelope's `_txc.*` namespace, matching what `WHEN @path`, `SET @path = ...`, and `EMIT @path = ...` already do (the txcl parser rewrites `@x.y` to `_txc.x.y` at parse time — see chassis/txcl/parser/parser.go:216,234). So `{{@web.req.body}}` reads `_txc.web.req.body`. For a scratch value the author supplies (e.g. `{{@body_text}}` -> `_txc.body_text`), set it with `SET PRE @body_text = …`: SET PRE decorates only this op's input, so the template sees it but it never propagates to the next scope. Note `_txc.*` is the chassis control namespace — reserved fields (tenant, computed.*, budget, …) are NOT author-writable on the propagating envelope (see chassis/processor authorMayWriteTxc); the op-local SET PRE scratch above is exempt because it doesn't merge.
The substitution is JSON-escaped by default: string values are JSON-string-escaped with the outer quotes stripped, so they splice safely into the surrounding prompt context (no terminator breaks; no injection of quotes or backslashes that would mangle the prompt). Non-string values (objects, numbers, arrays, booleans, nulls) are marshaled to compact JSON.
Unknown paths render as the empty string and emit one debug log per occurrence (prompts tolerate missing data gracefully — erroring would turn every type-ahead-incomplete envelope into a request failure). Logger may be nil.
The verbatim opt-out form `{{!@path}}` is **intentionally rejected** in v1: any template containing it returns InvalidWithError. Trusted- fields-only insertion is the kind of escalation that wants its own review, and silently accepting it without escaping would be the wrong failure mode when the feature lands. Failing loud here means authors using the syntax today get a clear error, not the wrong escaping.
Prompt-injection caveat: the chassis cannot tell trusted from hostile input. The escaping makes hostile JSON inside a string value safe against trivial prompt-context breaks; it does NOT defend against an adversary who tells the model to ignore prior instructions. Fence- and-instruct is the recommended pattern; v2 may add a sanitize knob.
func StripWrappedNulls ¶ added in v0.2.59
func StripWrappedNulls(doc json.RawMessage, wrapped []string) json.RawMessage
StripWrappedNulls removes, from doc, a null at each wrapped pointer, and nothing else: a null a declaration allowed stays. A pointer segment `-` means every element of the array there. doc comes back unchanged when it is not valid JSON.
func ValidToolName ¶ added in v0.2.59
ValidToolName reports whether s may name a tool.
func ValidateTools ¶ added in v0.2.59
ValidateTools checks a request's definitions: a legal name, parameters that are an object schema and compile, a binding that is an object when present, and no two definitions with one name. The error is a *ToolRequestError of kind tool_invalid or tool_names.
Types ¶
type Backend ¶
type Backend interface {
// Name returns the registered name (must match the Register key).
Name() string
// Capabilities returns descriptive labels recorded on the trace event
// for observability. v1 does NOT match against these for routing;
// capability-superset selection across multiple backends is its own
// follow-up PR.
Capabilities() []string
// RequiredSecrets are the standardized secret names this backend
// needs to function. ExecAI materializes them automatically from the
// per-tenant secret store at backend-selection time (with optional
// env-var fallback) and passes the cleartext via the SecretBag.
// E.g., the OpenRouter backend returns []string{"OPENROUTER_KEY"};
// a self-hosted backend that needs URL + auth might return both.
RequiredSecrets() []string
// Run executes one chat completion. The secrets bag carries
// cleartext for every name in RequiredSecrets(); the implementation
// reads via bag.Get(name) and uses the cleartext only in local
// variables — never on the Backend struct, never on context, never
// in trace fields, never in logs. See the package godoc for the
// five leak-prevention guards.
Run(ctx context.Context, req Request, bag *secrets.SecretBag) (Response, error)
}
Backend is the chassis-facing interface every chat backend implements.
Lifecycle: backends are registered by name via Register() in an init(); the chassis Opens one at startup per Config; the resolved Backend is then long-lived across requests (Run is called once per ai://chat EXEC).
Run must be safe for concurrent use — the chassis dispatches multiple chat ops in parallel when WHEN/EMIT fan-out hits the same backend.
func Open ¶
Open constructs the named backend. Unknown name is an error listing what is available; a backend may also return an error for invalid config so misconfiguration fails loudly at boot.
func Resolve ¶
Resolve picks a backend for one ai://chat dispatch. v1 logic is intentionally minimal:
- providerHint non-empty → look up by name in the registry; error with NoBackendError if unknown. Trace records routing_decision = "provider-override".
- providerHint empty → return the first-registered backend; trace records routing_decision = "default". With a single v1 backend (OpenRouter), this is unambiguous.
Capability-superset matching across multiple registered backends is its own design exercise (ordering, ties, no-match fallback semantics) and lands alongside the second backend in a follow-up PR. Backend.Capabilities() is still captured in the trace today as descriptive metadata.
type CodedError ¶
CodedError lets callers extract a stable `txco_chat_*` code from any chat-package error without a type switch over every variant.
type Config ¶
type Config struct {
// HTTPClient is the chassis-owned http.Client (constructed in
// processor.New with egress.DialControl + otelhttp wrapping). Every
// outbound HTTPS call from a backend MUST use this client so the
// configured egress Guard applies. Backends never construct their
// own transport.
HTTPClient *http.Client
}
Config carries chat-package construction options resolved from chassis config. Backends extend it with their own fields without breaking existing callers (same convention as compute.EngineConfig and egress.Config).
type Constructor ¶
Constructor builds a Backend from resolved config.
type DetailedError ¶ added in v0.2.59
DetailedError is the optional interface an error implements to add a `detail` object beside `code` and `message` in `chat.error`. Errors that do not implement it keep the two-key shape they have today.
type InvalidWithError ¶
type InvalidWithError struct {
Reason string `json:"reason"`
Detail map[string]string `json:"detail,omitempty"`
}
InvalidWithError signals a malformed WITH clause set (e.g. both `prompt` and `messages` were supplied, or neither). Reason is operator-facing English; Detail is structured for trace.
func (*InvalidWithError) AsJSON ¶
func (e *InvalidWithError) AsJSON() string
func (*InvalidWithError) Code ¶
func (e *InvalidWithError) Code() string
func (*InvalidWithError) Error ¶
func (e *InvalidWithError) Error() string
type Limits ¶
type Limits struct {
TimeoutMs int `json:"timeout_ms,omitempty"`
MaxCostUSD float64 `json:"max_cost_usd,omitempty"`
}
Limits caps per-call work. Zero values mean "backend default."
type Message ¶
type Message struct {
Role string `json:"role"` // "system" | "user" | "assistant" | "tool"
Content string `json:"content"`
Name string `json:"name,omitempty"`
// ToolCalls are the calls an assistant turn made.
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
// ToolCallID, on a tool turn, names the call this message answers.
ToolCallID string `json:"tool_call_id,omitempty"`
// IsError, on a tool turn, marks a failed call. Providers with an error
// flag receive it; the rest receive the content alone, which should
// then say what failed.
IsError bool `json:"is_error,omitempty"`
}
Message is one turn in the conversation, in the chassis's neutral shape. A backend translates it to its provider's wire form; the JSON tags here are what a rule writes in `WITH messages` and what the envelope's `message` carries back. Content is always a string: see UnmarshalJSON (message.go) for what a tool message may carry.
func (*Message) UnmarshalJSON ¶ added in v0.2.59
UnmarshalJSON decodes a message as the struct's tags say, with two allowances for what a transcript carries:
- `"content": null` decodes as "" for every role, as it did before (an assistant turn that only calls tools has null content).
- On a `tool` message, `content` may be any JSON value: an executor hands a capability's answer back as it came. An object or array is stored compacted, so Content stays a string.
On any other role a non-string content is still an error, so a user message of content parts is refused as it was.
type MissingSecretError ¶
MissingSecretError signals one of the backend's RequiredSecrets() could not be found in either the per-tenant store or (when enabled) the chassis-wide env-var fallback. Names are the secret NAME and the backend NAME — never any cleartext.
func (*MissingSecretError) AsJSON ¶
func (e *MissingSecretError) AsJSON() string
func (*MissingSecretError) Code ¶
func (e *MissingSecretError) Code() string
func (*MissingSecretError) Error ¶
func (e *MissingSecretError) Error() string
type NoBackendError ¶
type NoBackendError struct {
ProviderHint string `json:"provider_hint,omitempty"`
Registered []string `json:"registered"`
}
NoBackendError signals no backend matches the requested provider hint. Lists the registered backends so the operator can diagnose typos / missed blank imports.
func (*NoBackendError) AsJSON ¶
func (e *NoBackendError) AsJSON() string
func (*NoBackendError) Code ¶
func (e *NoBackendError) Code() string
func (*NoBackendError) Error ¶
func (e *NoBackendError) Error() string
type ProviderHTTPError ¶
type ProviderHTTPError struct {
StatusCode int `json:"status_code"`
Body string `json:"body,omitempty"`
}
ProviderHTTPError signals a non-401 HTTP error from the provider. Body is the (potentially-sanitized) response body for diagnosis.
func (*ProviderHTTPError) AsJSON ¶
func (e *ProviderHTTPError) AsJSON() string
func (*ProviderHTTPError) Code ¶
func (e *ProviderHTTPError) Code() string
func (*ProviderHTTPError) Error ¶
func (e *ProviderHTTPError) Error() string
type ProviderNetError ¶
type ProviderNetError struct {
Reason string `json:"reason"`
}
ProviderNetError signals a network / DNS / timeout failure reaching the provider.
func (*ProviderNetError) AsJSON ¶
func (e *ProviderNetError) AsJSON() string
func (*ProviderNetError) Code ¶
func (e *ProviderNetError) Code() string
func (*ProviderNetError) Error ¶
func (e *ProviderNetError) Error() string
type ProviderParseError ¶
type ProviderParseError struct {
Reason string `json:"reason"`
BodyLen int `json:"body_len"` // 0 = empty body; positive = malformed
}
ProviderParseError signals the provider returned a 2xx with a body the backend could not decode (malformed JSON, empty body, missing required fields). Seen most often when a `:free`-tier provider hits a quota and returns an empty 200 instead of a clean 429 — upstream flake the chassis can't repair, but should surface with a specific code so rule authors can WHEN-handle (e.g., fall back to a paid model on @chat.error.code == "txco_chat_provider_parse").
func (*ProviderParseError) AsJSON ¶
func (e *ProviderParseError) AsJSON() string
func (*ProviderParseError) Code ¶
func (e *ProviderParseError) Code() string
func (*ProviderParseError) Error ¶
func (e *ProviderParseError) Error() string
type Request ¶
type Request struct {
// Messages is the conversation. Either authored by hand via
// WITH messages = [...], or built by the handler from
// WITH system = "..." + WITH prompt = "..." after template render.
Messages []Message `json:"messages"`
// Schema, when non-nil, triggers structured-output mode. The handler
// validates the model's response against this schema after the call;
// failure populates `chat.error` in the response envelope. Repair
// semantics (distinguishing "ok" / "repaired" / "failed") is deferred
// to a follow-up; v1 is binary ok-or-failed.
Schema json.RawMessage `json:"schema,omitempty"`
// Model is the resolved model identifier handed to the provider.
// v1: WITH model = "..." is passed through verbatim; if unset, the
// backend picks its default.
Model string `json:"model,omitempty"`
// Limits scopes the per-call work the backend is allowed to do.
Limits Limits `json:"limits"`
// Intent is a trace-only label authors can stamp for diagnosability
// (e.g. "classify_support_ticket"). Not sent on the wire.
Intent string `json:"intent,omitempty"`
// CacheKey, when set, is handed to providers that take a prompt cache
// key (OpenAI's `prompt_cache_key`), so calls from one run that share
// a prefix land in the same provider-side cache. Optional; a backend
// whose provider has no such field ignores it. Never read by the
// chassis itself.
CacheKey string `json:"cache_key,omitempty"`
// Tools are the definitions the model is offered (tools.go). Empty
// means a plain chat call, whose wire body is unchanged from before
// tools existed. A backend that does not implement ToolCapable is
// refused a request with tools before anything is sent.
Tools []Tool `json:"tools,omitempty"`
// ToolChoice is "auto" (the default when tools are offered), "none",
// "required", or the name of one offered tool to force. Ignored
// without Tools.
ToolChoice string `json:"tool_choice,omitempty"`
// Parallel, when set, asks the model for several calls per answer
// (true) or at most one (false). Nil leaves it to the model.
Parallel *bool `json:"parallel,omitempty"`
// Strict is "off" (the default), "prefer" or "require": whether the
// provider should decode tool arguments (and a schema answer) with
// its strict grammar. "prefer" falls back to ordinary decoding where
// strict cannot be honoured; "require" refuses the request instead.
Strict string `json:"strict,omitempty"`
}
Request is the chassis-normalized chat completion request. The handler decodes op.Meta (WITH-clause materialization) into this shape and the backend translates to its on-wire format (OpenAI-compatible for the v1 backend).
type Response ¶
type Response struct {
// Text is the assistant's message content; empty when the answer is
// tool calls alone.
Text string `json:"text"`
// ToolCalls are the calls the model made, in the neutral shape, with
// Arguments or Raw filled by the backend. Problem and Binding are the
// handler's to set. Empty on a plain answer.
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
// Finish says how the answer ended (FinishStop, FinishToolCalls, ...),
// or "" when the provider did not say.
Finish string `json:"finish,omitempty"`
// ResponseID is the provider's id for the response, when it gave one.
ResponseID string `json:"response_id,omitempty"`
// SchemaMode says how a schema call was sent, when the backend reports
// it: "json_schema" (the provider decoded strictly against the schema)
// or "json_object" (JSON mode: well-formed JSON, the schema checked by
// the chassis). Empty when no schema was sent, or the backend does not
// say.
SchemaMode string `json:"schema_mode,omitempty"`
// SchemaValidated, when non-nil, is the schema-validated payload
// (Text parsed as JSON against Request.Schema). Present when
// Request.Schema was set AND validation succeeded.
SchemaValidated json.RawMessage `json:"schema_validated_payload,omitempty"`
// Provider, Model are observability fields surfaced in the trace
// event and the response envelope.
Provider string `json:"provider"`
Model string `json:"model"`
// TokensIn, TokensOut are reported by the provider. Recorded in
// trace + `_txc.chat.tokens` metadata; NEVER charged to the chassis
// fuel meter (provider compute is a separate dimension; see the
// package godoc).
TokensIn int64 `json:"tokens_in"`
TokensOut int64 `json:"tokens_out"`
// TokensCached is the part of TokensIn the provider served from its
// prefix cache; TokensReasoning is the part of TokensOut a reasoning
// model spent thinking before it answered. Both are observability
// only, zero when the provider does not report them, and NEVER
// charged to the chassis fuel meter (same rationale as TokensIn /
// TokensOut).
TokensCached int64 `json:"tokens_cached"`
TokensReasoning int64 `json:"tokens_reasoning"`
// LatencyMS is wall-clock from request build to response parse.
LatencyMS int64 `json:"latency_ms"`
// Retries is the count of provider retries the backend performed
// (0 if the first attempt succeeded).
Retries int `json:"retries"`
}
Response is the chassis-normalized chat completion result. Backends translate the provider's on-wire shape into this struct.
type SchemaFailedError ¶
type SchemaFailedError struct {
Reason string `json:"reason"`
}
SchemaFailedError signals the model's response failed JSON-schema validation. The request still completes (the raw text is preserved in the envelope); rule authors handle via `WHEN @chat.error EXEC ...`.
func (*SchemaFailedError) AsJSON ¶
func (e *SchemaFailedError) AsJSON() string
func (*SchemaFailedError) Code ¶
func (e *SchemaFailedError) Code() string
func (*SchemaFailedError) Error ¶
func (e *SchemaFailedError) Error() string
type Tool ¶ added in v0.2.59
type Tool struct {
// Name is what the model calls. It must already be legal on every
// provider this dialect family serves: letters, digits, `_` and `-`, at
// most 64. The chassis refuses any other name rather than mapping it;
// the catalogue derives a legal one (`web.search` → `web_search`).
Name string `json:"name"`
// Description is what the model reads to decide whether to call.
Description string `json:"description,omitempty"`
// Parameters is the JSON Schema of the arguments: an object schema.
Parameters json.RawMessage `json:"parameters"`
// Binding is the executor's own note of how to run a call to this tool
// (`{capability, input, arguments_into}` in OnePony's use). The chassis
// never reads it and never sends it to a provider; it copies it onto
// each returned call to the matching offered tool, so one dispatch rule
// needs no lookup. It is request metadata, never model output.
Binding json.RawMessage `json:"binding,omitempty"`
}
Tool is one model-facing tool definition: what a model is offered, in the chassis's neutral shape. A backend translates it to its provider's wire form; the handler reads Name, Description and Parameters and carries Binding through untouched.
Where definitions come from is not this package's concern: the catalogue derives one from a capability's declaration (`txco://caps/list WITH format = "tools"`), an executor writes one for a tool it discovered elsewhere (an MCP server's, an OpenAPI operation). `ai://chat` never resolves a name against the catalogue: a string where a definition belongs is an error.
type ToolCall ¶ added in v0.2.59
type ToolCall struct {
// ID is the provider's id for the call; a result refers to it.
ID string `json:"id"`
// Name is the tool's name as offered (never a provider's wire name).
Name string `json:"name"`
// Arguments is the call's arguments when they parsed as a JSON object,
// else null (and Raw holds what the model wrote). Never omitted, so an
// executor can test it.
Arguments json.RawMessage `json:"arguments"`
// Raw is the model's argument text when Arguments could not be parsed
// as an object, kept so the transcript can be sent back as it was.
Raw string `json:"raw,omitempty"`
// Problem is set by the handler when the call's transport shape is
// wrong: not_offered, not_json, truncated or duplicate_id. A call with
// a problem must not run.
Problem *ToolProblem `json:"problem,omitempty"`
// Binding is copied by the handler from the offered Tool of the same
// request whose Name matches. Anything a provider returned under this
// key was dropped at the wire.
Binding json.RawMessage `json:"binding,omitempty"`
}
ToolCall is one call a model made, in the neutral shape.
type ToolCapable ¶ added in v0.2.59
type ToolCapable interface {
ToolFeatures() ToolFeatures
}
ToolCapable is the optional interface a backend implements to take tools. It is checked by type assertion, so a backend that does not implement it (a test double, an older backend) keeps compiling and is simply refused a request with tools.
type ToolFeatures ¶ added in v0.2.59
ToolFeatures are the fixed facts a backend states about tool calling: whether it takes tools at all, whether it can control parallel calls, whether it can decode strictly. Fixed per backend, not per model: the chassis translates what a backend guarantees and refuses the rest.
type ToolProblem ¶ added in v0.2.59
ToolProblem says why a returned call cannot run as it is.
type ToolRequestError ¶ added in v0.2.59
ToolRequestError is every tool-related refusal of a chat request. Its code is `txco_chat_<Kind>`. IDs, when set, name the tool calls the refusal is about (the unanswered ones of a pending_tool_result) and are surfaced as `chat.error.detail.ids`.
func (*ToolRequestError) AsJSON ¶ added in v0.2.59
func (e *ToolRequestError) AsJSON() string
func (*ToolRequestError) Code ¶ added in v0.2.59
func (e *ToolRequestError) Code() string
func (*ToolRequestError) Error ¶ added in v0.2.59
func (e *ToolRequestError) Error() string
func (*ToolRequestError) ErrorDetail ¶ added in v0.2.59
func (e *ToolRequestError) ErrorDetail() map[string]any
ErrorDetail is what `chat.error.detail` carries: the ids, when any.
type UnsupportedSubOpError ¶
type UnsupportedSubOpError struct {
SubOp string `json:"sub_op"`
}
UnsupportedSubOpError signals an ai://<op> the chassis doesn't dispatch in v1 (only "chat" is wired). Returned by ExecAI before backend selection.
func (*UnsupportedSubOpError) AsJSON ¶
func (e *UnsupportedSubOpError) AsJSON() string
func (*UnsupportedSubOpError) Code ¶
func (e *UnsupportedSubOpError) Code() string
func (*UnsupportedSubOpError) Error ¶
func (e *UnsupportedSubOpError) Error() string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package openai is a native OpenAI-direct ai://chat backend.
|
Package openai is a native OpenAI-direct ai://chat backend. |
|
Package openaicompat is the OpenAI Chat Completions dialect of the chassis's chat request: how a chat.Request becomes the JSON body every OpenAI-compatible endpoint accepts, and how such an endpoint's answer becomes a chat.Response.
|
Package openaicompat is the OpenAI Chat Completions dialect of the chassis's chat request: how a chat.Request becomes the JSON body every OpenAI-compatible endpoint accepts, and how such an endpoint's answer becomes a chat.Response. |
|
Package openrouter is the v1 ai://chat backend.
|
Package openrouter is the v1 ai://chat backend. |