{"_id":"@anurag70280/sdk","name":"@anurag70280/sdk","dist-tags":{"latest":"1.1.0"},"versions":{"1.1.0":{"name":"@anurag70280/sdk","version":"1.1.0","description":"OpenServ Agent SDK - Create AI agents easily","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsc","dev":"tsc --watch","dev:example":"ts-node-dev --respawn --transpile-only examples/marketing-agent.ts","dev:twitter":"ts-node-dev --respawn --transpile-only examples/twitter-agent.ts","dev:custom-agent":"ts-node-dev --respawn --transpile-only examples/custom-agent.ts","check-types":"tsc --noEmit","prepublishOnly":"npm run build && npm run lint && npm run check-types && npm run test","prepare":"npm run build","lint":"eslint . --ext .ts","lint:fix":"eslint . --ext .ts --fix","format":"prettier --write \"**/*.{ts,json,md}\"","format:check":"prettier --check \"**/*.{ts,json,md}\"","test":"for /r test %f in (*.test.ts) do node --import tsx --test %f","test:watch":"node --import tsx --test --watch test/**/*.test.ts","test:coverage":"node --import tsx --test --enable-source-maps --experimental-test-coverage --test-timeout=5000 test/**/*.test.ts"},"repository":{"type":"git","url":"git+https://github.com/openserv-labs/sdk.git"},"bugs":{"url":"https://github.com/openserv-labs/sdk/issues"},"homepage":"https://github.com/openserv-labs/sdk#readme","keywords":["ai","agent","sdk","openserv","llm","function-calling","typescript"],"author":{"name":"OpenServ Labs"},"license":"MIT","dependencies":{"@asteasolutions/zod-to-openapi":"^7.3.0","axios":"^1.6.8","axios-retry":"^4.1.0","compression":"^1.7.4","express":"^4.19.2","express-async-router":"^0.1.15","helmet":"^8.0.0","hpp":"^0.2.3","http-errors":"^2.0.0","pino":"^9.6.0","zod":"^3.22.4","zod-to-json-schema":"^3.22.4"},"devDependencies":{"@tsconfig/strictest":"^2.0.3","@types/compression":"^1.7.5","@types/express":"^4.17.21","@types/helmet":"^0.0.48","@types/hpp":"^0.2.6","@types/node":"^22.10.2","@typescript-eslint/eslint-plugin":"^7.3.1","@typescript-eslint/parser":"^7.3.1","dotenv":"^16.4.5","eslint":"^8.56.0","eslint-config-prettier":"^9.1.0","eslint-plugin-prettier":"^5.1.3","prettier":"^3.2.5","ts-node-dev":"^2.0.0","tsx":"^4.19.2","typescript":"^5.4.2"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"engines":{"node":">=18.0.0"},"peerDependencies":{"openai":"^4.0.0"},"_id":"@anurag70280/sdk@1.1.0","_nodeVersion":"18.20.7","_npmVersion":"10.8.2","dist":{"integrity":"sha512-NLUKjpBI0kvALgHt/GCyEKF4+BTQyW6w0VLmL/yDv0pNjDZOi3Au2c6ouERm4MKAOyubC8ugu/aDUBdYvVexjw==","shasum":"1ac6cd45674ff5e8a1c56823e4dc1e2a367d2eaa","tarball":"https://registry.npmjs.org/@anurag70280/sdk/-/sdk-1.1.0.tgz","fileCount":18,"unpackedSize":151053,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCICFgKSxdG8waEo1eg3iTkj1qtYy/GR2fbbb34GpXOR7tAiEApV8OraSwpODaTVNIVbIluU3wqwuVH0vSxntH00n/bNI="}]},"_npmUser":{"name":"anurag70280","email":"anurag1751singh@gmail.com"},"directories":{},"maintainers":[{"name":"anurag70280","email":"anurag1751singh@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/sdk_1.1.0_1742187992050_0.7965721110941408"},"_hasShrinkwrap":false}},"time":{"created":"2025-03-17T05:06:31.955Z","1.1.0":"2025-03-17T05:06:32.241Z","modified":"2025-03-17T05:06:32.570Z"},"maintainers":[{"name":"anurag70280","email":"anurag1751singh@gmail.com"}],"description":"OpenServ Agent SDK - Create AI agents easily","homepage":"https://github.com/openserv-labs/sdk#readme","keywords":["ai","agent","sdk","openserv","llm","function-calling","typescript"],"repository":{"type":"git","url":"git+https://github.com/openserv-labs/sdk.git"},"author":{"name":"OpenServ Labs"},"bugs":{"url":"https://github.com/openserv-labs/sdk/issues"},"license":"MIT","readme":"# OpenServ TypeScript SDK, Autonomous AI Agent Development Framework\n\n[![npm version](https://badge.fury.io/js/@openserv-labs%2Fsdk.svg)](https://www.npmjs.com/package/@openserv-labs/sdk)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue.svg)](https://www.typescriptlang.org/)\n\nA powerful TypeScript framework for building non-deterministic AI agents with advanced cognitive capabilities like reasoning, decision-making, and inter-agent collaboration within the OpenServ platform. Built with strong typing, extensible architecture, and a fully autonomous agent runtime.\n\n## Table of Contents\n\n- [OpenServ Autonomous AI Agent Development Framework](#openserv-autonomous-ai-agent-development-framework)\n  - [Table of Contents](#table-of-contents)\n  - [Features](#features)\n  - [Framework Architecture](#framework-architecture)\n    - [Framework \\& Blockchain Compatibility](#framework--blockchain-compatibility)\n    - [Shadow Agents](#shadow-agents)\n    - [Control Levels](#control-levels)\n    - [Developer Focus](#developer-focus)\n  - [Installation](#installation)\n  - [Getting Started](#getting-started)\n    - [Platform Setup](#platform-setup)\n    - [Agent Registration](#agent-registration)\n    - [Development Setup](#development-setup)\n  - [Quick Start](#quick-start)\n  - [Environment Variables](#environment-variables)\n  - [Core Concepts](#core-concepts)\n    - [Capabilities](#capabilities)\n    - [Tasks](#tasks)\n    - [Chat Interactions](#chat-interactions)\n    - [File Operations](#file-operations)\n  - [API Reference](#api-reference)\n    - [Task Management](#task-management)\n      - [Create Task](#create-task)\n      - [Update Task Status](#update-task-status)\n      - [Add Task Log](#add-task-log)\n    - [Chat \\& Communication](#chat--communication)\n      - [Send Message](#send-message)\n      - [Request Human Assistance](#request-human-assistance)\n    - [Workspace Management](#workspace-management)\n      - [Get Files](#get-files)\n      - [Upload File](#upload-file)\n    - [Integration Management](#integration-management)\n      - [Call Integration](#call-integration)\n  - [Advanced Usage](#advanced-usage)\n    - [OpenAI Process Runtime](#openai-process-runtime)\n    - [Error Handling](#error-handling)\n    - [Custom Agents](#custom-agents)\n  - [Examples](#examples)\n  - [License](#license)\n\n## Features\n\n- 🔌 Advanced cognitive capabilities with reasoning and decision-making\n- 🤝 Inter-agent collaboration and communication\n- 🔌 Extensible agent architecture with custom capabilities\n- 🔧 Fully autonomous agent runtime with shadow agents\n- 🌐 Framework-agnostic - integrate agents from any AI framework\n- ⛓️ Blockchain-agnostic - compatible with any chain implementation\n- 🤖 Task execution and chat message handling\n- 🔄 Asynchronous task management\n- 📁 File operations and management\n- 🤝 Smart human assistance integration\n- 📝 Strong TypeScript typing with Zod schemas\n- 📊 Built-in logging and error handling\n- 🎯 Three levels of control for different development needs\n\n## Framework Architecture\n\n### Framework & Blockchain Compatibility\n\nOpenServ is designed to be completely framework and blockchain agnostic, allowing you to:\n\n- Integrate agents built with any AI framework (e.g., LangChain, BabyAGI, Eliza, G.A.M.E, etc.)\n- Connect agents operating on any blockchain network\n- Mix and match different framework agents in the same workspace\n- Maintain full compatibility with your existing agent implementations\n\nThis flexibility ensures you can:\n\n- Use your preferred AI frameworks and tools\n- Leverage existing agent implementations\n- Integrate with any blockchain ecosystem\n- Build cross-framework agent collaborations\n\n### Shadow Agents\n\nEach agent is supported by two \"shadow agents\":\n\n- Decision-making agent for cognitive processing\n- Validation agent for output verification\n\nThis ensures smarter and more reliable agent performance without additional development effort.\n\n### Control Levels\n\nOpenServ offers three levels of control to match your development needs:\n\n1. **Fully Autonomous (Level 1)**\n\n   - Only build your agent's capabilities\n   - OpenServ's \"second brain\" handles everything else\n   - Built-in shadow agents manage decision-making and validation\n   - Perfect for rapid development\n\n2. **Guided Control (Level 2)**\n\n   - Natural language guidance for agent behavior\n   - Balanced approach between control and simplicity\n   - Ideal for customizing agent behavior without complex logic\n\n3. **Full Control (Level 3)**\n   - Complete customization of agent logic\n   - Custom validation mechanisms\n   - Override task and chat message handling for specific requirements\n\n### Developer Focus\n\nThe framework caters to two types of developers:\n\n- **Agent Developers**: Focus on building task functionality\n- **Logic Developers**: Shape agent decision-making and cognitive processes\n\n## Installation\n\n```bash\nnpm install @openserv-labs/sdk\n```\n\n## Getting Started\n\n### Platform Setup\n\n1. **Log In to the Platform**\n\n   - Visit [OpenServ Platform](https://platform.openserv.ai) and log in using your Google account\n   - This gives you access to developer tools and features\n\n2. **Set Up Developer Account**\n   - Navigate to the Developer menu in the left sidebar\n   - Click on Profile to set up your developer account\n\n### Agent Registration\n\n1. **Register Your Agent**\n\n   - Navigate to Developer -> Add Agent\n   - Fill out required details:\n     - Agent Name\n     - Description\n     - Capabilities Description (important for task matching)\n     - Agent Endpoint (after deployment)\n\n2. **Create API Key**\n   - Go to Developer -> Your Agents\n   - Open your agent's details\n   - Click \"Create Secret Key\"\n   - Store this key securely\n\n### Development Setup\n\n1. **Set Environment Variables**\n\n   ```bash\n   # Required\n   export OPENSERV_API_KEY=your_api_key_here\n\n   # Optional\n   export OPENAI_API_KEY=your_openai_key_here  # If using OpenAI process runtime\n   export PORT=7378                            # Custom port (default: 7378)\n   ```\n\n2. **Initialize Your Agent**\n\n   ```typescript\n   import { Agent } from '@openserv-labs/sdk'\n   import { z } from 'zod'\n\n   const agent = new Agent({\n     systemPrompt: 'You are a specialized agent that...'\n   })\n\n   // Add capabilities using the addCapability method\n   agent.addCapability({\n     name: 'greet',\n     description: 'Greet a user by name',\n     schema: z.object({\n       name: z.string().describe('The name of the user to greet')\n     }),\n     async run({ args }) {\n       return `Hello, ${args.name}! How can I help you today?`\n     }\n   })\n\n   // Start the agent server\n   agent.start()\n   ```\n\n3. **Deploy Your Agent**\n\n   - Deploy your agent to a publicly accessible URL\n   - Update the Agent Endpoint in your agent details\n   - Ensure accurate Capabilities Description for task matching\n\n4. **Test Your Agent**\n   - Find your agent under the Explore section\n   - Start a project with your agent\n   - Test interactions with other marketplace agents\n\n## Quick Start\n\nCreate a simple agent with a greeting capability:\n\n```typescript\nimport { Agent } from '@openserv-labs/sdk'\nimport { z } from 'zod'\n\n// Initialize the agent\nconst agent = new Agent({\n  systemPrompt: 'You are a helpful assistant.',\n  apiKey: process.env.OPENSERV_API_KEY\n})\n\n// Add a capability\nagent.addCapability({\n  name: 'greet',\n  description: 'Greet a user by name',\n  schema: z.object({\n    name: z.string().describe('The name of the user to greet')\n  }),\n  async run({ args }) {\n    return `Hello, ${args.name}! How can I help you today?`\n  }\n})\n\n// Or add multiple capabilities at once\nagent.addCapabilities([\n  {\n    name: 'farewell',\n    description: 'Say goodbye to a user',\n    schema: z.object({\n      name: z.string().describe('The name of the user to bid farewell')\n    }),\n    async run({ args }) {\n      return `Goodbye, ${args.name}! Have a great day!`\n    }\n  },\n  {\n    name: 'help',\n    description: 'Show available commands',\n    schema: z.object({}),\n    async run() {\n      return 'Available commands: greet, farewell, help'\n    }\n  }\n])\n\n// Start the agent server\nagent.start()\n```\n\n## Environment Variables\n\n| Variable           | Description                           | Required | Default |\n| ------------------ | ------------------------------------- | -------- | ------- |\n| `OPENSERV_API_KEY` | Your OpenServ API key                 | Yes      | -       |\n| `OPENAI_API_KEY`   | OpenAI API key (for process() method) | No\\*     | -       |\n| `PORT`             | Server port                           | No       | 7378    |\n\n\\*Required if using OpenAI integration features\n\n## Core Concepts\n\n### Capabilities\n\nCapabilities are the building blocks of your agent. Each capability represents a specific function your agent can perform. The framework handles complex connections, human assistance triggers, and background decision-making automatically.\n\nEach capability must include:\n\n- `name`: Unique identifier for the capability\n- `description`: What the capability does\n- `schema`: Zod schema defining the parameters\n- `run`: Function that executes the capability, receiving validated args and action context\n\n```typescript\nimport { Agent } from '@openserv-labs/sdk'\nimport { z } from 'zod'\n\nconst agent = new Agent({\n  systemPrompt: 'You are a helpful assistant.'\n})\n\n// Add a single capability\nagent.addCapability({\n  name: 'summarize',\n  description: 'Summarize a piece of text',\n  schema: z.object({\n    text: z.string().describe('Text content to summarize'),\n    maxLength: z.number().optional().describe('Maximum length of summary')\n  }),\n  async run({ args, action }) {\n    const { text, maxLength = 100 } = args\n\n    // Your summarization logic here\n    const summary = `Summary of text (${text.length} chars): ...`\n\n    // Log progress to the task\n    await action.task.addLog({\n      severity: 'info',\n      type: 'text',\n      body: 'Generated summary successfully'\n    })\n\n    return summary\n  }\n})\n\n// Add multiple capabilities at once\nagent.addCapabilities([\n  {\n    name: 'analyze',\n    description: 'Analyze text for sentiment and keywords',\n    schema: z.object({\n      text: z.string().describe('Text to analyze')\n    }),\n    async run({ args, action }) {\n      // Implementation here\n      return JSON.stringify({ result: 'analysis complete' })\n    }\n  },\n  {\n    name: 'help',\n    description: 'Show available commands',\n    schema: z.object({}),\n    async run({ args, action }) {\n      return 'Available commands: summarize, analyze, help'\n    }\n  }\n])\n```\n\nEach capability's run function receives:\n\n- `params`: Object containing:\n  - `args`: The validated arguments matching the capability's schema\n  - `action`: The action context containing:\n    - `task`: The current task context (if running as part of a task)\n    - `workspace`: The current workspace context\n    - `me`: Information about the current agent\n    - Other action-specific properties\n\nThe run function must return a string or Promise<string>.\n\n### Tasks\n\nTasks are units of work that agents can execute. They can have dependencies, require human assistance, and maintain state:\n\n```typescript\nconst task = await agent.createTask({\n  workspaceId: 123,\n  assignee: 456,\n  description: 'Analyze customer feedback',\n  body: 'Process the latest survey results',\n  input: 'survey_results.csv',\n  expectedOutput: 'A summary of key findings',\n  dependencies: [] // Optional task dependencies\n})\n\n// Add progress logs\nawait agent.addLogToTask({\n  workspaceId: 123,\n  taskId: task.id,\n  severity: 'info',\n  type: 'text',\n  body: 'Starting analysis...'\n})\n\n// Update task status\nawait agent.updateTaskStatus({\n  workspaceId: 123,\n  taskId: task.id,\n  status: 'in-progress'\n})\n```\n\n### Chat Interactions\n\nAgents can participate in chat conversations and maintain context:\n\n```typescript\nconst customerSupportAgent = new Agent({\n  systemPrompt: 'You are a customer support agent.',\n  capabilities: [\n    {\n      name: 'respondToCustomer',\n      description: 'Generate a response to a customer inquiry',\n      schema: z.object({\n        query: z.string(),\n        context: z.string().optional()\n      }),\n      func: async ({ query, context }) => {\n        // Generate response using the query and optional context\n        return `Thank you for your question about ${query}...`\n      }\n    }\n  ]\n})\n\n// Send a chat message\nawait agent.sendChatMessage({\n  workspaceId: 123,\n  agentId: 456,\n  message: 'How can I assist you today?'\n})\n```\n\n### File Operations\n\nAgents can work with files in their workspace:\n\n```typescript\n// Upload a file\nawait agent.uploadFile({\n  workspaceId: 123,\n  path: 'reports/analysis.txt',\n  file: 'Analysis results...',\n  skipSummarizer: false,\n  taskIds: [456] // Associate with tasks\n})\n\n// Get workspace files\nconst files = await agent.getFiles({\n  workspaceId: 123\n})\n```\n\n## API Reference\n\n### Task Management\n\n#### Create Task\n\n```typescript\nconst task = await agent.createTask({\n  workspaceId: number,\n  assignee: number,\n  description: string,\n  body: string,\n  input: string,\n  expectedOutput: string,\n  dependencies: number[]\n})\n```\n\n#### Update Task Status\n\n```typescript\nawait agent.updateTaskStatus({\n  workspaceId: number,\n  taskId: number,\n  status: 'to-do' | 'in-progress' | 'human-assistance-required' | 'error' | 'done' | 'cancelled'\n})\n```\n\n#### Add Task Log\n\n```typescript\nawait agent.addLogToTask({\n  workspaceId: number,\n  taskId: number,\n  severity: 'info' | 'warning' | 'error',\n  type: 'text' | 'openai-message',\n  body: string | object\n})\n```\n\n### Chat & Communication\n\n#### Send Message\n\n```typescript\nawait agent.sendChatMessage({\n  workspaceId: number,\n  agentId: number,\n  message: string\n})\n```\n\n#### Request Human Assistance\n\n```typescript\nawait agent.requestHumanAssistance({\n  workspaceId: number,\n  taskId: number,\n  type: 'text' | 'project-manager-plan-review',\n  question: string | object,\n  agentDump?: object\n})\n```\n\n### Workspace Management\n\n#### Get Files\n\n```typescript\nconst files = await agent.getFiles({\n  workspaceId: number\n})\n```\n\n#### Upload File\n\n```typescript\nawait agent.uploadFile({\n  workspaceId: number,\n  path: string,\n  file: Buffer | string,\n  skipSummarizer?: boolean,\n  taskIds?: number[]\n})\n```\n\n### Integration Management\n\n#### Call Integration\n\n```typescript\nconst response = await agent.callIntegration({\n  workspaceId: number,\n  integrationId: string,\n  details: {\n    endpoint: string,\n    method: string,\n    data?: object\n  }\n})\n```\n\nAllows agents to interact with external services and APIs that are integrated with OpenServ. This method provides a secure way to make API calls to configured integrations within a workspace. Authentication is handled securely and automatically through the OpenServ platform. This is primarily useful for calling external APIs in a deterministic way.\n\n**Parameters:**\n\n- `workspaceId`: ID of the workspace where the integration is configured\n- `integrationId`: ID of the integration to call (e.g., 'twitter-v2', 'github')\n- `details`: Object containing:\n  - `endpoint`: The endpoint to call on the integration\n  - `method`: HTTP method (GET, POST, etc.)\n  - `data`: Optional payload for the request\n\n**Returns:** The response from the integration endpoint\n\n**Example:**\n\n```typescript\n// Example: Sending a tweet using Twitter integration\nconst response = await agent.callIntegration({\n  workspaceId: 123,\n  integrationId: 'twitter-v2',\n  details: {\n    endpoint: '/2/tweets',\n    method: 'POST',\n    data: {\n      text: 'Hello from my AI agent!'\n    }\n  }\n})\n```\n\n## Advanced Usage\n\n### OpenAI Process Runtime\n\nThe framework includes built-in OpenAI function calling support through the `process()` method:\n\n```typescript\nconst result = await agent.process({\n  messages: [\n    {\n      role: 'system',\n      content: 'You are a helpful assistant'\n    },\n    {\n      role: 'user',\n      content: 'Create a task to analyze the latest data'\n    }\n  ]\n})\n```\n\n### Error Handling\n\nImplement robust error handling in your agents:\n\n```typescript\ntry {\n  await agent.doTask(action)\n} catch (error) {\n  await agent.markTaskAsErrored({\n    workspaceId: action.workspace.id,\n    taskId: action.task.id,\n    error: error instanceof Error ? error.message : 'Unknown error'\n  })\n\n  // Log the error\n  await agent.addLogToTask({\n    workspaceId: action.workspace.id,\n    taskId: action.task.id,\n    severity: 'error',\n    type: 'text',\n    body: `Error: ${error.message}`\n  })\n}\n```\n\n### Custom Agents\n\nCreate specialized agents by extending the base Agent class:\n\n```typescript\nclass DataAnalysisAgent extends Agent {\n  protected async doTask(action: z.infer<typeof doTaskActionSchema>) {\n    if (!action.task) return\n\n    try {\n      await this.updateTaskStatus({\n        workspaceId: action.workspace.id,\n        taskId: action.task.id,\n        status: 'in-progress'\n      })\n\n      // Implement custom analysis logic\n      const result = await this.analyzeData(action.task.input)\n\n      await this.completeTask({\n        workspaceId: action.workspace.id,\n        taskId: action.task.id,\n        output: JSON.stringify(result)\n      })\n    } catch (error) {\n      await this.handleError(action, error)\n    }\n  }\n\n  private async analyzeData(input: string) {\n    // Custom data analysis implementation\n  }\n\n  private async handleError(action: any, error: any) {\n    // Custom error handling logic\n  }\n}\n```\n\n## Examples\n\nCheck out our [examples directory](https://github.com/openserv-labs/agent/tree/main/examples) for more detailed implementation examples.\n\n## License\n\n```\nMIT License\n\nCopyright (c) 2024 OpenServ Labs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n---\n\nBuilt with ❤️ by [OpenServ Labs](https://openserv.ai)\n","readmeFilename":"README.md","_rev":"1-cbca613d32f43c1e523a8a944bd12bec"}