@runflow-ai/sdk 1.0.23 → 1.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,76 +1,111 @@
1
- # 🚀 Runflow SDK V2
1
+ # 🚀 Runflow SDK
2
2
 
3
- > **Framework Multi-Agent de IA para construir agentes inteligentes com TypeScript**
3
+ > **A powerful TypeScript-first framework for building intelligent AI agents and multi-agent systems**
4
4
 
5
- O Runflow SDK V2 é um framework completo e type-safe para construir agentes de IA, workflows complexos e sistemas multi-agent. Projetado para ser simples de usar, mas poderoso o suficiente para casos de uso avançados.
5
+ Runflow SDK is a comprehensive, type-safe framework for building AI agents, complex workflows, and multi-agent systems. Designed to be simple to use yet powerful enough for advanced use cases.
6
6
 
7
- [![npm version](https://img.shields.io/npm/v/@runflow-ai/sdk)](https://www.npmjs.com/package/@runflow-ai/sdk)
7
+ [![npm version](https://img.shields.io/npm/v/@runflow-ai/sdk.svg)](https://www.npmjs.com/package/@runflow-ai/sdk)
8
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
-
10
- ## 📑 Índice
11
-
12
- - [Instalação](#-instalação)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
10
+ [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D22.0.0-green.svg)](https://nodejs.org/)
11
+
12
+ ## ✨ Features
13
+
14
+ - 🤖 **Intelligent Agents** - Create agents with LLM, tools, memory, and RAG capabilities
15
+ - 🔧 **Type-Safe Tools** - Build custom tools with Zod schema validation
16
+ - 🔌 **Built-in Connectors** - HubSpot, Twilio, Email, Slack integrations out of the box
17
+ - 🌊 **Workflows** - Orchestrate complex multi-step processes with conditional logic
18
+ - 🧠 **Memory Management** - Persistent conversation history with automatic summarization
19
+ - 📚 **Agentic RAG** - LLM-driven semantic search in vector knowledge bases
20
+ - 👥 **Multi-Agent Systems** - Supervisor pattern with automatic agent routing
21
+ - 🔍 **Full Observability** - Automatic tracing with cost tracking and performance metrics
22
+ - 📡 **Streaming Support** - Real-time streaming responses with memory persistence
23
+ - 🎨 **Multi-Modal** - Support for text and images (vision models)
24
+ - 🔄 **Multiple Providers** - OpenAI, Anthropic (Claude), and AWS Bedrock
25
+
26
+ ## 📑 Table of Contents
27
+
28
+ - [Installation](#-installation)
13
29
  - [Quick Start](#-quick-start)
14
- - [Conceitos Fundamentais](#-conceitos-fundamentais)
30
+ - [Core Concepts](#-core-concepts)
15
31
  - [Agents](#agents)
16
- - [Context Management](#context-management-runflow)
32
+ - [Context Management](#context-management)
17
33
  - [Memory](#memory)
18
34
  - [Tools](#tools)
19
35
  - [Connectors](#connectors)
20
36
  - [Workflows](#workflows)
21
- - [RAG/Knowledge](#ragknowledge)
37
+ - [Knowledge (RAG)](#knowledge-rag)
22
38
  - [LLM Standalone](#llm-standalone)
23
39
  - [Observability](#observability)
24
- - [Arquitetura](#-arquitetura)
25
- - [Exemplos Avançados](#-exemplos-avançados)
26
- - [Configuração](#-configuração)
40
+ - [Advanced Examples](#-advanced-examples)
41
+ - [Real-World Use Cases](#-real-world-use-cases)
42
+ - [Customer Support Agent with RAG](#1-customer-support-agent-with-rag)
43
+ - [Sales Automation with Multi-Step Workflow](#2-sales-automation-with-multi-step-workflow)
44
+ - [Intelligent Collections Agent (WhatsApp)](#3-intelligent-collections-agent-whatsapp)
45
+ - [Customer Onboarding Assistant](#4-customer-onboarding-assistant)
46
+ - [Feedback Analysis System](#5-feedback-analysis-system)
47
+ - [Multi-Agent System (Supervisor Pattern)](#6-multi-agent-system-supervisor-pattern)
48
+ - [Configuration](#-configuration)
27
49
  - [API Reference](#-api-reference)
50
+ - [TypeScript Types](#-typescript-types)
28
51
  - [Providers](#-providers)
29
- - [Contribuindo](#-contribuindo)
52
+ - [Troubleshooting](#-troubleshooting)
53
+ - [Contributing](#-contributing)
54
+ - [License](#-license)
30
55
 
31
56
  ---
32
57
 
33
- ## 📦 Instalação
58
+ ## 📦 Installation
34
59
 
35
60
  ```bash
36
61
  npm install @runflow-ai/sdk
37
- # ou
62
+ # or
38
63
  yarn add @runflow-ai/sdk
64
+ # or
65
+ pnpm add @runflow-ai/sdk
39
66
  ```
40
67
 
41
- ### Requisitos
68
+ ### Requirements
42
69
 
43
70
  - **Node.js**: >= 22.0.0
44
- - **TypeScript**: >= 5.0.0 (recomendado)
45
- - **Zod**: ^3.22.0 ( incluído como dependência)
71
+ - **TypeScript**: >= 5.0.0 (recommended)
72
+ - **Zod**: ^3.22.0 (included as dependency)
46
73
 
47
74
  ---
48
75
 
49
76
  ## 🚀 Quick Start
50
77
 
51
- ### Agent Simples
78
+ > **Note on Parameters:**
79
+ > - `message` is **required** (the user's message)
80
+ > - `companyId` is **optional** (for multi-tenant applications - your end-user's company ID)
81
+ > - `sessionId` is **optional** but recommended (maintains conversation history)
82
+ > - `userId` is **optional** (for user identification)
83
+ > - All other fields are optional and can be set via `Runflow.identify()` or environment variables
84
+
85
+ ### Simple Agent
52
86
 
53
87
  ```typescript
54
88
  import { Agent, openai } from '@runflow-ai/sdk';
55
89
 
56
- // Criar agent básico
90
+ // Create a basic agent
57
91
  const agent = new Agent({
58
92
  name: 'Support Agent',
59
93
  instructions: 'You are a helpful customer support assistant.',
60
94
  model: openai('gpt-4o'),
61
95
  });
62
96
 
63
- // Processar mensagem
97
+ // Process a message
64
98
  const result = await agent.process({
65
- message: 'I need help with my order',
66
- companyId: 'company_123',
67
- sessionId: 'session_456',
99
+ message: 'I need help with my order', // Required
100
+ sessionId: 'session_456', // Optional: For conversation history
101
+ userId: 'user_789', // Optional: User identifier
102
+ companyId: 'company_123', // Optional: For multi-tenant apps
68
103
  });
69
104
 
70
105
  console.log(result.message);
71
106
  ```
72
107
 
73
- ### Agent com Memory
108
+ ### Agent with Memory
74
109
 
75
110
  ```typescript
76
111
  import { Agent, openai } from '@runflow-ai/sdk';
@@ -85,30 +120,28 @@ const agent = new Agent({
85
120
  },
86
121
  });
87
122
 
88
- // Primeira interação
123
+ // First interaction
89
124
  await agent.process({
90
125
  message: 'My name is John',
91
- companyId: 'company_123',
92
- sessionId: 'session_456',
126
+ sessionId: 'session_456', // Same session for conversation continuity
93
127
  });
94
128
 
95
- // Segunda interação - agent lembra o nome
129
+ // Second interaction - agent remembers the name
96
130
  const result = await agent.process({
97
131
  message: 'What is my name?',
98
- companyId: 'company_123',
99
- sessionId: 'session_456',
132
+ sessionId: 'session_456', // Same session
100
133
  });
101
134
 
102
135
  console.log(result.message); // "Your name is John"
103
136
  ```
104
137
 
105
- ### Agent com Tools
138
+ ### Agent with Tools
106
139
 
107
140
  ```typescript
108
141
  import { Agent, openai, createTool } from '@runflow-ai/sdk';
109
142
  import { z } from 'zod';
110
143
 
111
- // Criar tool customizada
144
+ // Create a custom tool
112
145
  const weatherTool = createTool({
113
146
  id: 'get-weather',
114
147
  description: 'Get current weather for a location',
@@ -116,7 +149,7 @@ const weatherTool = createTool({
116
149
  location: z.string(),
117
150
  }),
118
151
  execute: async ({ context }) => {
119
- // Simular busca de clima
152
+ // Fetch weather data
120
153
  return {
121
154
  temperature: 22,
122
155
  condition: 'Sunny',
@@ -125,7 +158,7 @@ const weatherTool = createTool({
125
158
  },
126
159
  });
127
160
 
128
- // Agent com tool
161
+ // Create agent with tool
129
162
  const agent = new Agent({
130
163
  name: 'Weather Agent',
131
164
  instructions: 'You help users check the weather.',
@@ -137,28 +170,54 @@ const agent = new Agent({
137
170
 
138
171
  const result = await agent.process({
139
172
  message: 'What is the weather in São Paulo?',
140
- companyId: 'company_123',
141
173
  });
142
174
 
143
175
  console.log(result.message);
144
176
  ```
145
177
 
178
+ ### Agent with RAG (Knowledge Base)
179
+
180
+ ```typescript
181
+ import { Agent, openai } from '@runflow-ai/sdk';
182
+
183
+ const agent = new Agent({
184
+ name: 'Support Agent',
185
+ instructions: 'You are a helpful support agent.',
186
+ model: openai('gpt-4o'),
187
+ rag: {
188
+ vectorStore: 'support-docs',
189
+ k: 5,
190
+ threshold: 0.7,
191
+ searchPrompt: `Use searchKnowledge tool when user asks about:
192
+ - Technical problems
193
+ - Process questions
194
+ - Specific information`,
195
+ },
196
+ });
197
+
198
+ // Agent automatically has 'searchKnowledge' tool
199
+ // LLM decides when to use it (not always searching - more efficient!)
200
+ const result = await agent.process({
201
+ message: 'How do I reset my password?',
202
+ });
203
+ ```
204
+
146
205
  ---
147
206
 
148
- ## 🎯 Conceitos Fundamentais
207
+ ## 🎯 Core Concepts
149
208
 
150
209
  ### Agents
151
210
 
152
- Os **Agents** são a unidade fundamental do Runflow SDK. Cada agent é configurado com:
211
+ **Agents** are the fundamental building blocks of the Runflow SDK. Each agent is configured with:
153
212
 
154
- - **Name**: Identificador do agent
155
- - **Instructions**: Instruções de comportamento (system prompt)
156
- - **Model**: Modelo LLM a ser utilizado (OpenAI, Anthropic, Bedrock)
157
- - **Tools**: Ferramentas disponíveis para o agent
158
- - **Memory**: Configuração de memória
159
- - **RAG**: Configuração de busca em base de conhecimento
213
+ - **Name**: Agent identifier
214
+ - **Instructions**: Behavior instructions (system prompt)
215
+ - **Model**: LLM model to use (OpenAI, Anthropic, Bedrock)
216
+ - **Tools**: Available tools for the agent
217
+ - **Memory**: Memory configuration
218
+ - **RAG**: Knowledge base search configuration
160
219
 
161
- #### Configuração Completa de Agent
220
+ #### Complete Agent Configuration
162
221
 
163
222
  ```typescript
164
223
  import { Agent, anthropic } from '@runflow-ai/sdk';
@@ -169,46 +228,54 @@ const agent = new Agent({
169
228
  - Always be polite and helpful
170
229
  - Solve problems efficiently
171
230
  - Use tools when needed`,
172
-
173
- // Modelo
231
+
232
+ // Model
174
233
  model: anthropic('claude-3-5-sonnet-20241022'),
175
-
176
- // Configuração do modelo
234
+
235
+ // Model configuration
177
236
  modelConfig: {
178
237
  temperature: 0.7,
179
238
  maxTokens: 4000,
180
239
  topP: 0.9,
240
+ frequencyPenalty: 0,
241
+ presencePenalty: 0,
181
242
  },
182
-
183
- // Memória
243
+
244
+ // Memory
184
245
  memory: {
185
246
  type: 'conversation',
186
247
  maxTurns: 20,
187
248
  summarizeAfter: 50,
188
249
  },
189
-
190
- // RAG
250
+
251
+ // RAG (Agentic - LLM decides when to search)
191
252
  rag: {
192
253
  vectorStore: 'support-docs',
193
- autoSearch: true,
194
254
  k: 5,
195
255
  threshold: 0.7,
256
+ searchPrompt: 'Use for technical questions',
196
257
  },
197
-
258
+
198
259
  // Tools
199
260
  tools: {
200
261
  createTicket: ticketTool,
201
262
  searchOrders: orderTool,
202
263
  },
203
-
264
+
265
+ // Tool iteration limit
266
+ maxToolIterations: 10,
267
+
204
268
  // Streaming
205
269
  streaming: {
206
270
  enabled: true,
207
271
  },
272
+
273
+ // Debug mode
274
+ debug: true,
208
275
  });
209
276
  ```
210
277
 
211
- #### Modelos Suportados
278
+ #### Supported Models
212
279
 
213
280
  ```typescript
214
281
  import { openai, anthropic, bedrock } from '@runflow-ai/sdk';
@@ -216,33 +283,109 @@ import { openai, anthropic, bedrock } from '@runflow-ai/sdk';
216
283
  // OpenAI
217
284
  const gpt4 = openai('gpt-4o');
218
285
  const gpt4mini = openai('gpt-4o-mini');
286
+ const gpt4turbo = openai('gpt-4-turbo');
219
287
  const gpt35 = openai('gpt-3.5-turbo');
220
288
 
221
- // Anthropic
289
+ // Anthropic (Claude)
222
290
  const claude35 = anthropic('claude-3-5-sonnet-20241022');
223
- const claude3 = anthropic('claude-3-sonnet-20240229');
291
+ const claude3opus = anthropic('claude-3-opus-20240229');
292
+ const claude3sonnet = anthropic('claude-3-sonnet-20240229');
293
+ const claude3haiku = anthropic('claude-3-haiku-20240307');
224
294
 
225
295
  // AWS Bedrock
226
296
  const claudeBedrock = bedrock('anthropic.claude-3-sonnet-20240229-v1:0');
227
297
  const titan = bedrock('amazon.titan-text-express-v1');
228
298
  ```
229
299
 
230
- ### Context Management (Runflow)
300
+ #### Agent Methods
301
+
302
+ ```typescript
303
+ // Process a message
304
+ const result = await agent.process(input: AgentInput): Promise<AgentOutput>;
305
+
306
+ // Stream a message
307
+ const stream = await agent.processStream(input: AgentInput): AsyncIterable<ChunkType>;
308
+
309
+ // Simple generation (without full agent context)
310
+ const response = await agent.generate(input: string | Message[]): Promise<{ text: string }>;
311
+
312
+ // Streaming generation
313
+ const stream = await agent.generateStream(prompt: string): AsyncIterable<ChunkType>;
314
+
315
+ // Generation with tools
316
+ const response = await agent.generateWithTools(input): Promise<{ text: string }>;
317
+ ```
318
+
319
+ #### Multi-Agent Systems (Supervisor Pattern)
320
+
321
+ ```typescript
322
+ const supervisor = new Agent({
323
+ name: 'Supervisor',
324
+ instructions: 'Route tasks to appropriate agents.',
325
+ model: openai('gpt-4o'),
326
+ agents: {
327
+ support: {
328
+ name: 'Support Agent',
329
+ instructions: 'Handle support requests.',
330
+ model: openai('gpt-4o-mini'),
331
+ },
332
+ sales: {
333
+ name: 'Sales Agent',
334
+ instructions: 'Handle sales inquiries.',
335
+ model: openai('gpt-4o-mini'),
336
+ },
337
+ },
338
+ });
339
+
340
+ // Supervisor automatically routes to the appropriate agent
341
+ await supervisor.process({
342
+ message: 'I want to buy your product',
343
+ sessionId: 'session_123',
344
+ });
345
+ ```
346
+
347
+ #### Debug Mode
348
+
349
+ ```typescript
350
+ const agent = new Agent({
351
+ name: 'Debug Agent',
352
+ instructions: 'Help users',
353
+ model: openai('gpt-4o'),
354
+
355
+ // Simple debug (all logs enabled)
356
+ debug: true,
357
+
358
+ // Or detailed debug configuration
359
+ debug: {
360
+ enabled: true,
361
+ logMessages: true, // Log messages
362
+ logLLMCalls: true, // Log LLM API calls
363
+ logToolCalls: true, // Log tool executions
364
+ logRAG: true, // Log RAG searches
365
+ logMemory: true, // Log memory operations
366
+ truncateAt: 1000, // Truncate logs at N characters
367
+ },
368
+ });
369
+ ```
370
+
371
+ ---
372
+
373
+ ### Context Management
231
374
 
232
- O **Runflow Context** é um singleton global que gerencia informações de execução e identificação de usuários. Ele permite que você identifique uma vez e todos os agents/workflows usem automaticamente.
375
+ The **Runflow Context** is a global singleton that manages execution information and user identification. It allows you to identify once and all agents/workflows automatically use this context.
233
376
 
234
- #### Uso Básico
377
+ #### Basic Usage
235
378
 
236
379
  ```typescript
237
380
  import { Runflow, Agent, openai } from '@runflow-ai/sdk';
238
381
 
239
- // Identificar usuário por telefone (WhatsApp)
382
+ // Identify user by phone (WhatsApp)
240
383
  Runflow.identify({
241
384
  type: 'phone',
242
385
  value: '+5511999999999',
243
386
  });
244
387
 
245
- // Agent usa automaticamente o context
388
+ // Agent automatically uses the context
246
389
  const agent = new Agent({
247
390
  name: 'WhatsApp Bot',
248
391
  instructions: 'You are a helpful assistant.',
@@ -253,17 +396,16 @@ const agent = new Agent({
253
396
  },
254
397
  });
255
398
 
256
- // Memória é automaticamente vinculada ao telefone
399
+ // Memory is automatically bound to the phone number
257
400
  await agent.process({
258
401
  message: 'Hello!',
259
- companyId: 'company_123',
260
402
  });
261
403
  ```
262
404
 
263
- #### Tipos de Identificação
405
+ #### Identification Types
264
406
 
265
407
  ```typescript
266
- // WhatsApp/SMS (por telefone)
408
+ // WhatsApp/SMS (by phone)
267
409
  Runflow.identify({
268
410
  type: 'phone',
269
411
  value: '+5511999999999',
@@ -282,14 +424,14 @@ Runflow.identify({
282
424
  userId: 'user@example.com',
283
425
  });
284
426
 
285
- // Custom (pedido, ticket, etc)
427
+ // Custom (order, ticket, etc)
286
428
  Runflow.identify({
287
429
  type: 'order',
288
430
  value: 'order_456',
289
431
  userId: 'customer_789',
290
432
  });
291
433
 
292
- // Com threadId customizado
434
+ // With custom threadId
293
435
  Runflow.identify({
294
436
  type: 'phone',
295
437
  value: '+5511999999999',
@@ -300,10 +442,14 @@ Runflow.identify({
300
442
  #### State Management
301
443
 
302
444
  ```typescript
303
- // Get estado completo
445
+ // Get complete state
304
446
  const state = Runflow.getState();
305
447
 
306
- // Set estado customizado (avançado)
448
+ // Get specific value
449
+ const threadId = Runflow.get('threadId');
450
+ const entityType = Runflow.get('entityType');
451
+
452
+ // Set custom state (advanced)
307
453
  Runflow.setState({
308
454
  entityType: 'custom',
309
455
  entityValue: 'xyz',
@@ -312,15 +458,17 @@ Runflow.setState({
312
458
  metadata: { custom: 'data' },
313
459
  });
314
460
 
315
- // Limpar estado (útil para testes)
461
+ // Clear state (useful for testing)
316
462
  Runflow.clearState();
317
463
  ```
318
464
 
465
+ ---
466
+
319
467
  ### Memory
320
468
 
321
- O sistema de **Memory** gerencia o histórico de conversação de forma inteligente.
469
+ The **Memory** system intelligently manages conversation history.
322
470
 
323
- #### Memory Integrada no Agent
471
+ #### Memory Integrated in Agent
324
472
 
325
473
  ```typescript
326
474
  const agent = new Agent({
@@ -329,90 +477,94 @@ const agent = new Agent({
329
477
  model: openai('gpt-4o'),
330
478
  memory: {
331
479
  type: 'conversation',
332
- maxTurns: 20, // Limitar turnos
333
- maxTokens: 4000, // Limitar tokens
334
- summarizeAfter: 50, // Resumir após N turnos
480
+ maxTurns: 20, // Limit turns
481
+ maxTokens: 4000, // Limit tokens
482
+ summarizeAfter: 50, // Summarize after N turns
483
+ persistAcrossSessions: true,
335
484
  },
336
485
  });
337
486
  ```
338
487
 
339
- #### Memory Standalone
488
+ #### Standalone Memory Manager
340
489
 
341
490
  ```typescript
342
491
  import { Memory } from '@runflow-ai/sdk';
343
492
 
344
- // Criar memory manager
345
- const memory = new Memory({
346
- sessionId: 'session_123',
347
- maxTurns: 10,
348
- });
349
-
350
- // Append mensagens
351
- await memory.append({
493
+ // Using static methods (most common - 99% of cases)
494
+ await Memory.append({
352
495
  role: 'user',
353
496
  content: 'Hello!',
354
497
  timestamp: new Date(),
355
498
  });
356
499
 
357
- await memory.append({
500
+ await Memory.append({
358
501
  role: 'assistant',
359
502
  content: 'Hi! How can I help you?',
360
503
  timestamp: new Date(),
361
504
  });
362
505
 
363
- // Get histórico formatado
364
- const history = await memory.getFormatted();
506
+ // Get formatted history
507
+ const history = await Memory.getFormatted();
365
508
  console.log(history);
366
509
 
367
- // Get mensagens recentes
368
- const recent = await memory.getRecent(5); // Últimos 5 turnos
510
+ // Get recent messages
511
+ const recent = await Memory.getRecent(5); // Last 5 turns
369
512
 
370
- // Buscar na memória
371
- const results = await memory.search('order');
513
+ // Search in memory
514
+ const results = await Memory.search('order');
372
515
 
373
- // Limpar memória
374
- await memory.clear();
516
+ // Check if memory exists
517
+ const exists = await Memory.exists();
518
+
519
+ // Get full memory data
520
+ const data = await Memory.get();
521
+
522
+ // Clear memory
523
+ await Memory.clear();
375
524
  ```
376
525
 
377
- #### Memory com Runflow Context
526
+ #### Memory with Runflow Context
378
527
 
379
528
  ```typescript
380
529
  import { Runflow, Memory } from '@runflow-ai/sdk';
381
530
 
382
- // Identificar usuário
531
+ // Identify user
383
532
  Runflow.identify({
384
533
  type: 'phone',
385
534
  value: '+5511999999999',
386
535
  });
387
536
 
388
- // Memory usa automaticamente o context
389
- const memory = new Memory({
390
- maxTurns: 10,
391
- });
392
-
393
- // Memória é vinculada ao telefone automaticamente
394
- await memory.append({
537
+ // Memory automatically uses the context
538
+ await Memory.append({
395
539
  role: 'user',
396
540
  content: 'My order number is 12345',
397
541
  timestamp: new Date(),
398
542
  });
543
+
544
+ // Memory is automatically bound to the phone number
399
545
  ```
400
546
 
401
547
  #### Custom Memory Key
402
548
 
403
549
  ```typescript
404
- // Override completo do memoryKey
550
+ // Create memory with custom key
405
551
  const memory = new Memory({
406
552
  memoryKey: 'custom_key_123',
407
553
  maxTurns: 10,
408
554
  });
555
+
556
+ // Now use instance methods
557
+ await memory.append({ role: 'user', content: 'Hello', timestamp: new Date() });
558
+ const history = await memory.getFormatted();
409
559
  ```
410
560
 
561
+ ---
562
+
411
563
  ### Tools
412
564
 
413
- **Tools** são funções que os agents podem chamar para executar ações específicas. O SDK usa Zod para validação type-safe.
565
+ **Tools** are functions that agents can call to perform specific actions. The SDK uses Zod for type-safe validation.
414
566
 
415
- #### Criar Tool Básica
567
+ #### Create Basic Tool
416
568
 
417
569
  ```typescript
418
570
  import { createTool } from '@runflow-ai/sdk';
@@ -429,10 +581,10 @@ const weatherTool = createTool({
429
581
  temperature: z.number(),
430
582
  condition: z.string(),
431
583
  }),
432
- execute: async ({ context, runflow }) => {
433
- // Implementar lógica
584
+ execute: async ({ context, runflow, projectId }) => {
585
+ // Implement logic
434
586
  const weather = await fetchWeather(context.location);
435
-
587
+
436
588
  return {
437
589
  temperature: weather.temp,
438
590
  condition: weather.condition,
@@ -441,7 +593,7 @@ const weatherTool = createTool({
441
593
  });
442
594
  ```
443
595
 
444
- #### Tool com Runflow API
596
+ #### Tool with Runflow API
445
597
 
446
598
  ```typescript
447
599
  const searchDocsTool = createTool({
@@ -451,12 +603,12 @@ const searchDocsTool = createTool({
451
603
  query: z.string(),
452
604
  }),
453
605
  execute: async ({ context, runflow }) => {
454
- // Usar Runflow API
606
+ // Use Runflow API for vector search
455
607
  const results = await runflow.vectorSearch(context.query, {
456
608
  vectorStore: 'docs',
457
609
  k: 5,
458
610
  });
459
-
611
+
460
612
  return {
461
613
  results: results.results.map(r => r.content),
462
614
  };
@@ -464,7 +616,7 @@ const searchDocsTool = createTool({
464
616
  });
465
617
  ```
466
618
 
467
- #### Tool com Connector
619
+ #### Tool with Connector
468
620
 
469
621
  ```typescript
470
622
  const createTicketTool = createTool({
@@ -476,7 +628,7 @@ const createTicketTool = createTool({
476
628
  priority: z.enum(['low', 'medium', 'high']),
477
629
  }),
478
630
  execute: async ({ context, runflow }) => {
479
- // Usar connector
631
+ // Use connector
480
632
  const ticket = await runflow.connector(
481
633
  'hubspot',
482
634
  'tickets',
@@ -487,22 +639,31 @@ const createTicketTool = createTool({
487
639
  priority: context.priority,
488
640
  }
489
641
  );
490
-
642
+
491
643
  return { ticketId: ticket.id };
492
644
  },
493
645
  });
494
646
  ```
495
647
 
648
+ #### Tool Execution Context
649
+
650
+ The `execute` function receives:
651
+ - `context`: Validated input parameters (from `inputSchema`)
652
+ - `runflow`: Runflow API client for vector search, connectors, memory
653
+ - `projectId`: Current project ID
654
+
655
+ ---
656
+
496
657
  ### Connectors
497
658
 
498
- **Connectors** são integrações pré-configuradas com serviços externos (HubSpot, Twilio, Email, Slack).
659
+ **Connectors** are pre-configured integrations with external services (HubSpot, Twilio, Email, Slack).
499
660
 
500
- #### Criar Connector Tool
661
+ #### Create Connector Tool
501
662
 
502
663
  ```typescript
503
664
  import { createConnectorTool } from '@runflow-ai/sdk';
504
665
 
505
- // HubSpot - Criar contato
666
+ // HubSpot - Create contact
506
667
  const createContact = createConnectorTool(
507
668
  'hubspot',
508
669
  'contacts',
@@ -516,7 +677,7 @@ const createContact = createConnectorTool(
516
677
  }
517
678
  );
518
679
 
519
- // Twilio - Enviar WhatsApp
680
+ // Twilio - Send WhatsApp
520
681
  const sendWhatsApp = createConnectorTool(
521
682
  'twilio',
522
683
  'messages',
@@ -528,7 +689,7 @@ const sendWhatsApp = createConnectorTool(
528
689
  }
529
690
  );
530
691
 
531
- // Email - Enviar email
692
+ // Email - Send email
532
693
  const sendEmail = createConnectorTool(
533
694
  'email',
534
695
  'messages',
@@ -540,9 +701,22 @@ const sendEmail = createConnectorTool(
540
701
  html: 'boolean?',
541
702
  }
542
703
  );
704
+
705
+ // Slack - Send message
706
+ const sendSlack = createConnectorTool(
707
+ 'slack',
708
+ 'messages',
709
+ 'send',
710
+ {
711
+ channel: 'string',
712
+ message: 'string',
713
+ username: 'string?',
714
+ iconEmoji: 'string?',
715
+ }
716
+ );
543
717
  ```
544
718
 
545
- #### Usar Built-in Shortcuts
719
+ #### Use Built-in Shortcuts
546
720
 
547
721
  ```typescript
548
722
  import { hubspot, twilio, email, slack } from '@runflow-ai/sdk';
@@ -552,52 +726,58 @@ const agent = new Agent({
552
726
  instructions: 'You help customers.',
553
727
  model: openai('gpt-4o'),
554
728
  tools: {
729
+ // Built-in connector shortcuts
555
730
  createContact: hubspot.createContact(),
731
+ getContact: hubspot.getContact(),
732
+ createTicket: hubspot.createTicket(),
556
733
  sendWhatsApp: twilio.sendWhatsApp(),
734
+ sendSMS: twilio.sendSMS(),
557
735
  sendEmail: email.send(),
558
736
  sendSlack: slack.sendMessage(),
559
737
  },
560
738
  });
561
739
  ```
562
740
 
563
- #### Tipos de Parâmetros
741
+ #### Parameter Types
564
742
 
565
743
  ```typescript
566
744
  const tool = createConnectorTool('service', 'resource', 'action', {
567
- // Tipos básicos
745
+ // Basic types
568
746
  name: 'string',
569
747
  age: 'number',
570
748
  active: 'boolean',
571
-
572
- // Opcionais
749
+ createdAt: 'date',
750
+
751
+ // Optional (append ?)
573
752
  nickname: 'string?',
574
753
  score: 'number?',
575
-
576
- // Validações especiais
754
+
755
+ // Special validations
577
756
  email: 'email',
578
757
  website: 'url',
579
- birthday: 'date',
580
-
758
+
581
759
  // Enum
582
760
  priority: { enum: ['low', 'medium', 'high'] },
583
-
761
+
584
762
  // Arrays
585
763
  tags: { array: 'string' },
586
764
  scores: { array: 'number' },
587
765
  });
588
766
  ```
589
767
 
768
+ ---
769
+
590
770
  ### Workflows
591
771
 
592
- **Workflows** orquestram múltiplos agents, functions e connectors em sequência.
772
+ **Workflows** orchestrate multiple agents, functions, and connectors in sequence.
593
773
 
594
- #### Workflow Básico
774
+ #### Basic Workflow
595
775
 
596
776
  ```typescript
597
777
  import { createWorkflow, Agent, openai } from '@runflow-ai/sdk';
598
778
  import { z } from 'zod';
599
779
 
600
- // Definir schema de entrada/saída
780
+ // Define input/output schemas
601
781
  const inputSchema = z.object({
602
782
  customerEmail: z.string().email(),
603
783
  issueDescription: z.string(),
@@ -609,7 +789,7 @@ const outputSchema = z.object({
609
789
  emailSent: z.boolean(),
610
790
  });
611
791
 
612
- // Criar agents
792
+ // Create agents
613
793
  const analyzerAgent = new Agent({
614
794
  name: 'Issue Analyzer',
615
795
  instructions: 'Analyze customer issues and categorize them.',
@@ -622,7 +802,7 @@ const responderAgent = new Agent({
622
802
  model: openai('gpt-4o'),
623
803
  });
624
804
 
625
- // Criar workflow
805
+ // Create workflow
626
806
  const workflow = createWorkflow({
627
807
  id: 'support-workflow',
628
808
  name: 'Support Ticket Workflow',
@@ -647,7 +827,7 @@ const workflow = createWorkflow({
647
827
  })
648
828
  .build();
649
829
 
650
- // Executar workflow
830
+ // Execute workflow
651
831
  const result = await workflow.execute({
652
832
  customerEmail: 'customer@example.com',
653
833
  issueDescription: 'My order has not arrived',
@@ -656,7 +836,7 @@ const result = await workflow.execute({
656
836
  console.log(result);
657
837
  ```
658
838
 
659
- #### Workflow com Parallel Steps
839
+ #### Workflow with Parallel Steps
660
840
 
661
841
  ```typescript
662
842
  const workflow = createWorkflow({
@@ -669,7 +849,7 @@ const workflow = createWorkflow({
669
849
  createAgentStep('agent2', agent2),
670
850
  createAgentStep('agent3', agent3),
671
851
  ], {
672
- waitForAll: true, // Aguardar todos completarem
852
+ waitForAll: true, // Wait for all to complete
673
853
  })
674
854
  .function('merge', async (input, context) => {
675
855
  // Merge results
@@ -680,7 +860,7 @@ const workflow = createWorkflow({
680
860
  .build();
681
861
  ```
682
862
 
683
- #### Workflow com Conditional Steps
863
+ #### Workflow with Conditional Steps
684
864
 
685
865
  ```typescript
686
866
  const workflow = createWorkflow({
@@ -707,7 +887,7 @@ const workflow = createWorkflow({
707
887
  .build();
708
888
  ```
709
889
 
710
- #### Workflow com Retry
890
+ #### Workflow with Retry
711
891
 
712
892
  ```typescript
713
893
  const workflow = createWorkflow({
@@ -726,7 +906,7 @@ const workflow = createWorkflow({
726
906
  },
727
907
  retryConfig: {
728
908
  maxAttempts: 3,
729
- backoff: 'exponential',
909
+ backoff: 'exponential', // 'fixed', 'exponential', 'linear'
730
910
  delay: 1000,
731
911
  retryableErrors: ['timeout', 'network'],
732
912
  },
@@ -734,11 +914,43 @@ const workflow = createWorkflow({
734
914
  .build();
735
915
  ```
736
916
 
737
- ### RAG/Knowledge
917
+ #### Workflow Step Types
918
+
919
+ ```typescript
920
+ import {
921
+ createAgentStep,
922
+ createFunctionStep,
923
+ createConnectorStep
924
+ } from '@runflow-ai/sdk';
925
+
926
+ // Agent step
927
+ const agentStep = createAgentStep('step-id', agent, {
928
+ promptTemplate: 'Process: {{input.data}}',
929
+ });
930
+
931
+ // Function step
932
+ const functionStep = createFunctionStep('step-id', async (input, context) => {
933
+ // Custom logic
934
+ return { result: 'processed' };
935
+ });
936
+
937
+ // Connector step
938
+ const connectorStep = createConnectorStep(
939
+ 'step-id',
940
+ 'hubspot',
941
+ 'contacts',
942
+ 'create',
943
+ { email: '{{input.email}}' }
944
+ );
945
+ ```
946
+
947
+ ---
948
+
949
+ ### Knowledge (RAG)
738
950
 
739
- O módulo **Knowledge** (também chamado de RAG) gerencia busca semântica em bases de conhecimento.
951
+ The **Knowledge** module (also called RAG) manages semantic search in vector knowledge bases.
740
952
 
741
- #### Knowledge Standalone
953
+ #### Standalone Knowledge Manager
742
954
 
743
955
  ```typescript
744
956
  import { Knowledge } from '@runflow-ai/sdk';
@@ -749,7 +961,7 @@ const knowledge = new Knowledge({
749
961
  threshold: 0.7,
750
962
  });
751
963
 
752
- // Busca básica
964
+ // Basic search
753
965
  const results = await knowledge.search('How to reset password?');
754
966
 
755
967
  results.forEach(result => {
@@ -757,7 +969,7 @@ results.forEach(result => {
757
969
  console.log('Score:', result.score);
758
970
  });
759
971
 
760
- // Get context formatado para LLM
972
+ // Get formatted context for LLM
761
973
  const context = await knowledge.getContext('password reset', { k: 3 });
762
974
  console.log(context);
763
975
  ```
@@ -788,7 +1000,9 @@ const results = await knowledge.multiQuery(
788
1000
  );
789
1001
  ```
790
1002
 
791
- #### Knowledge no Agent (Agentic RAG)
1003
+ #### Agentic RAG in Agent
1004
+
1005
+ When RAG is configured in an agent, the SDK automatically creates a `searchKnowledge` tool that the LLM can decide when to use. This is more efficient than always searching, as the LLM only searches when necessary.
792
1006
 
793
1007
  ```typescript
794
1008
  const agent = new Agent({
@@ -799,49 +1013,78 @@ const agent = new Agent({
799
1013
  vectorStore: 'support-docs',
800
1014
  k: 5,
801
1015
  threshold: 0.7,
802
-
803
- // Prompt customizável - orienta quando buscar
1016
+
1017
+ // Custom search prompt - guides when to search
804
1018
  searchPrompt: `Use searchKnowledge tool when user asks about:
805
1019
  - Technical problems
806
1020
  - Process questions
807
1021
  - Specific information
808
1022
 
809
1023
  Don't use for greetings or casual chat.`,
810
-
1024
+
811
1025
  toolDescription: 'Search in support documentation for solutions',
812
1026
  },
813
1027
  });
814
1028
 
815
- // Agent tem tool 'searchKnowledge' gerada automaticamente
816
- // LLM decide quando buscar (não busca sempre - mais eficiente!)
1029
+ // Agent automatically has 'searchKnowledge' tool
1030
+ // LLM decides when to search (not always - more efficient!)
817
1031
  const result = await agent.process({
818
1032
  message: 'How do I reset my password?',
819
- companyId: 'company_123',
820
1033
  });
821
1034
  ```
822
1035
 
1036
+ #### Multiple Vector Stores
1037
+
1038
+ ```typescript
1039
+ const agent = new Agent({
1040
+ name: 'Advanced Support Agent',
1041
+ instructions: 'Help users with multiple knowledge bases.',
1042
+ model: openai('gpt-4o'),
1043
+ rag: {
1044
+ vectorStores: [
1045
+ {
1046
+ id: 'support-docs',
1047
+ name: 'Support Documentation',
1048
+ description: 'General support articles',
1049
+ threshold: 0.7,
1050
+ k: 5,
1051
+ },
1052
+ {
1053
+ id: 'api-docs',
1054
+ name: 'API Documentation',
1055
+ description: 'Technical API reference',
1056
+ threshold: 0.8,
1057
+ k: 3,
1058
+ },
1059
+ ],
1060
+ },
1061
+ });
1062
+ ```
1063
+
1064
+ ---
1065
+
823
1066
  ### LLM Standalone
824
1067
 
825
- O módulo **LLM** permite usar modelos de linguagem diretamente, sem criar agents.
1068
+ The **LLM** module allows you to use language models directly without creating agents.
826
1069
 
827
- #### Uso Básico
1070
+ #### Basic Usage
828
1071
 
829
1072
  ```typescript
830
1073
  import { LLM } from '@runflow-ai/sdk';
831
1074
 
832
- // Criar LLM
1075
+ // Create LLM
833
1076
  const llm = LLM.openai('gpt-4o', {
834
1077
  temperature: 0.7,
835
1078
  maxTokens: 2000,
836
1079
  });
837
1080
 
838
- // Gerar resposta
1081
+ // Generate response
839
1082
  const response = await llm.generate('What is the capital of Brazil?');
840
1083
  console.log(response.text);
841
1084
  console.log('Tokens:', response.usage);
842
1085
  ```
843
1086
 
844
- #### Com Mensagens
1087
+ #### With Messages
845
1088
 
846
1089
  ```typescript
847
1090
  const response = await llm.generate([
@@ -850,7 +1093,7 @@ const response = await llm.generate([
850
1093
  ]);
851
1094
  ```
852
1095
 
853
- #### Com System Prompt
1096
+ #### With System Prompt
854
1097
 
855
1098
  ```typescript
856
1099
  const response = await llm.generate(
@@ -882,7 +1125,7 @@ import { LLM } from '@runflow-ai/sdk';
882
1125
  // OpenAI
883
1126
  const gpt4 = LLM.openai('gpt-4o', { temperature: 0.7 });
884
1127
 
885
- // Anthropic
1128
+ // Anthropic (Claude)
886
1129
  const claude = LLM.anthropic('claude-3-5-sonnet-20241022', {
887
1130
  temperature: 0.9,
888
1131
  maxTokens: 4000,
@@ -894,39 +1137,42 @@ const bedrock = LLM.bedrock('anthropic.claude-3-sonnet-20240229-v1:0', {
894
1137
  });
895
1138
  ```
896
1139
 
1140
+ ---
1141
+
897
1142
  ### Observability
898
1143
 
899
- O sistema de **Observability** coleta traces automáticos de execuções para análise e debugging.
1144
+ The **Observability** system automatically collects execution traces for analysis and debugging.
900
1145
 
901
- #### Trace Automático (Agent)
1146
+ #### Automatic Tracing (Agent)
902
1147
 
903
1148
  ```typescript
904
- // Traces são coletados automaticamente
1149
+ // Traces are collected automatically
905
1150
  const agent = new Agent({
906
1151
  name: 'Support Agent',
907
1152
  instructions: 'Help customers.',
908
1153
  model: openai('gpt-4o'),
909
1154
  });
910
1155
 
911
- // Cada execução gera traces automaticamente
1156
+ // Each execution automatically generates traces
912
1157
  await agent.process({
913
1158
  message: 'Help me',
914
- companyId: 'company_123',
915
- sessionId: 'session_456',
916
- executionId: 'exec_123', // Opcional
917
- threadId: 'thread_789', // Opcional
1159
+ companyId: 'company_123', // Optional
1160
+ sessionId: 'session_456', // Optional
1161
+ executionId: 'exec_123', // Optional
1162
+ threadId: 'thread_789', // Optional
918
1163
  });
919
1164
  ```
920
1165
 
921
- #### Trace Manual
1166
+ #### Manual Tracing
922
1167
 
923
1168
  ```typescript
924
1169
  import { createTraceCollector } from '@runflow-ai/sdk';
925
1170
 
926
- // Criar collector
1171
+ // Create collector
927
1172
  const collector = createTraceCollector(apiClient, 'project_123', {
928
1173
  batchSize: 10,
929
1174
  flushInterval: 5000,
1175
+ maxRetries: 3,
930
1176
  });
931
1177
 
932
1178
  // Start span
@@ -938,14 +1184,18 @@ const span = collector.startSpan('custom_operation', {
938
1184
  span.setInput({ data: 'input' });
939
1185
 
940
1186
  try {
941
- // Executar operação
1187
+ // Execute operation
942
1188
  const result = await doSomething();
943
-
1189
+
944
1190
  span.setOutput(result);
945
1191
  span.setCosts({
946
1192
  tokens: { input: 100, output: 50, total: 150 },
947
- costs: { inputCost: 0.003, outputCost: 0.002, totalCost: 0.005, currency: 'USD' },
948
- totalCost: 0.005,
1193
+ costs: {
1194
+ inputCost: 0.003,
1195
+ outputCost: 0.002,
1196
+ totalCost: 0.005,
1197
+ currency: 'USD'
1198
+ },
949
1199
  });
950
1200
  } catch (error) {
951
1201
  span.setError(error);
@@ -953,172 +1203,51 @@ try {
953
1203
 
954
1204
  span.finish();
955
1205
 
956
- // Forçar flush
1206
+ // Force flush
957
1207
  await collector.flush();
958
1208
  ```
959
1209
 
960
- #### Decorator para Auto-Tracing
1210
+ #### Decorator for Auto-Tracing
961
1211
 
962
1212
  ```typescript
963
1213
  import { traced } from '@runflow-ai/sdk';
964
1214
 
965
1215
  class MyService {
966
1216
  private traceCollector: TraceCollector;
967
-
1217
+
968
1218
  @traced('my_operation', { agentName: 'My Agent' })
969
1219
  async myMethod(input: any) {
970
- // Automaticamente traced
1220
+ // Automatically traced
971
1221
  return processData(input);
972
1222
  }
973
1223
  }
974
1224
  ```
975
1225
 
976
- #### Traces Locais (Development)
977
-
978
- ```typescript
979
- // .env
980
- RUNFLOW_LOCAL_TRACES=true
981
-
982
- // Traces serão salvos em .runflow/traces.json
983
- // Formato estruturado por executionId para análise
984
- ```
985
-
986
- ---
987
-
988
- ## 🏗️ Arquitetura
989
-
990
- ### Estrutura do SDK
991
-
992
- ```
993
- @runflow-ai/sdk/
994
- ├── core/ # Núcleo do SDK
995
- │ ├── agent.ts # Classe Agent principal
996
- │ ├── api-client.ts # Cliente da API Runflow
997
- │ ├── context.ts # Runflow singleton (context management)
998
- │ └── models.ts # Model providers (openai, anthropic, bedrock)
999
-
1000
- ├── tools/ # Sistema de Tools
1001
- │ └── tool-creator.ts # Factory para criar tools
1002
-
1003
- ├── connectors/ # Sistema de Connectors
1004
- │ ├── connector-creator.ts
1005
- │ └── built-in/ # HubSpot, Twilio, Email, Slack
1006
-
1007
- ├── workflows/ # Sistema de Workflows
1008
- │ └── workflow.ts # Workflow engine + builder
1009
-
1010
- ├── memory/ # Sistema de Memory
1011
- │ └── memory-manager.ts
1012
-
1013
- ├── knowledge/ # Sistema de RAG
1014
- │ └── knowledge-manager.ts
1015
-
1016
- ├── llm/ # LLM Standalone
1017
- │ └── llm-manager.ts
1018
-
1019
- ├── observability/ # Sistema de Traces
1020
- │ └── trace-collector.ts
1021
-
1022
- ├── providers/ # Provider interfaces
1023
- │ ├── types.ts # MemoryProvider, KnowledgeProvider, LLMProvider
1024
- │ └── runflow/ # Implementações padrão
1025
-
1026
- └── types/ # TypeScript types
1027
- └── all-types.ts # Todos os tipos do SDK
1028
- ```
1029
-
1030
- ### Fluxo de Execução
1031
-
1032
- ```
1033
- 1. Developer cria Agent/Workflow
1034
- 2. SDK configura API Client (auto ou injetado)
1035
- 3. Agent.process() é chamado
1036
- 4. Context é resolvido (Runflow.identify() ou input direto)
1037
- 5. Memory é carregada (se configurado)
1038
- 6. RAG busca contexto (se configurado)
1039
- 7. LLM é chamado com prompt + context
1040
- 8. Tools são executadas (se chamadas)
1041
- 9. Response é gerada
1042
- 10. Memory é salva (se configurado)
1043
- 11. Traces são coletados (automático)
1044
- 12. Output é retornado
1045
- ```
1046
-
1047
- ### Multi-Agent Pattern
1048
-
1049
- ```typescript
1050
- // Supervisor Pattern (automático)
1051
- const agent = new Agent({
1052
- name: 'Supervisor',
1053
- instructions: 'Route tasks to appropriate agents.',
1054
- model: openai('gpt-4o'),
1055
- agents: {
1056
- support: {
1057
- name: 'Support Agent',
1058
- instructions: 'Handle support requests.',
1059
- model: openai('gpt-4o-mini'),
1060
- },
1061
- sales: {
1062
- name: 'Sales Agent',
1063
- instructions: 'Handle sales inquiries.',
1064
- model: openai('gpt-4o-mini'),
1065
- },
1066
- },
1067
- });
1068
-
1069
- // Supervisor decide automaticamente qual agent usar
1070
- await agent.process({
1071
- message: 'I want to buy your product',
1072
- companyId: 'company_123',
1073
- });
1074
- ```
1075
-
1076
- ---
1077
-
1078
- ## 🔧 Configuração
1079
-
1080
- ### Variáveis de Ambiente
1226
+ #### Local Traces (Development)
1081
1227
 
1082
1228
  ```bash
1083
- # API Configuration
1084
- RUNFLOW_API_URL=http://localhost:3001
1085
- RUNFLOW_API_KEY=your_api_key_here
1086
- RUNFLOW_TENANT_ID=your_tenant_id
1087
- RUNFLOW_AGENT_ID=your_agent_id
1088
-
1089
- # Execution Context (opcional - geralmente vem da engine)
1090
- RUNFLOW_EXECUTION_ID=exec_123
1091
- RUNFLOW_THREAD_ID=thread_456
1092
- RUNFLOW_TENANT_ID=company_123
1093
-
1094
- # Development
1095
- RUNFLOW_ENV=development
1229
+ # .env
1096
1230
  RUNFLOW_LOCAL_TRACES=true
1097
1231
  ```
1098
1232
 
1099
- ### Arquivo de Configuração (.runflow/rf.json)
1100
-
1101
- ```json
1102
- {
1103
- "agentId": "your_agent_id",
1104
- "tenantId": "your_tenant_id",
1105
- "apiKey": "your_api_key",
1106
- "apiUrl": "http://localhost:3001"
1107
- }
1108
- ```
1109
-
1110
- O SDK busca automaticamente `.runflow/rf.json` no diretório atual e nos pais.
1233
+ Traces will be saved to `.runflow/traces.json` in a structured format organized by `executionId` for analysis.
1111
1234
 
1112
- **Prioridade de configuração:**
1235
+ #### Trace Types
1113
1236
 
1114
- 1. Config explícito no código
1115
- 2. `.runflow/rf.json`
1116
- 3. Variáveis de ambiente
1117
- 4. Defaults
1237
+ The SDK supports various trace types:
1238
+ - `agent_execution` - Full agent processing
1239
+ - `workflow_execution` - Workflow processing
1240
+ - `workflow_step` - Individual workflow step
1241
+ - `tool_call` - Tool execution
1242
+ - `llm_call` - LLM API call
1243
+ - `vector_search` - Vector search operation
1244
+ - `memory_operation` - Memory access
1245
+ - `connector_call` - Connector execution
1246
+ - `streaming_session` - Streaming response
1118
1247
 
1119
1248
  ---
1120
1249
 
1121
- ## 📚 Exemplos Avançados
1250
+ ## 🏗️ Advanced Examples
1122
1251
 
1123
1252
  ### Multi-Modal (Images)
1124
1253
 
@@ -1131,7 +1260,6 @@ const agent = new Agent({
1131
1260
 
1132
1261
  await agent.process({
1133
1262
  message: 'What is in this image?',
1134
- companyId: 'company_123',
1135
1263
  messages: [
1136
1264
  {
1137
1265
  role: 'user',
@@ -1147,7 +1275,7 @@ await agent.process({
1147
1275
  });
1148
1276
  ```
1149
1277
 
1150
- ### Streaming com Memory
1278
+ ### Streaming with Memory
1151
1279
 
1152
1280
  ```typescript
1153
1281
  const agent = new Agent({
@@ -1165,7 +1293,6 @@ const agent = new Agent({
1165
1293
 
1166
1294
  const stream = await agent.processStream({
1167
1295
  message: 'Tell me a story',
1168
- companyId: 'company_123',
1169
1296
  sessionId: 'session_123',
1170
1297
  });
1171
1298
 
@@ -1183,26 +1310,33 @@ import { Memory, MemoryProvider } from '@runflow-ai/sdk';
1183
1310
 
1184
1311
  class RedisMemoryProvider implements MemoryProvider {
1185
1312
  async get(key: string): Promise<MemoryData> {
1186
- // Implementar com Redis
1187
1313
  const data = await redis.get(key);
1188
1314
  return JSON.parse(data);
1189
1315
  }
1190
-
1316
+
1191
1317
  async set(key: string, data: MemoryData): Promise<void> {
1192
1318
  await redis.set(key, JSON.stringify(data));
1193
1319
  }
1194
-
1195
- // ... outros métodos
1320
+
1321
+ async append(key: string, message: MemoryMessage): Promise<void> {
1322
+ const data = await this.get(key);
1323
+ data.messages.push(message);
1324
+ await this.set(key, data);
1325
+ }
1326
+
1327
+ async clear(key: string): Promise<void> {
1328
+ await redis.del(key);
1329
+ }
1196
1330
  }
1197
1331
 
1198
- // Usar custom provider
1332
+ // Use custom provider
1199
1333
  const memory = new Memory({
1200
1334
  provider: new RedisMemoryProvider(),
1201
1335
  maxTurns: 10,
1202
1336
  });
1203
1337
  ```
1204
1338
 
1205
- ### Complex Workflow
1339
+ ### Complex E-Commerce Workflow
1206
1340
 
1207
1341
  ```typescript
1208
1342
  const workflow = createWorkflow({
@@ -1217,7 +1351,7 @@ const workflow = createWorkflow({
1217
1351
  .agent('analyzer', analyzerAgent, {
1218
1352
  promptTemplate: 'Analyze customer query: {{input.query}}',
1219
1353
  })
1220
-
1354
+
1221
1355
  // 2. Load customer data in parallel
1222
1356
  .parallel([
1223
1357
  createFunctionStep('load-profile', async (input, ctx) => {
@@ -1230,7 +1364,7 @@ const workflow = createWorkflow({
1230
1364
  return await searchProducts(ctx.stepResults.get('analyzer').text);
1231
1365
  }),
1232
1366
  ])
1233
-
1367
+
1234
1368
  // 3. Conditional: Sales vs Support
1235
1369
  .condition(
1236
1370
  'route',
@@ -1251,7 +1385,7 @@ const workflow = createWorkflow({
1251
1385
  }),
1252
1386
  ]
1253
1387
  )
1254
-
1388
+
1255
1389
  // 4. Send response
1256
1390
  .agent('responder', responderAgent, {
1257
1391
  promptTemplate: 'Create final response based on context',
@@ -1266,70 +1400,684 @@ const result = await workflow.execute({
1266
1400
 
1267
1401
  ---
1268
1402
 
1269
- ## 📖 API Reference
1270
-
1271
- ### Exports Principais
1272
-
1273
- ```typescript
1274
- // Core
1275
- export { Agent, Runflow, openai, anthropic, bedrock } from '@runflow-ai/sdk';
1276
-
1277
- // Tools & Connectors
1278
- export { createTool, createConnectorTool } from '@runflow-ai/sdk';
1279
- export { hubspot, twilio, email, slack } from '@runflow-ai/sdk';
1280
-
1281
- // Workflows
1282
- export {
1283
- Workflow,
1284
- createWorkflow,
1285
- createStep,
1286
- createAgentStep,
1287
- createFunctionStep,
1288
- createConnectorStep,
1289
- } from '@runflow-ai/sdk';
1290
-
1291
- // Standalone Modules
1292
- export { Memory, Knowledge, RAG, LLM } from '@runflow-ai/sdk';
1403
+ ## 💡 Real-World Use Cases
1293
1404
 
1294
- // Observability
1295
- export {
1296
- createTraceCollector,
1297
- RunflowTraceCollector,
1298
- traced
1299
- } from '@runflow-ai/sdk';
1405
+ Complete, production-ready examples showcasing the platform's potential.
1300
1406
 
1301
- // Types
1302
- export type {
1303
- AgentConfig,
1304
- AgentInput,
1305
- AgentOutput,
1306
- ModelProvider,
1307
- RunflowTool,
1308
- ToolConfig,
1309
- WorkflowConfig,
1310
- MemoryConfig,
1311
- TraceData,
1312
- // ... etc
1313
- } from '@runflow-ai/sdk';
1314
- ```
1407
+ ### 1. Customer Support Agent with RAG
1315
1408
 
1316
- ### Sub-path Imports
1409
+ A sophisticated support agent that searches documentation, remembers context, and creates tickets in HubSpot.
1317
1410
 
1318
1411
  ```typescript
1319
- // Core
1320
- import { Agent } from '@runflow-ai/sdk/core';
1412
+ import { Agent, openai, createTool } from '@runflow-ai/sdk';
1413
+ import { hubspotConnector } from '@runflow-ai/sdk/connectors';
1414
+ import { z } from 'zod';
1321
1415
 
1322
- // Models
1323
- import { openai, anthropic, bedrock } from '@runflow-ai/sdk/models';
1416
+ // Create a support agent with memory and RAG
1417
+ const supportAgent = new Agent({
1418
+ name: 'Customer Support AI',
1419
+ instructions: `You are a helpful customer support agent.
1420
+ - Search the knowledge base for relevant information
1421
+ - Remember previous conversations
1422
+ - Create tickets for complex issues
1423
+ - Always be professional and empathetic`,
1324
1424
 
1325
- // Tools
1326
- import { createTool } from '@runflow-ai/sdk/tools';
1425
+ model: openai('gpt-4o'),
1426
+
1427
+ // Remember conversation history
1428
+ memory: {
1429
+ type: 'conversation',
1430
+ maxTurns: 20,
1431
+ summarization: {
1432
+ enabled: true,
1433
+ threshold: 10,
1434
+ },
1435
+ },
1436
+
1437
+ // Search in documentation
1438
+ knowledge: {
1439
+ vectorStore: 'support-docs',
1440
+ k: 5,
1441
+ threshold: 0.7,
1442
+ },
1443
+
1444
+ // Available tools
1445
+ tools: {
1446
+ createTicket: hubspotConnector.tickets.create,
1447
+ searchOrders: createTool({
1448
+ id: 'search-orders',
1449
+ description: 'Search customer orders',
1450
+ inputSchema: z.object({
1451
+ customerId: z.string(),
1452
+ }),
1453
+ execute: async ({ context }) => {
1454
+ const orders = await fetchOrders(context.input.customerId);
1455
+ return { orders };
1456
+ },
1457
+ }),
1458
+ },
1459
+ });
1460
+
1461
+ // Handle customer message
1462
+ const result = await supportAgent.process({
1463
+ message: 'My order #12345 has not arrived yet',
1464
+ sessionId: 'session_xyz', // For conversation history
1465
+ userId: 'user_123', // For user identification
1466
+ });
1467
+
1468
+ console.log(result.message);
1469
+ // Agent searches docs, retrieves order info, and provides solution
1470
+ ```
1471
+
1472
+ ### 2. Sales Automation with Multi-Step Workflow
1473
+
1474
+ Automate lead qualification, deal creation, and team notifications using workflows.
1475
+
1476
+ ```typescript
1477
+ import { createWorkflow, Agent, openai } from '@runflow-ai/sdk';
1478
+ import { hubspotConnector, slackConnector } from '@runflow-ai/sdk/connectors';
1479
+ import { z } from 'zod';
1480
+
1481
+ // Qualification agent
1482
+ const qualifierAgent = new Agent({
1483
+ name: 'Lead Qualifier',
1484
+ instructions: 'Analyze lead data and assign a score (1-10) with reasoning.',
1485
+ model: openai('gpt-4o-mini'),
1486
+ });
1487
+
1488
+ // Sales copy agent
1489
+ const copywriterAgent = new Agent({
1490
+ name: 'Sales Copywriter',
1491
+ instructions: 'Write a personalized email for the lead based on their profile.',
1492
+ model: openai('gpt-4o'),
1493
+ });
1494
+
1495
+ // Complete workflow
1496
+ const salesWorkflow = createWorkflow({
1497
+ id: 'lead-to-deal',
1498
+ inputSchema: z.object({
1499
+ leadEmail: z.string().email(),
1500
+ leadName: z.string(),
1501
+ company: z.string(),
1502
+ notes: z.string(),
1503
+ }),
1504
+ outputSchema: z.any(),
1505
+ })
1506
+ // Step 1: Qualify the lead
1507
+ .agent('qualify', qualifierAgent, {
1508
+ promptTemplate: `Analyze this lead:
1509
+ Name: {{input.leadName}}
1510
+ Company: {{input.company}}
1511
+ Notes: {{input.notes}}
1512
+
1513
+ Provide score (1-10) and reasoning.`,
1514
+ })
1515
+
1516
+ // Step 2: Conditional - Only proceed if score >= 7
1517
+ .condition(
1518
+ 'check-score',
1519
+ (ctx) => {
1520
+ const score = parseInt(ctx.stepResults.get('qualify').text.match(/\d+/)?.[0] || '0');
1521
+ return score >= 7;
1522
+ },
1523
+ // High quality lead path
1524
+ [
1525
+ // Create contact in HubSpot
1526
+ {
1527
+ id: 'create-contact',
1528
+ type: 'connector',
1529
+ config: {
1530
+ connector: 'hubspot',
1531
+ resource: 'contacts',
1532
+ action: 'create',
1533
+ parameters: {
1534
+ email: '{{input.leadEmail}}',
1535
+ firstname: '{{input.leadName}}',
1536
+ company: '{{input.company}}',
1537
+ lifecyclestage: 'lead',
1538
+ },
1539
+ },
1540
+ },
1541
+
1542
+ // Create deal
1543
+ {
1544
+ id: 'create-deal',
1545
+ type: 'connector',
1546
+ config: {
1547
+ connector: 'hubspot',
1548
+ resource: 'deals',
1549
+ action: 'create',
1550
+ parameters: {
1551
+ dealname: 'Deal - {{input.company}}',
1552
+ amount: 5000,
1553
+ dealstage: 'qualifiedtobuy',
1554
+ pipeline: 'default',
1555
+ hubspot_owner_id: '12345',
1556
+ },
1557
+ },
1558
+ },
1559
+
1560
+ // Generate personalized email
1561
+ {
1562
+ id: 'write-email',
1563
+ type: 'agent',
1564
+ config: {
1565
+ agent: copywriterAgent,
1566
+ promptTemplate: `Write a personalized sales email for:
1567
+ Name: {{input.leadName}}
1568
+ Company: {{input.company}}
1569
+ Qualification: {{qualify.text}}`,
1570
+ },
1571
+ },
1572
+
1573
+ // Notify sales team on Slack
1574
+ {
1575
+ id: 'notify-team',
1576
+ type: 'connector',
1577
+ config: {
1578
+ connector: 'slack',
1579
+ resource: 'messages',
1580
+ action: 'send',
1581
+ parameters: {
1582
+ channel: '#sales',
1583
+ text: `🎯 New qualified lead: *{{input.leadName}}* from *{{input.company}}*\nScore: High\nDeal created: {{create-deal.id}}`,
1584
+ },
1585
+ },
1586
+ },
1587
+ ],
1588
+ // Low quality lead path
1589
+ [
1590
+ {
1591
+ id: 'log-rejected',
1592
+ type: 'function',
1593
+ config: {
1594
+ execute: async (input, ctx) => {
1595
+ console.log(`Lead ${input.leadName} rejected - Low score`);
1596
+ return { rejected: true };
1597
+ },
1598
+ },
1599
+ },
1600
+ ]
1601
+ )
1602
+ .build();
1603
+
1604
+ // Execute workflow
1605
+ const result = await salesWorkflow.execute({
1606
+ leadEmail: 'john@techcorp.com',
1607
+ leadName: 'John Smith',
1608
+ company: 'TechCorp Inc',
1609
+ notes: 'Interested in enterprise plan. Budget: $10k/month. Timeline: Q1 2025.',
1610
+ });
1611
+
1612
+ console.log('Workflow completed:', result);
1613
+ ```
1614
+
1615
+ ### 3. Intelligent Collections Agent (WhatsApp)
1616
+
1617
+ Automate debt collection with personalized WhatsApp messages using context-aware AI.
1618
+
1619
+ ```typescript
1620
+ import { Agent, openai, Runflow } from '@runflow-ai/sdk';
1621
+ import { twilioConnector } from '@runflow-ai/sdk/connectors';
1622
+ import { z } from 'zod';
1623
+
1624
+ // Collections agent with empathy and context
1625
+ const collectionsAgent = new Agent({
1626
+ name: 'Collections AI',
1627
+ instructions: `You are an empathetic debt collection agent.
1628
+ - Analyze customer history and payment patterns
1629
+ - Create personalized, respectful messages
1630
+ - Offer payment plan options
1631
+ - Never be aggressive or rude`,
1632
+
1633
+ model: openai('gpt-4o'),
1634
+
1635
+ memory: {
1636
+ type: 'conversation',
1637
+ maxTurns: 10,
1638
+ },
1639
+
1640
+ tools: {
1641
+ sendWhatsApp: twilioConnector.whatsapp.send,
1642
+ getPaymentHistory: createTool({
1643
+ id: 'get-payment-history',
1644
+ description: 'Get customer payment history',
1645
+ inputSchema: z.object({
1646
+ customerId: z.string(),
1647
+ }),
1648
+ execute: async ({ context }) => {
1649
+ const history = await fetchPaymentHistory(context.input.customerId);
1650
+ return { history };
1651
+ },
1652
+ }),
1653
+ },
1654
+ });
1655
+
1656
+ // Process overdue invoice
1657
+ async function processOverdueInvoice(invoice: any) {
1658
+ // Set customer context
1659
+ Runflow.identify({
1660
+ type: 'customer',
1661
+ value: invoice.customerId,
1662
+ userId: invoice.customerId,
1663
+ });
1664
+
1665
+ const result = await collectionsAgent.process({
1666
+ message: `Create a personalized WhatsApp message for customer ${invoice.customerName}.
1667
+ Invoice: ${invoice.id}
1668
+ Amount: $${invoice.amount}
1669
+ Days overdue: ${invoice.daysOverdue}
1670
+ Previous payment history: Check using the tool.
1671
+
1672
+ If history is good, offer a payment plan. Send via WhatsApp.`,
1673
+ sessionId: `collection_${invoice.id}`,
1674
+ });
1675
+
1676
+ console.log('Collection message sent:', result);
1677
+ }
1678
+
1679
+ // Batch process overdue invoices
1680
+ const overdueInvoices = await fetchOverdueInvoices();
1681
+ for (const invoice of overdueInvoices) {
1682
+ await processOverdueInvoice(invoice);
1683
+ }
1684
+ ```
1685
+
1686
+ ### 4. Customer Onboarding Assistant
1687
+
1688
+ Guide new users through onboarding with an interactive, multi-turn conversation.
1689
+
1690
+ ```typescript
1691
+ import { Agent, openai } from '@runflow-ai/sdk';
1692
+ import { emailConnector, slackConnector } from '@runflow-ai/sdk/connectors';
1693
+
1694
+ const onboardingAgent = new Agent({
1695
+ name: 'Onboarding Assistant',
1696
+ instructions: `You are an onboarding specialist.
1697
+ - Guide users step by step
1698
+ - Celebrate their progress
1699
+ - Provide helpful resources
1700
+ - Detect when they're stuck and offer help
1701
+ - Track completion of onboarding steps`,
1702
+
1703
+ model: openai('gpt-4o'),
1704
+
1705
+ memory: {
1706
+ type: 'conversation',
1707
+ maxTurns: 50, // Long conversation
1708
+ summarization: {
1709
+ enabled: true,
1710
+ threshold: 20,
1711
+ },
1712
+ },
1713
+
1714
+ knowledge: {
1715
+ vectorStore: 'onboarding-docs',
1716
+ k: 3,
1717
+ },
1718
+
1719
+ tools: {
1720
+ sendEmail: emailConnector.messages.send,
1721
+ notifyTeam: slackConnector.messages.send,
1722
+ markStepComplete: createTool({
1723
+ id: 'mark-step-complete',
1724
+ description: 'Mark an onboarding step as complete',
1725
+ inputSchema: z.object({
1726
+ stepName: z.string(),
1727
+ userId: z.string(),
1728
+ }),
1729
+ execute: async ({ context }) => {
1730
+ await updateOnboardingProgress(
1731
+ context.input.userId,
1732
+ context.input.stepName
1733
+ );
1734
+ return { success: true };
1735
+ },
1736
+ }),
1737
+ },
1738
+ });
1739
+
1740
+ // Interactive onboarding session
1741
+ const sessionId = `onboarding_user_${userId}`;
1742
+
1743
+ // Step 1
1744
+ await onboardingAgent.process({
1745
+ message: 'Start onboarding for new user',
1746
+ sessionId,
1747
+ userId,
1748
+ });
1749
+
1750
+ // User responds
1751
+ await onboardingAgent.process({
1752
+ message: 'I want to create my first agent',
1753
+ sessionId,
1754
+ userId,
1755
+ });
1756
+
1757
+ // Agent guides through agent creation...
1758
+ ```
1759
+
1760
+ ### 5. Feedback Analysis System
1761
+
1762
+ Collect customer feedback, analyze sentiment, and create actionable tickets.
1763
+
1764
+ ```typescript
1765
+ import { createWorkflow, Agent, openai } from '@runflow-ai/sdk';
1766
+ import { hubspotConnector, slackConnector } from '@runflow-ai/sdk/connectors';
1767
+ import { z } from 'zod';
1768
+
1769
+ // Sentiment analyzer
1770
+ const sentimentAgent = new Agent({
1771
+ name: 'Sentiment Analyzer',
1772
+ instructions: 'Analyze feedback sentiment (positive/neutral/negative) and extract key themes.',
1773
+ model: openai('gpt-4o-mini'),
1774
+ });
1775
+
1776
+ // Action recommender
1777
+ const actionAgent = new Agent({
1778
+ name: 'Action Recommender',
1779
+ instructions: 'Recommend specific actions based on feedback analysis.',
1780
+ model: openai('gpt-4o'),
1781
+ });
1782
+
1783
+ const feedbackWorkflow = createWorkflow({
1784
+ id: 'feedback-analysis',
1785
+ inputSchema: z.object({
1786
+ feedback: z.string(),
1787
+ customerEmail: z.string(),
1788
+ customerName: z.string(),
1789
+ source: z.string(),
1790
+ }),
1791
+ outputSchema: z.any(),
1792
+ })
1793
+ // Analyze sentiment
1794
+ .agent('analyze', sentimentAgent, {
1795
+ promptTemplate: 'Analyze: {{input.feedback}}',
1796
+ })
1797
+
1798
+ // Recommend actions
1799
+ .agent('recommend', actionAgent, {
1800
+ promptTemplate: `Feedback: {{input.feedback}}
1801
+ Sentiment: {{analyze.text}}
1802
+
1803
+ What actions should we take?`,
1804
+ })
1805
+
1806
+ // Conditional: Create ticket if negative
1807
+ .condition(
1808
+ 'check-negative',
1809
+ (ctx) => ctx.stepResults.get('analyze').text.toLowerCase().includes('negative'),
1810
+ // Negative feedback path
1811
+ [
1812
+ {
1813
+ id: 'create-ticket',
1814
+ type: 'connector',
1815
+ config: {
1816
+ connector: 'hubspot',
1817
+ resource: 'tickets',
1818
+ action: 'create',
1819
+ parameters: {
1820
+ subject: 'Negative Feedback - {{input.customerName}}',
1821
+ content: '{{input.feedback}}\n\nAnalysis: {{analyze.text}}\n\nRecommended actions: {{recommend.text}}',
1822
+ priority: 'high',
1823
+ category: 'feedback',
1824
+ },
1825
+ },
1826
+ },
1827
+ {
1828
+ id: 'alert-team',
1829
+ type: 'connector',
1830
+ config: {
1831
+ connector: 'slack',
1832
+ resource: 'messages',
1833
+ action: 'send',
1834
+ parameters: {
1835
+ channel: '#customer-success',
1836
+ text: `⚠️ Negative feedback from *{{input.customerName}}*\nTicket created: {{create-ticket.id}}`,
1837
+ },
1838
+ },
1839
+ },
1840
+ ],
1841
+ // Positive/neutral feedback path
1842
+ [
1843
+ {
1844
+ id: 'log-positive',
1845
+ type: 'function',
1846
+ config: {
1847
+ execute: async (input, ctx) => {
1848
+ console.log('Positive feedback logged');
1849
+ return { logged: true };
1850
+ },
1851
+ },
1852
+ },
1853
+ ]
1854
+ )
1855
+ .build();
1856
+
1857
+ // Process feedback
1858
+ const result = await feedbackWorkflow.execute({
1859
+ feedback: 'The support team was unhelpful and the product is buggy',
1860
+ customerEmail: 'unhappy@customer.com',
1861
+ customerName: 'Jane Doe',
1862
+ source: 'email',
1863
+ });
1864
+ ```
1865
+
1866
+ ### 6. Multi-Agent System (Supervisor Pattern)
1867
+
1868
+ Route requests to specialized agents based on intent.
1869
+
1870
+ ```typescript
1871
+ import { Agent, openai } from '@runflow-ai/sdk';
1872
+
1873
+ // Specialized agents
1874
+ const salesAgent = new Agent({
1875
+ name: 'Sales Specialist',
1876
+ instructions: 'You are a sales expert. Help with pricing, demos, and purchasing.',
1877
+ model: openai('gpt-4o'),
1878
+ tools: { /* sales tools */ },
1879
+ });
1880
+
1881
+ const supportAgent = new Agent({
1882
+ name: 'Technical Support',
1883
+ instructions: 'You are a technical support expert. Help with technical issues.',
1884
+ model: openai('gpt-4o'),
1885
+ knowledge: { vectorStore: 'tech-docs', k: 5 },
1886
+ });
1887
+
1888
+ const billingAgent = new Agent({
1889
+ name: 'Billing Specialist',
1890
+ instructions: 'You handle billing, invoices, and payment issues.',
1891
+ model: openai('gpt-4o'),
1892
+ tools: { /* billing tools */ },
1893
+ });
1894
+
1895
+ // Supervisor agent
1896
+ const supervisorAgent = new Agent({
1897
+ name: 'Supervisor',
1898
+ instructions: `You route customer requests to the right specialist:
1899
+ - Sales: pricing, demos, purchasing
1900
+ - Support: technical issues, bugs
1901
+ - Billing: invoices, payments, subscriptions
1902
+
1903
+ Analyze the request and respond with: ROUTE_TO: [sales|support|billing]`,
1904
+ model: openai('gpt-4o-mini'),
1905
+ });
1906
+
1907
+ // Routing function
1908
+ async function handleCustomerRequest(message: string, context: any) {
1909
+ // 1. Supervisor analyzes intent
1910
+ const routing = await supervisorAgent.process({
1911
+ message: `Analyze this request: "${message}"`,
1912
+ ...context,
1913
+ });
1914
+
1915
+ // 2. Extract route
1916
+ const route = routing.message.match(/ROUTE_TO: (\w+)/)?.[1] || 'support';
1917
+
1918
+ // 3. Route to specialist
1919
+ const agents = {
1920
+ sales: salesAgent,
1921
+ support: supportAgent,
1922
+ billing: billingAgent,
1923
+ };
1924
+
1925
+ const specialistAgent = agents[route];
1926
+
1927
+ // 4. Specialist handles request
1928
+ const result = await specialistAgent.process({
1929
+ message,
1930
+ ...context,
1931
+ });
1932
+
1933
+ return {
1934
+ route,
1935
+ response: result.message,
1936
+ };
1937
+ }
1938
+
1939
+ // Example usage
1940
+ const result = await handleCustomerRequest(
1941
+ 'I want to upgrade to the enterprise plan',
1942
+ {
1943
+ sessionId: 'session_456',
1944
+ userId: 'user_789',
1945
+ }
1946
+ );
1947
+
1948
+ console.log(`Routed to: ${result.route}`);
1949
+ console.log(`Response: ${result.response}`);
1950
+ ```
1951
+
1952
+ ---
1953
+
1954
+ ## 🔧 Configuration
1955
+
1956
+ ### Environment Variables
1957
+
1958
+ ```bash
1959
+ # API Configuration
1960
+ RUNFLOW_API_URL=http://localhost:3001
1961
+ RUNFLOW_API_KEY=your_api_key_here
1962
+ RUNFLOW_TENANT_ID=your_tenant_id
1963
+ RUNFLOW_AGENT_ID=your_agent_id
1964
+
1965
+ # Execution Context (optional - usually comes from engine)
1966
+ RUNFLOW_EXECUTION_ID=exec_123
1967
+ RUNFLOW_THREAD_ID=thread_456
1968
+
1969
+ # Development
1970
+ RUNFLOW_ENV=development
1971
+ RUNFLOW_LOCAL_TRACES=true
1972
+ NODE_ENV=development
1973
+ ```
1974
+
1975
+ ### Configuration File (.runflow/rf.json)
1976
+
1977
+ ```json
1978
+ {
1979
+ "agentId": "your_agent_id",
1980
+ "tenantId": "your_tenant_id",
1981
+ "apiKey": "your_api_key",
1982
+ "apiUrl": "http://localhost:3001"
1983
+ }
1984
+ ```
1985
+
1986
+ The SDK automatically searches for `.runflow/rf.json` in the current directory and parent directories.
1987
+
1988
+ **Configuration Priority:**
1989
+
1990
+ 1. Explicit config in code
1991
+ 2. `.runflow/rf.json`
1992
+ 3. Environment variables
1993
+ 4. Defaults
1994
+
1995
+ ### Manual API Client Configuration
1996
+
1997
+ ```typescript
1998
+ import { createRunflowAPIClient, Agent, openai } from '@runflow-ai/sdk';
1999
+
2000
+ const apiClient = createRunflowAPIClient({
2001
+ apiUrl: 'https://api.runflow.ai',
2002
+ apiKey: 'your_api_key',
2003
+ tenantId: 'your_tenant_id',
2004
+ agentId: 'your_agent_id',
2005
+ });
2006
+
2007
+ // Inject into agent
2008
+ const agent = new Agent({
2009
+ name: 'My Agent',
2010
+ instructions: 'Help users',
2011
+ model: openai('gpt-4o'),
2012
+ });
2013
+
2014
+ agent._setAPIClient(apiClient);
2015
+ ```
2016
+
2017
+ ---
2018
+
2019
+ ## 📖 API Reference
2020
+
2021
+ ### Main Exports
2022
+
2023
+ ```typescript
2024
+ // Core
2025
+ import { Agent, Runflow, openai, anthropic, bedrock } from '@runflow-ai/sdk';
2026
+
2027
+ // Tools & Connectors
2028
+ import { createTool, createConnectorTool } from '@runflow-ai/sdk';
2029
+ import { hubspot, twilio, email, slack } from '@runflow-ai/sdk';
2030
+
2031
+ // Workflows
2032
+ import {
2033
+ Workflow,
2034
+ createWorkflow,
2035
+ createStep,
2036
+ createAgentStep,
2037
+ createFunctionStep,
2038
+ createConnectorStep,
2039
+ WorkflowBuilder,
2040
+ } from '@runflow-ai/sdk';
2041
+
2042
+ // Standalone Modules
2043
+ import { Memory, Knowledge, RAG, LLM } from '@runflow-ai/sdk';
2044
+
2045
+ // Observability
2046
+ import {
2047
+ createTraceCollector,
2048
+ RunflowTraceCollector,
2049
+ RunflowTraceSpan,
2050
+ traced
2051
+ } from '@runflow-ai/sdk';
2052
+
2053
+ // API Client
2054
+ import { createRunflowAPIClient } from '@runflow-ai/sdk';
2055
+
2056
+ // Providers
2057
+ import {
2058
+ MemoryProvider,
2059
+ KnowledgeProvider,
2060
+ LLMProvider,
2061
+ RunflowMemoryProvider,
2062
+ } from '@runflow-ai/sdk';
2063
+ ```
2064
+
2065
+ ### Sub-path Imports
2066
+
2067
+ ```typescript
2068
+ // Core
2069
+ import { Agent } from '@runflow-ai/sdk/core';
2070
+ import { Runflow } from '@runflow-ai/sdk/core';
2071
+ import { openai, anthropic, bedrock } from '@runflow-ai/sdk/core';
2072
+
2073
+ // Tools
2074
+ import { createTool } from '@runflow-ai/sdk/tools';
1327
2075
 
1328
2076
  // Connectors
1329
- import { createConnectorTool, hubspot } from '@runflow-ai/sdk/connectors';
2077
+ import { createConnectorTool, hubspot, twilio, email, slack } from '@runflow-ai/sdk/connectors';
1330
2078
 
1331
2079
  // Workflows
1332
- import { createWorkflow } from '@runflow-ai/sdk/workflows';
2080
+ import { createWorkflow, WorkflowBuilder } from '@runflow-ai/sdk/workflows';
1333
2081
 
1334
2082
  // Memory
1335
2083
  import { Memory } from '@runflow-ai/sdk/memory';
@@ -1341,22 +2089,260 @@ import { Knowledge, RAG } from '@runflow-ai/sdk/knowledge';
1341
2089
  import { LLM } from '@runflow-ai/sdk/llm';
1342
2090
 
1343
2091
  // Observability
1344
- import { createTraceCollector } from '@runflow-ai/sdk/observability';
2092
+ import { createTraceCollector, traced } from '@runflow-ai/sdk/observability';
1345
2093
 
1346
2094
  // Types
1347
- import type { AgentConfig } from '@runflow-ai/sdk/types';
2095
+ import type { AgentConfig, AgentInput, AgentOutput } from '@runflow-ai/sdk/types';
1348
2096
 
1349
2097
  // Providers
1350
- import type { MemoryProvider } from '@runflow-ai/sdk/providers';
2098
+ import type { MemoryProvider, KnowledgeProvider, LLMProvider } from '@runflow-ai/sdk/providers';
2099
+ ```
2100
+
2101
+ ---
2102
+
2103
+ ## 📝 TypeScript Types
2104
+
2105
+ ### Core Types
2106
+
2107
+ ```typescript
2108
+ interface AgentInput {
2109
+ message: string;
2110
+ companyId: string;
2111
+ userId?: string;
2112
+ sessionId?: string;
2113
+ executionId?: string;
2114
+ threadId?: string;
2115
+ entityType?: string;
2116
+ entityValue?: string;
2117
+ channel?: string;
2118
+ messages?: Message[];
2119
+ metadata?: Record<string, any>;
2120
+ }
2121
+
2122
+ interface AgentOutput {
2123
+ message: string;
2124
+ metadata?: Record<string, any>;
2125
+ }
2126
+
2127
+ interface AgentConfig {
2128
+ name: string;
2129
+ instructions: string;
2130
+ model: ModelProvider;
2131
+ modelConfig?: ModelConfig;
2132
+ tools?: Record<string, RunflowTool>;
2133
+ maxToolIterations?: number;
2134
+ rag?: RAGConfig;
2135
+ memory?: MemoryConfig;
2136
+ streaming?: StreamingConfig;
2137
+ agents?: Record<string, AgentConfig>;
2138
+ debug?: boolean | DebugConfig;
2139
+ }
2140
+
2141
+ interface ModelConfig {
2142
+ temperature?: number;
2143
+ maxTokens?: number;
2144
+ topP?: number;
2145
+ frequencyPenalty?: number;
2146
+ presencePenalty?: number;
2147
+ stop?: string[];
2148
+ seed?: number;
2149
+ }
2150
+
2151
+ interface DebugConfig {
2152
+ enabled: boolean;
2153
+ logMessages?: boolean;
2154
+ logLLMCalls?: boolean;
2155
+ logToolCalls?: boolean;
2156
+ logRAG?: boolean;
2157
+ logMemory?: boolean;
2158
+ truncateAt?: number;
2159
+ }
2160
+ ```
2161
+
2162
+ ### Memory Types
2163
+
2164
+ ```typescript
2165
+ interface MemoryConfig {
2166
+ type: 'conversation' | 'entity' | 'summary' | 'hybrid';
2167
+ maxTurns?: number;
2168
+ maxTokens?: number;
2169
+ summarizeAfter?: number;
2170
+ entityExtraction?: boolean;
2171
+ persistAcrossSessions?: boolean;
2172
+ memoryKey?: string;
2173
+ }
2174
+
2175
+ interface MemoryData {
2176
+ sessionId: string;
2177
+ messages: MemoryMessage[];
2178
+ entities: Record<string, any>;
2179
+ summary?: string;
2180
+ metadata: {
2181
+ createdAt: Date;
2182
+ updatedAt: Date;
2183
+ totalTurns: number;
2184
+ totalTokens: number;
2185
+ };
2186
+ }
2187
+
2188
+ interface MemoryMessage {
2189
+ role: 'user' | 'assistant' | 'system';
2190
+ content: string;
2191
+ timestamp: Date;
2192
+ metadata?: {
2193
+ toolsUsed?: string[];
2194
+ ragUsed?: boolean;
2195
+ model?: string;
2196
+ tokens?: number;
2197
+ };
2198
+ }
2199
+ ```
2200
+
2201
+ ### RAG Types
2202
+
2203
+ ```typescript
2204
+ interface RAGConfig {
2205
+ vectorStore?: string;
2206
+ vectorStores?: Array<{
2207
+ id: string;
2208
+ name: string;
2209
+ threshold?: number;
2210
+ k?: number;
2211
+ description?: string;
2212
+ }>;
2213
+ threshold?: number;
2214
+ k?: number;
2215
+ searchPrompt?: string;
2216
+ toolDescription?: string;
2217
+ }
2218
+
2219
+ interface SearchResult {
2220
+ content: string;
2221
+ score: number;
2222
+ metadata?: Record<string, any>;
2223
+ }
2224
+ ```
2225
+
2226
+ ### Tool Types
2227
+
2228
+ ```typescript
2229
+ interface ToolConfig<TInput = any, TOutput = any> {
2230
+ id: string;
2231
+ description: string;
2232
+ inputSchema: z.ZodSchema<TInput>;
2233
+ outputSchema?: z.ZodSchema<TOutput>;
2234
+ execute: (params: {
2235
+ context: TInput;
2236
+ runflow: RunflowAPIClient;
2237
+ projectId: string;
2238
+ }) => Promise<TOutput>;
2239
+ }
2240
+
2241
+ interface RunflowTool {
2242
+ id: string;
2243
+ name?: string;
2244
+ description: string;
2245
+ parameters: Record<string, ToolParameter>;
2246
+ execute: (params: any, context: ToolContext) => Promise<any>;
2247
+ }
2248
+
2249
+ interface ToolContext {
2250
+ projectId: string;
2251
+ companyId: string;
2252
+ userId?: string;
2253
+ sessionId?: string;
2254
+ runflowAPI: RunflowAPIClient;
2255
+ }
2256
+ ```
2257
+
2258
+ ### Workflow Types
2259
+
2260
+ ```typescript
2261
+ interface WorkflowConfig {
2262
+ id: string;
2263
+ name?: string;
2264
+ description?: string;
2265
+ inputSchema: z.ZodSchema;
2266
+ outputSchema: z.ZodSchema;
2267
+ steps: WorkflowStep[];
2268
+ options?: WorkflowOptions;
2269
+ }
2270
+
2271
+ interface WorkflowStep {
2272
+ id: string;
2273
+ name?: string;
2274
+ description?: string;
2275
+ type: 'agent' | 'function' | 'connector' | 'condition' | 'parallel';
2276
+ config: StepConfig;
2277
+ inputTransform?: (previousOutput: any, workflowInput: any) => any;
2278
+ outputTransform?: (stepOutput: any) => any;
2279
+ condition?: (context: WorkflowContext) => boolean;
2280
+ retryConfig?: RetryConfig;
2281
+ }
2282
+
2283
+ interface RetryConfig {
2284
+ maxAttempts: number;
2285
+ backoff: 'fixed' | 'exponential' | 'linear';
2286
+ delay: number;
2287
+ retryableErrors?: string[];
2288
+ }
2289
+ ```
2290
+
2291
+ ### Trace Types
2292
+
2293
+ ```typescript
2294
+ interface TraceData {
2295
+ traceId: string;
2296
+ parentTraceId?: string;
2297
+ projectId: string;
2298
+ executionId?: string;
2299
+ threadId?: string;
2300
+ type: TraceType;
2301
+ operation: string;
2302
+ input: any;
2303
+ output?: any;
2304
+ status: 'success' | 'error' | 'timeout' | 'cancelled';
2305
+ error?: string;
2306
+ startTime: Date;
2307
+ endTime?: Date;
2308
+ duration: number;
2309
+ metadata: TraceMetadata;
2310
+ costs?: TraceCosts;
2311
+ }
2312
+
2313
+ type TraceType =
2314
+ | 'agent_execution'
2315
+ | 'workflow_execution'
2316
+ | 'workflow_step'
2317
+ | 'tool_call'
2318
+ | 'connector_call'
2319
+ | 'vector_search'
2320
+ | 'memory_operation'
2321
+ | 'llm_call'
2322
+ | 'streaming_session';
2323
+
2324
+ interface TraceCosts {
2325
+ tokens?: {
2326
+ input: number;
2327
+ output: number;
2328
+ total: number;
2329
+ };
2330
+ costs?: {
2331
+ inputCost: number;
2332
+ outputCost: number;
2333
+ totalCost: number;
2334
+ currency: string;
2335
+ };
2336
+ }
1351
2337
  ```
1352
2338
 
1353
2339
  ---
1354
2340
 
1355
2341
  ## 🔌 Providers
1356
2342
 
1357
- O SDK suporta **providers plugáveis** para memória, knowledge e LLM.
2343
+ The SDK supports **pluggable providers** for memory, knowledge, and LLM.
1358
2344
 
1359
- ### Memory Providers
2345
+ ### Memory Provider Interface
1360
2346
 
1361
2347
  ```typescript
1362
2348
  interface MemoryProvider {
@@ -1369,15 +2355,16 @@ interface MemoryProvider {
1369
2355
  }
1370
2356
  ```
1371
2357
 
1372
- ### Knowledge Providers
2358
+ ### Knowledge Provider Interface
1373
2359
 
1374
2360
  ```typescript
1375
2361
  interface KnowledgeProvider {
1376
2362
  search(query: string, options: SearchOptions): Promise<SearchResult[]>;
2363
+ embed?(text: string): Promise<number[]>;
1377
2364
  }
1378
2365
  ```
1379
2366
 
1380
- ### LLM Providers
2367
+ ### LLM Provider Interface
1381
2368
 
1382
2369
  ```typescript
1383
2370
  interface LLMProvider {
@@ -1386,22 +2373,142 @@ interface LLMProvider {
1386
2373
  }
1387
2374
  ```
1388
2375
 
2376
+ ### Built-in Providers
2377
+
2378
+ ```typescript
2379
+ import { RunflowMemoryProvider } from '@runflow-ai/sdk';
2380
+
2381
+ // Use Runflow's built-in memory provider
2382
+ const memory = new Memory({
2383
+ provider: new RunflowMemoryProvider(apiClient),
2384
+ maxTurns: 10,
2385
+ });
2386
+ ```
2387
+
2388
+ ---
2389
+
2390
+ ## 🔍 Troubleshooting
2391
+
2392
+ ### Common Issues
2393
+
2394
+ #### API Client Not Configured
2395
+
2396
+ ```
2397
+ Error: Runflow API Client is not configured
2398
+ ```
2399
+
2400
+ **Solution:** Ensure you have either:
2401
+ 1. Environment variables set (`RUNFLOW_API_KEY`, `RUNFLOW_TENANT_ID`)
2402
+ 2. A `.runflow/rf.json` file
2403
+ 3. Manually configured the API client
2404
+
2405
+ ```typescript
2406
+ import { createRunflowAPIClient, Agent, openai } from '@runflow-ai/sdk';
2407
+
2408
+ const apiClient = createRunflowAPIClient({
2409
+ apiKey: 'your_api_key',
2410
+ tenantId: 'your_tenant_id',
2411
+ });
2412
+
2413
+ const agent = new Agent({
2414
+ name: 'My Agent',
2415
+ instructions: 'Help users',
2416
+ model: openai('gpt-4o'),
2417
+ });
2418
+
2419
+ agent._setAPIClient(apiClient);
2420
+ ```
2421
+
2422
+ #### Memory Not Persisting
2423
+
2424
+ **Issue:** Memory is not persisting between sessions
2425
+
2426
+ **Solution:** Ensure you're passing the same `sessionId` or using `Runflow.identify()` consistently:
2427
+
2428
+ ```typescript
2429
+ // Use Runflow.identify() for automatic session management
2430
+ Runflow.identify({
2431
+ type: 'phone',
2432
+ value: '+5511999999999',
2433
+ });
2434
+
2435
+ // OR pass sessionId explicitly
2436
+ await agent.process({
2437
+ message: 'Hello',
2438
+ sessionId: 'session_456', // Same session ID
2439
+ });
2440
+ ```
2441
+
2442
+ #### Tool Not Being Called
2443
+
2444
+ **Issue:** Agent is not calling tools even when it should
2445
+
2446
+ **Solution:**
2447
+ 1. Make sure tool descriptions are clear and specific
2448
+ 2. Use `debug: true` to see what the agent is doing
2449
+ 3. Check that `maxToolIterations` is not set too low
2450
+
2451
+ ```typescript
2452
+ const agent = new Agent({
2453
+ name: 'My Agent',
2454
+ instructions: 'You MUST use the weather tool when users ask about weather.',
2455
+ model: openai('gpt-4o'),
2456
+ tools: {
2457
+ weather: weatherTool,
2458
+ },
2459
+ maxToolIterations: 10, // Default
2460
+ debug: true, // Enable debug logging
2461
+ });
2462
+ ```
2463
+
2464
+ #### RAG Not Finding Results
2465
+
2466
+ **Issue:** Knowledge base search returns no results
2467
+
2468
+ **Solution:**
2469
+ 1. Check `threshold` value (lower = more results)
2470
+ 2. Increase `k` value for more results
2471
+ 3. Verify vector store name is correct
2472
+
2473
+ ```typescript
2474
+ rag: {
2475
+ vectorStore: 'support-docs', // Verify this exists
2476
+ k: 10, // Increase for more results
2477
+ threshold: 0.5, // Lower for more lenient matching
2478
+ }
2479
+ ```
2480
+
2481
+ #### TypeScript Errors
2482
+
2483
+ **Issue:** TypeScript errors when using the SDK
2484
+
2485
+ **Solution:** Make sure you're using TypeScript >= 5.0.0 and have proper types:
2486
+
2487
+ ```bash
2488
+ npm install --save-dev typescript@^5.0.0
2489
+ ```
2490
+
2491
+ ```typescript
2492
+ // Use proper type imports
2493
+ import type { AgentConfig, AgentInput, AgentOutput } from '@runflow-ai/sdk';
2494
+ ```
2495
+
1389
2496
  ---
1390
2497
 
1391
- ## 🤝 Contribuindo
2498
+ ## 🤝 Contributing
1392
2499
 
1393
- Contribuições são bem-vindas! Por favor:
2500
+ Contributions are welcome! Please:
1394
2501
 
1395
- 1. Fork o projeto
1396
- 2. Crie uma branch para sua feature (`git checkout -b feature/amazing-feature`)
1397
- 3. Commit suas mudanças (`git commit -m 'Add amazing feature'`)
1398
- 4. Push para a branch (`git push origin feature/amazing-feature`)
1399
- 5. Abra um Pull Request
2502
+ 1. Fork the project
2503
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
2504
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
2505
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
2506
+ 5. Open a Pull Request
1400
2507
 
1401
- ### Desenvolvimento Local
2508
+ ### Local Development
1402
2509
 
1403
2510
  ```bash
1404
- # Instalar dependências
2511
+ # Install dependencies
1405
2512
  npm install
1406
2513
 
1407
2514
  # Build
@@ -1410,32 +2517,32 @@ npm run build
1410
2517
  # Watch mode
1411
2518
  npm run dev
1412
2519
 
1413
- # Testes
2520
+ # Tests
1414
2521
  npm test
1415
2522
 
1416
- # Validar antes de publicar
2523
+ # Validate before publishing
1417
2524
  npm run validate
1418
2525
  ```
1419
2526
 
1420
2527
  ---
1421
2528
 
1422
- ## 📄 Licença
2529
+ ## 📄 License
1423
2530
 
1424
- MIT License - veja [LICENSE](LICENSE) para detalhes.
2531
+ MIT License - see [LICENSE](LICENSE) for details.
1425
2532
 
1426
2533
  ---
1427
2534
 
1428
2535
  ## 🔗 Links
1429
2536
 
1430
2537
  - **Homepage**: https://runflow.ai
1431
- - **Documentação**: https://docs.runflow.ai
2538
+ - **Documentation**: https://docs.runflow.ai
1432
2539
  - **GitHub**: https://github.com/runflow-ai/runflow-sdk
1433
2540
  - **NPM**: https://www.npmjs.com/package/@runflow-ai/sdk
1434
2541
  - **Discord**: https://discord.gg/runflow
1435
2542
 
1436
2543
  ---
1437
2544
 
1438
- ## 💡 Suporte
2545
+ ## 💡 Support
1439
2546
 
1440
2547
  - 📧 Email: support@runflow.ai
1441
2548
  - 💬 Discord: https://discord.gg/runflow
@@ -1443,5 +2550,4 @@ MIT License - veja [LICENSE](LICENSE) para detalhes.
1443
2550
 
1444
2551
  ---
1445
2552
 
1446
- **Feito com ❤️ pela equipe Runflow**
1447
-
2553
+ **Built with ❤️ by the Runflow team**