Agent Runtime
Agent Runtime
The Grid agent turns natural-language intent into deployable .grid
source. This page covers how to run it; the rules it follows when
generating code live in ai-agent-guide.md.
The agent is exposed on four surfaces:
| Surface | Use it for |
|---|---|
| HTTP | Calling the agent from any client or service |
| Library | Embedding generation in Node/TypeScript code |
| Frontend | The in-product "generate a model" experience |
| Scripting / CLI | One-off generation and validation from a script |
Two different "AI" things. The agent on this page writes Grid models. The in-formula AI functions (
AI_PROMPT,ASK,ASK_*,ML_SCORE) are something else: they run inside a model at evaluation time, served bygrid-ai-coreundergrid-runtime-host. For those, seeexternal-functions.mdand../specs/local_llm.md.
1. How It Works
The agent wraps an AI SDK tool-loop with Grid's system prompt, a
structured output schema, and a step cap. When host-backed tools are
available it runs a validate → evaluate → fix loop against
grid-runtime-host over RPC before returning:
validate_grid— compile the draft and read diagnostics.evaluate_grid— evaluate the draft and check for error cells.inspect_cell— fetch the unified cell inspection payload for a resident model cell (value, formula context, dimensions, sensitivity drivers, optional confidence bands, lineage, and runtime profile).lookup_function— confirm a function exists and inspect its signature.
With no tools supplied it falls back to a single-shot structured generation from built-in knowledge. Either way the result conforms to a fixed schema (see §6).
2. Providers And Configuration
The agent supports three providers, selectable per call or via env var:
| Provider | Default model | Key env var |
|---|---|---|
gateway (default) |
anthropic/claude-sonnet-4.5 |
AI_GATEWAY_API_KEY |
anthropic |
claude-sonnet-4-5 |
ANTHROPIC_API_KEY |
openai |
gpt-5.1 |
OPENAI_API_KEY |
Environment overrides:
GRID_AGENT_PROVIDER=anthropic # default provider
GRID_AGENT_MODEL=claude-sonnet-4-5 # default model id
GRID_AGENT_API_KEY=... # provider-agnostic key overrideAPI-key precedence (highest first):
- An explicit
apiKeyoption (the HTTP routes load this from the encrypted provider key store when available). GRID_AGENT_API_KEY(provider-agnostic).- The provider-native env var (
AI_GATEWAY_API_KEY,ANTHROPIC_API_KEY,OPENAI_API_KEY).
3. HTTP
Generate a model:
curl -X POST http://localhost:3000/api/agent/generate \
-H 'content-type: application/json' \
-d '{"prompt": "A pricing model: list price, 7% discount, 21% tax."}'Response:
{
"output": {
"source": "MODEL \"Pricing\"\n...\nEND MODEL",
"explanation": "Computes discounted and gross price.",
"runtime": "rust",
"validatedClean": true,
"warnings": []
},
"provider": "gateway",
"model": "anthropic/claude-sonnet-4.5"
}Optional body fields: provider and model. On error the route returns
400 (bad request / generation failure) or 503 (provider key store
unavailable) with { "error": "..." }.
Provider key management
GET /api/agent/provider-keys # list providers + key status
PUT /api/agent/provider-keys/:provider # body: { "apiKey": "..." }
DELETE /api/agent/provider-keys/:provider # remove a stored keyKeys are stored in an encrypted per-scope store; the list endpoint
reports whether a key is stored and whether a matching env-var fallback
exists, without revealing the secret. Auth boundaries are in
../api/auth.md.
4. Library
The factory lives in web/backend/src/agent:
import { createGridAgent } from "./web/backend/src/agent/index.js";
const agent = createGridAgent({
provider: "anthropic", // optional; defaults to gateway
model: "claude-sonnet-4-5", // optional; provider default otherwise
apiKey: process.env.MY_KEY, // optional; env fallback otherwise
// tools: buildAgentTools({ runtimeRpc, getFunctionCatalog }) // enables the validate/evaluate/fix loop
});
const result = await agent.generate({
prompt: "A pricing model: list price, 7% discount, 21% tax."
});
console.log(result.output.source);createGridAgent options:
| Option | Meaning |
|---|---|
provider |
"gateway" | "anthropic" | "openai" |
model |
Provider model id |
apiKey |
Explicit key (overrides env) |
maxSteps |
Step cap; defaults to 6 with tools, 1 without |
instructions |
Override the system prompt entirely (advanced) |
tools |
Host-backed validate_grid / evaluate_grid / inspect_cell / lookup_function |
The module also exports describeResolvedModel, gridAgentOutputSchema,
GRID_AGENT_PROVIDERS, resolveModel, and the ProviderKeyStore.
5. Frontend
The browser client wraps the HTTP routes:
import { runAgent, listProviderKeys, setProviderKey } from "./web/frontend/src/agent/client";
const response = await runAgent("A pricing model with discount and tax", {
provider: "anthropic",
model: "claude-sonnet-4-5"
});
// response.output.source is ready to deployrunAgent(prompt, options) posts to /api/agent/generate and returns
the same { output, provider, model } shape. listProviderKeys,
setProviderKey, and deleteProviderKey drive the provider-key settings
UI.
6. Output Schema
Every generation returns a structured object:
| Field | Meaning |
|---|---|
source |
The complete .grid source, ready to deploy |
explanation |
One to three sentences describing the model |
runtime |
Always "rust" |
validatedClean |
The author asserts the source obeys every hard rule |
evaluatedClean |
evaluate_grid ran on the final source with no error cells |
inputs |
Symbols the user should provide values for |
keyOutputs |
The 1–5 most important output cells |
sampleValues |
Optional representative values keyed by symbol |
warnings |
Non-blocking notes (style, gotchas, missing capability) |
7. Scripting And Validation (CLI)
There is no dedicated grid agent CLI binary. For scripted or one-off
use, either curl the HTTP route (§3) or call the library from a short
tsx script (§4).
Whichever surface you use, validate the generated source before
deploying it. The compiler CLI parses and compiles a .grid file and
reports diagnostics:
npm run compile:model generated.gridWhen the agent runs with host-backed tools it already does this in its
loop (validatedClean / evaluatedClean reflect the outcome). For
agents calling a provider without tools, run the compile step yourself
and surface any diagnostics back to the user.
8. See Also
ai-agent-guide.md— the rules the agent follows; feed it (orgrammar.json) as system context.grammar.json— machine-readable grammar profile for programmatic validation.external-functions.md— in-formula AI functions (AI_PROMPT,ASK_*,ML_SCORE).../specs/local_llm.md— howgrid-ai-coreserves in-formula LLM routes.../specs/rust_ai_host.md— the resident AI host.../api/auth.md— auth boundaries for agent routes.../api/models.md— cell inspection HTTP routes used byinspect_cell.