@agentionai/agents

中文文档
1.18.2发布于 2026/10/12TypeScriptCommonJS近 30 天下载 1799

Agent Library

原始使用文档
文档目录28 节
  1. Quick Start
  2. 1. Install
  3. 2. Get API Key
  4. 3. Create Your First Agent
  5. Selective Imports
  6. Features
  7. Agent with Tools
  8. Context Management
  9. Local Models (Ollama / llama.cpp / OpenAI-compatible server…
  10. Built-In Tools
  11. Streaming
  12. Multi-Agent Pipeline
  13. Agent Delegation
  14. Multimodal / Vision
  15. Core Concepts
  16. Agents
  17. Tools
  18. Context Management
  19. Multimodal / Vision
  20. Graph Pipelines
  21. RAG & Vector Stores
  22. Observability
  23. Documentation
  24. Why Agention?
  25. Examples
  26. Built with Agention
  27. Contributing
  28. Links

Agention

AI Agents Without the Magic

npm version

A comprehensive TypeScript toolkit for building LLM-powered agents with RAG, and multi-agent workflows. No hidden state machines, no forced abstractions—just typed agents, composable graphs, and complete control in a complete toolkit.

Documentation • Examples • GitLab • npm

Quick Start

1. Install

Install only what you need with selective imports:

# Install core library + Claude SDK
npm install @agentionai/agents @anthropic-ai/sdk

2. Get API Key

Get an API key from your chosen provider:

Set it as an environment variable:

export ANTHROPIC_API_KEY=your-key-here

3. Create Your First Agent

// Import only Claude - no other agent SDKs required!
import { ClaudeAgent } from '@agentionai/agents/claude';

const agent = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  id: 'assistant',
  name: 'Assistant',
  description: 'You are a helpful assistant.',
  model: 'claude-sonnet-4-5',
});

const response = await agent.execute('What can you help me with?');
console.log(response);

Selective Imports

Import only the agents you need:

import { ClaudeAgent } from '@agentionai/agents/claude';     // Requires @anthropic-ai/sdk
import { OpenAiAgent } from '@agentionai/agents/openai';     // Requires openai
import { GeminiAgent } from '@agentionai/agents/gemini';     // Requires @google/generative-ai
import { MistralAgent } from '@agentionai/agents/mistral';   // Requires @mistralai/mistralai
import { OpenRouterAgent } from '@agentionai/agents/openrouter'; // Requires @openrouter/sdk
import { OllamaAgent } from '@agentionai/agents/ollama';     // Requires ollama (local, no API key)
import { LlamaCppAgent } from '@agentionai/agents/llamacpp'; // Requires openai (local, no API key)

Or import everything (requires all SDKs):

import { ClaudeAgent, OpenAiAgent } from '@agentionai/agents';

Features

  • Multi-Provider, No Lock-in - Claude, OpenAI, Gemini, Mistral, OpenRouter (one key, dozens of upstream providers), plus local models via Ollama and llama.cpp—same interface. Switch models with one line. listModels() asks any provider what it currently offers, in one shared shape.
  • Composable Context Management - Tool result masking (lossless, free) + rolling summarization (auto-firing) + sub-agent delegation (token isolation by architecture).
  • Streaming - executeStream() on Claude, OpenAI, OpenRouter, and all OpenAI-compatible agents. Yields { type: "text" | "reasoning" } chunks; tool calls handled transparently.
  • Built-In Tools - Use provider-defined server-side tools (e.g. Anthropic's web search, bash, text editor) alongside your own.
  • Composable, Not Magical - Agents are objects. Pipelines are arrays. No hidden state, no surprises.
  • Multimodal / Vision - Send images alongside text with a unified MessageContent[] API across all providers.
  • Full Observability - Per-call token counts, execution timing, pipeline structure visualization.
  • TypeScript-Native - Strict typing, interfaces, and generics from the ground up.
  • RAG Ready - LanceDB vector store, token-aware chunking, ingestion pipeline out of the box.

Agent with Tools

import { GeminiAgent, Tool } from '@agentionai/agents/gemini';

const weatherTool = new Tool({
  name: 'get_weather',
  description: 'Get the current weather for a location',
  inputSchema: {
    type: 'object',
    properties: {
      location: { type: 'string', description: 'City name' },
    },
    required: ['location'],
  },
  execute: async ({ location }) => {
    // In production, call a weather API
    return JSON.stringify({
      location,
      temperature: 22,
      conditions: 'Sunny',
    });
  },
});

const agent = new GeminiAgent({
  apiKey: process.env.GEMINI_API_KEY,
  id: 'weather-agent',
  name: 'Weather Agent',
  description: 'You are a weather assistant.',
  model: 'gemini-flash-lite-latest',
  tools: [weatherTool],
});

const response = await agent.execute("What's the weather in Paris?");

Context Management

Every agent conversation grows — tool results pile up, turns accumulate, tokens compound. Agention's history plugins keep the context window lean automatically, without manual bookkeeping.

import { toolResultMaskingPlugin, compressionPlugin } from '@agentionai/agents/history/plugins';
import { History } from '@agentionai/agents/history';

// Mask old tool results at read time — sync, free, lossless
const maskingPlugin = toolResultMaskingPlugin({ keepRecentResults: 2 });

// Compress old turns into a rolling summary — auto-fires past a token budget
const history = new History([], { maxTokens: 50000 })
  .use(maskingPlugin)
  .use(compressionPlugin(summaryAgent, { autoReduceWhen: { maxTokens: 8000 } }));

const agent = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  id: 'researcher',
  name: 'Researcher',
  description: 'Research topics thoroughly.',
  model: 'claude-sonnet-4-6',
  tools: [searchTool, maskingPlugin.retrieveTool],
}, history);
StrategyCostData lossTrigger
toolResultMaskingPluginZero — sync, no LLM callsNone — full content always retrievableEvery getEntries() call
compressionPluginLLM tokens (use a cheap model)Yes — detail traded for brevityautoReduceWhen threshold or manual history.reduce()
Tool.fromAgent()None — structural choiceNone in main context (sub-agent history is independent)Automatic — just wrap an agent as a tool

