Context
Reference: Context
Context lets you pass runtime data into an agent’s execution — user info, session state, feature flags, or any other data your agent needs.
Passing context
await agent.run("Hello", {
context: {
userId: "user_123",
username: "Tony",
preferences: { theme: "dark" },
},
});Using context in instructions
Instructions can be a function that receives the context:
import { Agent } from "kernl";
import { anthropic } from "@kernl-sdk/ai/anthropic";
const agent = new Agent({
id: "assistant",
name: "Assistant",
model: anthropic("claude-sonnet-4-5"),
instructions: (ctx) => `
You are helping ${ctx.context.username}.
Their user ID is ${ctx.context.userId}.
`,
});Type-safe context
Define a context type for type safety:
import { Agent } from "kernl";
import { anthropic } from "@kernl-sdk/ai/anthropic";
interface UserContext {
userId: string;
username: string;
preferences: { theme: string };
};
const agent = new Agent<UserContext>({
id: "assistant",
name: "Assistant",
model: anthropic("claude-sonnet-4-5"),
instructions: (ctx) => `You are helping ${ctx.context.username}.`,
});
// Typescript knows what context expects
await agent.run("Hello", {
context: {
userId: "user_123",
username: "Tony",
preferences: { theme: "dark" },
},
});Accessing context in tools
Tools also have access to context:
import { tool } from "kernl";
import { z } from "zod";
const greet = tool({
id: "greet",
description: "Greet the user by name",
parameters: z.object({}),
execute: async (ctx) => {
return `Hello, ${ctx.context.username}!`;
},
});Last updated on