Astreus

上下文

在 Astreus 文档中了解 上下文,获取用于构建智能体系统的设置指导、API 模式和实用示例。 了解构建可靠的 Astreus 智能体系统所需的设置模式、API 和实用示例。

通过自动压缩实现长对话的智能上下文管理

概述

Astreus 中的自动上下文压缩功能可以智能管理对话,自动处理较长的对话历史。系统会压缩较早的消息,同时保留重要信息,确保代理能够维持连贯的长对话,而不会超出模型的 token 限制。

基本用法

启用自动上下文压缩,即可获得自动化的对话管理:

import { Agent } from '@astreus-ai/astreus';

// Create an agent with auto context compression enabled
const agent = await Agent.create({
  name: 'ContextAwareAgent',
  model: 'gpt-4o',
  autoContextCompression: true  // Enable smart context management
});

// Long conversations are automatically managed
for (let i = 1; i <= 50; i++) {
  const response = await agent.ask(`Tell me fact #${i} about TypeScript`);
  console.log(`Fact ${i}:`, response);
}

// Agent can still reference early conversation through compressed context
const summary = await agent.ask('What was the first fact you told me?');
console.log(summary); // System retrieves from compressed context

任务示例

自动上下文压缩既适用于直接对话,也适用于任务:

const agent = await Agent.create({
  name: 'ResearchAgent',
  model: 'gpt-4o',
  autoContextCompression: true,
  memory: true // Often used together with memory
});

// Create multiple related tasks
const task1 = await agent.createTask({
  prompt: "Research the latest trends in AI development"
});

const result1 = await agent.executeTask(task1.id);

const task2 = await agent.createTask({
  prompt: "Based on the research, what are the key opportunities?"
});

const result2 = await agent.executeTask(task2.id);
// Task can reference previous context even if it was compressed

自动上下文压缩确保代理能够处理任意长度的对话和任务,同时保持连贯性并处于 token 限制之内。

配置选项

你可以通过以下参数自定义自动上下文压缩的行为:

const agent = await Agent.create({
  name: 'CustomContextAgent',
  model: 'gpt-4o',
  autoContextCompression: true,
  
  // Context compression configuration
  maxContextLength: 4000,           // Trigger compression at 4000 tokens
  preserveLastN: 5,                 // Keep last 5 messages uncompressed
  compressionRatio: 0.4,            // Target 40% size reduction
  compressionStrategy: 'hybrid',    // Use hybrid compression strategy
  
  memory: true,
});

配置参数

参数类型默认值描述
autoContextCompressionbooleanfalse启用自动上下文压缩
maxContextLengthnumber8000触发压缩的 token 限制
preserveLastNnumber3保留不压缩的最近消息数量
compressionRationumber0.3目标压缩比(0.1 表示压缩 90%)
compressionStrategystring'hybrid'使用的压缩算法

压缩的数学原理

压缩比决定了上下文被压缩的程度:

Compression Ratio=compressed tokensoriginal tokens\text{Compression Ratio} = \frac{\text{compressed tokens}}{\text{original tokens}}

例如,压缩比为 0.3 时:

  • 原始:1000 tokens
  • 压缩后:300 tokens
  • 压缩幅度:70%

token 削减百分比计算方式为: Reduction %=(1ratio)×100%\text{Reduction \%} = (1 - \text{ratio}) \times 100\%

compressionRatio = 0.3 时: Reduction=(10.3)×100%=70%\text{Reduction} = (1 - 0.3) \times 100\% = 70\%

压缩策略

选择最适合你使用场景的压缩策略:

'summarize' - 文本摘要

  • 最适合:通用对话、问答、讨论
  • 工作方式:为消息组生成简明摘要
  • 优点:保持上下文连贯,适用于大多数场景
  • 缺点:可能丢失部分细节
const agent = await Agent.create({
  name: 'SummarizingAgent',
  autoContextCompression: true,
  compressionStrategy: 'summarize',
  preserveLastN: 4
});

'selective' - 重要消息筛选

  • 最适合:任务导向型对话、技术讨论
  • 工作方式:使用 AI 识别并保留重要消息
  • 优点:保留关键信息完整
  • 缺点:可能消耗更多资源