Context Management guide → · History API →

Local Models (Ollama / llama.cpp / OpenAI-compatible servers)

Run models on your own machine — no API key required. Same agent interface as every other provider:

import { OllamaAgent } from '@agentionai/agents/ollama';
import { LlamaCppAgent } from '@agentionai/agents/llamacpp';

// Ollama (https://ollama.com) — pull a model first: `ollama pull qwen2.5`
const ollama = new OllamaAgent({
  id: 'local-ollama',
  name: 'Local Assistant',
  description: 'You are a helpful assistant.',
  model: 'qwen2.5',
  apiKey: '',
});

// llama.cpp server (`llama-server -m model.gguf`) — OpenAI-compatible API
const llamaCpp = new LlamaCppAgent({
  id: 'local-llamacpp',
  name: 'Local Assistant',
  description: 'You are a helpful assistant.',
  apiKey: '',
  baseURL: 'http://localhost:8080/v1',
});

const response = await ollama.execute('What can you run locally?');

// Discover which models are available on the server
const models = await ollama.listModels();

Custom OpenAI-compatible server (vLLM, LM Studio, Together AI, Groq, …): extend OpenAICompatibleAgent directly:

import { OpenAICompatibleAgent, OpenAICompatibleConfig } from '@agentionai/agents/llamacpp';

class VLLMAgent extends OpenAICompatibleAgent {
  constructor(config: Omit<OpenAICompatibleConfig, 'vendor'>) {
    super({ ...config, vendor: 'llamacpp', baseURL: config.baseURL ?? 'http://localhost:8000/v1' });
  }
  protected getVendorName() { return 'vLLM'; }
}

Full guide →

Built-In Tools

Use a provider's own server-side tools (executed by the provider, not locally) alongside your custom tools:

import { ClaudeAgent, webSearchTool } from '@agentionai/agents/claude';

const agent = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  id: 'researcher',
  name: 'Researcher',
  description: 'You are a helpful research assistant with web access.',
  model: 'claude-sonnet-4-6',
  builtInTools: [webSearchTool({ maxUses: 5 })],
});

const response = await agent.execute('What happened in the news today?');

Streaming

All three major providers support streaming via executeStream(), which returns an AsyncGenerator<StreamChunk>. Each chunk is { type: "text" | "reasoning"; content: string } — text for visible output, reasoning for internal thinking tokens (DeepSeek R1, Claude extended thinking, OpenAI o-series).

import { ClaudeAgent } from '@agentionai/agents/claude';

const agent = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  id: 'assistant',
  name: 'Assistant',
  description: 'You are a helpful assistant.',
});

for await (const chunk of agent.executeStream('Tell me a story')) {
  if (chunk.type === 'text') process.stdout.write(chunk.content);
}

Tool calls are handled transparently — the generator continues streaming after each round-trip. The same API works across ClaudeAgent, OpenAiAgent, and LlamaCppAgent / any OpenAICompatibleAgent subclass.

Multi-Agent Pipeline

Chain agents together with different providers and models:

import { ClaudeAgent } from '@agentionai/agents/claude';
import { OpenAiAgent } from '@agentionai/agents/openai';
import { Pipeline } from '@agentionai/agents/core';

const researcher = new OpenAiAgent({
  apiKey: process.env.OPENAI_API_KEY,
  id: 'researcher',
  name: 'Researcher',
  description: 'Research the given topic and provide key facts.',
  model: 'gpt-4o',
  tools: [searchTool],
});

const writer = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  id: 'writer',
  name: 'Writer',
  description: 'Write a blog post based on the research provided.',
  model: 'claude-sonnet-4-5',
});

const pipeline = new Pipeline([researcher, writer]);
const result = await pipeline.execute('Renewable energy trends in 2024');

Agent Delegation

Use agents as tools for hierarchical workflows:

import { ClaudeAgent } from '@agentionai/agents/claude';
import { OpenAiAgent } from '@agentionai/agents/openai';

