Astreus

コンテキスト

Astreusのドキュメントでコンテキストについて学び、エージェントシステムを構築するためのセットアップの手引き、APIのパターン、実践的な例を確認しましょう。 信頼性の高いAstreusエージェントシステムを構築するために必要なセットアップのパターン、API、実践的な例を学びましょう。

自動圧縮による、長い会話のためのスマートなコンテキスト管理

概要

Astreusにおける自動コンテキスト圧縮は、長い会話履歴を自動的に処理することで、知的な会話管理を提供します。システムは重要な情報を保持しながら古いメッセージを圧縮し、エージェントがモデルのトークン上限を超えることなく一貫した長い会話を維持できるようにします。

基本的な使い方

自動コンテキスト圧縮を有効にすると、会話管理が自動化されます。

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

自動コンテキスト圧縮により、エージェントは一貫性を保ちながらトークン上限内に収まる形で、あらゆる長さの会話やタスクを処理できます。

設定オプション

以下のパラメータで自動コンテキスト圧縮の動作をカスタマイズできます。

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圧縮が発動するトークン上限
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トークン
  • 圧縮後: 300トークン
  • 削減率: 70%

トークン削減率は次のように計算されます。 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' - テキスト要約

  • 最適な用途: 一般的な会話、Q&A、ディスカッション
  • 仕組み: メッセージグループの簡潔な要約を作成
  • メリット: コンテキストの流れを維持し、ほとんどのユースケースに適している
  • デメリット: 細部の情報が失われる可能性がある
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

トークン監視: エージェントは会話内の合計トークン数を継続的に監視します

2

発動ポイント: トークン数が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}}'

コンテキストのインポート/クリアのレスポンス

インポートおよびクリア操作はvoidを返します。

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

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

最終更新日: 2026年7月6日