const agent = await Agent.create({
  name: 'SelectiveAgent',
  autoContextCompression: true,
  compressionStrategy: 'selective',
  preserveLastN: 3
});

'hybrid' - 混合策略(推荐)

  • 最适合:大多数应用场景,兼顾平衡
  • 工作方式:结合摘要与选择性保留
  • 优点:在上下文保留与效率之间取得平衡
  • 缺点:无明显缺点
const agent = await Agent.create({
  name: 'HybridAgent',
  autoContextCompression: true,
  compressionStrategy: 'hybrid', // Default and recommended
});

高级用法

按使用场景自定义压缩设置

高频对话

适用于消息较短且频繁的聊天机器人或交互式代理:

const chatbot = await Agent.create({
  name: 'Chatbot',
  autoContextCompression: true,
  maxContextLength: 2000,     // Compress more frequently
  preserveLastN: 8,           // Keep more recent messages
  compressionRatio: 0.5,      // More aggressive compression
  compressionStrategy: 'summarize'
});

长篇内容创作

适用于处理详细内容的代理:

const writer = await Agent.create({
  name: 'ContentWriter',
  autoContextCompression: true,
  maxContextLength: 12000,    // Allow longer context
  preserveLastN: 3,           // Keep recent context tight
  compressionRatio: 0.2,      // Gentle compression
  compressionStrategy: 'selective'
});

技术文档

适用于处理复杂技术讨论的代理:

const techAgent = await Agent.create({
  name: 'TechnicalAssistant',
  autoContextCompression: true,
  maxContextLength: 6000,
  preserveLastN: 5,           
  compressionRatio: 0.3,      
  compressionStrategy: 'hybrid' // Best for mixed content
});

上下文压缩的工作原理

压缩流程

1

Token 监控:代理持续监控对话中的总 token 数量

2

触发点:当 token 数超过 maxContextLength 时,触发压缩

3

消息保留:最近的 preserveLastN 条消息保持不压缩

4

内容分析:根据所选策略分析较早的消息

5

压缩:将消息压缩为摘要或精选内容

6

上下文更新:压缩后的上下文替换原始消息

哪些内容会被保留

  • 系统提示词:始终保留
  • 最近消息:基于 preserveLastN 保留最后 N 条消息
  • 重要上下文:由压缩策略识别出的关键信息
  • 压缩摘要:较早对话的浓缩版本

压缩流程示例

// Before compression (1200 tokens)
[
  { role: 'user', content: 'Tell me about TypeScript' },
  { role: 'assistant', content: 'TypeScript is...' },
  { role: 'user', content: 'What about interfaces?' },
  { role: 'assistant', content: 'Interfaces in TypeScript...' },
  { role: 'user', content: 'Show me an example' },
  { role: 'assistant', content: 'Here\'s an example...' },
]

// After compression (400 tokens)
[
  { role: 'system', content: '[Compressed] User asked about TypeScript basics, interfaces, and examples. Assistant provided comprehensive explanations...' },
  { role: 'user', content: 'Show me an example' },
  { role: 'assistant', content: 'Here\'s an example...' },
]

监控与调试

上下文窗口信息

获取当前上下文状态的详细信息:

const contextWindow = agent.getContextWindow();

console.log({
  messageCount: contextWindow.messages.length,
  totalTokens: contextWindow.totalTokens,
  maxTokens: contextWindow.maxTokens,
  utilization: `${contextWindow.utilizationPercentage.toFixed(1)}%`
});

// Check if compression occurred
const hasCompression = contextWindow.messages.some(
  msg => msg.metadata?.type === 'summary'
);
console.log('Context compressed:', hasCompression);

上下文分析

分析上下文以发现优化机会:

const analysis = agent.analyzeContext();

console.log({
  compressionNeeded: analysis.compressionNeeded,
  averageTokensPerMessage: analysis.averageTokensPerMessage,
  suggestedCompressionRatio: analysis.suggestedCompressionRatio
});

响应类型

