models

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 34 Imported by: 0 modules, 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 models is kōjō's model gateway client. Every model call of the factory goes through a Gateway, which maps a tier (fast, strong) to a concrete model, falls back to the tier's alternatives, rate-limits, and prices each call. The gateway is built on Genkit Go and runs embedded in the kōjō process, calling providers directly, or in front of an external OpenAI-compatible gateway such as hikyaku.

Index

Constants

View Source
const (
	RoleUser  = "user"
	RoleModel = "model"
	RoleTool  = "tool"
)

Roles of a message.

Variables

View Source
var ErrNoEmbedder = errors.New("models: no embedder configured")

ErrNoEmbedder is returned by Embed when no embedder is configured. Team memory then searches by full text.

Functions

func Cost

func Cost(p *config.Price, tokensIn, tokensOut int64) float64

Cost prices a call with the tier's configured price. Without one it is 0.

Types

type Gateway

type Gateway interface {
	// Generate runs one model turn. Tool calls are returned, not executed:
	// the caller runs them and records each as a step.
	Generate(ctx context.Context, req Request) (*Response, error)
	// Embed returns one vector per text.
	Embed(ctx context.Context, texts []string) ([][]float32, error)
	// Check verifies a tier's model answers. It is what kojo doctor runs.
	Check(ctx context.Context, settings config.ModelSettings, tier string) error
	// CheckProviders verifies, for each provider that a tier, a fallback
	// or the embedder uses, or that kojo.yaml configures, that its
	// credentials resolve and that one of its models answers. Only the
	// embedded gateway has providers: the others return nothing.
	CheckProviders(ctx context.Context, settings config.ModelSettings) []ProviderCheck
	// Mode describes the gateway for doctor: "embedded", "replay", or the
	// external gateway's URL.
	Mode() string
}

Gateway is the model gateway.

func New

func New(ctx context.Context, o Options) (gw Gateway, err error)

New builds the gateway from the deployment config.

With models.recordings set (or the mock provider) it replays recorded responses and needs no network or keys; KOJO_LIVE_MODELS=1 switches a recordings setup to the real providers. With KOJO_RECORD=1 on top, live responses are written to the recordings directory.

type Message

type Message struct {
	Role string `json:"role"`
	Text string `json:"text,omitempty"`
	// ToolCalls are the tools a model message asks for.
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	// ToolResults are the answers of a tool message.
	ToolResults []ToolResult `json:"tool_results,omitempty"`
	// Raw is the provider's own form of a model message. Some providers
	// attach data to a turn (reasoning signatures) that must be sent back
	// unchanged; Raw keeps it across checkpoints.
	Raw json.RawMessage `json:"raw,omitempty"`
}

Message is one turn of a conversation. It is what session checkpoints store, so it is plain JSON.

func UserText

func UserText(text string) Message

UserText builds a user message.

type Options

type Options struct {
	Config config.Models
	Logger *slog.Logger
	// Getenv reads the environment. Default os.Getenv.
	Getenv func(string) string
	// contains filtered or unexported fields
}

Options configure New.

type ProviderCheck added in v0.2.0

type ProviderCheck struct {
	Provider string
	// Used is false for a provider kojo.yaml configures and nothing uses.
	Used bool
	// Detail says where the credentials came from and which model
	// answered. It never holds a credential.
	Detail string
	Err    error
}

ProviderCheck is the result of checking one provider.

type RecordedCall

type RecordedCall struct {
	Name  string         `yaml:"name" json:"name"`
	Input map[string]any `yaml:"input,omitempty" json:"input,omitempty"`
}

RecordedCall is a recorded tool call.

type Recording

type Recording struct {
	// Purpose is orchestrator, subagent:<skill>, judge:<skill>, risk or
	// doctor. A trailing * matches any suffix: "judge:*".
	Purpose string `yaml:"purpose" json:"purpose"`
	// Match must be contained in the system prompt or the user messages.
	Match string `yaml:"match,omitempty" json:"match,omitempty"`
	Turns []Turn `yaml:"turns" json:"turns"`
	// RepeatLast answers with the last turn once the turns are used up,
	// instead of failing.
	RepeatLast bool `yaml:"repeat_last,omitempty" json:"repeat_last,omitempty"`
}

Recording is a scripted conversation the mock provider replays: the dev stacks, the end-to-end tests and the skill evals in CI run on these, with no network and no keys.

A recording is chosen by Purpose (who is calling) and, when set, Match (a substring of the prompt). The reply to give is the turn whose index equals the number of model messages already in the conversation, so replay is stateless: a session resumed from a checkpoint gets the same answers.

func LoadRecordings

func LoadRecordings(dir string) ([]Recording, error)

LoadRecordings reads every .yaml file of dir (recursively). Each file is a list of recordings.

type Request

type Request struct {
	// Tier names the tier; Settings resolve it. A session passes the
	// settings of its own config snapshot, so a tier change in the dashboard
	// applies to new sessions only.
	Tier     string
	Settings config.ModelSettings
	System   string
	Messages []Message
	Tools    []ToolDef
	// Schema asks for a JSON object of this shape as the answer.
	Schema map[string]any
	// Purpose says who is calling: orchestrator, subagent:<skill>,
	// judge:<skill>, risk. The mock provider picks recordings by it.
	Purpose   string
	SessionID string
}

Request is one model call.

type Response

type Response struct {
	Message Message
	// Model is the provider/model that answered (a fallback, possibly).
	Model     string
	TokensIn  int64
	TokensOut int64
	CostUSD   float64
}

Response is what the model answered.

type ToolCall

type ToolCall struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

ToolCall is a model asking for a tool.

type ToolDef

type ToolDef struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Schema      map[string]any `json:"schema"`
}

ToolDef describes a tool to the model.

type ToolResult

type ToolResult struct {
	ID     string          `json:"id"`
	Name   string          `json:"name"`
	Output json.RawMessage `json:"output"`
}

ToolResult answers a ToolCall.

type Turn

type Turn struct {
	Text      string         `yaml:"text,omitempty" json:"text,omitempty"`
	ToolCalls []RecordedCall `yaml:"tool_calls,omitempty" json:"tool_calls,omitempty"`
	// JSON is a structured answer (a judge's verdict).
	JSON      any   `yaml:"json,omitempty" json:"json,omitempty"`
	TokensIn  int64 `yaml:"tokens_in,omitempty" json:"tokens_in,omitempty"`
	TokensOut int64 `yaml:"tokens_out,omitempty" json:"tokens_out,omitempty"`
}

Turn is one recorded model reply.

Directories

Path Synopsis
Package modelstest fakes the HTTP APIs of the cloud model providers the embedded gateway calls: Azure OpenAI's v1 API, Amazon Bedrock's Converse and InvokeModel, and Vertex AI's generateContent with a Google OAuth token endpoint.
Package modelstest fakes the HTTP APIs of the cloud model providers the embedded gateway calls: Azure OpenAI's v1 API, Amazon Bedrock's Converse and InvokeModel, and Vertex AI's generateContent with a Google OAuth token endpoint.

Jump to

Keyboard shortcuts

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