The Agent is the core orchestrator that manages prompts, tools, memory, and execution flow.
function createAgent(config: AgentConfig): Agent
async run(prompt: string): Promise<AgentRunResult>
Execute the agent with a single prompt. Handles tool loops automatically.
const agent = createAgent({
name: "assistant",
model: "gpt-5.2",
systemPrompt: "You are a helpful assistant"
});
const result = await agent.run("What is 2+2?");
console.log(result.response.choices[0].message.content);
async stream(prompt: string): Promise<ResponseStream>
Stream the agent's response in real-time.
const stream = await agent.stream("Tell me a story");
for await (const event of stream) {
if (event.type === 'token') {
process.stdout.write(event.value);
}
}
Tools are functions that agents can call to perform specific actions.
function tool(definition: ToolDefinition): Tool
import { tool } from "@runmesh/tools";
import { z } from "zod";
const weatherTool = tool({
name: "get_weather",
description: "Get current weather for a location",
schema: z.object({
location: z.string().describe("City name or coordinates"),
units: z.enum(["celsius", "fahrenheit"]).default("celsius")
}),
handler: async (input) => {
// Call weather API
const response = await fetch(`api.weather.com?q=${input.location}`);
const data = await response.json();
return {
temperature: data.temp,
conditions: data.weather
};
}
});
class ToolRegistry
const tools = new ToolRegistry();
tools.register(weatherTool);
tools.register(calculatorTool);
tools.register(searchTool);
const agent = createAgent({
name: "assistant",
model: "gpt-5.2",
tools // Pass the registry
});
Memory adapters enable agents to maintain conversation history and context.
interface MemoryAdapter {
add(agentName: string, message: ChatMessage): Promise<void>;
history(agentName: string, limit?: number): Promise<MemoryMessage[]>;
}
import { InMemoryAdapter } from "@runmesh/memory";
const memory = new InMemoryAdapter();
const agent = createAgent({
name: "assistant",
model: "gpt-5.2",
memory // Agent will remember conversation history
});
Stream responses in real-time for responsive user experiences.
const stream = await agent.stream(userInput);
for await (const event of stream) {
switch (event.type) {
case 'token':
process.stdout.write(event.value);
break;
case 'tool_call':
console.log(`Tool call: ${event.toolCall?.function?.name ?? "unknown"}`);
break;
case 'final':
console.log(`Final: ${event.message?.content ?? ""}`);
break;
}
}
Policies enforce rules and constraints on agent behavior.
type Policy = (context: PolicyContext) => PolicyResult | Promise<PolicyResult>
const rateLimitPolicy: Policy = async (context) => {
const requestCount = await getRequestCount(context.agent);
if (requestCount > 100) {
return {
allow: false,
reason: "Rate limit exceeded"
};
}
return { allow: true };
};
const agent = createAgent({
name: "assistant",
model: "gpt-5.2",
policies: [rateLimitPolicy]
});
const contentFilterPolicy: Policy = (context) => {
const lastMessage = context.messages[context.messages.length - 1];
const content = lastMessage.content.toLowerCase();
const bannedWords = ["spam", "abuse"];
const hasBannedContent = bannedWords.some(word => content.includes(word));
if (hasBannedContent) {
return {
allow: false,
reason: "Content violates policy"
};
}
return { allow: true };
};
Extract structured, validated data from agent responses.
async function generateStructuredOutput<T>(
options: StructuredGenerateOptions<T>
): Promise<StructuredResult<T>>
import { createOpenAI, generateStructuredOutput } from "@runmesh/core";
import { z } from "zod";
const contactSchema = z.object({
name: z.string(),
email: z.string().email(),
phone: z.string().optional(),
company: z.string().optional()
});
const client = createOpenAI({
apiKey: process.env.OPENAI_API_KEY,
defaultModel: "gpt-5.2"
});
const result = await generateStructuredOutput({
client,
request: {
messages: [
{ role: "user", content: "Extract contact info: John Doe, john@example.com, works at Acme Inc" }
]
},
schema: contactSchema,
maxRetries: 2
});
console.log(result.value);
// { name: "John Doe", email: "john@example.com", company: "Acme Inc" }
import { createAgent } from "@runmesh/agent";
import { tool, ToolRegistry } from "@runmesh/tools";
import { InMemoryAdapter } from "@runmesh/memory";
import { z } from "zod";
// Define tools
const tools = new ToolRegistry();
tools.register(tool({
name: "calculator",
description: "Perform mathematical calculations",
schema: z.object({
expression: z.string()
}),
handler: (input) => eval(input.expression)
}));
tools.register(tool({
name: "search_web",
description: "Search the web for information",
schema: z.object({
query: z.string()
}),
handler: async (input) => {
// Implement web search
return { results: [...] };
}
}));
// Create agent with memory
const agent = createAgent({
name: "research-assistant",
model: "gpt-5.2",
systemPrompt: "You are a research assistant with web search and calculation capabilities.",
tools,
memory: new InMemoryAdapter()
});
// Use the agent
const result1 = await agent.run("What is 15 * 23?");
const result2 = await agent.run("Search for recent AI developments");
const result3 = await agent.run("What did you calculate earlier?"); // Uses memory