上下文管理方法会返回详细对象,用于监控和控制对话上下文。

上下文窗口响应

获取当前上下文窗口及其使用率指标:

const window = agent.getContextWindow();

// Response structure:
{
  messages: [
    {
      role: "user",
      content: "How do I use TypeScript?",
      timestamp: Date('2024-01-15T10:00:00Z'),
      tokens: 8
    },
    {
      role: "assistant",
      content: "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript...",
      timestamp: Date('2024-01-15T10:00:05Z'),
      tokens: 50
    }
    // ... more messages
  ],
  totalTokens: 3500,
  maxTokens: 8000,
  utilizationPercentage: 43.75
}

上下文分析响应

分析当前上下文使用情况及压缩需求:

const analysis = agent.analyzeContext();

// Response structure:
{
  totalTokens: 6500,
  messageCount: 15,
  averageTokensPerMessage: 433,
  contextUtilization: 0.8125,              // 81.25% of max context used
  compressionNeeded: true,
  suggestedCompressionRatio: 0.5           // Suggest 50% compression
}

压缩结果响应

压缩上下文并获取详细的压缩指标:

const compression = await agent.compressContext();

// Response structure:
{
  success: true,
  compressedMessages: [
    {
      role: "system",
      content: "Summary: User asked about TypeScript features. Discussed types, interfaces, and generics...",
      timestamp: Date('2024-01-15T10:05:00Z'),
      tokens: 35
    },
    {
      role: "user",
      content: "Can you explain decorators?",
      timestamp: Date('2024-01-15T10:10:00Z'),
      tokens: 8
    }
    // ... compressed messages (8 instead of 15)
  ],
  tokensReduced: 3250,                     // Tokens saved
  compressionRatio: 0.5,                   // 50% reduction achieved
  strategy: "summarize"                    // Strategy used
}

// On failure:
{
  success: false,
  compressedMessages: [],
  tokensReduced: 0,
  compressionRatio: 0,
  error: "Compression failed: Minimum context threshold not reached"
}

上下文摘要响应

生成 AI 驱动的对话摘要:

const summary = await agent.generateContextSummary();

// Response structure:
{
  mainTopics: [
    "TypeScript development",
    "API design patterns",
    "Testing strategies"
  ],
  keyEntities: [
    "Express.js",
    "Jest",
    "PostgreSQL",
    "Docker"
  ],
  conversationFlow: "Discussion started with TypeScript setup and configuration. Moved to API design patterns using Express.js. Covered database integration with PostgreSQL. Concluded with comprehensive testing strategies using Jest and continuous integration.",
  importantFacts: [
    "User prefers functional programming style",
    "Project deadline is March 15th, 2024",
    "Must support Node.js 18+",
    "Team size is 5 developers"
  ],
  actionItems: [
    "Set up Jest test framework with coverage reporting",
    "Create API documentation using OpenAPI/Swagger",
    "Configure Docker containers for development environment",
    "Implement CI/CD pipeline with GitHub Actions"
  ]
}

获取上下文消息响应

以数组形式获取所有上下文消息:

const messages = agent.getContext();
// OR
const messages = agent.getContextMessages();

// Response structure:
[
  {
    role: "user",
    content: "How do I use async/await?",
    timestamp: Date('2024-01-15T09:30:00Z'),
    tokens: 10
  },
  {
    role: "assistant",
    content: "Async/await is syntactic sugar for promises...",
    timestamp: Date('2024-01-15T09:30:15Z'),
    tokens: 85
  }
  // ... more messages
]

导出上下文响应

导出上下文会返回一个 JSON 字符串:

const exported = agent.exportContext();

// Response: JSON string
'{"messages":[{"role":"user","content":"...","timestamp":"2024-01-15T10:00:00.000Z","tokens":10},...],"metadata":{"exportedAt":"2024-01-15T11:00:00.000Z","totalTokens":3500}}'

导入/清除上下文响应

导入和清除操作没有返回值:

// Import context
agent.importContext(jsonString);
// Returns: void

// Clear context
agent.clearContext();
// Returns: void

最后更新时间:2026年7月6日