// Research assistant (cheaper model for data gathering)
const researchAssistant = new OpenAiAgent({
  apiKey: process.env.OPENAI_API_KEY,
  id: 'research-assistant',
  name: 'Research Assistant',
  description: 'Search and summarize information on topics.',
  model: 'gpt-4o-mini',
  tools: [searchTool],
});

// Lead researcher delegates to assistant, synthesizes findings
const researcher = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  id: 'researcher',
  name: 'Lead Researcher',
  description: 'Research topics thoroughly using your assistant.',
  model: 'claude-sonnet-4-5',
  agents: [researchAssistant],  // Assistant available as a tool
});

const result = await researcher.execute('Latest developments in quantum computing');

Multimodal / Vision

Send images alongside text using imageUrl() or imageBase64(). The same MessageContent[] interface works across all providers:

import { ClaudeAgent } from '@agentionai/agents/claude';
import { imageUrl, imageBase64 } from '@agentionai/agents/core';
import * as fs from 'fs';

const agent = new ClaudeAgent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  id: 'vision-agent',
  name: 'VisionAgent',
  description: 'You analyze images.',
  model: 'claude-opus-4-6',
});

// Remote image by URL
const response = await agent.execute([
  imageUrl('https://example.com/chart.png'),
  { type: 'text', text: 'Summarize this chart in one sentence.' },
]);

// Local image as base64
const data = fs.readFileSync('./photo.jpg').toString('base64');
const response2 = await agent.execute([
  imageBase64(data, 'image/jpeg'),
  { type: 'text', text: 'What plant is this?' },
]);
ProviderURLBase64
Claude✅✅
OpenAI✅✅
Gemini✅✅
Mistral✅❌

Core Concepts

Agents

Unified interface across Claude, OpenAI, Gemini, Mistral, and local models via Ollama and llama.cpp. Tools, history, and token tracking built-in.

Learn more →

Tools

JSON Schema + handler pattern. Unique capability: wrap any agent as a tool for delegation hierarchies. Also supports provider-defined built-in tools (e.g. Anthropic's web search, bash, text editor) that run server-side.

Learn more →

Context Management

Tool result masking (lossless, free) + rolling summarization (auto-firing) + sub-agent delegation (token isolation by architecture). Composable plugins keep the context window lean automatically.

Learn more → · History API →

Multimodal / Vision

Unified MessageContent[] interface for images across all providers. URL and base64 images, mix text and images freely in a single call.

Learn more →

Graph Pipelines

Compose sequential, parallel, voting, routing, and nested graphs. Mix models and providers freely.

Learn more →

RAG & Vector Stores

LanceDB vector store, token-aware chunking, ingestion pipeline, and retrieval tools out of the box.

Learn more →

Observability

Per-call and per-node token counts, duration metrics, full execution visibility.

Learn more →

Documentation

Why Agention?

Raw SDKsHeavy FrameworksAgention
ControlFullLimitedFull
BoilerplateHighLowLow
TransparencyFullLimitedFull
Multi-providerManualVariesBuilt-in
TypeScriptVariesOften partialNative
  • Ship faster — Stop rebuilding agent infrastructure for every project
  • Stay flexible — Swap providers, mix models, customize everything
  • Keep control — See exactly what's happening at every step
  • Scale confidently — Built-in metrics, token tracking, and observability

Examples

Check out the examples directory for complete working examples:

  • Basic agents with different providers
  • Custom tools and agent delegation
  • Sequential, parallel, and voting pipelines
  • RAG applications with vector search
  • Document ingestion and chunking

Built with Agention

  • Marshall — a coding agent for open weights. Runs a planner/coder/reviewer loop entirely on local hardware via llama.cpp or Ollama, no API key, account, or cloud required — with approval-gated file writes and shell commands, and support for mixing local and paid models across roles.

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

版本与发布记录

@agentionai/agents 共发布 49 个版本,首次发布于 2026/01/27;过去 12 个月发布了 49 个版本。

版本发布日期距今
1.18.2latest2026/10/1227 天前
1.18.12026/10/1029 天前
1.18.02026/09/291 个月前
1.17.02026/09/281 个月前
1.16.02026/09/281 个月前
1.15.02026/09/111 个月前

其他发布通道:beta → 1.6.0-beta.0。

关于 @agentionai/agents 的常见问题

@agentionai/agents 是什么?

Agent Library

如何安装 @agentionai/agents?

在项目目录运行 npm install @agentionai/agents,或使用 pnpm add / yarn add / bun add。

@agentionai/agents 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@agentionai/agents 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@agentionai/agents 可以商用吗?

@agentionai/agents 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@agentionai/agents 的下载量有多少?

根据 npm 官方下载统计,@agentionai/agents 在 2026/10/05 – 2026/11/03 这 30 天内被下载 1,799 次,日均约 60 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@agentionai/agents 还在维护吗?

最新版本 1.18.2 发布于 2026/10/12(27 天前);至今共发布 49 个版本,其中过去 12 个月发布了 49 个;首次发布于 2026/01/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。