concevent-ai-agent-sdk 1.0.0

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.
Files changed (82) hide show
  1. package/README.md +993 -0
  2. package/dist/adapters/index.d.ts +3 -0
  3. package/dist/adapters/index.d.ts.map +1 -0
  4. package/dist/adapters/index.js +2 -0
  5. package/dist/adapters/index.js.map +1 -0
  6. package/dist/adapters/websocket.d.ts +23 -0
  7. package/dist/adapters/websocket.d.ts.map +1 -0
  8. package/dist/adapters/websocket.js +95 -0
  9. package/dist/adapters/websocket.js.map +1 -0
  10. package/dist/core/agent.d.ts +11 -0
  11. package/dist/core/agent.d.ts.map +1 -0
  12. package/dist/core/agent.js +296 -0
  13. package/dist/core/agent.js.map +1 -0
  14. package/dist/core/errors.d.ts +16 -0
  15. package/dist/core/errors.d.ts.map +1 -0
  16. package/dist/core/errors.js +55 -0
  17. package/dist/core/errors.js.map +1 -0
  18. package/dist/core/index.d.ts +13 -0
  19. package/dist/core/index.d.ts.map +1 -0
  20. package/dist/core/index.js +8 -0
  21. package/dist/core/index.js.map +1 -0
  22. package/dist/core/logger.d.ts +24 -0
  23. package/dist/core/logger.d.ts.map +1 -0
  24. package/dist/core/logger.js +95 -0
  25. package/dist/core/logger.js.map +1 -0
  26. package/dist/core/openrouter-client.d.ts +8 -0
  27. package/dist/core/openrouter-client.d.ts.map +1 -0
  28. package/dist/core/openrouter-client.js +16 -0
  29. package/dist/core/openrouter-client.js.map +1 -0
  30. package/dist/core/openrouter-utils.d.ts +20 -0
  31. package/dist/core/openrouter-utils.d.ts.map +1 -0
  32. package/dist/core/openrouter-utils.js +163 -0
  33. package/dist/core/openrouter-utils.js.map +1 -0
  34. package/dist/core/session.d.ts +19 -0
  35. package/dist/core/session.d.ts.map +1 -0
  36. package/dist/core/session.js +47 -0
  37. package/dist/core/session.js.map +1 -0
  38. package/dist/core/summarization.d.ts +14 -0
  39. package/dist/core/summarization.d.ts.map +1 -0
  40. package/dist/core/summarization.js +83 -0
  41. package/dist/core/summarization.js.map +1 -0
  42. package/dist/core/tool-executor.d.ts +22 -0
  43. package/dist/core/tool-executor.d.ts.map +1 -0
  44. package/dist/core/tool-executor.js +87 -0
  45. package/dist/core/tool-executor.js.map +1 -0
  46. package/dist/index.d.ts +6 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +4 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/react/AgentProvider.d.ts +15 -0
  51. package/dist/react/AgentProvider.d.ts.map +1 -0
  52. package/dist/react/AgentProvider.js +20 -0
  53. package/dist/react/AgentProvider.js.map +1 -0
  54. package/dist/react/index.d.ts +6 -0
  55. package/dist/react/index.d.ts.map +1 -0
  56. package/dist/react/index.js +3 -0
  57. package/dist/react/index.js.map +1 -0
  58. package/dist/react/types.d.ts +26 -0
  59. package/dist/react/types.d.ts.map +1 -0
  60. package/dist/react/types.js +2 -0
  61. package/dist/react/types.js.map +1 -0
  62. package/dist/react/useAgent.d.ts +15 -0
  63. package/dist/react/useAgent.d.ts.map +1 -0
  64. package/dist/react/useAgent.js +167 -0
  65. package/dist/react/useAgent.js.map +1 -0
  66. package/dist/types/config.d.ts +84 -0
  67. package/dist/types/config.d.ts.map +1 -0
  68. package/dist/types/config.js +2 -0
  69. package/dist/types/config.js.map +1 -0
  70. package/dist/types/events.d.ts +85 -0
  71. package/dist/types/events.d.ts.map +1 -0
  72. package/dist/types/events.js +8 -0
  73. package/dist/types/events.js.map +1 -0
  74. package/dist/types/index.d.ts +5 -0
  75. package/dist/types/index.d.ts.map +1 -0
  76. package/dist/types/index.js +2 -0
  77. package/dist/types/index.js.map +1 -0
  78. package/dist/types/messages.d.ts +30 -0
  79. package/dist/types/messages.d.ts.map +1 -0
  80. package/dist/types/messages.js +2 -0
  81. package/dist/types/messages.js.map +1 -0
  82. package/package.json +78 -0
