### Complete Agent Configuration Example Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Provides a comprehensive example of configuring an agent with various options, including name, instructions, LLM model (Anthropic), model configuration, memory settings, RAG, tools, tool iteration limits, streaming, and debug mode. ```typescript import { Agent, anthropic } from '@runflow-ai/sdk'; const agent = new Agent({ name: 'Advanced Support Agent', instructions: `You are an expert customer support agent. - Always be polite and helpful - Solve problems efficiently - Use tools when needed`, // Model model: anthropic('claude-3-5-sonnet-20241022'), // Model configuration modelConfig: { temperature: 0.7, maxTokens: 4000, topP: 0.9, frequencyPenalty: 0, presencePenalty: 0, }, // Memory memory: { type: 'conversation', maxTurns: 20, summarizeAfter: 50, }, // RAG (Agentic - LLM decides when to search) rag: { vectorStore: 'support-docs', k: 5, threshold: 0.7, searchPrompt: 'Use for technical questions', }, // Tools tools: { createTicket: ticketTool, searchOrders: orderTool, }, // Tool iteration limit maxToolIterations: 10, // Streaming streaming: { enabled: true, }, // Debug mode debug: true, }); ``` -------------------------------- ### Install TypeScript and Import Types (Bash/TypeScript) Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=readme Instructions for ensuring compatibility with the Runflow SDK by installing a recent version of TypeScript and demonstrating the correct way to import SDK types for better code maintainability and type safety. ```bash npm install --save-dev typescript@^5.0.0 ``` ```typescript // Use proper type imports import type { AgentConfig, AgentInput, AgentOutput } from '@runflow-ai/sdk'; ``` -------------------------------- ### Create Connector Tools with Runflow AI SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Demonstrates the creation of various connector tools using the `createConnectorTool` function. This includes examples for interacting with HubSpot, Twilio, Email, and Slack services. ```typescript import { createConnectorTool } from '@runflow-ai/sdk'; // HubSpot - Create contact const createContact = createConnectorTool( 'hubspot', 'contacts', 'create', { email: 'email', firstName: 'string?', lastName: 'string?', phone: 'string?', company: 'string?', } ); // Twilio - Send WhatsApp const sendWhatsApp = createConnectorTool( 'twilio', 'messages', 'send-whatsapp', { to: 'string', message: 'string', mediaUrl: 'url?', } ); // Email - Send email const sendEmail = createConnectorTool( 'email', 'messages', 'send', { to: 'email', subject: 'string', body: 'string', html: 'boolean?', } ); // Slack - Send message const sendSlack = createConnectorTool( 'slack', 'messages', 'send', { channel: 'string', message: 'string', username: 'string?', iconEmoji: 'string?', } ); ``` -------------------------------- ### Install Runflow SDK using npm, yarn, or pnpm Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk This snippet shows how to install the Runflow SDK package using different package managers. Ensure you have Node.js version 22.0.0 or higher and TypeScript 5.0.0 or higher installed. ```bash npm install @runflow-ai/sdk # or yarn add @runflow-ai/sdk # or pnpm add @runflow-ai/sdk ``` -------------------------------- ### JSON Configuration for RAG Settings Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Provides example JSON configuration for Retrieval-Augmented Generation (RAG) settings, including the vector store name, `k` value for results, and the similarity `threshold`. ```json rag: { vectorStore: 'support-docs', // Verify this exists k: 10, // Increase for more results threshold: 0.5, // Lower for more lenient matching } ``` -------------------------------- ### Bash: Local Development Commands for Runflow SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Provides essential bash commands for local development of the Runflow SDK, including installing dependencies, building the project, running in watch mode, executing tests, and validating before publishing. ```bash # Install dependencies npm install # Build npm run build # Watch mode npm run dev # Tests npm test # Validate before publishing npm run validate ``` -------------------------------- ### Customer Onboarding Assistant with Runflow SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk This agent guides new users through an onboarding process with interactive, multi-turn conversations. It utilizes OpenAI for natural language interaction, memory summarization for long conversations, and tools for sending emails, Slack notifications, and tracking onboarding step completion. ```typescript import { Agent, openai } from '@runflow-ai/sdk'; import { emailConnector, slackConnector } from '@runflow-ai/sdk/connectors'; const onboardingAgent = new Agent({ name: 'Onboarding Assistant', instructions: `You are an onboarding specialist. - Guide users step by step - Celebrate their progress - Provide helpful resources - Detect when they're stuck and offer help - Track completion of onboarding steps`, model: openai('gpt-4o'), memory: { type: 'conversation', maxTurns: 50, // Long conversation summarization: { enabled: true, threshold: 20, }, }, knowledge: { vectorStore: 'onboarding-docs', k: 3, }, tools: { sendEmail: emailConnector.messages.send, notifyTeam: slackConnector.messages.send, markStepComplete: createTool({ id: 'mark-step-complete', description: 'Mark an onboarding step as complete', inputSchema: z.object({ stepName: z.string(), userId: z.string(), }), execute: async ({ context }) => { await updateOnboardingProgress( context.input.userId, context.input.stepName ); return { success: true }; }, }), }, }); // Interactive onboarding session const sessionId = `onboarding_user_${userId}`; // Step 1 await onboardingAgent.process({ message: 'Start onboarding for new user', sessionId, userId, }); // User responds await onboardingAgent.process({ message: 'I want to create my first agent', sessionId, userId, }); // Agent guides through agent creation... ``` -------------------------------- ### Install Runflow SDK using npm, yarn, or pnpm Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=dependents Instructions for installing the Runflow SDK package using common Node.js package managers. This package is essential for utilizing the framework's features. ```bash npm install @runflow-ai/sdk ``` ```bash yarn add @runflow-ai/sdk ``` ```bash pnpm add @runflow-ai/sdk ``` -------------------------------- ### LLM Factory Methods for Different Providers Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Provides examples of using factory methods within the LLM module to initialize language models from various providers, including OpenAI, Anthropic, and Bedrock. Each method allows for specifying the model name and configuration options. ```javascript import { LLM } from '@runflow-ai/sdk'; // OpenAI const gpt4 = LLM.openai('gpt-4o', { temperature: 0.7 }); // Anthropic (Claude) const claude = LLM.anthropic('claude-3-5-sonnet-20241022', { temperature: 0.9, maxTokens: 4000, }); // Bedrock const bedrock = LLM.bedrock('anthropic.claude-3-sonnet-20240229-v1:0', { temperature: 0.8, }); ``` -------------------------------- ### Install TypeScript Development Dependency Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=versions Instructs on how to install TypeScript version 5.0.0 or higher as a development dependency using npm, essential for avoiding TypeScript errors when using the SDK. ```bash npm install --save-dev typescript@^5.0.0 ``` -------------------------------- ### Configure Advanced Agent with Tools, RAG, and Memory Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=versions Provides a comprehensive example of agent configuration, including specifying instructions, LLM model (Anthropic Claude), model parameters, conversation memory, RAG settings, multiple tools (`createTicket`, `searchOrders`), tool iteration limits, streaming, and debug mode. ```typescript import { Agent, anthropic } from '@runflow-ai/sdk'; const agent = new Agent({ name: 'Advanced Support Agent', instructions: `You are an expert customer support agent. - Always be polite and helpful - Solve problems efficiently - Use tools when needed`, // Model model: anthropic('claude-3-5-sonnet-20241022'), // Model configuration modelConfig: { temperature: 0.7, maxTokens: 4000, topP: 0.9, frequencyPenalty: 0, presencePenalty: 0 }, // Memory memory: { type: 'conversation', maxTurns: 20, summarizeAfter: 50 }, // RAG (Agentic - LLM decides when to search) rag: { vectorStore: 'support-docs', k: 5, threshold: 0.7, searchPrompt: 'Use for technical questions' }, // Tools tools: { createTicket: ticketTool, searchOrders: orderTool }, // Tool iteration limit maxToolIterations: 10, // Streaming streaming: { enabled: true }, // Debug mode debug: true }); ``` -------------------------------- ### TypeScript Example: Using Built-in Memory Provider Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Demonstrates how to instantiate and use the built-in Runflow memory provider with the SDK's Memory class, configuring it with a maximum number of turns. ```typescript import { RunflowMemoryProvider } from '@runflow-ai/sdk'; // Use Runflow's built-in memory provider const memory = new Memory({ provider: new RunflowMemoryProvider(apiClient), maxTurns: 10, }); ``` -------------------------------- ### TypeScript Example: Configuring Agent with Tools and Debugging Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Configures an Agent with specific instructions to use a weather tool, sets `maxToolIterations`, and enables `debug` mode for detailed logging during execution. ```typescript const agent = new Agent({ name: 'My Agent', instructions: 'You MUST use the weather tool when users ask about weather.', model: openai('gpt-4o'), tools: { weather: weatherTool, }, maxToolIterations: 10, // Default debug: true, // Enable debug logging }); ``` -------------------------------- ### Create Connector Tool Definitions with TypeScript Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=readme Defines reusable connector tools for interacting with various external services like HubSpot, Twilio, Email, and Slack. The `createConnectorTool` function simplifies the setup by specifying the service, resource, action, and parameter schema. ```typescript import { createConnectorTool } from '@runflow-ai/sdk'; // HubSpot - Create contact const createContact = createConnectorTool( 'hubspot', 'contacts', 'create', { email: 'string', firstName: 'string?', lastName: 'string?', phone: 'string?', company: 'string?', } ); // Twilio - Send WhatsApp const sendWhatsApp = createConnectorTool( 'twilio', 'messages', 'send-whatsapp', { to: 'string', message: 'string', mediaUrl: 'url?', } ); // Email - Send email const sendEmail = createConnectorTool( 'email', 'messages', 'send', { to: 'email', subject: 'string', body: 'string', html: 'boolean?', } ); // Slack - Send message const sendSlack = createConnectorTool( 'slack', 'messages', 'send', { channel: 'string', message: 'string', username: 'string?', iconEmoji: 'string?', } ); ``` -------------------------------- ### Configure Agent with RAG and Custom Search Prompt Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Demonstrates configuring an agent with Retrieval Augmented Generation (RAG). The SDK automatically creates a searchKnowledge tool, and a custom searchPrompt guides the LLM on when to use it, optimizing search operations by only searching when necessary. ```javascript const agent = new Agent({ name: 'Support Agent', instructions: 'You are a helpful support agent.', model: openai('gpt-4o'), rag: { vectorStore: 'support-docs', k: 5, threshold: 0.7, // Custom search prompt - guides when to search searchPrompt: `Use searchKnowledge tool when user asks about: - Technical problems - Process questions - Specific information Don't use for greetings or casual chat.`, toolDescription: 'Search in support documentation for solutions', }, }); // Agent automatically has 'searchKnowledge' tool // LLM decides when to search (not always - more efficient!) const result = await agent.process({ message: 'How do I reset my password?', }); ``` -------------------------------- ### Use Built-in Connector Shortcuts with Runflow AI SDK Agent Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Shows how to integrate pre-configured connector shortcuts into an `Agent`'s tools. This example uses shortcuts for HubSpot, Twilio, Email, and Slack within the agent's configuration. ```typescript import { hubspot, twilio, email, slack } from '@runflow-ai/sdk'; const agent = new Agent({ name: 'Support Agent', instructions: 'You help customers.', model: openai('gpt-4o'), tools: { // Built-in connector shortcuts createContact: hubspot.createContact(), getContact: hubspot.getContact(), createTicket: hubspot.createTicket(), sendWhatsApp: twilio.sendWhatsApp(), sendSMS: twilio.sendSMS(), sendEmail: email.send(), sendSlack: slack.sendMessage(), }, }); ``` -------------------------------- ### Configure Runflow AI SDK with JSON File Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=dependencies This example shows the structure of a `.runflow/rf.json` configuration file for the runflow-ai SDK. It specifies essential parameters like `agentId`, `tenantId`, `apiKey`, and `apiUrl`. The SDK automatically detects this file in the current or parent directories, providing a convenient way to manage configuration. ```json { "agentId": "your_agent_id", "tenantId": "your_tenant_id", "apiKey": "your_api_key", "apiUrl": "http://localhost:3001" } ``` -------------------------------- ### Create Tool with Connector Integration using Runflow AI SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Shows how to create a tool that interacts with external services through Runflow's connector functionality. The example uses the `runflow.connector` to create a support ticket in HubSpot. ```typescript const createTicketTool = createTool({ id: 'create-ticket', description: 'Create a support ticket', inputSchema: z.object({ subject: z.string(), description: z.string(), priority: z.enum(['low', 'medium', 'high']), }), execute: async ({ context, runflow }) => { // Use connector const ticket = await runflow.connector( 'hubspot', 'tickets', 'create', { subject: context.subject, content: context.description, priority: context.priority, } ); return { ticketId: ticket.id }; }, }); ``` -------------------------------- ### Create Tool Using Runflow API with Runflow AI SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Illustrates how to create a tool that leverages the Runflow API for operations like vector search. The example shows searching documentation using `runflow.vectorSearch` within the tool's `execute` function. ```typescript const searchDocsTool = createTool({ id: 'search-docs', description: 'Search in documentation', inputSchema: z.object({ query: z.string(), }), execute: async ({ context, runflow }) => { // Use Runflow API for vector search const results = await runflow.vectorSearch(context.query, { vectorStore: 'docs', k: 5, }); return { results: results.results.map(r => r.content), }; }, }); ``` -------------------------------- ### Custom Redis Memory Provider for runflow-ai SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Illustrates how to implement a custom memory provider using Redis with the runflow-ai SDK. This example defines a `RedisMemoryProvider` class that handles getting, setting, appending messages, and clearing data from Redis, allowing for persistent conversation history. ```typescript import { Memory, MemoryProvider } from '@runflow-ai/sdk'; class RedisMemoryProvider implements MemoryProvider { async get(key: string): Promise { const data = await redis.get(key); return JSON.parse(data); } async set(key: string, data: MemoryData): Promise { await redis.set(key, JSON.stringify(data)); } async append(key: string, message: MemoryMessage): Promise { const data = await this.get(key); data.messages.push(message); await this.set(key, data); } async clear(key: string): Promise { await redis.del(key); } } // Use custom provider const memory = new Memory({ provider: new RedisMemoryProvider(), maxTurns: 10, }); ``` -------------------------------- ### Create Agent with RAG (Knowledge Base) Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Shows how to configure an agent with a Retrieval-Augmented Generation (RAG) setup. This allows the agent to search a knowledge base (vector store) for relevant information when processing user queries, improving its ability to answer specific questions. ```typescript import { Agent, openai } from '@runflow-ai/sdk'; const agent = new Agent({ name: 'Support Agent', instructions: 'You are a helpful support agent.', model: openai('gpt-4o'), rag: { vectorStore: 'support-docs', k: 5, threshold: 0.7, searchPrompt: `Use searchKnowledge tool when user asks about: - Technical problems - Process questions - Specific information`, }, }); // Agent automatically has 'searchKnowledge' tool // LLM decides when to use it (not always searching - more efficient!) const result = await agent.process({ message: 'How do I reset my password?', }); ``` -------------------------------- ### Import Workflow Modules in TypeScript Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=dependents Provides examples of importing functions for creating and building workflows using the Runflow.ai SDK. This enables the definition of complex, multi-step processes that can involve agents, functions, and connectors. ```typescript import { createWorkflow, WorkflowBuilder } from '@runflow-ai/sdk/workflows'; ``` -------------------------------- ### Define Workflow Step Types: Agent, Function, Connector Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Provides examples for creating different types of workflow steps using the Runflow.ai SDK. It shows how to define agent steps with prompt templates, function steps for custom logic, and connector steps for integrating with external services like HubSpot. ```typescript import { createAgentStep, createFunctionStep, createConnectorStep } from '@runflow-ai/sdk'; // Agent step const agentStep = createAgentStep('step-id', agent, { promptTemplate: 'Process: {{input.data}}', }); // Function step const functionStep = createFunctionStep('step-id', async (input, context) => { // Custom logic return { result: 'processed' }; }); // Connector step const connectorStep = createConnectorStep( 'step-id', 'hubspot', 'contacts', 'create', { email: '{{input.email}}' } ); ``` -------------------------------- ### Create Workflow with Parallel Steps Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Illustrates how to construct a workflow where multiple steps execute in parallel. This example uses `parallel` with `waitForAll: true` to ensure all parallel branches complete before proceeding. It also shows a subsequent function step to merge the results from the parallel execution. ```typescript const workflow = createWorkflow({ id: 'parallel-workflow', inputSchema: z.object({ query: z.string() }), outputSchema: z.any(), }) .parallel([ createAgentStep('agent1', agent1), createAgentStep('agent2', agent2), createAgentStep('agent3', agent3), ], { waitForAll: true, // Wait for all to complete }) .function('merge', async (input, context) => { // Merge results return { combined: Object.values(context.stepResults.get('parallel')), }; }) .build(); ``` -------------------------------- ### Standalone Memory Manager Operations Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Illustrates how to use the standalone Memory manager for appending messages, retrieving formatted history, getting recent messages, searching memory, checking existence, getting raw data, and clearing memory. ```javascript import { Memory } from '@runflow-ai/sdk'; // Using static methods (most common - 99% of cases) await Memory.append({ role: 'user', content: 'Hello!', timestamp: new Date(), }); await Memory.append({ role: 'assistant', content: 'Hi! How can I help you?', timestamp: new Date(), }); // Get formatted history const history = await Memory.getFormatted(); console.log(history); // Get recent messages const recent = await Memory.getRecent(5); // Last 5 turns // Search in memory const results = await Memory.search('order'); // Check if memory exists const exists = await Memory.exists(); // Get full memory data const data = await Memory.get(); // Clear memory await Memory.clear(); ``` -------------------------------- ### TypeScript Example: Session Management with Runflow.identify Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Illustrates two methods for ensuring memory persistence: using `Runflow.identify()` for automatic session management or explicitly passing a `sessionId` to the agent's `process` method. ```typescript // Use Runflow.identify() for automatic session management Runflow.identify({ type: 'phone', value: '+5511999999999', }); // OR pass sessionId explicitly await agent.process({ message: 'Hello', sessionId: 'session_456', // Same session ID }); ``` -------------------------------- ### Create Workflow with Conditional Steps Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Shows how to implement conditional logic within a Runflow.ai workflow. The `condition` function allows defining a boolean expression to determine which path to take. This example branches into different agent and connector steps based on an input 'priority' field. ```typescript const workflow = createWorkflow({ id: 'conditional-workflow', inputSchema: z.object({ priority: z.string() }), outputSchema: z.any(), }) .condition( 'check-priority', (context) => context.input.priority === 'high', // True path [ createAgentStep('urgent-agent', urgentAgent), createConnectorStep('notify-slack', 'slack', 'messages', 'send', { channel: '#urgent', message: 'High priority issue!', }), ], // False path [ createAgentStep('normal-agent', normalAgent), ] ) .build(); ``` -------------------------------- ### Define Memory Provider Interface (TypeScript) Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=readme Defines the TypeScript interface for a MemoryProvider, outlining the methods required for managing conversational memory. These methods include getting, setting, appending to, and clearing memory data, with optional methods for summarizing and searching memory. ```typescript interface MemoryProvider { get(key: string): Promise; set(key: string, data: MemoryData): Promise; append(key: string, message: MemoryMessage): Promise; clear(key: string): Promise; summarize?(key: string): Promise; search?(key: string, query: string): Promise; } ``` -------------------------------- ### Runflow Context State Management Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Provides functions to manage the global state of the Runflow context. Includes methods to get the entire state, retrieve specific values, set custom state, and clear the state. ```javascript // Get complete state const state = Runflow.getState(); // Get specific value const threadId = Runflow.get('threadId'); const entityType = Runflow.get('entityType'); // Set custom state (advanced) Runflow.setState({ entityType: 'custom', entityValue: 'xyz', threadId: 'my_custom_thread_123', userId: 'user_123', metadata: { custom: 'data' }, }); // Clear state (useful for testing) Runflow.clearState(); ``` -------------------------------- ### Complex E-Commerce Workflow with runflow-ai SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Details a sophisticated e-commerce workflow orchestrated using the runflow-ai SDK. This example chains agents, parallel function calls, conditional logic for routing (sales vs. support), and connector integrations (HubSpot) to handle customer queries. ```typescript const workflow = createWorkflow({ id: 'e-commerce-workflow', inputSchema: z.object({ customerId: z.string(), query: z.string(), }), outputSchema: z.any(), }) // 1. Analyze intent .agent('analyzer', analyzerAgent, { promptTemplate: 'Analyze customer query: {{input.query}}', }) // 2. Load customer data in parallel .parallel([ createFunctionStep('load-profile', async (input, ctx) => { return await loadCustomerProfile(input.customerId); }), createFunctionStep('load-orders', async (input, ctx) => { return await loadCustomerOrders(input.customerId); }), createFunctionStep('search-products', async (input, ctx) => { return await searchProducts(ctx.stepResults.get('analyzer').text); }), ]) // 3. Conditional: Sales vs Support .condition( 'route', (ctx) => ctx.stepResults.get('analyzer').text.includes('buy'), // Sales path [ createAgentStep('sales', salesAgent), createConnectorStep('update-crm', 'hubspot', 'contacts', 'update', { contactId: '{{input.customerId}}', lastContact: new Date().toISOString(), }), ], // Support path [ createAgentStep('support', supportAgent), createConnectorStep('create-ticket', 'hubspot', 'tickets', 'create', { subject: '{{analyzer.text}}', }), ] ) // 4. Send response .agent('responder', responderAgent, { promptTemplate: 'Create final response based on context', }) .build(); const result = await workflow.execute({ customerId: 'customer_123', query: 'I want to buy a laptop', }); ``` -------------------------------- ### Create and Execute a Basic Workflow with Agents and Connectors Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=code Demonstrates how to create a workflow with agents for analysis and response, and connectors for interacting with external services like HubSpot and email. It defines input/output schemas and executes the workflow. ```typescript import { createWorkflow, Agent, openai } from '@runflow-ai/sdk'; import { z } from 'zod'; // Define input/output schemas const inputSchema = z.object({ customerEmail: z.string().email(), issueDescription: z.string(), }); const outputSchema = z.object({ ticketId: z.string(), response: z.string(), emailSent: z.boolean(), }); // Create agents const analyzerAgent = new Agent({ name: 'Issue Analyzer', instructions: 'Analyze customer issues and categorize them.', model: openai('gpt-4o'), }); const responderAgent = new Agent({ name: 'Responder', instructions: 'Write helpful responses to customers.', model: openai('gpt-4o'), }); // Create workflow const workflow = createWorkflow({ id: 'support-workflow', name: 'Support Ticket Workflow', inputSchema, outputSchema, }) .agent('analyze', analyzerAgent, { promptTemplate: 'Analyze this issue: {{input.issueDescription}}', }) .connector('create-ticket', 'hubspot', 'tickets', 'create', { subject: '{{analyze.text}}', content: '{{input.issueDescription}}', priority: 'medium', }) .agent('respond', responderAgent, { promptTemplate: 'Write a response for: {{input.issueDescription}}', }) .connector('send-email', 'email', 'messages', 'send', { to: '{{input.customerEmail}}', subject: 'Your Support Request', body: '{{respond.text}}', }) .build(); // Execute workflow const result = await workflow.execute({ customerEmail: 'customer@example.com', issueDescription: 'My order has not arrived', }); console.log(result); ``` -------------------------------- ### Create Basic Tool with Runflow AI SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Demonstrates how to create a basic tool using the `createTool` function from the Runflow AI SDK. This includes defining input and output schemas with Zod and implementing the tool's execution logic. ```typescript import { createTool } from '@runflow-ai/sdk'; import { z } from 'zod'; const weatherTool = createTool({ id: 'get-weather', description: 'Get current weather for a location', inputSchema: z.object({ location: z.string().describe('City name'), units: z.enum(['celsius', 'fahrenheit']).optional(), }), outputSchema: z.object({ temperature: z.number(), condition: z.string(), }), execute: async ({ context, runflow, projectId }) => { // Implement logic const weather = await fetchWeather(context.location); return { temperature: weather.temp, condition: weather.condition, }; }, }); ``` -------------------------------- ### LLM Text Generation with System Prompt and Options Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Shows how to generate text using the LLM module by providing a user prompt along with specific system instructions and generation parameters like temperature. This allows for fine-tuning the LLM's behavior and output style. ```javascript const response = await llm.generate( 'What is 2+2?', { system: 'You are a math teacher.', temperature: 0.1, } ); ``` -------------------------------- ### Create Agent with RAG Knowledge Base Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=versions Demonstrates setting up an agent with Retrieval-Augmented Generation (RAG) capabilities. This allows the agent to search a knowledge base (e.g., 'support-docs') for relevant information before responding. The `searchKnowledge` tool is automatically available and used by the LLM when appropriate. ```typescript import { Agent, openai } from '@runflow-ai/sdk'; const agent = new Agent({ name: 'Support Agent', instructions: 'You are a helpful support agent.', model: openai('gpt-4o'), rag: { vectorStore: 'support-docs', k: 5, threshold: 0.7, searchPrompt: `Use searchKnowledge tool when user asks about: - Technical problems - Process questions - Specific information` } }); // Agent automatically has 'searchKnowledge' tool // LLM decides when to use it (not always searching - more efficient!) const result = await agent.process({ message: 'How do I reset my password?' }); ``` -------------------------------- ### Create Basic Workflow with Agents and Connectors Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Demonstrates how to create a basic workflow using the Runflow.ai SDK. This includes defining input/output schemas, creating agents, chaining agents with connectors (like HubSpot and email), and executing the workflow. It utilizes Zod for schema validation and OpenAI for agent models. ```typescript import { createWorkflow, Agent, openai } from '@runflow-ai/sdk'; import { z } from 'zod'; // Define input/output schemas const inputSchema = z.object({ customerEmail: z.string().email(), issueDescription: z.string(), }); const outputSchema = z.object({ ticketId: z.string(), response: z.string(), emailSent: z.boolean(), }); // Create agents const analyzerAgent = new Agent({ name: 'Issue Analyzer', instructions: 'Analyze customer issues and categorize them.', model: openai('gpt-4o'), }); const responderAgent = new Agent({ name: 'Responder', instructions: 'Write helpful responses to customers.', model: openai('gpt-4o'), }); // Create workflow const workflow = createWorkflow({ id: 'support-workflow', name: 'Support Ticket Workflow', inputSchema, outputSchema, }) .agent('analyze', analyzerAgent, { promptTemplate: 'Analyze this issue: {{input.issueDescription}}', }) .connector('create-ticket', 'hubspot', 'tickets', 'create', { subject: '{{analyze.text}}', content: '{{input.issueDescription}}', priority: 'medium', }) .agent('respond', responderAgent, { promptTemplate: 'Write a response for: {{input.issueDescription}}', }) .connector('send-email', 'email', 'messages', 'send', { to: '{{input.customerEmail}}', subject: 'Your Support Request', body: '{{respond.text}}', }) .build(); // Execute workflow const result = await workflow.execute({ customerEmail: 'customer@example.com', issueDescription: 'My order has not arrived', }); console.log(result); ``` -------------------------------- ### Initialize and Use Standalone Knowledge Manager Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Shows how to initialize and use the `Knowledge` module from the Runflow.ai SDK for semantic search in vector databases. It covers basic search operations, retrieving results with scores, and formatting context for LLM prompts. Configuration includes vector store name, `k` value, and a similarity threshold. ```typescript import { Knowledge } from '@runflow-ai/sdk'; const knowledge = new Knowledge({ vectorStore: 'support-docs', k: 5, threshold: 0.7, }); // Basic search const results = await knowledge.search('How to reset password?'); results.forEach(result => { console.log(result.content); console.log('Score:', result.score); }); // Get formatted context for LLM const context = await knowledge.getContext('password reset', { k: 3 }); console.log(context); ``` -------------------------------- ### LLM Basic Usage for Text Generation Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Demonstrates the basic usage of the LLM module for direct text generation. It initializes an LLM instance with a specific model and configuration, then generates a response to a given prompt, returning the text and token usage information. ```javascript import { LLM } from '@runflow-ai/sdk'; // Create LLM const llm = LLM.openai('gpt-4o', { temperature: 0.7, maxTokens: 2000, }); // Generate response const response = await llm.generate('What is the capital of Brazil?'); console.log(response.text); console.log('Tokens:', response.usage); ``` -------------------------------- ### Create Customer Support Agent with RAG - JavaScript/TypeScript Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=readme This code snippet demonstrates how to instantiate a customer support agent using the runflow-ai SDK. It configures the agent with a name, instructions, a language model (OpenAI GPT-4o), conversation memory with summarization, RAG for knowledge retrieval from a vector store, and defines available tools like creating HubSpot tickets and searching customer orders. The agent is then used to process a customer message, simulating a support interaction. ```javascript import { Agent, openai, createTool } from '@runflow-ai/sdk'; import { hubspotConnector } from '@runflow-ai/sdk/connectors'; import { z } from 'zod'; // Create a support agent with memory and RAG const supportAgent = new Agent({ name: 'Customer Support AI', instructions: `You are a helpful customer support agent. - Search the knowledge base for relevant information - Remember previous conversations - Create tickets for complex issues - Always be professional and empathetic`, model: openai('gpt-4o'), // Remember conversation history memory: { type: 'conversation', maxTurns: 20, summarization: { enabled: true, threshold: 10, }, }, // Search in documentation knowledge: { vectorStore: 'support-docs', k: 5, threshold: 0.7, }, // Available tools tools: { createTicket: hubspotConnector.tickets.create, searchOrders: createTool({ id: 'search-orders', description: 'Search customer orders', inputSchema: z.object({ customerId: z.string(), }), execute: async ({ context }) => { const orders = await fetchOrders(context.input.customerId); return { orders }; }, }), }, }); // Handle customer message const result = await supportAgent.process({ message: 'My order #12345 has not arrived yet', sessionId: 'session_xyz', // For conversation history userId: 'user_123', // For user identification }); console.log(result.message); // Agent searches docs, retrieves order info, and provides solution ``` -------------------------------- ### Sales Automation Workflow with Runflow AI SDK Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Automates lead qualification, deal creation in HubSpot, and Slack notifications using a multi-step workflow. It leverages custom agents for lead analysis and sales copy generation. The workflow includes conditional logic based on lead score. ```typescript import { createWorkflow, Agent, openai } from '@runflow-ai/sdk'; import { hubspotConnector, slackConnector } from '@runflow-ai/sdk/connectors'; import { z } from 'zod'; // Qualification agent const qualifierAgent = new Agent({ name: 'Lead Qualifier', instructions: 'Analyze lead data and assign a score (1-10) with reasoning.', model: openai('gpt-4o-mini'), }); // Sales copy agent const copywriterAgent = new Agent({ name: 'Sales Copywriter', instructions: 'Write a personalized email for the lead based on their profile.', model: openai('gpt-4o'), }); // Complete workflow const salesWorkflow = createWorkflow({ id: 'lead-to-deal', inputSchema: z.object({ leadEmail: z.string().email(), leadName: z.string(), company: z.string(), notes: z.string(), }), outputSchema: z.any(), }) // Step 1: Qualify the lead .agent('qualify', qualifierAgent, { promptTemplate: `Analyze this lead: Name: {{input.leadName}} Company: {{input.company}} Notes: {{input.notes}} Provide score (1-10) and reasoning.`, }) // Step 2: Conditional - Only proceed if score >= 7 .condition( 'check-score', (ctx) => { const score = parseInt(ctx.stepResults.get('qualify').text.match(/\d+/)?.[0] || '0'); return score >= 7; }, // High quality lead path [ // Create contact in HubSpot { id: 'create-contact', type: 'connector', config: { connector: 'hubspot', resource: 'contacts', action: 'create', parameters: { email: '{{input.leadEmail}}', firstname: '{{input.leadName}}', company: '{{input.company}}', lifecyclestage: 'lead', }, }, }, // Create deal { id: 'create-deal', type: 'connector', config: { connector: 'hubspot', resource: 'deals', action: 'create', parameters: { dealname: 'Deal - {{input.company}}', amount: 5000, dealstage: 'qualifiedtobuy', pipeline: 'default', hubspot_owner_id: '12345', }, }, }, // Generate personalized email { id: 'write-email', type: 'agent', config: { agent: copywriterAgent, promptTemplate: `Write a personalized sales email for: Name: {{input.leadName}} Company: {{input.company}} Qualification: {{qualify.text}}`, }, }, // Notify sales team on Slack { id: 'notify-team', type: 'connector', config: { connector: 'slack', resource: 'messages', action: 'send', parameters: { channel: '#sales', text: `🎯 New qualified lead: *{{input.leadName}}* from *{{input.company}}*\nScore: High\nDeal created: {{create-deal.id}}`, }, }, }, ], // Low quality lead path [ { id: 'log-rejected', type: 'function', config: { execute: async (input, ctx) => { console.log(`Lead ${input.leadName} rejected - Low score`); return { rejected: true }; }, }, }, ] ) .build(); // Execute workflow const result = await salesWorkflow.execute({ leadEmail: 'john@techcorp.com', leadName: 'John Smith', company: 'TechCorp Inc', notes: 'Interested in enterprise plan. Budget: $10k/month. Timeline: Q1 2025.', }); console.log('Workflow completed:', result); ``` -------------------------------- ### Import Tools and Connectors in JavaScript Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=dependents Shows how to import modules for creating and using tools and connectors within the Runflow SDK, such as `createTool`, `createConnectorTool`, and specific connectors like `hubspot`, `twilio`, `email`, and `slack`. ```javascript // Tools & Connectors import { createTool, createConnectorTool } from '@runflow-ai/sdk'; import { hubspot, twilio, email, slack } from '@runflow-ai/sdk'; ``` -------------------------------- ### Create Agent with Custom Tool Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk_activetab=versions Defines how to create a custom tool using `createTool` and integrate it into an agent. The tool fetches weather data based on a provided location. This requires the `zod` library for schema definition and the `@runflow-ai/sdk`. ```typescript import { Agent, openai, createTool } from '@runflow-ai/sdk'; import { z } from 'zod'; // Create a custom tool const weatherTool = createTool({ id: 'get-weather', description: 'Get current weather for a location', inputSchema: z.object({ location: z.string() }), execute: async ({ context }) => { // Fetch weather data return { temperature: 22, condition: 'Sunny', location: context.location }; } }); // Create agent with tool const agent = new Agent({ name: 'Weather Agent', instructions: 'You help users check the weather.', model: openai('gpt-4o'), tools: { weather: weatherTool } }); const result = await agent.process({ message: 'What is the weather in São Paulo?' }); console.log(result.message); ``` -------------------------------- ### Import Core SDK Components (JavaScript) Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Lists the main exports available from the '@runflow-ai/sdk' package, including core classes like Agent and Runflow, LLM providers (openai, anthropic, bedrock), tools, connectors, workflow utilities, memory modules, and observability tools. This is useful for understanding the SDK's capabilities and importing necessary modules. ```javascript // Core import { Agent, Runflow, openai, anthropic, bedrock } from '@runflow-ai/sdk'; // Tools & Connectors import { createTool, createConnectorTool } from '@runflow-ai/sdk'; import { hubspot, twilio, email, slack } from '@runflow-ai/sdk'; // Workflows import { Workflow, createWorkflow, createStep, createAgentStep, createFunctionStep, createConnectorStep, WorkflowBuilder, } from '@runflow-ai/sdk'; // Standalone Modules import { Memory, Knowledge, RAG, LLM } from '@runflow-ai/sdk'; // Observability import { createTraceCollector, RunflowTraceCollector, RunflowTraceSpan, traced } from '@runflow-ai/sdk'; // API Client import { createRunflowAPIClient } from '@runflow-ai/sdk'; // Providers import { MemoryProvider, KnowledgeProvider, LLMProvider, RunflowMemoryProvider, } from '@runflow-ai/sdk'; ``` -------------------------------- ### TypeScript: Importing Agent Types Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Demonstrates how to properly import TypeScript types for Agent configuration, input, and output to ensure type safety when using the SDK. ```typescript // Use proper type imports import type { AgentConfig, AgentInput, AgentOutput } from '@runflow-ai/sdk'; ``` -------------------------------- ### Instantiate Supported LLM Models Source: https://www.npmjs.com/package/@runflow-ai/sdk/package/%40runflow-ai/sdk Illustrates how to instantiate different LLM models supported by the Runflow SDK, including models from OpenAI, Anthropic, and AWS Bedrock, by calling their respective factory functions with specific model identifiers. ```typescript import { openai, anthropic, bedrock } from '@runflow-ai/sdk'; // OpenAI const gpt4 = openai('gpt-4o'); const gpt4mini = openai('gpt-4o-mini'); const gpt4turbo = openai('gpt-4-turbo'); const gpt35 = openai('gpt-3.5-turbo'); // Anthropic (Claude) const claude35 = anthropic('claude-3-5-sonnet-20241022'); const claude3opus = anthropic('claude-3-opus-20240229'); const claude3sonnet = anthropic('claude-3-sonnet-20240229'); const claude3haiku = anthropic('claude-3-haiku-20240307'); // AWS Bedrock const claudeBedrock = bedrock('anthropic.claude-3-sonnet-20240229-v1:0'); const titan = bedrock('amazon.titan-text-express-v1'); ```