Contextual simplifies the development, deployment, operations, and scaling of the AI-enabled services behind your applications, automations, and integrations.
- instances
- 2
- size
- small
- config
- prod
- build
- build-20261118170212
The code and data behind your solution.
Workers
Workers run the code behind your solution in TypeScript, Rust, Go, or Python. Contextual builds, deploys, and scales your Worker and provides its logs.
About Workersuse contextual_worker::{Worker, json};
fn main() -> std::process::ExitCode {
Worker::new("hello-managed", env!("CARGO_PKG_VERSION"))
.handler("default", |_, _| async {
Ok(json!({
"status": 200,
"headers": {"content-type": "text/plain"},
"body": "Hello from Contextual",
}))
})
.run()
}export default {
apiVersion: "1",
name: "hello-managed",
version: "1.0.0",
parseConfig: (config: unknown) => config,
async run() {
return {
status: 200,
headers: { "content-type": "text/plain" },
body: "Hello from Contextual",
}
},
}package main
import (
"context"
"os"
"contextual.io/worker"
)
func main() {
w := worker.New("hello-managed", "1.0.0")
w.Handle("default", func(
_ context.Context, _ worker.Event, _ *worker.Context,
) (any, error) {
return map[string]any{
"status": 200,
"headers": map[string]string{"content-type": "text/plain"},
"body": "Hello from Contextual",
}, nil
})
os.Exit(w.Run())
}from contextual_worker import Worker
worker = Worker("hello-managed", "1.0.0")
@worker.handler("default")
async def default(event, ctx):
return {
"status": 200,
"headers": {"content-type": "text/plain"},
"body": "Hello from Contextual",
}Object Types and Records
Bring your business data into your solution as records. Define custom Object Types as JSON schemas with validation and versions.
Your tenant provides an API for every Object Type so your Workers can read and write records right away.
Object Typesuse contextual_worker::{Context, Value, anyhow::{Context as _, Result}, json};
pub async fn approve_invoice(ctx: &Context, id: &str) -> Result<Value> {
let records = ctx.records();
let invoice = records.get("invoices", id, Default::default()).await?;
let hash = invoice["_metaData"]["hash"].as_str().context("Missing record hash")?;
let patch = json!([{"op": "add", "path": "/status", "value": "approved"}]);
records.patch("invoices", id, patch, hash).await
}import type { Context } from "./worker-types"
export async function approveInvoice(context: Context<unknown>, id: string) {
const records = context.records!
const invoice = await records.get("invoices", id)
const hash = invoice._metaData?.hash
if (!hash) throw new Error("Missing record hash")
return records.patch("invoices", id, [
{ op: "add", path: "/status", value: "approved" },
], hash)
}package main
import (
"errors"
"contextual.io/worker"
)
func approveInvoice(c *worker.Context, id string) (map[string]any, error) {
records := c.Records()
var invoice struct {
MetaData struct{ Hash string } `json:"_metaData"`
}
if err := records.Get("invoices", id, nil, &invoice); err != nil {
return nil, err
}
if invoice.MetaData.Hash == "" {
return nil, errors.New("missing record hash")
}
patch := []map[string]any{{"op": "add", "path": "/status", "value": "approved"}}
var updated map[string]any
err := records.Patch("invoices", id, patch, invoice.MetaData.Hash, &updated)
return updated, err
}from contextual_worker import Context
async def approve_invoice(ctx: Context, invoice_id: str):
invoice = await ctx.records.get("invoices", invoice_id)
revision = invoice["_metaData"]["hash"]
patch = [{"op": "add", "path": "/status", "value": "approved"}]
return await ctx.records.patch("invoices", invoice_id, patch, revision)Ship your first Worker in minutes.
AI is one call away.
Classify, extract, answer, and act without managing keys or models.
Generate
Classify a message or extract an invoice into your own schema. Use a configured AI Route to choose the provider, model, retries, and fallback.
AI RoutesSearch
Find the passages that answer a question from your own documents. Use a Search Profile and a named index to apply the retrieval settings you configured.
AI SearchTools
Give an agent tools that act in your other systems. The model calls functions your handler implements.
Platform CapabilitiesAI Calls
Run a saved prompt by ID and use a label such as stable to control its version. The example needs AI Calls enabled and managed host 0.18.0 or later.
Explore AI Callsuse contextual_worker::{Context, Value, anyhow::Result, json};
pub async fn answer(ctx: &Context, route_id: &str, question: &str) -> Result<Value> {
ctx.ai().generate(json!({
"route": route_id,
"system": "Answer in one sentence.",
"prompt": question,
"maxTokens": 128,
})).await
}use contextual_worker::{AiSearchQueryOptions, Context, Value, anyhow::Result};
pub async fn search(
ctx: &Context, profile_id: &str, index_id: &str, question: &str,
) -> Result<Value> {
let options = AiSearchQueryOptions {
index_id: Some(index_id.into()),
top_k: Some(5),
};
let result = ctx.ai_search().query(profile_id, question, options).await?;
Ok(result["items"].clone())
}use contextual_worker::{Context, Value, anyhow::Result, json};
pub async fn answer_with_tools(ctx: &Context, route_id: &str, question: &str) -> Result<Value> {
let request = json!({
"route": route_id,
"system": "Use lookup_order for shipping status. If it returns unknown, say so.",
"prompt": question,
"maxSteps": 4,
"timeoutMs": 15000,
"tools": {
"lookup_order": {
"description": "Read an order's shipping status",
"inputSchema": {
"type": "object",
"properties": { "id": { "type": "string" } },
"required": ["id"],
},
},
},
});
ctx.ai().generate_with_tools(request, |_, args| async move {
let status = if args["id"] == "order-2041" { "shipped" } else { "unknown" };
Ok(json!({ "status": status }))
}).await
}use contextual_worker::{Context, Value, anyhow::Result, json};
pub async fn summarize_order(ctx: &Context, note: &str) -> Result<Value> {
let request = json!({
"call": { "id": "order-summary", "label": "stable" },
"variables": { "note": note },
});
let reply = ctx.platform_call("ai.generateCall", request).await?;
Ok(reply["value"].clone())
}import type { Context } from "./worker-types"
export async function answer(context: Context<unknown>, routeId: string, question: string) {
return context.ai!.generate({
route: routeId,
system: "Answer in one sentence.",
prompt: question,
maxTokens: 128,
})
}import type { Context } from "./worker-types"
export async function search(
context: Context<unknown>, profileId: string, indexId: string, question: string,
) {
const result = await context.aiSearch!.query(profileId, question, { indexId, topK: 5 })
return result.items
}import type { Context } from "./worker-types"
export async function checkOrder(context: Context<unknown>, routeId: string, question: string) {
return context.ai!.generateWithTools({
route: routeId,
system: "Use lookup_order for shipping status. If it returns unknown, say so.",
prompt: question,
maxSteps: 4,
timeoutMs: 15000,
tools: {
lookup_order: {
description: "Look up an order's status",
inputSchema: {
type: "object",
properties: { id: { type: "string" } },
required: ["id"],
},
},
},
}, async (name, args) => {
if (name !== "lookup_order") throw new Error("Unexpected tool")
const { id } = args as { id: string }
return { id, status: id === "order-2041" ? "shipped" : "unknown" }
})
}import type { Context } from "./worker-types"
export async function summarizeOrder(context: Context<unknown>, note: string) {
const reply = await context.platform!.call("ai.generateCall", {
call: { id: "order-summary", label: "stable" },
variables: { note },
})
if (typeof reply !== "object" || reply === null || !("ok" in reply)
|| reply.ok !== true || !("value" in reply)) {
throw new Error("AI Call failed", { cause: reply })
}
return reply.value
}package main
import "contextual.io/worker"
func answer(c *worker.Context, routeID, question string) (map[string]any, error) {
return c.AI().Generate(map[string]any{
"route": routeID,
"system": "Answer in one sentence.",
"prompt": question,
"maxTokens": 128,
})
}package main
import "contextual.io/worker"
func search(c *worker.Context, profileID, indexID, question string) (any, error) {
options := &worker.AISearchQueryOptions{IndexID: indexID, TopK: 5}
var result map[string]any
if err := c.AISearch().Query(profileID, question, options, &result); err != nil {
return nil, err
}
return result["items"], nil
}package main
import (
"context"
"contextual.io/worker"
)
func answerWithTools(c *worker.Context, routeID, question string) (map[string]any, error) {
request := map[string]any{
"route": routeID,
"system": "Use lookup_order for shipping status. If it returns unknown, say so.",
"prompt": question,
"maxSteps": 4,
"timeoutMs": 15000,
"tools": map[string]any{
"lookup_order": map[string]any{
"description": "Read an order's shipping status",
"inputSchema": map[string]any{
"type": "object",
"properties": map[string]any{"id": map[string]any{"type": "string"}},
"required": []string{"id"},
},
},
},
}
return c.AI().GenerateWithTools(request,
func(_ context.Context, _ string, args map[string]any) (any, error) {
status := "unknown"
if args["id"] == "order-2041" {
status = "shipped"
}
return map[string]any{"status": status}, nil
},
)
}package main
import "contextual.io/worker"
func summarizeOrder(c *worker.Context, note string) (any, error) {
request := map[string]any{
"call": map[string]any{"id": "order-summary", "label": "stable"},
"variables": map[string]any{"note": note},
}
var reply struct {
Value any `json:"value"`
}
if err := c.PlatformCall("ai.generateCall", request, &reply); err != nil {
return nil, err
}
return reply.Value, nil
}from contextual_worker import Context
async def answer(ctx: Context, route_id: str, question: str):
return await ctx.ai().generate({
"route": route_id,
"system": "Answer in one sentence.",
"prompt": question,
"maxTokens": 128,
})from contextual_worker import Context
async def search(ctx: Context, profile_id: str, index_id: str, question: str):
result = await ctx.ai_search.query(profile_id, question, index_id=index_id, top_k=5)
return result["items"]from contextual_worker import Context
async def check_order(ctx: Context, route_id: str, question: str):
async def tool(name, args):
if name != "lookup_order":
raise ValueError("Unexpected tool")
order_id = args["id"]
return {"id": order_id, "status": "shipped" if order_id == "order-2041" else "unknown"}
return await ctx.ai().generate_with_tools({
"route": route_id,
"system": "Use lookup_order for shipping status. If it returns unknown, say so.",
"prompt": question,
"maxSteps": 4,
"timeoutMs": 15000,
"tools": {
"lookup_order": {
"description": "Look up an order's status",
"inputSchema": {
"type": "object",
"properties": {"id": {"type": "string"}},
"required": ["id"],
},
},
},
}, tool)from contextual_worker import Context
async def summarize_order(ctx: Context, note: str):
reply = await ctx.platform_call("ai.generateCall", {
"call": {"id": "order-summary", "label": "stable"},
"variables": {"note": note},
})
return reply["value"]Build with a coding agent.
Give your coding agent access to Contextual documentation and the tools to build and deploy.
Solution AI Knowledge MCP
Give your agent tools to search and read the docs. Add this server to your agent and follow the sign-in prompt.
https://contextual-docs-mcp.contextualio.workers.devSolution AI Connect
A plugin for Claude Code and Codex with Contextual docs, CLI, and data-modeling skills.
Get the pluginContextual CLI
Your agent uses ctxl to deploy Workers and work with your tenant.
npm install -g @contextual-io/cli