package/README.md ADDED
@@ -0,0 +1,993 @@
1
+ # concevent-ai-agent-sdk
2
+
3
+ A framework-agnostic AI Agent SDK for building intelligent conversational agents with tool calling, automatic conversation summarization, and comprehensive event handling. Built on top of OpenAI-compatible APIs (including OpenRouter).
4
+
5
+ ## Features
6
+
7
+ - 🤖 **AI Agent Framework** - Create intelligent agents with tool/function calling capabilities
8
+ - 🔧 **Tool Execution** - Define and execute custom tools with typed parameters using Zod schemas
9
+ - 💬 **Conversation Management** - Automatic history tracking with built-in summarization
10
+ - ⚛️ **React Integration** - First-class React hooks and context providers
11
+ - 📊 **Token Usage Tracking** - Monitor token consumption across conversations
12
+ - 🔄 **Auto-Summarization** - Automatically summarize long conversations to stay within context limits
13
+ - 🎯 **Event Callbacks** - Comprehensive event system for real-time updates
14
+ - ⛔ **Abort Support** - Cancel ongoing requests with AbortController
15
+ - 🔄 **Retry Logic** - Built-in retry mechanism for resilient operations
16
+ - 📝 **Reasoning Support** - Access model reasoning/thinking outputs
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install concevent-ai-agent-sdk
22
+ # or
23
+ yarn add concevent-ai-agent-sdk
24
+ # or
25
+ pnpm add concevent-ai-agent-sdk
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ```typescript
31
+ import { createAgent } from "concevent-ai-agent-sdk";
32
+ import type {
33
+ ToolDefinition,
34
+ ToolExecutorContext,
35
+ } from "concevent-ai-agent-sdk";
36
+ import { z } from "zod";
37
+ import { zodToJsonSchema } from "zod-to-json-schema";
38
+
39
+ // Define your tools
40
+ const tools: ToolDefinition[] = [
41
+ {
42
+ declaration: {
43
+ name: "getWeather",
44
+ description: "Get current weather for a city",
45
+ parametersJsonSchema: zodToJsonSchema(
46
+ z.object({
47
+ city: z.string().describe("City name"),
48
+ })
49
+ ),
50
+ },
51
+ executor: async (args) => {
52
+ const city = args.city as string;
53
+ // Your weather API logic here
54
+ return { city, temperature: 22, condition: "sunny" };
55
+ },
56
+ },
57
+ ];
58
+
59
+ // Create the agent
60
+ const agent = createAgent({
61
+ apiKey: process.env.OPENROUTER_API_KEY!,
62
+ model: "anthropic/claude-3.5-sonnet",
63
+ systemPrompts: ["You are a helpful weather assistant."],
64
+ tools,
65
+ });
66
+
67
+ // Chat with the agent
68
+ const result = await agent.chat("What's the weather in Tokyo?", {
69
+ userId: "user-123",
70
+ timezone: "Asia/Tokyo",
71
+ });
72
+
73
+ console.log(result.message);
74
+ // "The weather in Tokyo is currently sunny with a temperature of 22°C."
75
+ ```
76
+
77
+ ## Table of Contents
78
+
79
+ - [Installation](#installation)
80
+ - [Quick Start](#quick-start)
81
+ - [Core Concepts](#core-concepts)
82
+ - [API Reference](#api-reference)
83
+ - [createAgent](#createagent)
84
+ - [Agent Interface](#agent-interface)
85
+ - [Tool Definitions](#tool-definitions)
86
+ - [Callbacks & Events](#callbacks--events)
87
+ - [Types](#types)
88
+ - [React Integration](#react-integration)
89
+ - [useAgent Hook](#useagent-hook)
90
+ - [AgentProvider](#agentprovider)
91
+ - [Advanced Usage](#advanced-usage)
92
+ - [Conversation Summarization](#conversation-summarization)
93
+ - [Error Handling](#error-handling)
94
+ - [Abort Requests](#abort-requests)
95
+
96
+ ---
97
+
98
+ ## Core Concepts
99
+
100
+ ### Agent
101
+
102
+ An Agent is the main interface for interacting with AI models. It manages conversation history, executes tools, handles token usage tracking, and provides automatic summarization when context limits are reached.
103
+
104
+ ### Tools
105
+
106
+ Tools (also known as functions) extend the agent's capabilities. Each tool has:
107
+
108
+ - A **declaration** describing its name, purpose, and parameter schema
109
+ - An **executor** function that performs the actual work
110
+
111
+ ### Conversation History
112
+
113
+ The agent automatically maintains conversation history, including user messages, assistant responses, and tool calls. This history can be retrieved, set, or cleared as needed.
114
+
115
+ ---
116
+
117
+ ## API Reference
118
+
119
+ ### createAgent
120
+
121
+ Creates a new agent instance with the specified configuration.
122
+
123
+ ```typescript
124
+ import { createAgent } from 'concevent-ai-agent-sdk';
125
+
126
+ const agent = createAgent(config: AgentConfig): Agent;
127
+ ```
128
+
129
+ #### AgentConfig
130
+
131
+ | Property | Type | Required | Default | Description |
132
+ | ----------------- | ----------------------------- | -------- | ------------------- | -------------------------------------------------------- |
133
+ | `apiKey` | `string` | ✅ | - | API key for the AI provider |
134
+ | `model` | `string` | ✅ | - | Model identifier (e.g., `'anthropic/claude-3.5-sonnet'`) |
135
+ | `systemPrompts` | `string[]` | ✅ | - | Array of system prompt messages |
136
+ | `tools` | `ToolDefinition[]` | ✅ | - | Array of tool definitions |
137
+ | `baseURL` | `string` | ❌ | OpenRouter default | Custom API base URL |
138
+ | `temperature` | `number` | ❌ | `0.1` | Sampling temperature (0-2) |
139
+ | `reasoningEffort` | `'low' \| 'medium' \| 'high'` | ❌ | `'high'` | Reasoning effort level for supported models |
140
+ | `maxIterations` | `number` | ❌ | `20` | Maximum tool execution iterations per chat |
141
+ | `summarization` | `SummarizationConfig` | ❌ | `{ enabled: true }` | Summarization settings |
142
+ | `errorMessages` | `ErrorMessages` | ❌ | Default messages | Custom error messages |
143
+
144
+ #### SummarizationConfig
145
+
146
+ ```typescript
147
+ interface SummarizationConfig {
148
+ enabled: boolean;
149
+ prompt?: string; // Custom summarization prompt
150
+ contextLimitTokens?: number; // Default: 100,000 tokens
151
+ }
152
+ ```
153
+
154
+ #### Example with Full Configuration
155
+
156
+ ```typescript
157
+ const agent = createAgent({
158
+ apiKey: process.env.OPENROUTER_API_KEY!,
159
+ model: "anthropic/claude-3.5-sonnet",
160
+ baseURL: "https://openrouter.ai/api/v1",
161
+ temperature: 0.7,
162
+ reasoningEffort: "high",
163
+ maxIterations: 10,
164
+ systemPrompts: [
165
+ "You are a helpful assistant.",
166
+ "Always be concise and accurate.",
167
+ ],
168
+ tools: myTools,
169
+ summarization: {
170
+ enabled: true,
171
+ contextLimitTokens: 50000,
172
+ prompt: "Summarize the key points of this conversation...",
173
+ },
174
+ errorMessages: {
175
+ maxIterations: "Too many steps required. Please simplify your request.",
176
+ genericError: "Something went wrong. Please try again.",
177
+ },
178
+ });
179
+ ```
180
+
181
+ ---
182
+
183
+ ### Agent Interface
184
+
185
+ The agent instance returned by `createAgent` implements the following interface:
186
+
187
+ ```typescript
188
+ interface Agent {
189
+ chat(
190
+ message: string,
191
+ context: ToolExecutorContext,
192
+ callbacks?: AgentCallbacks
193
+ ): Promise<AgentResult>;
194
+
195
+ abort(): void;
196
+ getHistory(): ChatMessage[];
197
+ setHistory(history: ChatMessage[]): void;
198
+ clearHistory(): void;
199
+ getTokenUsage(): UsageMetadata;
200
+ }
201
+ ```
202
+
203
+ #### agent.chat()
204
+
205
+ Sends a message to the agent and receives a response. The agent may execute multiple tool calls before returning a final response.
206
+
207
+ ```typescript
208
+ const result = await agent.chat(
209
+ message: string,
210
+ context: ToolExecutorContext,
211
+ callbacks?: AgentCallbacks
212
+ ): Promise<AgentResult>;
213
+ ```
214
+
215
+ **Parameters:**
216
+
217
+ | Parameter | Type | Description |
218
+ | ----------- | --------------------- | --------------------------------- |
219
+ | `message` | `string` | The user's message |
220
+ | `context` | `ToolExecutorContext` | Execution context passed to tools |
221
+ | `callbacks` | `AgentCallbacks` | Optional event callbacks |
222
+
223
+ **Returns:** `AgentResult`
224
+
225
+ ```typescript
226
+ interface AgentResult {
227
+ message: string; // Final response message
228
+ reasoning?: {
229
+ // Model's reasoning (if available)
230
+ text?: string;
231
+ details?: ReasoningDetail[];
232
+ tokenCount?: number;
233
+ };
234
+ conversationHistory: ChatMessage[]; // Full conversation history
235
+ usageMetadata: UsageMetadata; // Token usage statistics
236
+ requestId?: string; // API request ID
237
+ iterations: number; // Number of iterations taken
238
+ summarized: boolean; // Whether summarization occurred
239
+ }
240
+ ```
241
+
242
+ **Example:**
243
+
244
+ ```typescript
245
+ const result = await agent.chat(
246
+ "Calculate 25 * 4 and tell me the weather in Paris",
247
+ { userId: "user-123", timezone: "Europe/Paris" },
248
+ {
249
+ onToolCallStart: (calls) => {
250
+ console.log(
251
+ "Executing tools:",
252
+ calls.map((c) => c.name)
253
+ );
254
+ },
255
+ onMessage: (message) => {
256
+ console.log("Response:", message);
257
+ },
258
+ }
259
+ );
260
+ ```
261
+
262
+ #### agent.abort()
263
+
264
+ Aborts the current chat request.
265
+
266
+ ```typescript
267
+ agent.abort();
268
+ ```
269
+
270
+ #### agent.getHistory()
271
+
272
+ Returns the current conversation history.
273
+
274
+ ```typescript
275
+ const history: ChatMessage[] = agent.getHistory();
276
+ ```
277
+
278
+ #### agent.setHistory()
279
+
280
+ Sets the conversation history (useful for restoring sessions).
281
+
282
+ ```typescript
283
+ agent.setHistory(previousHistory);
284
+ ```
285
+
286
+ #### agent.clearHistory()
287
+
288
+ Clears all conversation history.
289
+
290
+ ```typescript
291
+ agent.clearHistory();
292
+ ```
293
+
294
+ #### agent.getTokenUsage()
295
+
296
+ Returns cumulative token usage statistics.
297
+
298
+ ```typescript
299
+ const usage: UsageMetadata = agent.getTokenUsage();
300
+ console.log(`Total tokens used: ${usage.totalTokenCount}`);
301
+ ```
302
+
303
+ ---
304
+
305
+ ### Tool Definitions
306
+
307
+ Tools extend the agent's capabilities by allowing it to perform actions or retrieve information.
308
+
309
+ ```typescript
310
+ interface ToolDefinition {
311
+ declaration: FunctionDeclaration;
312
+ executor: ToolExecutor;
313
+ }
314
+
315
+ interface FunctionDeclaration {
316
+ name: string;
317
+ description: string;
318
+ parametersJsonSchema: JsonSchema7Type;
319
+ }
320
+
321
+ type ToolExecutor = (
322
+ args: Record<string, unknown>,
323
+ context: ToolExecutorContext
324
+ ) => Promise<unknown>;
325
+
326
+ interface ToolExecutorContext {
327
+ userId: string;
328
+ timezone: string;
329
+ abortSignal?: AbortSignal;
330
+ }
331
+ ```
332
+
333
+ #### Creating Tools with Zod
334
+
335
+ Using Zod for parameter validation is recommended:
336
+
337
+ ```typescript
338
+ import { z } from 'zod';
339
+ import { zodToJsonSchema } from 'zod-to-json-schema';
340
+ import type { ToolDefinition } from 'concevent-ai-agent-sdk';
341
+
342
+ // Define parameter schema with Zod
343
+ const searchSchema = z.object({
344
+ query: z.string().describe('Search query'),
345
+ limit: z.number().optional().default(10).describe('Maximum results'),
346
+ });
347
+
348
+ // Create the tool
349
+ const searchTool: ToolDefinition = {
350
+ declaration: {
351
+ name: 'search',
352
+ description: 'Search for information in the database',
353
+ parametersJsonSchema: zodToJsonSchema(searchSchema),
354
+ },
355
+ executor: async (args, context) => {
356
+ const { query, limit } = args as z.infer<typeof searchSchema>;
357
+
358
+ // Access context information
359
+ console.log(`User ${context.userId} searching for: ${query}`);
360
+
361
+ // Perform search...
362
+ return { results: [...], total: 42 };
363
+ },
364
+ };
365
+ ```
366
+
367
+ #### Tool with Abort Support
368
+
369
+ ```typescript
370
+ const longRunningTool: ToolDefinition = {
371
+ declaration: {
372
+ name: "processData",
373
+ description: "Process large dataset",
374
+ parametersJsonSchema: zodToJsonSchema(
375
+ z.object({
376
+ datasetId: z.string(),
377
+ })
378
+ ),
379
+ },
380
+ executor: async (args, context) => {
381
+ // Check for abort signal
382
+ if (context.abortSignal?.aborted) {
383
+ throw new Error("Operation cancelled");
384
+ }
385
+
386
+ // Pass abort signal to async operations
387
+ const response = await fetch(`/api/process/${args.datasetId}`, {
388
+ signal: context.abortSignal,
389
+ });
390
+
391
+ return response.json();
392
+ },
393
+ };
394
+ ```
395
+
396
+ ---
397
+
398
+ ### Callbacks & Events
399
+
400
+ The SDK provides a comprehensive callback system for real-time updates during agent execution.
401
+
402
+ #### AgentCallbacks
403
+
404
+ ```typescript
405
+ interface AgentCallbacks {
406
+ onThinking?: (thinking: string, details?: ReasoningDetail[]) => void;
407
+ onMessage?: (
408
+ message: string,
409
+ reasoning?: {
410
+ text?: string;
411
+ details?: ReasoningDetail[];
412
+ tokenCount?: number;
413
+ }
414
+ ) => void;
415
+ onToolCallStart?: (calls: ToolCallStartData[]) => void;
416
+ onToolResult?: (result: ToolResultData) => void;
417
+ onUsageUpdate?: (usage: UsageMetadata) => void;
418
+ onSummarizationStart?: (originalMessageCount: number) => void;
419
+ onSummarizationEnd?: (summary: string, tokensEstimate: number) => void;
420
+ onIterationStart?: (iteration: number, maxIterations: number) => void;
421
+ onError?: (error: {
422
+ code: string;
423
+ message: string;
424
+ recoverable: boolean;
425
+ }) => void;
426
+ onComplete?: (result: AgentResult) => void;
427
+ onAborted?: () => void;
428
+ }
429
+ ```
430
+
431
+ #### Callback Examples
432
+
433
+ ```typescript
434
+ await agent.chat("Help me with my task", context, {
435
+ // Called when the model is "thinking" (for reasoning models)
436
+ onThinking: (thinking, details) => {
437
+ console.log("Model thinking:", thinking);
438
+ },
439
+
440
+ // Called when a final message is received
441
+ onMessage: (message, reasoning) => {
442
+ console.log("Assistant:", message);
443
+ if (reasoning?.text) {
444
+ console.log("Reasoning:", reasoning.text);
445
+ }
446
+ },
447
+
448
+ // Called before tool execution starts
449
+ onToolCallStart: (calls) => {
450
+ calls.forEach((call) => {
451
+ console.log(`Calling ${call.name} with:`, call.args);
452
+ });
453
+ },
454
+
455
+ // Called after each tool completes
456
+ onToolResult: (result) => {
457
+ if (result.error) {
458
+ console.error(`Tool ${result.functionName} failed:`, result.error);
459
+ } else {
460
+ console.log(`Tool ${result.functionName} returned:`, result.result);
461
+ }
462
+ },
463
+
464
+ // Called when token usage is updated
465
+ onUsageUpdate: (usage) => {
466
+ console.log(`Tokens used: ${usage.totalTokenCount}`);
467
+ },
468
+
469
+ // Called when summarization begins
470
+ onSummarizationStart: (messageCount) => {
471
+ console.log(`Summarizing ${messageCount} messages...`);
472
+ },
473
+
474
+ // Called when summarization completes
475
+ onSummarizationEnd: (summary, tokens) => {
476
+ console.log(`Summarized to ~${tokens} tokens`);
477
+ },
478
+
479
+ // Called at the start of each iteration
480
+ onIterationStart: (iteration, max) => {
481
+ console.log(`Iteration ${iteration}/${max}`);
482
+ },
483
+
484
+ // Called on errors
485
+ onError: (error) => {
486
+ console.error(`Error [${error.code}]:`, error.message);
487
+ if (!error.recoverable) {
488
+ // Handle fatal error
489
+ }
490
+ },
491
+
492
+ // Called when processing completes
493
+ onComplete: (result) => {
494
+ console.log(`Completed in ${result.iterations} iterations`);
495
+ },
496
+
497
+ // Called when request is aborted
498
+ onAborted: () => {
499
+ console.log("Request was cancelled");
500
+ },
501
+ });
502
+ ```
503
+
504
+ #### Event Types
505
+
506
+ The SDK also exports event types and a `createEvent` helper for building event-driven systems:
507
+
508
+ ```typescript
509
+ import { createEvent } from "concevent-ai-agent-sdk";
510
+ import type { AgentEventType, AgentEvent } from "concevent-ai-agent-sdk";
511
+
512
+ // Create typed events
513
+ const messageEvent = createEvent("message", {
514
+ message: "Hello!",
515
+ reasoning: undefined,
516
+ });
517
+
518
+ const errorEvent = createEvent("error", {
519
+ code: "TOOL_EXECUTION_FAILED",
520
+ message: "Tool failed to execute",
521
+ recoverable: true,
522
+ });
523
+
524
+ // Event types available:
525
+ // 'thinking' | 'message' | 'tool_call_start' | 'tool_result' |
526
+ // 'usage_update' | 'summarization_start' | 'summarization_end' |
527
+ // 'iteration_start' | 'error' | 'complete' | 'aborted'
528
+ ```
529
+
530
+ ---
531
+
532
+ ### Types
533
+
534
+ #### ChatMessage
535
+
536
+ ```typescript
537
+ interface ChatMessage {
538
+ role: "user" | "assistant" | "system" | "tool-call" | "tool-call-results";
539
+ content: string;
540
+ timestamp: Date;
541
+ toolCalls?: ToolCall[];
542
+ toolCallId?: string;
543
+ reasoning?: string;
544
+ reasoning_details?: ReasoningDetail[];
545
+ reasoningTokenCount?: number;
546
+ }
547
+ ```
548
+
549
+ #### UsageMetadata
550
+
551
+ ```typescript
552
+ interface UsageMetadata {
553
+ promptTokenCount?: number;
554
+ candidatesTokenCount?: number;
555
+ totalTokenCount?: number;
556
+ cachedContentTokenCount?: number;
557
+ reasoningTokenCount?: number;
558
+ }
559
+ ```
560
+
561
+ #### ReasoningDetail
562
+
563
+ ```typescript
564
+ interface ReasoningDetail {
565
+ id?: string;
566
+ type: string;
567
+ text?: string;
568
+ data?: string;
569
+ format: string;
570
+ index: number;
571
+ }
572
+ ```
573
+
574
+ #### ToolCallStartData & ToolResultData
575
+
576
+ ```typescript
577
+ interface ToolCallStartData {
578
+ id: string;
579
+ name: string;
580
+ args: Record<string, unknown>;
581
+ }
582
+
583
+ interface ToolResultData {
584
+ id: string;
585
+ functionName: string;
586
+ result: unknown;
587
+ error?: string;
588
+ }
589
+ ```
590
+
591
+ ---
592
+
593
+ ## React Integration
594
+
595
+ The SDK provides React hooks and components for easy integration with React applications.
596
+
597
+ ### useAgent Hook
598
+
599
+ A React hook that manages agent state and provides a convenient interface for chat interactions.
600
+
601
+ ```typescript
602
+ import { useAgent } from "concevent-ai-agent-sdk/react";
603
+ import type {
604
+ UseAgentReturn,
605
+ UseAgentOptions,
606
+ } from "concevent-ai-agent-sdk/react";
607
+ ```
608
+
609
+ #### Usage
610
+
611
+ ```tsx
612
+ import { useAgent } from "concevent-ai-agent-sdk/react";
613
+ import type { AgentConfig } from "concevent-ai-agent-sdk";
614
+
615
+ function ChatComponent() {
616
+ const config: AgentConfig = {
617
+ apiKey: process.env.NEXT_PUBLIC_API_KEY!,
618
+ model: "anthropic/claude-3.5-sonnet",
619
+ systemPrompts: ["You are a helpful assistant."],
620
+ tools: [],
621
+ };
622
+
623
+ const {
624
+ chat,
625
+ abort,
626
+ history,
627
+ chatItems,
628
+ isLoading,
629
+ error,
630
+ tokenUsage,
631
+ clearHistory,
632
+ clearError,
633
+ } = useAgent(config, {
634
+ onMessage: (message) => console.log("New message:", message),
635
+ onError: (error) => console.error("Error:", error),
636
+ });
637
+
638
+ const handleSubmit = async (message: string) => {
639
+ const result = await chat(message, {
640
+ userId: "user-123",
641
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
642
+ });
643
+
644
+ if (result) {
645
+ console.log("Chat completed:", result.message);
646
+ }
647
+ };
648
+
649
+ return (
650
+ <div>
651
+ {chatItems.map((item) => (
652
+ <div key={item.id}>
653
+ {item.type === "message" && (
654
+ <p>
655
+ {item.message?.role}: {item.message?.content}
656
+ </p>
657
+ )}
658
+ {item.type === "function_call" && (
659
+ <p>🔧 {item.functionCall?.functionName}</p>
660
+ )}
661
+ </div>
662
+ ))}
663
+
664
+ {isLoading && <p>Thinking...</p>}
665
+ {error && <p>Error: {error.message}</p>}
666
+
667
+ <button onClick={abort} disabled={!isLoading}>
668
+ Cancel
669
+ </button>
670
+ <button onClick={clearHistory}>Clear Chat</button>
671
+ </div>
672
+ );
673
+ }
674
+ ```
675
+
676
+ #### UseAgentReturn
677
+
678
+ ```typescript
679
+ interface UseAgentReturn {
680
+ chat: (
681
+ message: string,
682
+ context: ToolExecutorContext
683
+ ) => Promise<AgentResult | null>;
684
+ abort: () => void;
685
+ history: ChatMessage[]; // Raw conversation history
686
+ chatItems: ChatItem[]; // Formatted items for UI rendering
687
+ isLoading: boolean;
688
+ error: Error | null;
689
+ tokenUsage: UsageMetadata;
690
+ clearHistory: () => void;
691
+ clearError: () => void;
692
+ }
693
+ ```
694
+
695
+ #### UseAgentOptions
696
+
697
+ ```typescript
698
+ interface UseAgentOptions {
699
+ onMessage?: (message: ChatMessage) => void;
700
+ onFunctionCall?: (call: FunctionCallDisplay) => void;
701
+ onError?: (error: Error) => void;
702
+ }
703
+ ```
704
+
705
+ #### ChatItem Type
706
+
707
+ ```typescript
708
+ interface ChatItem {
709
+ id: string;
710
+ type: "message" | "function_call";
711
+ timestamp: Date;
712
+ message?: ChatMessage;
713
+ functionCall?: FunctionCallDisplay;
714
+ }
715
+
716
+ interface FunctionCallDisplay {
717
+ functionName: string;
718
+ args: Record<string, unknown>;
719
+ timestamp: Date;
720
+ }
721
+ ```
722
+
723
+ ---
724
+
725
+ ### AgentProvider
726
+
727
+ A React context provider for sharing an agent instance across components.
728
+
729
+ ```tsx
730
+ import { AgentProvider, useAgentContext } from "concevent-ai-agent-sdk/react";
731
+ ```
732
+
733
+ #### Usage
734
+
735
+ ```tsx
736
+ import { AgentProvider, useAgentContext } from "concevent-ai-agent-sdk/react";
737
+ import type { AgentConfig } from "concevent-ai-agent-sdk";
738
+
739
+ const config: AgentConfig = {
740
+ apiKey: process.env.NEXT_PUBLIC_API_KEY!,
741
+ model: "anthropic/claude-3.5-sonnet",
742
+ systemPrompts: ["You are a helpful assistant."],
743
+ tools: myTools,
744
+ };
745
+
746
+ // Wrap your app with the provider
747
+ function App() {
748
+ return (
749
+ <AgentProvider config={config}>
750
+ <ChatInterface />
751
+ </AgentProvider>
752
+ );
753
+ }
754
+
755
+ // Access the agent in child components
756
+ function ChatInterface() {
757
+ const { agent, config } = useAgentContext();
758
+
759
+ const handleChat = async () => {
760
+ const result = await agent.chat("Hello!", {
761
+ userId: "user-123",
762
+ timezone: "UTC",
763
+ });
764
+ console.log(result.message);
765
+ };
766
+
767
+ return (
768
+ <div>
769
+ <p>Using model: {config.model}</p>
770
+ <button onClick={handleChat}>Send Message</button>
771
+ </div>
772
+ );
773
+ }
774
+ ```
775
+
776
+ #### AgentProviderProps
777
+
778
+ ```typescript
779
+ interface AgentProviderProps {
780
+ config: AgentConfig;
781
+ children: ReactNode;
782
+ }
783
+ ```
784
+
785
+ ---
786
+
787
+ ## Advanced Usage
788
+
789
+ ### Conversation Summarization
790
+
791
+ When conversations become too long, the agent automatically summarizes them to stay within context limits.
792
+
793
+ ```typescript
794
+ const agent = createAgent({
795
+ apiKey: process.env.API_KEY!,
796
+ model: "anthropic/claude-3.5-sonnet",
797
+ systemPrompts: ["You are a helpful assistant."],
798
+ tools: [],
799
+ summarization: {
800
+ enabled: true,
801
+ contextLimitTokens: 50000, // Summarize when approaching 50k tokens
802
+ prompt: `
803
+ Summarize this conversation, preserving:
804
+ 1. Key user requests and questions
805
+ 2. Important decisions made
806
+ 3. Any data or numbers mentioned
807
+ 4. Context needed to continue the conversation
808
+ `,
809
+ },
810
+ });
811
+
812
+ // Listen for summarization events
813
+ await agent.chat("Continue our discussion...", context, {
814
+ onSummarizationStart: (messageCount) => {
815
+ console.log(`Summarizing ${messageCount} messages to save context...`);
816
+ },
817
+ onSummarizationEnd: (summary, tokensEstimate) => {
818
+ console.log(
819
+ `Conversation summarized. Estimated tokens saved: ${tokensEstimate}`
820
+ );
821
+ },
822
+ });
823
+ ```
824
+
825
+ ### Error Handling
826
+
827
+ The SDK provides typed errors and customizable error messages.
828
+
829
+ ```typescript
830
+ import { createAgent } from "concevent-ai-agent-sdk";
831
+
832
+ const agent = createAgent({
833
+ // ... config
834
+ errorMessages: {
835
+ apiKeyRequired: "Please provide an API key",
836
+ modelRequired: "Please specify a model",
837
+ emptyResponse: "No response received, please try again",
838
+ maxIterations: "Request too complex. Please simplify.",
839
+ toolExecutionFailed: "A tool failed to execute",
840
+ genericError: "Something went wrong",
841
+ },
842
+ });
843
+
844
+ // Handle errors via callbacks
845
+ await agent.chat("Do something", context, {
846
+ onError: (error) => {
847
+ switch (error.code) {
848
+ case "MAX_ITERATIONS":
849
+ console.log("Too many iterations, simplify the request");
850
+ break;
851
+ case "TOOL_EXECUTION_FAILED":
852
+ console.log("Tool failed:", error.message);
853
+ break;
854
+ case "REQUEST_ABORTED":
855
+ console.log("Request was cancelled");
856
+ break;
857
+ default:
858
+ console.log("Error:", error.message);
859
+ }
860
+
861
+ if (!error.recoverable) {
862
+ // Handle fatal error
863
+ }
864
+ },
865
+ });
866
+ ```
867
+
868
+ #### Error Codes
869
+
870
+ | Code | Description | Recoverable |
871
+ | ----------------------- | --------------------------- | ----------- |
872
+ | `API_KEY_REQUIRED` | API key not provided | No |
873
+ | `MODEL_REQUIRED` | Model name not provided | No |
874
+ | `EMPTY_RESPONSE` | API returned empty response | No |
875
+ | `REQUEST_ABORTED` | Request was aborted | No |
876
+ | `NO_RESPONSE` | No response from API | No |
877
+ | `NO_RESPONSE_MESSAGE` | Response missing message | No |
878
+ | `MAX_ITERATIONS` | Max iterations reached | Yes |
879
+ | `TOOL_EXECUTION_FAILED` | Tool execution failed | Yes |
880
+ | `SUMMARIZATION_FAILED` | Summarization failed | Yes |
881
+ | `GENERIC_ERROR` | Unknown error occurred | No |
882
+
883
+ ### Abort Requests
884
+
885
+ Cancel ongoing requests using the abort functionality.
886
+
887
+ ```typescript
888
+ const agent = createAgent(config);
889
+
890
+ // Start a chat
891
+ const chatPromise = agent.chat("Process this large dataset", context, {
892
+ onAborted: () => {
893
+ console.log("Request cancelled by user");
894
+ },
895
+ });
896
+
897
+ // Cancel after 5 seconds
898
+ setTimeout(() => {
899
+ agent.abort();
900
+ }, 5000);
901
+
902
+ try {
903
+ const result = await chatPromise;
904
+ } catch (error) {
905
+ if (error.name === "AbortError") {
906
+ console.log("Chat was aborted");
907
+ }
908
+ }
909
+ ```
910
+
911
+ #### With Custom AbortSignal
912
+
913
+ ```typescript
914
+ const abortController = new AbortController();
915
+
916
+ // Pass abort signal in context
917
+ agent.chat("Hello", {
918
+ userId: "user-123",
919
+ timezone: "UTC",
920
+ abortSignal: abortController.signal,
921
+ });
922
+
923
+ // Cancel from external source
924
+ abortController.abort();
925
+ ```
926
+
927
+ ---
928
+
929
+ ## Exports Summary
930
+
931
+ ### Main Entry (`concevent-ai-agent-sdk`)
932
+
933
+ ```typescript
934
+ // Functions
935
+ export { createAgent } from "./core/agent";
936
+ export { createEvent } from "./types/events";
937
+
938
+ // Constants
939
+ export { ENCRYPTED_REASONING_MARKER } from "./core/openrouter-utils";
940
+
941
+ // Types
942
+ export type {
943
+ Agent,
944
+ ReasoningDetail,
945
+ ChatMessage,
946
+ FunctionDeclaration,
947
+ ToolExecutorContext,
948
+ ToolDefinition,
949
+ AgentConfig,
950
+ UsageMetadata,
951
+ AgentResult,
952
+ ToolCallStartData,
953
+ ToolResultData,
954
+ AgentCallbacks,
955
+ AgentEventType,
956
+ ThinkingEventData,
957
+ UsageUpdateEventData,
958
+ ErrorEventData,
959
+ CompleteEventData,
960
+ AgentEvent,
961
+ } from "./types";
962
+ ```
963
+
964
+ ### React Entry (`concevent-ai-agent-sdk/react`)
965
+
966
+ ```typescript
967
+ // Hooks
968
+ export { useAgent } from "./useAgent";
969
+ export { useAgentContext } from "./AgentProvider";
970
+
971
+ // Components
972
+ export { AgentProvider } from "./AgentProvider";
973
+
974
+ // Types
975
+ export type {
976
+ UseAgentReturn,
977
+ AgentProviderProps,
978
+ ChatItem,
979
+ FunctionCallDisplay,
980
+ AgentState,
981
+ UseAgentOptions,
982
+ } from "./types";
983
+ ```
984
+
985
+ ---
986
+
987
+ ## License
988
+
989
+ MIT
990
+
991
+ ## Contributing
992
+
993
+ Contributions are welcome! Please read our contributing guidelines before submitting a pull request.