跳到正文
DEV Community· Roedy Rustam·· 3 小時前AI 評分33

如何在 Node.js 使用 sinapsai 建立零依賴 AI 智能體,無需 LangChain

How to Build a Zero-Dependency AI Agent in Node.js Without LangChain

AI 導讀

教學示範如何在 Node.js 使用 sinapsai 建立零外部依賴的 AI 智能體,並透過統一 LLM API 串接不同供應商。sinapsai 的 AgentLoop 支援 MCP 工具整合,亦可設定速率限制、斷路器及個人資料遮罩。

正文

Building autonomous AI agents in Node.js usually means reaching for massive frameworks like LangChain. While powerful, these frameworks often come with a steep learning curve, heavy dependency trees, and can feel like overkill for many projects.

If you are building an edge-compatible app or just want absolute control over your AI orchestration without the bloat, you need a different approach.

In this tutorial, we will build a lightweight, zero-dependency AI Agent in Node.js using sinapsai—an in-process AI Gateway and Control Plane that handles the heavy lifting of LLM routing, agent loops, and Model Context Protocol (MCP) integrations out of the box.


Why Skip the Heavy Frameworks?

When you rely on massive AI orchestration frameworks, you often encounter:

  1. Dependency Hell: Hundreds of sub-dependencies that slow down npm install and increase your deployment footprint.
  2. Edge Incompatibility: Heavy libraries often rely on Node-specific primitives that break when deployed to edge environments like Cloudflare Workers, Vercel Edge Functions, or Bun/Deno.
  3. Abstraction Lock-in: When something fails deep inside an agent's reasoning loop, debugging complex framework abstractions can be a nightmare.

This is where sinapsai shines. It provides a Unified LLM API and an Autonomous Agent Loop with zero external dependencies, making it blazing fast, secure, and ready for edge runtimes.


Prerequisites

  • Node.js installed (v18+ recommended)
  • An API key from an LLM provider (OpenAI, Anthropic, or Gemini)
  • Basic knowledge of JavaScript or TypeScript

Step 1: Project Setup & Installation

Create a new directory for your project, initialize it, and install sinapsai.

mkdir lightweight-ai-agent
cd lightweight-ai-agent
npm init -y
npm install sinapsai

Note: Make sure your package.json includes "type": "module" since sinapsai uses modern ES Modules syntax.

{
  "name": "lightweight-ai-agent",
  "version": "1.0.0",
  "type": "module",
  "main": "index.js",
  "dependencies": {
    "sinapsai": "^1.0.0"
  }
}

Step 2: Setting Up the Unified LLM API

One of the biggest headaches in AI development is vendor lock-in and handling different API specs for OpenAI, Anthropic, Gemini, or DeepSeek. sinapsai acts as an in-process gateway, allowing you to use a single standard interface across providers.

Create a file named index.js and set up your client:

import { SinapsClient } from 'sinapsai';

// Initialize the client
// You can easily swap 'openai' with 'anthropic', 'gemini', or 'deepseek'
const client = new SinapsClient({
  provider: 'openai', 
  apiKey: process.env.OPENAI_API_KEY
});

async function basicCall() {
  const response = await client.chat({
    model: 'gpt-4o-mini',
    messages: [
      { role: 'system', content: 'You are a helpful assistant.' },
      { role: 'user', content: 'What is the capital of Indonesia?' }
    ]
  });

  console.log('AI Response:', response.text);
}

// basicCall();

Step 3: Building the Autonomous Agent Loop with MCP Tools

An AI Agent is more than just a chat interface—it needs to reason, decide which tools to execute, run those tools, and evaluate the results. This cycle is called the Agent Loop.

Let's build an agent that uses the Model Context Protocol (MCP) bridge built into sinapsai. We will equip the agent with a custom tool to fetch weather data.

import { SinapsClient, AgentLoop } from 'sinapsai';

const client = new SinapsClient({
  provider: 'openai',
  apiKey: process.env.OPENAI_API_KEY
});

// Define an MCP-compatible tool for the agent
const weatherTool = {
  name: 'get_weather',
  description: 'Get the current weather for a given city.',
  parameters: {
    type: 'object',
    properties: {
      city: { type: 'string', description: 'The name of the city.' }
    },
    required: ['city']
  },
  execute: async ({ city }) => {
    console.log(`\n[Tool Executing] Fetching weather for ${city}...`);
    // Simulated weather API response
    if (city.toLowerCase() === 'tokyo') return JSON.stringify({ temp: '15°C', condition: 'Rainy' });
    return JSON.stringify({ temp: '28°C', condition: 'Sunny' });
  }
};

async function runAgent() {
  // Initialize the Agent Loop with tools and prompts
  const agent = new AgentLoop({
    client: client,
    model: 'gpt-4o',
    tools: [weatherTool],
    systemPrompt: "You are an autonomous assistant. Use available tools to answer queries accurately."
  });

  console.log("Starting agent task...");

  // The agent will autonomously decide if it needs to trigger 'get_weather'
  const result = await agent.run("Should I wear a raincoat in Tokyo today?");

  console.log("\n--- Final Agent Answer ---");
  console.log(result.finalResponse);
}

runAgent();

How the Loop Works Under the Hood:

  1. User Prompt: You ask if you need a raincoat in Tokyo.
  2. Reasoning: The LLM inspects the available tools and determines get_weather with city: "tokyo" is required.
  3. Execution: sinapsai intercepts the tool request, safely runs weatherTool.execute, and gets { temp: '15°C', condition: 'Rainy' }.
  4. Resolution: The agent passes the result back to the model, which formulates a helpful recommendation (e.g., "Yes, you should wear a raincoat because it is 15°C and rainy in Tokyo").

Step 4: Production Control Plane & Safety Guardrails

Running agents in production requires safeguards. If an external API encounters an outage, or if a user inputs sensitive information, your application must handle it safely.

Because sinapsai is designed as an in-process gateway, you can apply rate limiting, circuit breakers, and PII masking without adding third-party infrastructure.

const secureClient = new SinapsClient({
  provider: 'openai',
  apiKey: process.env.OPENAI_API_KEY,
  gatewayConfig: {
    // 1. Circuit Breaker: Prevent cascading failures if OpenAI is down
    circuitBreaker: {
      enabled: true,
      failureThreshold: 3,
      resetTimeout: 30000 // 30 seconds
    },
    // 2. Rate Limiter: Prevent API quota exhaustion and unexpected costs
    rateLimit: {
      requestsPerMinute: 60
    },
    // 3. PII Guardrail: Mask sensitive information before sending to LLM
    piiGuardrail: {
      enabled: true,
      maskEmails: true,
      maskCreditCards: true
    }
  }
});

Conclusion

You don't need multi-megabyte orchestration frameworks with deep dependency trees to build intelligent AI agents. By leveraging a lightweight, zero-dependency package like sinapsai, you get:

  • Unified multi-provider LLM support
  • Autonomous Agent Loops & MCP tool execution
  • Built-in reliability features (Circuit Breakers, Rate Limiting, PII masking)
  • Complete freedom to deploy on Node.js, Cloudflare Workers, or Vercel Edge

Get Started:

Check out sinapsai on NPM and consider contributing or giving it a star on GitHub!


What's your take on AI orchestration? Do you prefer heavy frameworks like LangChain, or lightweight, modular packages? Let me know in the comments below!

來源:DEV Community · dev.to