AI Integration
The AI Module provides LLM text generation, Pydantic structured output validation, autonomous multi-turn agent execution, tool-calling pipelines with row-level security (RLS), and human-in-the-loop approval workflows powered by pydantic-ai.
Kirak currently launches with an initial set of first-class model providers (OpenAI, Anthropic Claude, Google Gemini, Ollama), with support for new foundation models, inference runtimes, and local LLM engines continuously expanding across Kirak and the community ecosystem. Any provider supported by pydantic-ai (Groq, Mistral, OpenRouter, Cohere) can be plugged in immediately.
Installation & Provider Extras
Section titled “Installation & Provider Extras”Install provider SDKs via Kirak extras:
pip install "kirak[ai-openai]" # OpenAI GPT models (GPT-4o, o3-mini)pip install "kirak[ai-anthropic]" # Anthropic Claude models (Claude 3.5 Sonnet, Haiku)pip install "kirak[ai-google]" # Google Gemini models (Gemini 2.0 / 2.5)pip install "kirak[all-ai]" # All first-class provider SDKspip install "kirak[ai]" # Core pydantic-ai only (bring your own provider SDK)Other Supported Providers: Any provider supported by
pydantic-ai(Groq, Mistral, OpenRouter, Ollama) can be used by pairingkirak[ai]withpydantic-ai-slim[<provider>](e.g.pip install "kirak[ai]" "pydantic-ai-slim[groq]").
Enable the module in kirak.json:
{ "modules": ["ai"], "ai": { "default_model": "openai:gpt-4o-mini", "request_timeout_seconds": 60, "compaction_token_threshold": 150000 }}Set the provider API key in your environment using the provider’s standard environment variable:
OPENAI_API_KEY=sk-...ANTHROPIC_API_KEY=sk-ant-...GOOGLE_API_KEY=AIza...All `ai` Settings & Model Providers
ai key |
Type | Description |
|---|---|---|
default_model |
string | “provider:model” used when an agent or call names no model. |
conversation_ttl_seconds |
integer | Seconds a saved agent conversation is kept. Default 3600. |
compaction_token_threshold |
integer or null | Token count at which a long conversation is compacted. null turns compaction off. Default 150000. |
request_timeout_seconds |
integer | Read timeout in seconds for each model-provider call. A hung provider fails after this instead of hanging. Default 60. |
model_prices |
object | Prices in USD per 1M tokens, by model string, for models genai-prices does not price (e.g. models on Amazon Bedrock’s OpenAI-compatible endpoint). Used for a run’s cost and an agent’s max_budget_usd; a price here wins over genai-prices’. Not needed for models genai-prices lists. |
Provider outages. When a model provider answers a 5xx (overloaded, such as Gemini’s 503 “high demand” or Anthropic’s 529) or drops the connection, Kirak sends that one request again after 2, 5, 10 and 25 seconds before the call fails. Only the failed request is repeated, so tools already called in the run do not run again; a streamed response is retried only before its first event. A 4xx (bad request, key, quota, rate limit) and a timeout are not retried.
| Provider | Model prefixes | Install | API key variable |
|---|---|---|---|
| openai | openai:, openai-responses: |
pip install "kirak[ai-openai]" |
OPENAI_API_KEY |
| anthropic | anthropic: |
pip install "kirak[ai-anthropic]" |
ANTHROPIC_API_KEY |
google-gla:, google: |
pip install "kirak[ai-google]" |
GOOGLE_API_KEY, GEMINI_API_KEY |
Autonomous Agent Execution & Human-in-the-Loop Pipeline
Section titled “Autonomous Agent Execution & Human-in-the-Loop Pipeline”The following sequence details how Kirak coordinates agent execution, enforces tool access permissions, handles human approvals for sensitive actions, and manages conversation history:
sequenceDiagram autonumber actor User as User / Client participant API as Kirak AI Module participant Store as Session Store (Redis / DB) participant LLM as Provider LLM (OpenAI / Claude / Gemini) participant Engine as Kirak Engine (CRUD / Tools)
User->>API: POST /ai/agents/support/run {prompt: "Refund order #1234"} API->>Store: Load conversation history & check owner API->>API: Enforce token compaction if > compaction_token_threshold API->>LLM: Send system prompt, history, and tool declarations
LLM-->>API: Tool Call: refund_order(order_id="1234", amount=49.99) API->>API: Inspect tool: requires_confirmation = true?
alt Tool Requires Confirmation (Human-in-the-Loop) API->>Store: Persist state with HMAC signature; issue approval_id API-->>User: 200 OK {status: "approval_required", approval_id: "uuid"} Note over User,API: User inspects pending tool call & signs off User->>API: POST /ai/agents/support/resume {approval_id: "uuid", approved: true} API->>API: Verify caller identity & claim approval atomically end
API->>Engine: Dispatch tool call with ambient caller identity (RLS applied) Engine-->>API: Tool Result: {refund_id: "ref_987", status: "completed"}
API->>LLM: Return tool output to model LLM-->>API: Final synthesis: "Order #1234 has been refunded." API->>Store: Update conversation history API-->>User: 200 OK {output: "...", trace: [...], usage: {...}}One-Shot Prompting (kirak.ai.prompt)
Section titled “One-Shot Prompting (kirak.ai.prompt)”For stateless, single-turn LLM generation without tools or conversation memory:
result = await kirak.ai.prompt({ "prompt": "Summarize the key differences between ACID and BASE in two sentences.", "model": "anthropic:claude-3-5-haiku-latest", # Optional: overrides default_model "temperature": 0.2, "max_tokens": 150,})
summary = result["data"]["output"]Structured Output with Pydantic
Section titled “Structured Output with Pydantic”Pass an output_schema to enforce typed JSON extraction:
from pydantic import BaseModel, Field
class SentimentAnalysis(BaseModel): sentiment: str = Field(description="'positive', 'negative', or 'neutral'") score: float = Field(description="Confidence between 0.0 and 1.0")
result = await kirak.ai.prompt({ "prompt": "I love the speedy delivery, but the packaging was damaged.", "output_schema": SentimentAnalysis,})
# result["data"]["output"] is a validated dictionary matching SentimentAnalysis:# {"sentiment": "mixed", "score": 0.85}Declarative Agents (agents/*.json)
Section titled “Declarative Agents (agents/*.json)”Production agents are declared as JSON files in the project’s agents/ directory. At application startup Kirak checks each file, and fails startup when a file is invalid or an agent’s provider key is not set (for example google: models need GOOGLE_API_KEY or GEMINI_API_KEY). Each agent is built on its first use, so a model’s provider is contacted only when that agent runs. Kirak generates tools and mounts REST endpoints.
agents/customer-support.json:
{ "$schema": "../.kirak/agent.schema.json", "name": "customer-support", "description": "Assists customers with order lookups and updates", "model": "anthropic:claude-3-5-haiku-latest", "access": "User", "max_budget_usd": 0.10, "max_turns": 8, "instructions": "You are a customer support agent. Always verify order status before proposing actions.", "tools": { "orders_fetch": { "operation": "orders.fetch", "description": "Fetch customer orders" }, "orders_cancel": { "operation": "orders.update", "description": "Cancel an order", "requires_confirmation": true } }}thinking sets the reasoning effort of thinking models: true (the provider’s default effort), false (off; models that always think ignore it), or "minimal", "low", "medium", "high", "xhigh", mapped to the closest level the model supports (Gemini thinking levels, Anthropic thinking budgets, OpenAI reasoning effort). Without it the provider’s default applies. Thinking tokens are billed as output, and a run’s usage reports them as thinking_tokens and thinking_cost_usd, so a lower effort is the first thing to try on an agent whose task is routine.
An agent on an anthropic: model asks Anthropic to cache its prompt: from the second request of a run, the instructions, tools and history already sent are read from the cache at a tenth of the input price (writing them costs 1.25 times the input price), and usage reports them as cached_input_tokens. Gemini and OpenAI cache on their own.
fallback_model (a "provider:name" string, usually another provider’s) answers a request that model fails: after one retry 2 seconds later for a 5xx or a dropped connection (without a fallback, model is retried for about 40 seconds), and at once for any other provider error, such as a quota or a bad key. The fallback itself is retried for the full 40 seconds. Only that request goes to the fallback; the run continues from it, and the next request tries model again. The fallback’s provider key is checked at startup like the model’s. With a fallback from another provider, the agent’s history is compacted the provider-neutral way, since either model may read it. Monitoring records a run under fallback_model when only the fallback answered it, and under model otherwise; a run’s cost_usd is the price of the model that answered each request.
{ "name": "ticket-router", "model": "google:gemini-3.5-flash", "thinking": "low"}Running an Agent Programmatically
Section titled “Running an Agent Programmatically”result = await kirak.ai.run_agent({ "agent": "customer-support", "prompt": "What is the status of my order ORD-9921?", "conversation_id": "conv-uuid-here", # Optional: continue existing session "max_budget_usd": 0.05, # Optional: lower the agent's spending limit})
output = result["data"]["output"]trace = result["data"]["trace"] # This run's LLM turns, tool executions and text (not earlier turns)usage = result["data"]["usage"] # input/output/total tokens, requests, cost_usd, cached_input_tokens, # thinking_tokens and thinking_cost_usd (thinking is part of output)result["data"]["usage"] holds the run’s tokens, requests and cost_usd (None when the model has no pricing data). thinking_tokens is the part of output_tokens the model spent thinking (reasoning), as Gemini, OpenAI and Anthropic report it, thinking_cost_usd their share of the output price (None without pricing data), and cached_input_tokens the part of input_tokens read from the provider’s prompt cache; the token counts are 0 when the provider reports none. A streamed run’s done event carries them too. With goal_condition, it covers every iteration, and max_turns and max_budget_usd cap all iterations together. A run that fails after reaching the model (USAGE_LIMIT_EXCEEDED, retries used up, a provider error mid-run) raises, but monitoring still records what it spent in ai_runs, so cost reports count failed runs. The raised KirakException carries the same usage in details["usage"] (as do TOOL_NOT_USED and QUALITY_FAILED), for budgets an app keeps itself, such as a chat session’s total; it is absent when no request reached the model.
Model Prices for Unlisted Models
Section titled “Model Prices for Unlisted Models”A run’s cost_usd and an agent’s max_budget_usd come from the model’s price in genai-prices, the price list pydantic-ai installs with it. It covers the major providers’ models (OpenAI, Anthropic, Google, Groq, Mistral and others), so most apps need nothing here.
A model it does not list runs with cost_usd None, and its max_budget_usd never stops a run. That is the case for models reached through a provider genai-prices does not know, such as Amazon Bedrock’s OpenAI-compatible endpoint, a self-hosted model or a model released after your install. For those only, give the price in kirak.json, in US dollars per million tokens:
{ "ai": { "model_prices": { "openai-chat:google.gemma-4-31b": {"input": 0.14, "output": 0.40} } }}- The key is the model string your agents use. The model is matched by the name after the
provider:prefix (google.gemma-4-31b), which is the name the provider reports. cache_read(optional) prices cached input tokens; without it they cost the input price.- A price here also replaces genai-prices’ price for the same model, for example a negotiated rate.
kirak validatewarns (budget_not_enforced) when an agent setsmax_budget_usdand its model has no price in either place.- pydantic-ai’s optional price download (
pydantic_ai.prices.update_in_background()) replaces the price list, and with it these prices; do not use both.
Tool Calling & Permissions
Section titled “Tool Calling & Permissions”Agents can execute three categories of tools:
- Model CRUD Operations: Any operation on your models (
orders.fetch,users.search,invoices.create). All calls execute with the ambient caller’s identity: row-level security (RLS) and field access permissions are strictly enforced. - Module Operations: Declared module operations (
vector.search,notifications.send_email,payments.verify_payment). - Custom Python Tools: Registered via
@kirak.agent().tool:
from pydantic_ai import RunContextfrom kirak.ai import KirakDeps
@kirak.agent("customer-support").toolasync def verify_shipping_address(ctx: RunContext[KirakDeps], address: str) -> dict: """Validate a customer shipping address.""" # Access ambient caller, database, and context: user = ctx.deps.current_user db = ctx.deps.kirak return {"valid": True, "formatted": address.strip()}Tools that end the run
Section titled “Tools that end the run”Every tool call normally costs one more model request: the tool’s result goes back to the
model, which then answers. A tool that hands the turn to the user (asking a question, showing
buttons) has nothing left for the model to do, so register it with ends_run=True:
from pydantic_ai import ModelRetry
async def ask_user(ctx: RunContext[KirakDeps], question: str) -> dict: """Ask the user a question. The call ends the turn.""" if not question.strip(): raise ModelRetry("Write the question.") return {"asked": question}
kirak.agent("customer-support").tool(ask_user, ends_run=True)- When the model calls it, the run ends with no further model request, and the tool’s return
value is the run’s
output. Text the model wrote before the call is kept. - Raise
ModelRetryto have the model correct the call; the run then continues. The model may correct it once by default;.tool(fn, ends_run=True, retries=3)allows more (retriesalso works for ordinary tools). - The run’s
tracerecords the call as atool_call/tool_resultpair, like any tool. - Tools the model calls before it in the same response still run first.
- It cannot have
requires_confirmation, andtimeoutdoes not apply to it. - With
"require_tool_use": truein the agent file, the run must end with a run-ending tool: a text answer is not an output, so it goes back to the model to make the call. Without it, the model may also finish with text, which is then the run’soutput.
Human-in-the-Loop Approvals
Section titled “Human-in-the-Loop Approvals”When a tool is configured with "requires_confirmation": true (or decorated via .tool(fn, requires_confirmation=True)), the agent pauses execution when the LLM attempts to call it:
- The initial run pauses and returns:
{"statusCode": 200,"status": "success","data": {"status": "approval_required","approval_id": "8f8b3c92-..."}}
- Inspect pending calls via
await kirak.ai.pending_approval(approval_id). - Resume the execution by approving or declining:
Terminal window POST /ai/agents/customer-support/resumeContent-Type: application/jsonAuthorization: Bearer <user_token>{"approval_id": "8f8b3c92-...","approved": true}
Security Bindings on Approvals: Approvals are cryptographically signed with
KIRAK_AUTH_JWT_SECRET_KEYand enforce two strict security checks on resumption:
- Caller Binding: Only the authenticated user who initiated the run can resume or decline it (
403 FORBIDDENfor other callers).- Agent Binding: The resume request must be submitted to the same agent that generated the approval.
A paused run stores its message history and tool arguments, not the caller’s bearer token. The resume’s Authorization header is the token the rest of the run uses.
Conversations & Automatic Compaction
Section titled “Conversations & Automatic Compaction”- Persistence: Sessions are stored in Redis (
KIRAK_REDIS_URL) or in theai_conversationstable. - TTL: Conversations have a 3600-second (1-hour) inactivity timeout.
- Compaction: When conversation token usage approaches
compaction_token_threshold(default 150,000):- For Anthropic & OpenAI: Uses server-side summary compaction.
- For Gemini / Other Providers: Kirak applies tiered compaction (stripping old tool payloads before sliding message windows).
HTTP REST Endpoints
Section titled “HTTP REST Endpoints”| Method | Path | Auth | Description |
|---|---|---|---|
POST |
/ai/prompt |
User / Admin | Execute a one-shot prompt |
POST |
/ai/agents/{name}/run |
Matches Agent access |
Run an agent (supports SSE streaming via stream: true; a client that disconnects mid-stream stops the run, including the model request in flight) |
POST |
/ai/agents/{name}/resume |
Original Caller | Resume or decline a paused tool approval |
GET |
/ai/agents/{name} |
Matches Agent access |
Describe agent schema and available tools |
GET |
/ai/agents |
Matches Agent access |
List all available declarative agents |