### Run Agent SDK Examples using npm Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Instructions for cloning the repository, installing dependencies, setting up an API key, and running specific examples using npm commands. ```bash # Clone repository git clone https://github.com/Cognipeer/agent-sdk cd agent-sdk # Install dependencies npm install # Set up API key export OPENAI_API_KEY=sk-... # Run an example npm run example:basic npm run example:planning npm run example:multi-agent ``` -------------------------------- ### Run Agent SDK Examples Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Execute example scripts from the Agent SDK repository using `tsx`. Ensure the package is built (`npm run build`) and set necessary environment variables, such as `OPENAI_API_KEY`, before running. ```bash OPENAI_API_KEY=... npx tsx examples/tools/tools.ts ``` -------------------------------- ### Install Cognipeer Agent SDK and Dependencies Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Installs the core agent SDK and Zod for schema validation using npm. Optionally installs LangChain adapters for OpenAI integration. ```sh npm install @cognipeer/agent-sdk zod # Optional: install if you want LangChain adapters or MCP tool clients npm install @langchain/core @langchain/openai ``` -------------------------------- ### Setup Ruby for Local Jekyll Preview Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/CONTRIBUTING.md Installs Jekyll and its dependencies using Bundler and then starts the local Jekyll server for documentation preview. This method requires a local Ruby installation. ```sh gem install bundler jekyll cd docs && bundle init && echo 'gem "just-the-docs"' >> Gemfile && bundle && bundle exec jekyll serve ``` -------------------------------- ### Run Structured Output Example (Bash) Source: https://github.com/cognipeer/agent-sdk/blob/main/examples/structured-output/README.md Command to execute the structured output example using Node.js with TypeScript. It optionally sets the OpenAI API key. Ensure tsx is installed for TypeScript execution. ```bash export OPENAI_API_KEY=sk-... # optional node --loader tsx ./examples/structured-output/structured-output.ts ``` -------------------------------- ### Setup Docker for Local Jekyll Preview Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/CONTRIBUTING.md This command allows you to preview the documentation locally using Docker without installing Ruby dependencies. It mounts the local docs directory and serves the site on port 4000. ```sh docker run --rm -p 4000:4000 -v "$PWD/docs":/site -w /site bretfisher/jekyll-serve ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/CONTRIBUTING.md Clones the Agent SDK repository and installs project dependencies using npm. This is a standard setup process for Node.js projects. ```bash git clone https://github.com/Cognipeer/agent-sdk cd agent-sdk npm install ``` -------------------------------- ### Build and Run Agent SDK Examples Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/CONTRIBUTING.md Commands to build the Agent SDK package and run a basic example. These commands are essential for testing changes and verifying functionality. ```bash npm run build npm run example:basic ``` -------------------------------- ### Create a Smart Agent with Planning and Summarization (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Demonstrates creating a smart agent using `createSmartAgent`. It includes a Zod-backed tool, integrates with a LangChain model, and enables planning and tracing. The agent is invoked with a user message, and the result is logged. ```typescript import { createSmartAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk"; import { ChatOpenAI } from "@langchain/openai"; import { z } from "zod"; const echo = createTool({ name: "echo", description: "Echo back", schema: z.object({ text: z.string().min(1) }), func: async ({ text }) => ({ echoed: text }), }); const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY, })); const agent = createSmartAgent({ name: "Planner", model, tools: [echo], useTodoList: true, limits: { maxToolCalls: 5, maxToken: 6000 }, tracing: { enabled: true }, }); const res = await agent.invoke({ messages: [{ role: "user", content: "Plan a greeting and send it via the echo tool" }], }); console.log(res.content); ``` -------------------------------- ### Create a Minimal Agent Loop (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Illustrates creating a basic agent using `createAgent`. This minimal version lacks a system prompt and auto-summarization, offering full control to the developer. It uses a Zod-backed tool and a LangChain model. ```typescript import { createAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk"; import { ChatOpenAI } from "@langchain/openai"; import { z } from "zod"; const echo = createTool({ name: "echo", description: "Echo back", schema: z.object({ text: z.string().min(1) }), func: async ({ text }) => ({ echoed: text }), }); const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY, })); const agent = createAgent({ model, tools: [echo], limits: { maxToolCalls: 5 }, }); const res = await agent.invoke({ messages: [{ role: "user", content: "Say hi via echo" }], }); console.log(res.content); ``` -------------------------------- ### Running Multi-Agent Example (Bash) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/multi-agent.md Provides the command to execute the multi-agent example using npm. This is a typical command for running examples within Node.js projects managed by npm. ```bash npm run example:multi-agent ``` -------------------------------- ### Install Cognipeer Agent SDK and Dependencies Source: https://github.com/cognipeer/agent-sdk/blob/main/README.md Installs the core agent SDK package along with optional peer dependencies like LangChain core and Zod. Also includes optional LangChain OpenAI bindings for quick starts. Ensure Node.js 18.17+ is used. ```sh npm install @cognipeer/agent-sdk @langchain/core zod # Optional: LangChain OpenAI bindings for quick starts npm install @langchain/openai ``` -------------------------------- ### Start Local Documentation Development Server Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/CONTRIBUTING.md Starts the VitePress development server for local preview of the documentation. This allows you to see changes in real-time as you edit the markdown files. ```bash npm run docs:dev ``` -------------------------------- ### Run Example Scripts - Shell Source: https://github.com/cognipeer/agent-sdk/blob/main/README.md Instructions on how to build the CogniPeer agent SDK package and then run example scripts using `tsx`. This requires setting the OPENAI_API_KEY environment variable. ```shell # from repo root npm run build OPENAI_API_KEY=... npx tsx examples/tools/tools.ts ``` -------------------------------- ### Listen for Smart Agent Plan Events (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Shows how to subscribe to events emitted by the smart agent during its execution, specifically listening for 'plan' events to track the agent's planning progress. ```typescript await agent.invoke( { messages: [{ role: "user", content: "Plan and echo hi" }] }, { onEvent: (event) => { if (event.type === "plan") { console.log("Plan size", event.todoList?.length ?? 0); } }, } ); ``` -------------------------------- ### Agent Execution Commands (Bash) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/basic.md Provides the necessary bash commands to set the OpenAI API key and run the basic agent example. This is essential for executing the TypeScript code. ```bash export OPENAI_API_KEY=sk-... npm run example:basic ``` -------------------------------- ### Install and Build Agent SDK (Shell) Source: https://github.com/cognipeer/agent-sdk/blob/main/README.md Commands to install dependencies and build the agent-sdk package using npm. This is a prerequisite for development and local testing. ```sh cd agent-sdk npm install npm run build ``` -------------------------------- ### Configure Agent for Offline Use with Fake Model (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Shows how to set up an agent to run offline by providing a mock `fakeModel` object that simulates model behavior, useful for testing without API calls. ```typescript const fakeModel = { bindTools() { return this; }, async invoke() { return { role: "assistant", content: "hello (fake)" }; }, }; const agent = createAgent({ model: fakeModel as any }); ``` -------------------------------- ### Set Environment Variable for API Key Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Exports the OpenAI API key as an environment variable for the agent to use. This should be added to your shell profile for persistence. ```sh export OPENAI_API_KEY=sk-... ``` -------------------------------- ### Enable Structured Tracing in SmartAgent Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Activate structured JSON tracing for enhanced observability within SmartAgent. Set `tracing.enabled: true` to start capturing traces, and `tracing.logData: true` to include payload snapshots. Traces are typically saved to `logs/[session]/trace.session.json`. ```typescript createSmartAgent({ model, tracing: { enabled: true, logData: true, }, }); ``` -------------------------------- ### Multi-Step Research Example with Planning Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/guide/planning.md A complete example of creating a researcher agent with planning enabled. It specifies tools and demonstrates an invocation for a multi-step research task, showing the expected automated plan generation. ```typescript const agent = createSmartAgent({ name: "Researcher", model, tools: [searchTool, analyzeTool, summarizeTool], useTodoList: true, }); const result = await agent.invoke({ messages: [{ role: "user", content: "Research recent developments in quantum computing and create a summary" }], }); // Agent creates plan: // 1. [in-progress] Search for quantum computing news // 2. [not-started] Analyze top 5 results // 3. [not-started] Create structured summary // 4. [not-started] Validate sources // After each step, plan is updated automatically ``` -------------------------------- ### Add Structured Output Validation with Zod Schema (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Demonstrates how to enforce structured output from an agent by providing an `outputSchema` (using Zod). The agent's response will be parsed, and `res.output` will contain the validated data. ```typescript const Result = z.object({ title: z.string(), bullets: z.array(z.string()).min(1) }); const agent = createAgent({ model, outputSchema: Result }); const res = await agent.invoke({ messages: [{ role: "user", content: "Give 3 bullets about agents" }], }); console.log(res.output?.bullets); ``` -------------------------------- ### Create and Run a Basic Agent with Echo Tool (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/basic.md Demonstrates creating a tool with a Zod schema, configuring a smart agent with a LangChain model, and invoking the agent to process user messages. This snippet requires the '@cognipeer/agent-sdk' and '@langchain/openai' packages, and an OPENAI_API_KEY environment variable. ```typescript import { createSmartAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk"; import { ChatOpenAI } from "@langchain/openai"; import { z } from "zod"; // Define a simple echo tool const echo = createTool({ name: "echo", description: "Echo back the input text", schema: z.object({ text: z.string().min(1).describe("Text to echo") }), func: async ({ text }) => { return { echoed: text, timestamp: new Date().toISOString() }; }, }); // Create model adapter const model = fromLangchainModel( new ChatOpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY, }) ); // Create agent const agent = createSmartAgent({ name: "EchoBot", model, tools: [echo], limits: { maxToolCalls: 5 }, tracing: { enabled: true }, }); // Run agent const result = await agent.invoke({ messages: [ { role: "user", content: "Please echo 'Hello, World!'" } ], }); console.log("Result:", result.content); console.log("Usage:", result.usage); ``` -------------------------------- ### Convert LangChain Tools to Agent SDK Format Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/adapters.md This code example shows how to convert LangChain tools into the Agent SDK's format using the `fromLangchainTools` adapter. It takes an array of LangChain tools, typically defined using `DynamicTool`, and transforms them into a structure compatible with the Agent SDK's `createSmartAgent` function. Ensure `@langchain/core` is installed. ```typescript import { fromLangchainTools } from "@cognipeer/agent-sdk"; import { DynamicTool } from "@langchain/core/tools"; const langchainTools = [ new DynamicTool({ name: "search", description: "Search the web", func: async (query: string) => { // Search implementation return `Results for: ${query}`; }, }), ]; const sdkTools = fromLangchainTools(langchainTools); const agent = createSmartAgent({ model, tools: sdkTools, }); ``` -------------------------------- ### Basic Agent with Echo Tool (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Demonstrates the creation of a simple agent with a single tool ('echo') using Zod schemas for validation. It showcases the basic invoke flow and simple error handling. ```typescript import { createSmartAgent, createTool } from "@cognipeer/agent-sdk"; import { z } from "zod"; const echo = createTool({ name: "echo", description: "Echo back text", schema: z.object({ text: z.string() }), func: async ({ text }) => ({ echoed: text }), }); const agent = createSmartAgent({ model, tools: [echo] }); const result = await agent.invoke({ messages: [{ role: "user", content: "Say hello" }], }); ``` -------------------------------- ### Agent with Planning and TODOs (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Illustrates how to enable planning mode for an agent and monitor plan execution events. This is useful for multi-step task breakdown and management. ```typescript const agent = createSmartAgent({ model, tools, useTodoList: true, onEvent: (event) => { if (event.type === "plan") { console.log("Plan:", event.todoList); } }, }); ``` -------------------------------- ### Install Dependencies for MCP Integration Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/guide/mcp.md Installs the necessary packages for agent SDK and MCP adapters. Includes optional packages for LangChain integration. ```sh npm install @cognipeer/agent-sdk npm install @langchain/mcp-adapters # Optional when reusing LangChain models/tools npm install @langchain/core @langchain/openai ``` -------------------------------- ### Configure Context Summarization with SmartAgent Limits Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Enable and adjust context summarization in SmartAgent by setting `limits.maxToken` and related summarization parameters. This helps manage the context window size for long conversations. Summarization can be fully disabled by setting `summarization: false`. ```typescript createSmartAgent({ model, tools: [echo], limits: { maxToolCalls: 8, maxToken: 6000, contextTokenLimit: 4000, summaryTokenLimit: 600, }, }); ``` -------------------------------- ### Tool Approval Workflow with Pause/Resume (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Demonstrates a human-in-the-loop approval process before a tool is executed. The agent pauses execution, waits for user approval, and then resumes. ```typescript const result = await agent.invoke(state, { onStateChange: (s) => { const lastMsg = s.messages.at(-1); if (lastMsg?.tool_calls) { // Pause for approval return true; } }, }); // Show tools to user, get approval const approved = await getUserApproval(result.state); if (approved) { const resumed = await agent.resume( agent.snapshot(result.state) ); } ``` -------------------------------- ### Install Agent SDK Packages Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/index.md Installs the necessary Agent SDK and Zod packages using different package managers (npm, yarn, pnpm). These packages are essential for utilizing the agent framework and its schema validation capabilities. ```bash npm install @cognipeer/agent-sdk zod ``` ```bash yarn add @cognipeer/agent-sdk zod ``` ```bash pnpm add @cognipeer/agent-sdk zod ``` -------------------------------- ### Example Trace Session JSON Structure Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/debugging/README.md An example JSON structure representing a complete agent invocation trace. This includes session metadata, agent runtime information, summary statistics, ordered events, and errors. ```json { "sessionId": "sess_pK4y6xQd2Z9LcvGk", "startedAt": "2025-09-29T08:15:30.123Z", "endedAt": "2025-09-29T08:15:35.412Z", "durationMs": 5289, "agent": { "name": "SupportAgent", "version": "2025.09", "model": "gpt-4.1-mini", "provider": "openai" }, "config": { "enabled": true, "logData": true, "sink": { "type": "file", "path": ".../logs" } }, "summary": { "totalDurationMs": 3120, "totalInputTokens": 812, "totalOutputTokens": 431, "totalCachedInputTokens": 48, "totalBytesIn": 18240, "totalBytesOut": 9211, "eventCounts": { "ai_call": 2, "tool_call": 1 } }, "events": [ { "id": "evt_0001_abcd", "sessionId": "sess_pK4y6xQd2Z9LcvGk", "type": "ai_call", "label": "Assistant Response #1", "sequence": 1, "timestamp": "2025-09-29T08:15:30.987Z", "actor": { "scope": "agent", "name": "SupportAgent", "role": "assistant", "version": "2025.09" }, "status": "success", "durationMs": 1780, "inputTokens": 320, "outputTokens": 198, "totalTokens": 518, "cachedInputTokens": 12, "requestBytes": 14280, "responseBytes": 9211, "model": "gpt-4.1-mini", "provider": "openai", "data": { "sections": [ { "id": "message-evt_0001_abcd-01", "kind": "message", "label": "User Prompt", "role": "user", "content": "How do I reset my password?" }, { "id": "message-evt_0001_abcd-02", "kind": "message", "label": "Assistant Response", "role": "assistant", "content": "Here are the steps to reset your password..." } ] } } ], "status": "success", "errors": [] } ``` -------------------------------- ### Configure OpenAI and Anthropic Models with Langchain Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/adapters.md This example shows how to configure specific models from OpenAI and Anthropic using Langchain's integration. It includes setting up OpenAI with streaming capabilities and Anthropic with a system prompt and API key. ```typescript // OpenAI with streaming const model = fromLangchainModel( new ChatOpenAI({ model: "gpt-4o-mini", streaming: true, callbacks: [/* streaming callbacks */], }) ); // Anthropic with system prompt const model = fromLangchainModel( new ChatAnthropic({ model: "claude-3-5-sonnet-20241022", anthropicApiKey: process.env.ANTHROPIC_API_KEY, }) ); ``` -------------------------------- ### Runtime Handoff Configuration (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/multi-agent.md Illustrates setting up an agent with 'handoffs', allowing it to seamlessly delegate tasks to another agent (e.g., 'specialistAgent') during runtime. This is crucial for dynamic task management and agent collaboration. ```typescript const agent = createSmartAgent({ model, tools, handoffs: [specialistAgent.asHandoff()], }); ``` -------------------------------- ### Enable Multimodal Input with Images (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Shows how to enable multimodal input for an agent, allowing it to process both text and images. The example demonstrates sending a message containing text and an image URL, utilizing the `image_url` type for image input. ```typescript const result = await agent.invoke({ messages: [{ role: "user", content: [ { type: "text", text: "What's in this image?" }, { type: "image_url", image_url: "https://example.com/image.jpg" }, ], }], }); ``` -------------------------------- ### Enable and Use Planning Mode in TypeScript Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/planning.md This TypeScript code snippet demonstrates how to initialize a smart agent with planning mode enabled. It shows how to configure the agent to use a TODO list for managing multi-step tasks and how to listen for plan-related events. The agent is invoked with a user message to initiate the planning and execution process. ```typescript import { createSmartAgent, createTool } from "@cognipeer/agent-sdk"; const agent = createSmartAgent({ name: "Planner", model, tools: [searchTool, analyzeTool, summarizeTool], useTodoList: true, // Enable planning onEvent: (event) => { if (event.type === "plan") { console.log(` === Plan v${event.version} ===`); event.todoList.forEach((item) => { console.log(`[${item.status}] ${item.title}`); }); } }, }); const result = await agent.invoke({ messages: [{ role: "user", content: "Research AI frameworks and create a comparison" }], }); ``` -------------------------------- ### Set Tool Call Limits in Agent Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/getting-started/README.md Configure the maximum number of tool calls and parallel tool executions an agent can perform. This prevents excessive resource consumption or runaway loops. When a limit is reached, a system message is injected, requiring the model to provide a direct answer. ```typescript createAgent({ model, tools: [echo], limits: { maxToolCalls: 3, maxParallelTools: 2 }, }); ``` -------------------------------- ### Integrate MCP Tools with Agent (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Illustrates how to integrate with Model Context Protocol (MCP) servers to use remote tools. This snippet shows setting up an MCP client, connecting to a transport, discovering remote tools, converting them for use with the agent, and then initializing the agent with these tools. ```typescript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; const client = new Client(/* ... */); await client.connect(transport); const mcpTools = await client.listTools(); const tools = fromLangchainTools(/* convert MCP tools */); const agent = createSmartAgent({ model, tools }); ``` -------------------------------- ### Multi-Agent Composition with Delegation (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Shows how to compose multiple agents, allowing one agent ('Specialist') to be used as a tool by another ('Coordinator'). This demonstrates nested agent execution and result aggregation. ```typescript const specialist = createSmartAgent({ name: "Specialist", model, tools: [specializedTool], }); const coordinator = createSmartAgent({ name: "Coordinator", model, tools: [specialist.asTool({ toolName: "delegate" })], }); ``` -------------------------------- ### Structured Output with Schema Validation (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Example of creating an agent that enforces a specific output schema using Zod. The agent automatically parses and validates the output, providing type-safe results. ```typescript const agent = createSmartAgent({ model, tools, outputSchema: z.object({ summary: z.string(), items: z.array(z.string()), confidence: z.number().min(0).max(1), }), }); const result = await agent.invoke({ messages }); console.log(result.output); // Typed and validated ``` -------------------------------- ### Configure Agent Guardrails with Presets (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md This snippet shows how to initialize a smart agent with built-in guardrail presets for content filtering and safety checks. It imports `guardrailPresets` from the SDK and includes `noSecrets` and `noCodeExecution` presets in the agent's configuration. ```typescript import { guardrailPresets } from "@cognipeer/agent-sdk"; const agent = createSmartAgent({ model, tools, guardrails: [ ...guardrailPresets.noSecrets, ...guardrailPresets.noCodeExecution, ], }); ``` -------------------------------- ### Create Basic Agent with Langchain Model - TypeScript Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/agent.md Illustrates the creation of a basic `Agent` using `createAgent`. This function provides a minimal control loop without automatic summarization or planning. The example shows how to integrate a custom tool and specifies system messages. ```typescript import { createAgent, fromLangchainModel } from "@cognipeer/agent-sdk"; const agent = createAgent({ model: fromLangchainModel(model), tools: [customTool], // No system prompt, no planning, no summarization }); const result = await agent.invoke({ messages: [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Hello!" }, ], }); ``` -------------------------------- ### Enable Basic Tracing - TypeScript Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/debugging/README.md Enables tracing for an agent with basic logging of metrics and payloads. This is the simplest way to start collecting trace data. ```typescript const agent = createSmartAgent({ model, tolls, tracing: { enabled: true, logData: true, }, }); ``` -------------------------------- ### Agent as Tool Composition (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/multi-agent.md Defines how to create a 'Specialist' agent with domain-specific tools and a 'Coordinator' agent that can delegate tasks to the specialist using its 'asTool' method. This pattern facilitates modular agent design. ```typescript const specialist = createSmartAgent({ name: "Specialist", model, tools: [domainTool], }); const coordinator = createSmartAgent({ name: "Coordinator", model, tools: [ specialist.asTool({ toolName: "consult_specialist", toolDescription: "Delegate to domain specialist", }), ], }); ``` -------------------------------- ### Unit Test a Tool's Functionality Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/guide/tool-development.md Provides an example of how to write a unit test for a tool's `func` implementation using `expect` and `resolves.toMatchObject`. This ensures the tool behaves as expected with specific inputs. ```typescript const input = { city: "Berlin", units: "c" }; await expect(weather.func(input)).resolves.toMatchObject({ city: "Berlin" }); ``` -------------------------------- ### Tool Definition Structure (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/basic.md Illustrates the structure for defining a tool within the Cognipeer Agent SDK, emphasizing the use of Zod for schema definition and defining the tool's function. This pattern is reusable for creating custom tools. ```typescript const tool = createTool({ name: "tool_name", description: "What the tool does", schema: z.object({ /* parameters */ }), func: async (params) => { /* implementation */ }, }); ``` -------------------------------- ### Bind Tools to Agent SDK Models Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/adapters.md The `withTools` helper simplifies binding a list of tools to an Agent SDK model, particularly useful for models that support tool binding via a `bindTools` method. This example shows how to initialize a model and then use `withTools` to prepare it for use with specific tools. ```typescript import { withTools, fromLangchainModel } from "@cognipeer/agent-sdk"; import { ChatOpenAI } from "@langchain/openai"; const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o-mini" })); const tools = [searchTool, calculatorTool]; // Automatically binds tools if model supports bindTools() const modelWithTools = withTools(model, tools); ``` -------------------------------- ### Agent Invocation Pattern (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/basic.md Shows the standard method for invoking an agent with a list of messages. The 'invoke' method accepts an object containing the message history, allowing the agent to process conversational context. ```typescript const result = await agent.invoke({ messages: [{ role: "user", content: "..." }], }); ``` -------------------------------- ### Event Handling in Agent Invocation Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/README.md Demonstrates how to subscribe to and handle events emitted during an agent's invocation. This example shows logging 'tool_call' events, allowing for real-time monitoring of agent activity. ```typescript await agent.invoke(state, { onEvent: (event) => { if (event.type === "tool_call") console.log(event); } }); ``` -------------------------------- ### Manage Agent Session with Pause and Resume (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/examples/index.md Demonstrates long-running session management for an agent. It covers invoking the agent, handling state changes to determine when to pause, creating a snapshot of the agent's state, saving it to a file, and later resuming the agent from that saved snapshot. ```typescript // Initial run const result = await agent.invoke(state, { onStateChange: (s) => shouldPause(s), }); // Save snapshot const snapshot = agent.snapshot(result.state, { tag: "checkpoint-1", }); fs.writeFileSync("checkpoint.json", JSON.stringify(snapshot)); // Later: resume const savedSnapshot = JSON.parse(fs.readFileSync("checkpoint.json")); const resumed = await agent.resume(savedSnapshot); ``` -------------------------------- ### Create a Custom Model Adapter for Agent SDK Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/adapters.md This example defines a `CustomModelAdapter` class that implements the `ModelAdapter` interface from `@cognipeer/agent-sdk`. It allows integration with any LLM provider by handling API calls, message formatting, and response parsing. The adapter must implement the `invoke` method and optionally the `bindTools` method for tool support. ```typescript import { ModelAdapter, Message, AssistantMessage } from "@cognipeer/agent-sdk"; class CustomModelAdapter implements ModelAdapter { constructor(private apiKey: string, private model: string) {} async invoke(messages: Message[]): Promise { // Convert messages to your API format const response = await fetch("https://api.example.com/chat", { method: "POST", headers: { "Authorization": `Bearer ${this.apiKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: this.model, messages: messages.map(m => ({ role: m.role, content: m.content, })), }), }); const data = await response.json(); // Return in Agent SDK format return { role: "assistant", content: data.message.content, // Optional: include tool calls if supported tool_calls: data.tool_calls, }; } // Optional: support tool binding bindTools(tools: ToolInterface[]): ModelAdapter { return new CustomModelAdapter(this.apiKey, this.model); } } // Usage const model = new CustomModelAdapter( process.env.CUSTOM_API_KEY, "custom-model-v1" ); const agent = createSmartAgent({ model, tools }); ``` -------------------------------- ### Connect to MCP Server with MultiServerMCPClient Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/guide/mcp.md Establishes a connection to one or more MCP servers using MultiServerMCPClient. Configurable options include error handling, tool name prefixing, and content block standardization. The example demonstrates connecting to Tavily's hosted MCP server. ```typescript import { MultiServerMCPClient } from "@langchain/mcp-adapters"; const client = new MultiServerMCPClient({ throwOnLoadError: true, prefixToolNameWithServerName: true, useStandardContentBlocks: true, mcpServers: { "tavily-remote-mcp": { transport: "stdio", command: "npx", args: ["-y", "mcp-remote", `https://mcp.tavily.com/mcp/?tavilyApiKey=${process.env.TAVILY_API_KEY}`], }, }, }); ``` -------------------------------- ### Implement and Use Custom Tool (TypeScript) Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/tools/README.md This example shows how to create a custom tool implementation that exposes an `invoke` method. The `customTool` for 'weather' takes a 'city' argument and uses an external `fetchWeather` function to retrieve data. This custom tool can then be passed to `createAgent`. ```typescript const customTool = { name: "weather", description: "Lookup weather", async invoke({ city }) { const data = await fetchWeather(city); // Assuming fetchWeather is defined elsewhere return { summary: data.description, tempC: data.tempC }; }, }; const agent = createAgent({ model, tools: [customTool] }); // Assuming model is defined elsewhere ``` -------------------------------- ### Implement Custom Tool - TypeScript Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/tools.md Demonstrates how to pass a custom tool implementation to the createAgent function. The custom tool object must expose an 'invoke' or 'call' method. This example shows a 'weather' tool that fetches data asynchronously. The agent can then utilize this custom tool. ```typescript const customTool = { name: "weather", description: "Lookup weather", async invoke({ city }) { const data = await fetchWeather(city); return { summary: data.description, tempC: data.tempC }; }, }; const agent = createAgent({ model, tools: [customTool] }); ``` -------------------------------- ### Guardrails for Safety and Compliance - TypeScript Source: https://context7.com/cognipeer/agent-sdk/llms.txt This example showcases the implementation of various guardrails within the Cognipeer Agent SDK. It includes regex-based filtering for sensitive data in requests, code detection in responses with a warning disposition, and JSON schema validation for response structure. These guardrails help enforce policies and ensure data integrity. ```typescript import { createAgent, createRegexGuardrail, createCodeGuardrail, createJsonGuardrail, GuardrailPhase } from "@cognipeer/agent-sdk"; import { z } from "zod"; // Block requests containing sensitive keywords const sensitiveFilter = createRegexGuardrail(/password|secret|api[_-]?key/i, { guardrailId: "sensitive-data", guardrailTitle: "Sensitive Data Filter", phases: [GuardrailPhase.Request], rule: { disposition: "block", failureMessage: "Request contains sensitive data and has been blocked", }, }); // Warn when responses contain code blocks const codeWarning = createCodeGuardrail({ guardrailId: "code-response", guardrailTitle: "Code in Response Detector", phases: [GuardrailPhase.Response], rule: { disposition: "warn", failureMessage: "Response contains code blocks", }, }); // Validate response structure const responseSchema = createJsonGuardrail( z.object({ answer: z.string(), citations: z.array(z.string()) }), { guardrailId: "response-structure", phases: [GuardrailPhase.Response], rule: { disposition: "warn" }, } ); const agent = createAgent({ model: fakeModel, // Assuming fakeModel is defined elsewhere guardrails: [sensitiveFilter, codeWarning, responseSchema], limits: { maxToolCalls: 5 }, }); const blocked = await agent.invoke({ messages: [{ role: "user", content: "My password is hunter2" }], }); console.log("Blocked:", blocked.messages.at(-1)?.content); // Output: "Request contains sensitive data and has been blocked" console.log("Incidents:", blocked.state?.guardrailResult?.incidents); // Output: [{ disposition: "block", reason: "...", ... }] ``` -------------------------------- ### Construct Base System Prompt with buildSystemPrompt Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/prompts.md Demonstrates how to use the `buildSystemPrompt` function to create a base system prompt for a smart agent. It allows specifying general instructions, enabling planning, and setting an agent name header. The generated prompt includes an agent header, conduct rules, an optional planning block, and custom instructions. ```typescript import { buildSystemPrompt } from "@cognipeer/agent-sdk"; const prompt = buildSystemPrompt( "Keep answers short and cite sources when available.", true, // planning enabled "ResearchHelper" // agent name header ); ``` -------------------------------- ### Append System Instructions to createSmartAgent Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/prompts/README.md Creates a smart agent with additional system instructions appended to the default prompt. The provided `systemPrompt` text is added verbatim under the 'Extra instructions:' section. This allows for concise and declarative guidance. ```typescript const agent = createSmartAgent({ model, tools, useTodoList: false, systemPrompt: "Answer using bullet points and cite documentation links when relevant.", }); ``` -------------------------------- ### Base Agent Creation Source: https://github.com/cognipeer/agent-sdk/blob/main/README.md Demonstrates the creation of a minimal agent using `createAgent` for basic loop execution without a system prompt or summarization. ```APIDOC ## POST /agent/create ### Description Creates a base agent with minimal configuration, suitable for simple conversational loops. ### Method POST ### Endpoint /agent/create ### Parameters #### Request Body - **model** (object) - Required - The language model to be used by the agent. - **tools** (array) - Optional - An array of tools that the agent can use. - **limits** (object) - Optional - Configuration for agent limits, such as `maxToolCalls` and `maxParallelTools`. - **maxToolCalls** (number) - Maximum number of tool calls allowed. - **maxParallelTools** (number) - Maximum number of tools that can be called in parallel. ### Request Example ```json { "model": { "name": "gpt-4o-mini", "apiKey": "your_openai_api_key" }, "tools": [ { "name": "echo", "description": "Echo back", "schema": { "type": "object", "properties": { "text": { "type": "string", "minLength": 1 } }, "required": ["text"] }, "func": "async ({ text }) => ({ echoed: text })" } ], "limits": { "maxToolCalls": 3, "maxParallelTools": 2 } } ``` ### Response #### Success Response (200) - **agentId** (string) - A unique identifier for the created agent. #### Response Example ```json { "agentId": "agent-12345" } ``` ``` -------------------------------- ### Construct Base System Prompt with buildSystemPrompt Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/prompts/README.md Builds a system prompt for a smart agent. It takes custom instructions, a boolean to enable planning, and the agent's name as input. The generated prompt includes an agent header, general conduct rules, an optional planning block, and custom instructions. ```typescript import { buildSystemPrompt } from "@cognipeer/agent-sdk"; const prompt = buildSystemPrompt( "Keep answers short and cite sources when available.", true, // planning enabled "ResearchHelper" // agent name header ); ``` -------------------------------- ### Create a Smart Agent with Planning and Summarization Source: https://github.com/cognipeer/agent-sdk/blob/main/README.md Demonstrates creating a smart agent using the @cognipeer/agent-sdk. This agent includes planning and summarization capabilities, utilizes a custom 'echo' tool, and integrates with a LangChain OpenAI model. The agent is configured with tool limits and tracing enabled. ```typescript import { createSmartAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk"; import { ChatOpenAI } from "@langchain/openai"; import { z } from "zod"; const echo = createTool({ name: "echo", description: "Echo back user text", schema: z.object({ text: z.string().min(1) }), func: async ({ text }) => ({ echoed: text }) }); const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY, })); const agent = createSmartAgent({ name: "ResearchHelper", model, tools: [echo], useTodoList: true, limits: { maxToolCalls: 5, maxToken: 8000 }, tracing: { enabled: true }, }); const result = await agent.invoke({ messages: [{ role: "user", content: "plan a greeting and send it via the echo tool" }], toolHistory: [], }); console.log(result.content); ``` -------------------------------- ### Publish Agent SDK Package (Shell) Source: https://github.com/cognipeer/agent-sdk/blob/main/README.md Steps to publish the agent-sdk package to a public registry using npm. Includes versioning and ensuring a fresh build before publishing. ```sh cd agent-sdk npm version npm publish --access public ``` -------------------------------- ### Append Additional Instructions to createSmartAgent Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/api/prompts.md Shows how to provide additional custom instructions to a smart agent when creating it with `createSmartAgent`. The `systemPrompt` option allows appending declarative text, which will be added under the 'Extra instructions:' section of the generated system message. This is useful for adding specific formatting or citation requirements. ```typescript const agent = createSmartAgent({ model, tools, useTodoList: false, systemPrompt: "Answer using bullet points and cite documentation links when relevant.", }); ``` -------------------------------- ### Create Minimal Agent with createAgent - TypeScript Source: https://github.com/cognipeer/agent-sdk/blob/main/README.md Demonstrates how to create a basic agent using `createAgent` from the CogniPeer SDK. It includes setting up a simple 'echo' tool and integrating it with a LangChain model. The agent is then invoked with a user message. ```typescript import { createAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk"; import { ChatOpenAI } from "@langchain/openai"; import { z } from "zod"; const echo = createTool({ name: "echo", description: "Echo back", schema: z.object({ text: z.string().min(1) }), func: async ({ text }) => ({ echoed: text }), }); const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY })); const agent = createAgent({ model, tools: [echo], limits: { maxToolCalls: 3, maxParallelTools: 2 }, }); const res = await agent.invoke({ messages: [{ role: "user", content: "say hi via echo" }] }); console.log(res.content); ``` -------------------------------- ### Create and Run a Smart Agent with Tools Source: https://github.com/cognipeer/agent-sdk/blob/main/docs/index.md Demonstrates the basic usage of the Agent SDK to create a smart agent. It includes defining a simple 'echo' tool using Zod schemas, adapting a LangChain model, and invoking the agent to plan and execute a task. The agent is configured with planning mode enabled and tracing activated. ```typescript import { createSmartAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk"; import { ChatOpenAI } from "@langchain/openai"; import { z } from "zod"; // Define a simple tool const echo = createTool({ name: "echo", description: "Echo back the input text", schema: z.object({ text: z.string().min(1) }), func: async ({ text }) => ({ echoed: text }), }); // Create model adapter const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY, })); // Create smart agent with planning const agent = createSmartAgent({ name: "Assistant", model, tools: [echo], useTodoList: true, limits: { maxToolCalls: 5, maxToken: 6000 }, tracing: { enabled: true }, }); // Run the agent const result = await agent.invoke({ messages: [{ role: "user", content: "Plan a greeting and send it via the echo tool" }], }); console.log(result.content); ``` -------------------------------- ### Create Smart Agent with Planning and Summarization - TypeScript Source: https://context7.com/cognipeer/agent-sdk/llms.txt Illustrates the creation of an enhanced agent using `createSmartAgent`. This function enables system prompts, automatic token-based summarization, and a TODO list planning workflow. It also supports context compression and event handling for monitoring agent execution, including plan updates, summarization events, and tool calls. ```typescript import { createSmartAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk"; import { ChatOpenAI } from "langchain/openai"; import { z } from "zod"; const searchTool = createTool({ name: "web_search", description: "Search the web for current information", schema: z.object({ query: z.string().min(3), maxResults: z.number().int().min(1).max(10).default(5), }), func: async ({ query, maxResults }) => { // Simulate API call return { results: [ { title: "Result 1", url: "https://example.com/1", snippet: "..." }, { title: "Result 2", url: "https://example.com/2", snippet: "..." }, ].slice(0, maxResults) }; }, }); const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o", apiKey: process.env.OPENAI_API_KEY, })); const agent = createSmartAgent({ name: "ResearchAssistant", version: "1.0.0", model, tools: [searchTool], useTodoList: true, // Enable planning mode with TODO tracking limits: { maxToolCalls: 20, maxToken: 8000, // Trigger summarization when approaching this limit contextTokenLimit: 6000, summaryTokenLimit: 2000, }, systemPrompt: "You are a research assistant. Always cite sources.", summarization: true, // Enable automatic context compression tracing: { enabled: true, logData: true }, }); const result = await agent.invoke( { messages: [{ role: "user", content: "Research recent developments in quantum computing and create a summary" }], }, { onEvent: (event) => { if (event.type === "plan") { console.log("Plan updated:", event.todoList); } if (event.type === "summarization") { console.log(`Archived ${event.archivedCount} tool responses`); } if (event.type === "tool_call") { console.log(`Tool ${event.name}: ${event.phase}`); } } } ); console.log(result.content); ```