### Quick Start Example Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/cli/index.mdx Create a new agent project using the 'simple-agent' template and then run the agent. This is a quick way to get started with ADK-TS. ```bash # Create a new agent project adk new my-ai-assistant --template simple-agent cd my-ai-assistant adk run ``` -------------------------------- ### Clone and Setup ADK-TS Examples Source: https://github.com/iqaicom/adk-ts/blob/main/README.md Steps to clone the ADK-TS repository, install dependencies, build the package, and set up environment variables for running examples. ```bash # 1. Clone and install the repository git clone https://github.com/IQAIcom/adk-ts.git cd adk-ts pnpm install # 2. Build the ADK-TS package (required for examples to work) pnpm build # 3. Setup API keys cd apps/examples echo "GOOGLE_API_KEY=your_google_api_key_here" > .env # 4. Run examples pnpm start ``` -------------------------------- ### Quick Start AgentBuilder Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/agents/agent-builder.mdx Use the convenience method for the simplest way to get started with AgentBuilder. This example demonstrates asking a question using a specified model. ```typescript import { AgentBuilder } from "@iqai/adk"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { const response = await AgentBuilder.withModel("gemini-2.5-flash").ask( "Hello, what can you help me with?", ); console.log("response: ", response); } main().catch(console.error); ``` -------------------------------- ### Setup Application Default Credentials (ADC) Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/tools/google-cloud-tools.mdx These bash commands guide you through installing the Google Cloud CLI, authenticating your local environment, setting your default project, and verifying your ADC setup by printing an access token. ```bash # Install Google Cloud CLI # Visit: https://cloud.google.com/sdk/docs/install # Authenticate with your Google account gcloud auth application-default login # Set your default project gcloud config set project YOUR_PROJECT_ID # Verify setup gcloud auth application-default print-access-token ``` -------------------------------- ### Run ADK-TS Examples Source: https://github.com/iqaicom/adk-ts/blob/main/apps/examples/README.md Executes ADK-TS examples. Use 'pnpm start' for interactive mode or 'pnpm start --name ' to run a specific example. ```bash cd apps/examples # Interactive mode - browse and select an example pnpm start # Or run a specific example directly pnpm start --name 01-getting-started pnpm start --name 06-mcp-and-integrations ``` -------------------------------- ### Initialize IQ Wiki Toolset (Simple) Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/iqwiki.mdx Initialize the McpIqWiki toolset for simple usage. This is the most straightforward way to get started. ```typescript import { McpIqWiki } from "@iqai/adk"; const toolset = McpIqWiki(); const tools = await toolset.getTools(); ``` -------------------------------- ### Quick Start: Simple Agent Ask Source: https://github.com/iqaicom/adk-ts/blob/main/packages/adk/README.md A basic example demonstrating how to create an agent and ask a question using a specified LLM model. ```typescript import { AgentBuilder } from "@iqai/adk"; const response = await AgentBuilder.withModel("gpt-4.1").ask( "What is the primary function of an AI agent?", ); console.log(response); ``` -------------------------------- ### Quick Start: Initialize and Use Third-Party MCP Wrappers Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/third-party-wrappers/index.mdx This example shows how to initialize the McpFilesystem and McpMemory wrappers, retrieve their tools, and combine them with other tools to create an LlmAgent. Remember to always close the toolsets after use. ```typescript import { McpFilesystem, McpMemory, LlmAgent } from "@iqai/adk"; // Initialize filesystem with allowed directories const filesystemToolset = McpFilesystem({ env: { ALLOWED_DIRECTORIES: "/workspace,/project/data", }, }); // Initialize memory (no config needed) const memoryToolset = McpMemory(); // Get tools const [fileTools, memoryTools] = await Promise.all([ filesystemToolset.getTools(), memoryToolset.getTools(), ]); // Create agent with combined tools const agent = new LlmAgent({ name: "smart_assistant", description: "An assistant with file system and memory capabilities", model: "gemini-2.5-flash", tools: [...fileTools, ...memoryTools], }); // Always cleanup await Promise.all([filesystemToolset.close(), memoryToolset.close()]); ``` -------------------------------- ### Build and Run Examples Source: https://github.com/iqaicom/adk-ts/blob/main/CONTRIBUTING.md Build the examples and then run them locally to explore and test example agents and flows. ```bash pnpm build cd apps/examples pnpm dev ``` -------------------------------- ### Quick Start with AgentBuilder Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/runtime/index.mdx Use AgentBuilder for a quick start, as it automatically handles session and runner setup for basic interactions. ```typescript import { AgentBuilder } from "@iqai/adk"; // Simple one-liner for basic interactions const response = await AgentBuilder.withModel("gemini-2.0-flash-exp").ask( "What is the capital of France?", ); console.log(response); // "The capital of France is Paris." ``` -------------------------------- ### Development Setup for @iqai/mcp-docs Source: https://github.com/iqaicom/adk-ts/blob/main/packages/mcp-docs/README.md Standard pnpm commands for managing the development of the @iqai/mcp-docs package, including installing dependencies, running in development mode, building for production, and executing tests. ```bash # Install dependencies pnpm install # Run in development mode pnpm dev # Build for production pnpm build # Run tests pnpm test ``` -------------------------------- ### Quick Start: Save and Load Artifacts Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/artifacts/index.mdx Demonstrates the basic usage of saving an artifact with text content and then loading it. This example uses the InMemoryArtifactService for demonstration purposes. ```typescript import { AgentBuilder, CallbackContext, InMemoryArtifactService, } from "@iqai/adk"; const { runner } = await AgentBuilder.create("my_agent") .withModel("gemini-2.5-flash") .withArtifactService(new InMemoryArtifactService()) .withBeforeAgentCallback(async (ctx: CallbackContext) => { const version = await ctx.saveArtifact("notes.txt", { text: "Agent started.", }); console.log(`Saved at version ${version}`); // 0 const artifact = await ctx.loadArtifact("notes.txt"); if (artifact?.text) console.log(artifact.text); return undefined; }) .build(); ``` -------------------------------- ### Clone and Run ADK Examples Source: https://github.com/iqaicom/adk-ts/blob/main/packages/adk/README.md Clone the ADK TypeScript repository to explore comprehensive examples. Install dependencies and run the examples locally to understand their implementation. ```bash git clone https://github.com/IQAIcom/adk-ts cd adk-ts/apps/examples pnpm install && pnpm dev ``` -------------------------------- ### Initialize Odos MCP Toolset (Simple) Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/odos.mdx Initialize the Odos MCP toolset with environment variables for wallet private key. This is a straightforward way to get started. ```typescript import { McpOdos } from "@iqai/adk"; const toolset = McpOdos({ env: { WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY, }, }); const tools = await toolset.getTools(); ``` -------------------------------- ### Run Simple Agent Example Source: https://github.com/iqaicom/adk-ts/blob/main/ARCHITECHTURE.md Set environment variables for API keys and run the simple agent example. ```bash # Set up environment variables export GOOGLE_API_KEY=your-google-api-key export OPENAI_API_KEY=your-openai-api-key # Run simple example cd apps/examples pnpm dev simple-agent ``` -------------------------------- ### Launch Web-Based Interface for Agent Testing Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/get-started/quickstart.mdx Start a local web server to access a graphical chat interface for testing your agent. This command assumes the CLI is installed globally. ```bash adk web ``` -------------------------------- ### Complete AgentBuilder Configuration Example Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/agents/agent-builder.mdx Demonstrates the full range of AgentBuilder capabilities, including model selection, tools, memory, session management, run configurations, and callbacks. Use this for complex agent setups requiring fine-grained control. ```typescript import { AgentBuilder, InMemoryMemoryService, BuiltInCodeExecutor, GoogleSearch, StreamingMode, } from "@iqai/adk"; import { config } from "dotenv"; // Load environment variables from .env file config(); const { runner } = await AgentBuilder.create("advanced_agent") .withModel("gemini-2.5-flash") .withDescription("Advanced research and analysis agent") .withInstruction("You are a thorough research assistant") .withTools(new GoogleSearch()) .withCodeExecutor(new BuiltInCodeExecutor()) .withMemory(new InMemoryMemoryService()) .withQuickSession({ userId: "user-123", appName: "research-app", }) .withRunConfig({ streamingMode: StreamingMode.SSE, maxLlmCalls: 50, saveInputBlobsAsArtifacts: true, }) .withBeforeAgentCallback(async context => { console.log(`Starting research task: ${context.sessionId}`); return undefined; }) .withAfterToolCallback(async context => { console.log(`Tool ${context.name} completed`); }) .build(); // User asks the agent to research the requested topic const result = await runner.ask("Research quantum computing trends"); ``` -------------------------------- ### Install MCP IQ Wiki Package Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/iqwiki.mdx Install the IQ Wiki MCP package using pnpm. ```bash pnpm add @iqai/mcp-iqwiki ``` -------------------------------- ### Install @iqai/mcp-abi Package Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/abi.mdx Install the necessary package for ABI interactions using pnpm. ```bash pnpm add @iqai/mcp-abi ``` -------------------------------- ### Full Agent Integration Example Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/defillama.mdx Example demonstrating how to integrate the DefiLlama MCP toolset into an agent for DeFi research. ```typescript import { AgentBuilder, McpDefillama } from "@iqai/adk"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { // Initialize McpDefillama toolset const toolset = McpDefillama(); // Get available McpDefillama tools const defillamaTools = await toolset.getTools(); // Create agent with McpDefillama tools const { runner } = await AgentBuilder.create("defillama_agent") .withModel("gemini-2.5-flash") .withDescription("A DeFi research agent powered by DefiLlama data") .withTools(...defillamaTools) .build(); const response = await runner.ask( "What are the top 5 DeFi protocols by TVL right now?", ); console.log(response); } main().catch(console.error); ``` -------------------------------- ### Heroku CLI Installation and Login Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/guides/deployment/telegram.mdx Install the Heroku CLI and log in to your account before creating an app. ```bash npm install -g heroku heroku login ``` -------------------------------- ### Set Up New Project from Scratch Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/get-started/quickstart.mdx Manually create a new project directory, initialize npm, and install necessary dependencies and TypeScript configuration. ```bash mkdir my-first-agent && cd my-first-agent pnpm init -y pnpm install @iqai/adk tsx typescript dotenv npx tsc --init --target ES2022 --module ESNext --moduleResolution bundler --allowImportingTsExtensions --noEmit ``` -------------------------------- ### Configure Local Development Environment Source: https://github.com/iqaicom/adk-ts/blob/main/apps/starter-templates/shade-agent/README.md Copy the example environment file to set up local development variables. Refer to .env.example for required and optional values. ```bash cp .env.example .env.development.local ``` -------------------------------- ### Configure Railway Build and Start Commands Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/guides/deployment/telegram.mdx Set the build and start commands for your Node.js project on Railway. Ensure dependencies are installed and the application is built before starting. ```bash pnpm install && pnpm build ``` ```bash node dist/index.js ``` -------------------------------- ### Quick Start: Set Up MCP Sampling Handler Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/tools/mcp-sampling.mdx This snippet demonstrates the quickest way to enable sampling by passing an agent's `ask` method directly as the sampling handler. It shows agent creation, wrapping the `ask` method, and configuring an MCP toolset. ```typescript import { AgentBuilder, createSamplingHandler, McpToolset } from "@iqai/adk"; // 1. Create an agent that will handle sampling requests const { runner } = await AgentBuilder.withModel("gemini-2.5-flash") .withInstruction("You are a helpful assistant.") .build(); // 2. Wrap its ask method as a sampling handler const samplingHandler = createSamplingHandler(runner.ask); // 3. Pass to an MCP toolset const toolset = new McpToolset({ name: "My MCP Server", description: "Server with sampling capabilities", samplingHandler, transport: { mode: "stdio", command: "node", args: ["./my-mcp-server/dist/index.js"], }, }); const tools = await toolset.getTools(); ``` -------------------------------- ### Start Development Server Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/README.md Run the Next.js development server to view the documentation locally and enable hot reloading. ```bash pnpm dev ``` -------------------------------- ### Getting Started with AgentScheduler Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/agents/agent-scheduler.mdx Build an agent using AgentBuilder, create an AgentScheduler instance, schedule a job with a cron expression, and start the scheduler. The scheduler validates cron expressions on registration. ```typescript import { AgentBuilder, AgentScheduler } from "@iqai/adk"; // 1. Build your agent const { runner } = await AgentBuilder.create("daily_reporter_agent") .withModel("gemini-2.5-flash") .withInstruction("Generate a daily summary report") .build(); // 2. Create the scheduler and add a job const scheduler = new AgentScheduler(); scheduler.schedule({ id: "daily-report", cron: "0 9 * * *", // Every day at 9 AM runner, userId: "system", input: "Generate today's report", }); // 3. Start the scheduler scheduler.start(); // Later: gracefully stop await scheduler.stop(); ``` -------------------------------- ### GcsArtifactService Setup and Usage Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/tools/google-cloud-tools.mdx Service for storing agent artifacts in Google Cloud Storage with automatic versioning. Includes installation, setup, and basic usage for saving and loading artifacts, as well as integration with an LlmAgent. ```bash # Install the Google Cloud Storage client library npm install @google-cloud/storage # Create a bucket gsutil mb gs://my-artifacts-bucket # Set up authentication (choose one) export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" # OR gcloud auth application-default login ``` ```typescript import { GcsArtifactService, LlmAgent } from "@iqai/adk"; import { Part } from "@google/genai"; const artifactService = new GcsArtifactService("my-artifacts-bucket"); // Provide the base64 image data (replace the placeholder with real data or load from fs) const imageBase64: string = ""; // Save an artifact const artifact: Part = { inlineData: { data: imageBase64, mimeType: "image/jpeg", }, }; const version = await artifactService.saveArtifact({ appName: "photo_app", userId: "user123", sessionId: "session456", filename: "profile.jpg", artifact, }); // Load an artifact const loadedArtifact = await artifactService.loadArtifact({ appName: "photo_app", userId: "user123", sessionId: "session456", filename: "profile.jpg", // version: 2, // Optional: load specific version }); // Use with an agent const agent = new LlmAgent({ name: "image_processor_agent", description: "Agent for processing images", model: "gemini-2.0-flash", artifactService: artifactService, // ... other agent configuration }); ``` -------------------------------- ### Complete Example of a Long-Running Tool Workflow Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/tools/function-tools.mdx This example demonstrates a full implementation of a long-running tool, including agent setup, tool definition, and an asynchronous execution flow. Ensure your application handles the status updates for the long-running operation. ```typescript import { LlmAgent, FunctionTool, AgentBuilder } from "@iqai/adk"; import * as dotenv from "dotenv"; dotenv.config(); // Requests human approval for an expense. function requestHumanApproval(purpose: string, amount: number) { return { status: "pending", requestId: `req-${Date.now()}`, message: `Approval requested for ${purpose} ($${amount})`, }; } // Create a long-running function tool const approvalTool = new FunctionTool(requestHumanApproval, { name: "request_approval_tool", description: "Requests human approval for an expense", isLongRunning: true, }); const approvalAgent = new LlmAgent({ name: "approval_agent", description: "Handles expense approval requests", tools: [approvalTool], }); const rootAgent = () => { return AgentBuilder.create("root_agent") .withModel("gemini-2.5-flash") .withDescription("You are a general purpose assistant.") .withSubAgents([approvalAgent]) .build(); }; async function main() { const { runner } = await rootAgent(); const response = await runner.ask( "Request approval for a business lunch with a client for $45.", ); console.log(`🤖 Response: ${response}`); } main().catch(console.error); ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/iqaicom/adk-ts/blob/main/apps/starter-templates/next-js-starter/README.md Copy the example environment file to create your local configuration. ```bash cp .env.example .env.local ``` -------------------------------- ### Initialize Simple McpMemory Toolset Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/third-party-wrappers/memory.mdx Initialize the McpMemory toolset for basic usage. This is the simplest way to get started with the memory server. ```typescript import { McpMemory } from "@iqai/adk"; const toolset = McpMemory(); const tools = await toolset.getTools(); ``` -------------------------------- ### Initialize IQ Wiki Toolset (Verbose) Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/iqwiki.mdx Initialize the McpIqWiki toolset with explicit configuration, including transport mode and command. Use this for more control over the client setup. ```typescript import { McpToolset } from "@iqai/adk"; const toolset = new McpToolset({ name: "IQWiki MCP Client", description: "Client for IQ Wiki blockchain knowledge base", transport: { mode: "stdio", command: "npx", args: ["-y", "@iqai/mcp-iqwiki"], }, }); const tools = await toolset.getTools(); ``` -------------------------------- ### Initialize Limitless MCP Toolset (Simple) Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/limitless.mdx Initialize the Limitless MCP toolset for basic usage. This is the simplest way to get started. ```typescript import { McpLimitless } from "@iqai/adk"; const toolset = McpLimitless(); const tools = await toolset.getTools(); ``` -------------------------------- ### Full Integration Example Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/limitless.mdx An example demonstrating how to initialize the Limitless MCP toolset, create an agent, and query prediction markets. Ensure environment variables are configured if necessary. ```typescript import { AgentBuilder, McpLimitless } from "@iqai/adk"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { // Initialize McpLimitless toolset const toolset = McpLimitless(); // Get available McpLimitless tools const limitlessTools = await toolset.getTools(); // Create agent with McpLimitless tools const { runner } = await AgentBuilder.create("limitless_agent") .withModel("gemini-2.5-flash") .withDescription("A prediction market research agent using Limitless data") .withTools(...limitlessTools) .build(); const response = await runner.ask( "What are the current open prediction markets on Limitless and what are their probabilities?", ); console.log(response); } main().catch(console.error); ``` -------------------------------- ### Start Terminal-Based Chat with Agent Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/get-started/quickstart.mdx Initiate an interactive chat session with your agent directly in the terminal. This command assumes the CLI is installed globally. ```bash adk run ``` -------------------------------- ### Initialize Sequential Thinking Toolset (Simple) Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/third-party-wrappers/sequential-thinking.mdx Import and initialize the Sequential Thinking toolset using the McpSequentialThinking function. This is the most straightforward way to get started. ```typescript import { McpSequentialThinking } from "@iqai/adk"; const toolset = McpSequentialThinking(); const tools = await toolset.getTools(); ``` -------------------------------- ### Complete Notion Agent Example Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/third-party-wrappers/notion.mdx This example demonstrates initializing the Notion MCP server, creating an LLM agent with Notion tools, and performing a task. It includes error handling and ensures the server is closed properly. ```typescript import { McpNotion, LlmAgent } from "@iqai/adk"; async function main() { const notionToolset = McpNotion({ env: { NOTION_TOKEN: process.env.NOTION_TOKEN, }, }); try { const tools = await notionToolset.getTools(); const agent = new LlmAgent({ name: "notion_agent", model: "gemini-2.5-flash", description: "An agent that reads and writes Notion content", instruction: `You have access to a Notion workspace. Use the available tools to search pages, read content, and create or update pages. Always confirm before making destructive changes.`, tools, }); const response = await agent.ask( "Search for pages about project planning and summarize what you find", ); console.log(response); } finally { await notionToolset.close(); } } main(); ``` -------------------------------- ### Deploy Agent Directly via Node.js on EC2 Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/guides/deployment/aws.mdx Steps to clone your agent repository, install dependencies with pnpm, build, and start the agent using PM2. ```bash # Clone and install git clone https://github.com/your-username/your-adk-agent.git cd your-adk-agent pnpm install --frozen-lockfile # Build and start pnpm build pm2 start dist/index.js --name adk-agent pm2 save pm2 startup pm2 startup ``` -------------------------------- ### Full Integration Example with AgentBuilder Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/bamm.mdx Demonstrates initializing the McpBamm toolset, retrieving tools, creating an agent with a specified model and description, and executing a DeFi operation. ```typescript import { AgentBuilder, McpBamm } from "@iqai/adk"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { // Initialize McpBamm toolset const toolset = McpBamm({ env: { WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY, }, }); // Get available McpBamm tools const bammTools = await toolset.getTools(); // Create agent with McpBamm tools const { runner } = await AgentBuilder.create("bamm_agent") .withModel("gemini-2.5-flash") .withDescription("A DeFi agent that manages BAMM positions on Fraxtal") .withTools(...bammTools) .build(); const response = await runner.ask( "Add 100 FRAX as collateral to BAMM position at 0xC5B225cF058915BF28D7d9DFA3043BD53C63Ea84", ); console.log(response); } main().catch(console.error); ``` -------------------------------- ### Stdio Mode Connection Example Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/external-mcps.mdx Demonstrates the 'stdio' connection mode for locally installed MCP servers. This is the most common mode for running MCP servers as separate processes. ```typescript const toolset = new McpToolset({ name: "Local Server", description: "A toolset that runs a local server using npx.", transport: { mode: "stdio", command: "npx", args: ["-y", "@package/mcp-server"], env: { API_KEY: process.env.API_KEY || "", PATH: process.env.PATH || "", }, }, }); ``` -------------------------------- ### Serve Existing Documentation Source: https://github.com/iqaicom/adk-ts/blob/main/apps/adk-api-docs/README.md Serve the already generated API documentation locally. This is faster than rebuilding if no changes were made. ```bash pnpm run docs:serve ``` -------------------------------- ### Agent Execution Flow Example Source: https://github.com/iqaicom/adk-ts/blob/main/ARCHITECHTURE.md Demonstrates the creation of an LlmAgent, setting up a session service, creating a runner, and executing the agent asynchronously. ```typescript // 1. Create an agent const agent = new LlmAgent({ name: "my_agent", model: "gemini-2.5-flash", description: "A helpful assistant", tools: [new MyCustomTool()], }); // 2. Set up session service const sessionService = new InMemorySessionService(); const session = await sessionService.createSession("app", "user-id"); // 3. Create runner const runner = new Runner({ appName: "my-app", agent, sessionService, }); // 4. Execute agent for await (const event of runner.runAsync({ userId: "user-id", sessionId: session.id, newMessage: { parts: [{ text: "Hello!" }] }, })) { // Process events } ``` -------------------------------- ### OpenTelemetry Collector Configuration Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/observability/integrations.mdx Example configuration for the OpenTelemetry Collector to receive OTLP via HTTP and export to Jaeger and Datadog. This setup allows for telemetry routing and processing. ```yaml receivers: otlp: protocols: http: endpoint: 0.0.0.0:4318 processors: batch: timeout: 10s send_batch_size: 1024 exporters: otlphttp/jaeger: endpoint: http://jaeger:4318 otlphttp/datadog: endpoint: https://otlp.datadoghq.com:4318 headers: DD-API-KEY: ${env:DD_API_KEY} service: pipelines: traces: receivers: [otlp] processors: [batch] exporters: [otlphttp/jaeger, otlphttp/datadog] metrics: receivers: [otlp] processors: [batch] exporters: [otlphttp/datadog] ``` -------------------------------- ### Example MCP Server Structure (FastMCP) Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/tools/mcp-tools.mdx A basic structure for an MCP server using FastMCP. It defines the server and adds a custom tool. The server is started with 'stdio' transport. ```typescript // src/index.ts import { FastMCP } from "fastmcp"; import { weatherTool } from "./tools/weather.js"; async function main() { const server = new FastMCP({ name: "Weather MCP Server", version: "1.0.0", }); server.addTool(weatherTool); await server.start({ transportType: "stdio", }); } main().catch(console.error); ``` ```typescript // src/tools/weather.ts import { z } from "zod"; export const weatherTool = { name: "get_weather", description: "Get current weather for a city", parameters: z.object({ city: z.string().describe("City name"), }), execute: async ({ city }: { city: string }) => { // Your weather API logic here return { temperature: 72, condition: "Sunny" }; }, }; ``` -------------------------------- ### Start ADK-TS CLI Server Source: https://github.com/iqaicom/adk-ts/blob/main/apps/adk-web/README.md Navigate to the starter-templates directory and run this command to start the ADK-TS CLI server. You can also navigate into a specific agent's directory to test it individually. ```bash # From the starter-templates directory ( contains all testable agents) cd apps/starter-templates adk run ``` ```bash # Or cd into a specific agent to test it individually cd apps/starter-templates/simple-agent adk run ``` -------------------------------- ### Initialize Fraxlend MCP Client (Simple) Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/fraxlend.mdx Initialize the Fraxlend MCP client with environment variables for wallet private key. ```typescript import { McpFraxlend } from "@iqai/adk"; const toolset = McpFraxlend({ env: { WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY, }, }); const tools = await toolset.getTools(); ``` -------------------------------- ### Complete Example: Agent with Sequential Thinking Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/third-party-wrappers/sequential-thinking.mdx Demonstrates initializing the sequential thinking toolset with debug logging enabled, creating an LlmAgent, and using it to solve a problem step by step. Remember to close the toolset when done. ```typescript import { McpSequentialThinking, LlmAgent } from "@iqai/adk"; async function main() { // Initialize sequential thinking toolset const thinkingToolset = McpSequentialThinking({ debug: true, }); try { const tools = await thinkingToolset.getTools(); const agent = new LlmAgent({ name: "reasoning_agent", model: "gemini-2.5-flash", description: "An agent that reasons through problems step by step", instruction: `For complex problems, use sequential thinking to work through each step before giving an answer. Revise your thinking if you find errors.`, tools, }); const response = await agent.ask( "A farmer has 17 sheep. All but 9 die. How many sheep are left?", ); console.log(response); } finally { await thinkingToolset.close(); } } main(); ``` -------------------------------- ### Quick Start: Processing Event Streams Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/events/index.mdx Iterate over the async generator returned by runner.runAsync() to process events as they arrive. This example shows how to extract and log the final text response from an event. ```typescript import { AgentBuilder } from "@iqai/adk"; const { runner } = await AgentBuilder.create("assistant") .withModel("gemini-2.5-flash") .withInstruction("You are a helpful assistant.") .build(); const events = runner.runAsync({ userId: "user-1", sessionId: "session-1", newMessage: { role: "user", parts: [{ text: "What is 2 + 2?" }] }, }); for await (const event of events) { if (event.isFinalResponse() && event.content?.parts?.[0]?.text) { console.log(event.content.parts[0].text); } } ``` -------------------------------- ### Initialize Observability and Run Agent Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/observability/getting-started.mdx This example shows how to initialize the telemetry service with OTLP endpoint and agent configuration, handle termination signals, and run an agent query. Ensure the OTLP endpoint is correctly configured for your observability backend. ```typescript import { telemetryService, AgentBuilder } from "@iqai/adk"; async function main() { await telemetryService.initialize({ appName: "example-agent", appVersion: "1.0.0", otlpEndpoint: "http://localhost:4318/v1/traces", enableMetrics: true, enableTracing: true, }); process.on("SIGTERM", async () => { await telemetryService.shutdown(5000); process.exit(0); }); process.on("SIGINT", async () => { await telemetryService.shutdown(5000); process.exit(0); }); const response = await AgentBuilder.withModel("gemini-2.5-flash").ask( "What is the capital of France?", ); console.log(response); } main().catch(console.error); ``` -------------------------------- ### GitHub Actions for Agent Evaluation Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/evaluation/evaluation-patterns.mdx Integrate agent evaluation into your CI/CD pipeline using GitHub Actions. This example sets up Node.js, installs dependencies, builds the project, and runs the evaluation script. ```yaml name: Agent Evaluation on: pull_request: paths: - "src/agents/**" - "evaluation/**" jobs: evaluate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - run: pnpm install - run: pnpm build - name: Run agent evaluation run: pnpm tsx evaluation/run.ts env: GOOGLE_API_KEY: ${{ secrets.GOOGLE_API_KEY }} ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/iqaicom/adk-ts/blob/main/apps/starter-templates/discord-bot/README.md Copies the example environment file to a new file for configuration. Required Discord bot token and Google AI API key should be added to the .env file. ```bash cp .env.example .env ``` -------------------------------- ### Run Documentation Site Locally Source: https://github.com/iqaicom/adk-ts/blob/main/CONTRIBUTING.md Navigate to the documentation site directory and run it locally. ```bash cd apps/docs pnpm dev ``` -------------------------------- ### Full Integration Example with AgentBuilder Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/upbit.mdx Demonstrates initializing the McpUpbit toolset, retrieving tools, and building an agent with these tools for crypto trading on Upbit. Includes environment variable loading for API keys. ```typescript import { AgentBuilder, McpUpbit } from "@iqai/adk"; import * as dotenv from "dotenv"; dotenv.config(); async function main() { // Initialize McpUpbit toolset const toolset = McpUpbit({ env: { UPBIT_ACCESS_KEY: process.env.UPBIT_ACCESS_KEY, UPBIT_SECRET_KEY: process.env.UPBIT_SECRET_KEY, UPBIT_ENABLE_TRADING: "true", }, }); // Get available McpUpbit tools const upbitTools = await toolset.getTools(); // Create agent with McpUpbit tools const { runner } = await AgentBuilder.create("upbit_agent") .withModel("gemini-2.5-flash") .withDescription("A crypto trading agent that monitors and trades on Upbit") .withTools(...upbitTools) .build(); const response = await runner.ask( "What is the current price of Bitcoin on Upbit and how has it moved in the last 24 hours?", ); console.log(response); } main().catch(console.error); ``` -------------------------------- ### Research Analyst Agent Configuration Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/agents/llm-agents.mdx Configure a specialized Research Analyst Agent with custom tools, memory services, and structured input/output validation using Zod schemas. This example showcases a production-ready setup with monitoring and state management. ```typescript import { LlmAgent, FunctionTool, GoogleSearch, InMemoryMemoryService, InMemorySessionService, AgentBuilder, } from "@iqai/adk"; import { z } from "zod"; import { config } from "dotenv"; // Load environment variables from .env file config(); // Define structured input/output schemas const AnalysisRequestSchema = z.object({ topic: z.string(), depth: z.enum(["brief", "detailed", "comprehensive"]), format: z.enum(["summary", "report", "presentation"]), }); const AnalysisResponseSchema = z.object({ topic: z.string(), summary: z.string(), keyFindings: z.array(z.string()), data: z.record(z.string(), z.any()), confidence: z.number(), sources: z.array(z.string()), recommendations: z.array(z.string()), }); // Custom analysis tools const analyzeData = (data: any[]) => { const stats = { count: data.length, average: data.reduce((a, b) => a + b, 0) / data.length, min: Math.min(...data), max: Math.max(...data), }; return stats; }; const generateReport = (findings: any) => { return `# Analysis Report\n\n${JSON.stringify(findings, null, 2)}`; }; // Research Analyst Agent const researchAnalyst = new LlmAgent({ name: "research_analyst", description: "Specialized agent for research, data analysis, and structured reporting", // Core model configuration model: "gemini-2.0-flash-exp", // Dynamic instructions with context awareness instruction: ctx => ` You are an expert research analyst. Your expertise includes: - Web research and information gathering - Data analysis and statistical processing - Structured report generation - Critical evaluation of sources and findings Current user: ${ctx.state.userProfile?.name || "Researcher"} Previous analyses: ${ctx.state.completedAnalyses?.length || 0} completed Always provide evidence-based conclusions with confidence scores. Use tools strategically and explain your analytical process. `, // Tool integration for enhanced capabilities tools: [ new GoogleSearch(), new FunctionTool(analyzeData, { name: "analyze_dataset", description: "Perform statistical analysis on numerical datasets", }), new FunctionTool(generateReport, { name: "format_report", description: "Generate formatted analysis reports from findings", }), ], // Persistence and memory memoryService: new InMemoryMemoryService(), sessionService: new InMemorySessionService(), // Structured I/O validation inputSchema: AnalysisRequestSchema, outputSchema: AnalysisResponseSchema, // Optimized generation parameters generateContentConfig: { temperature: 0.2, // Low creativity for analytical accuracy maxOutputTokens: 2000, topP: 0.9, topK: 30, }, // Session state management outputKey: "analysis_result", userId: "analyst_user", appName: "research_suite", // Monitoring and logging beforeAgentCallback: ctx => { console.log(`🔍 Starting analysis for: ${ctx.agentName}`); return undefined; }, afterAgentCallback: ctx => { console.log( `✅ Analysis completed for ${ctx.agentName} - stored in session state`, ); return undefined; }, }); // Build and use the agent async function initializeAgent() { const { runner } = await AgentBuilder.create() .withModel("gemini-2.0-flash") .withAgent(researchAnalyst) .build(); // Example usage with structured input const result = await runner.ask( "Analyze the impact of renewable energy adoption on global carbon emissions", ); // Parse the structured JSON response const analysis = JSON.parse(result); console.log("Analysis Summary:", analysis.summary); console.log("Key Findings:", analysis.keyFindings); console.log("Confidence Score:", analysis.confidence); } // Initialize the agent initializeAgent().catch(console.error); ``` -------------------------------- ### Run Agent Web Interface with npx Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/get-started/quickstart.mdx Launch the ADK-TS CLI's web interface using npx, avoiding the need for a global installation. This command starts a local server and provides a URL for accessing the chat interface in your browser. ```bash npx @iqai/adk-cli web ``` -------------------------------- ### Conditional Logic Instructions for Diagnostics Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/guides/agent-instructions.mdx Implement agent instructions with conditional logic to guide troubleshooting workflows. This example shows how to define decision trees based on issue categories and escalation rules, using tools for automated checks and log analysis. ```typescript const diagnosticAgent = new LlmAgent({ name: "technical_diagnostics", instruction: ` You are a technical diagnostic specialist for troubleshooting system issues. **Diagnostic workflow:** IF issue_category == "performance": 1. Check system_metrics for CPU, memory, disk usage 2. Review recent_logs for error patterns 3. If metrics > 80% → Recommend resource upgrade 4. If metrics normal → Check application-specific logs IF issue_category == "connectivity": 1. Run network_test to check connection status 2. If internal network fails → Check local configuration 3. If external network fails → Check firewall and DNS 4. If partial connectivity → Run traceroute analysis IF issue_category == "security": 1. Immediately run security_scan 2. If threats detected → Transfer to security_specialist IMMEDIATELY 3. If no threats → Check access_logs for unusual patterns 4. Document all findings in security_report **Escalation rules:** - Security threats → security_specialist (immediate) - Hardware failures → hardware_support - Complex network issues → network_specialist - Database problems → database_admin **Communication:** - Explain each diagnostic step to the user - Provide ETA for resolution when possible - Always confirm before making system changes Use run_diagnostic tool for automated checks, log_analysis for reviewing system logs. `, }); ``` -------------------------------- ### Initialize and Use MCP Server Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/mcp-servers/iq-ai-servers/index.mdx Demonstrates the common pattern for initializing an MCP server, retrieving its tools, creating an LlmAgent, and cleaning up resources. Ensure all required environment variables are set before initialization. ```typescript import { McpServerName, LlmAgent } from "@iqai/adk"; // Initialize with environment variables const toolset = McpServerName({ env: { REQUIRED_VAR: process.env.REQUIRED_VAR, }, }); // Get tools const tools = await toolset.getTools(); // Create agent const agent = new LlmAgent({ name: "my_agent", description: "Description of my agent", model: "gemini-2.5-flash", tools, }); // Always cleanup await toolset.close(); ``` -------------------------------- ### Sequential Pipeline Agent Example Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/agents/multi-agents.mdx Demonstrates a content creation pipeline using `SequentialAgent` with multiple `LlmAgent` instances. Each agent is configured with an `outputKey` to save its results to session state, and subsequent agents reference these outputs using `{key}` notation in their instructions. This setup ensures data flows correctly through the pipeline. ```typescript import { LlmAgent, SequentialAgent } from "@iqai/adk"; // Content creation pipeline example const contentResearcherAgent = new LlmAgent({ name: "content_researcher_agent", model: "gemini-2.5-flash", description: "Researches topics and gathers relevant information", instruction: "Research the given topic thoroughly. Gather key facts, statistics, and relevant information.", outputKey: "research_data", // Output saved to session state }); const contentOutlinerAgent = new LlmAgent({ name: "content_outliner_agent", model: "gemini-2.5-flash", description: "Creates structured outlines from research data", instruction: "Based on the research data: {research_data}, create a detailed content outline with main points and structure.", // References research_data from state outputKey: "content_outline", }); const contentWriterAgent = new LlmAgent({ name: "content_writer_agent", model: "gemini-2.5-flash", description: "Writes comprehensive articles based on research and outlines", instruction: "Using the research: {research_data} and outline: {content_outline}, write a comprehensive, well-structured article.", // References both previous outputs outputKey: "draft_content", }); const contentEditorAgent = new LlmAgent({ name: "content_editor_agent", model: "gemini-2.5-flash", description: "Reviews and edits content for quality and accuracy", instruction: "Review and edit the draft content: {draft_content}. Improve clarity, flow, and accuracy.", outputKey: "final_content", }); // Sequential pipeline orchestration const contentCreationPipelineAgent = new SequentialAgent({ name: "content_creation_pipeline_agent", description: "Complete content creation from research to final edited piece", subAgents: [ contentResearcherAgent, contentOutlinerAgent, contentWriterAgent, contentEditorAgent, ], }); // Execution flow: // 1. contentResearcherAgent → state["research_data"] // 2. contentOutlinerAgent → reads research_data → state["content_outline"] // 3. contentWriterAgent → reads research_data + content_outline → state["draft_content"] // 4. contentEditorAgent → reads draft_content → state["final_content"] ``` -------------------------------- ### Initialize and Use Built-in MCP Servers Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/tools/mcp-tools.mdx Use wrapper functions for IQ AI's pre-built servers with minimal configuration. Ensure to clean up resources when done. ```typescript import { McpAtp, LlmAgent } from "@iqai/adk"; // Initialize ATP MCP toolset const atpToolset = McpAtp({ env: { ATP_WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY, ATP_API_KEY: process.env.ATP_API_KEY, }, }); // Get tools and create agent const tools = await atpToolset.getTools(); const agent = new LlmAgent({ name: "blockchain_agent", model: "gemini-2.5-flash", description: "An agent that queries blockchain data and interacts with DeFi protocols", instruction: "Query blockchain data and interact with DeFi protocols", tools, }); // Always cleanup when done await atpToolset.close(); ``` -------------------------------- ### Start the Scheduler Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/agents/agent-scheduler.mdx Start the scheduler service. Once started, all enabled jobs will begin their scheduled timers. ```APIDOC ## start() ### Description Start the scheduler. All enabled jobs begin their timers. ### Method `start(): void` ``` -------------------------------- ### Direct Runtime Setup with LlmAgent Source: https://github.com/iqaicom/adk-ts/blob/main/apps/docs/content/docs/framework/runtime/index.mdx For production applications requiring explicit control, use the low-level Runtime API. This involves creating an agent, setting up services like InMemorySessionService, and then creating a Runner. ```typescript import { LlmAgent, Runner, InMemorySessionService } from "@iqai/adk"; // Step 1: Create your agent const agent = new LlmAgent({ name: "assistant", model: "gemini-2.0-flash-exp", description: "A helpful assistant", instruction: "You are a helpful assistant. Be concise and friendly.", }); // Step 2: Set up services const sessionService = new InMemorySessionService(); const session = await sessionService.createSession("my-app", "user_123"); // Step 3: Create the Runner const runner = new Runner({ appName: "my-app", agent, sessionService, }); // Step 4: Process user input for await (const event of runner.runAsync({ userId: "user_123", sessionId: session.id, newMessage: { parts: [{ text: "Hello! How are you?" }] }, })) { console.log(`${event.author}:`, event.content?.parts?.[0]?.text); } ``` -------------------------------- ### Basic Agent Usage Example Source: https://github.com/iqaicom/adk-ts/blob/main/packages/adk/README.md Demonstrates how to instantiate and run a simple AI agent with a specified model, description, and instructions. Ensure environment variables for API keys are loaded. ```typescript import { Agent } from "@iqai/adk"; import dotenv from "dotenv"; // Load environment variables dotenv.config(); // Instantiate the agent const myAgent = new LlmAgent({ name: "simple_query_assistant", model: "gemini-2.5-flash", // Or "gpt-4-turbo", "claude-3-opus" description: "A basic assistant to answer questions.", instructions: "You are a helpful AI. Respond clearly and concisely.", }); // Asynchronously run the agent async function runQuery() { try { const query = "What is the capital of France?"; console.log(`User: ${query}`); const response = await myAgent.run({ messages: [{ role: "user", content: query }], }); console.log(`Agent: ${response.content}`); } catch (error) { console.error("Error during agent execution:", error); } } runQuery(); ```