컨텍스트
Astreus 문서에서 컨텍스트에 대해 알아보고, 에이전트 시스템을 구축하기 위한 설정 안내, API 패턴, 실용적인 예제를 확인하세요. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.
자동 압축을 통한 긴 대화의 스마트 컨텍스트 관리
Overview
Astreus의 자동 컨텍스트 압축은 긴 대화 기록을 자동으로 처리하여 지능적인 대화 관리를 제공합니다. 시스템은 중요한 정보를 보존하면서 오래된 메시지를 압축하여, 에이전트가 모델의 토큰 한도를 초과하지 않고도 일관된 긴 대화를 유지할 수 있도록 합니다.
Basic Usage
자동 컨텍스트 압축을 활성화하면 자동 대화 관리 기능을 사용할 수 있습니다.
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 contextExample with Tasks
자동 컨텍스트 압축은 직접 대화와 작업 모두에서 동작합니다.
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자동 컨텍스트 압축은 에이전트가 일관성을 유지하고 토큰 한도 내에 머무르면서 어떤 길이의 대화와 작업도 처리할 수 있도록 보장합니다.
Configuration Options
다음 매개변수로 자동 컨텍스트 압축 동작을 커스터마이즈할 수 있습니다.
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,
});Configuration Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
autoContextCompression | boolean | false | 자동 컨텍스트 압축 활성화 |
maxContextLength | number | 8000 | 압축이 트리거되는 토큰 한도 |
preserveLastN | number | 3 | 압축하지 않고 유지할 최근 메시지 수 |
compressionRatio | number | 0.3 | 목표 압축 비율 (0.1 = 90% 감소) |
compressionStrategy | string | 'hybrid' | 사용할 압축 알고리즘 |
Compression Mathematics
압축 비율은 컨텍스트가 얼마나 줄어드는지를 결정합니다.
예를 들어, 비율이 0.3이면:
- 원본: 1000 토큰
- 압축 후: 300 토큰
- 감소량: 70%
토큰 감소율은 다음과 같이 계산됩니다.
compressionRatio = 0.3인 경우:
Compression Strategies
용도에 가장 적합한 압축 전략을 선택하세요.
'summarize' - Text Summarization
- 적합한 대상: 일반 대화, Q&A, 토론
- 동작 방식: 메시지 그룹의 간결한 요약을 생성합니다
- 장점: 대화 흐름을 유지하며, 대부분의 사용 사례에 적합합니다
- 단점: 세부 사항이 손실될 수 있습니다
const agent = await Agent.create({
name: 'SummarizingAgent',
autoContextCompression: true,
compressionStrategy: 'summarize',
preserveLastN: 4
});'selective' - Important Message Selection
- 적합한 대상: 작업 중심 대화, 기술적 토론
- 동작 방식: AI를 사용해 중요한 메시지를 식별하고 보존합니다
- 장점: 핵심 정보를 온전히 유지합니다
- 단점: 리소스 소모가 더 클 수 있습니다
const agent = await Agent.create({
name: 'SelectiveAgent',
autoContextCompression: true,
compressionStrategy: 'selective',
preserveLastN: 3
});'hybrid' - Combined Approach (Recommended)
- 적합한 대상: 대부분의 애플리케이션, 균형 잡힌 접근 방식
- 동작 방식: 요약과 선택적 보존을 결합합니다
- 장점: 컨텍스트 보존과 효율성 사이의 균형이 잘 맞습니다
- 단점: 특별한 단점 없음
const agent = await Agent.create({
name: 'HybridAgent',
autoContextCompression: true,
compressionStrategy: 'hybrid', // Default and recommended
});Advanced Usage
Custom Compression Settings by Use Case
High-Frequency Conversations
짧은 메시지가 많은 챗봇이나 대화형 에이전트의 경우:
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'
});Long-Form Content Creation
상세한 콘텐츠를 다루는 에이전트의 경우:
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'
});Technical Documentation
복잡한 기술적 토론을 다루는 에이전트의 경우:
const techAgent = await Agent.create({
name: 'TechnicalAssistant',
autoContextCompression: true,
maxContextLength: 6000,
preserveLastN: 5,
compressionRatio: 0.3,
compressionStrategy: 'hybrid' // Best for mixed content
});How Context Compression Works
Compression Process
토큰 모니터링: 에이전트가 대화에서 전체 토큰 수를 지속적으로 모니터링합니다
트리거 지점: 토큰이 maxContextLength를 초과하면 압축이 트리거됩니다
메시지 보존: 최근 preserveLastN개 메시지는 압축하지 않고 유지됩니다
콘텐츠 분석: 선택한 전략에 따라 오래된 메시지를 분석합니다
압축: 메시지가 요약 또는 선택된 항목으로 압축됩니다
컨텍스트 업데이트: 압축된 컨텍스트가 원본 메시지를 대체합니다
What Gets Preserved
- 시스템 프롬프트: 항상 보존됩니다
- 최근 메시지:
preserveLastN에 따른 마지막 N개 메시지 - 중요한 컨텍스트: 압축 전략이 식별한 핵심 정보
- 압축된 요약: 오래된 대화의 축약 버전
Example Compression Flow
// 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...' },
]Monitoring and Debugging
Context Window Information
현재 컨텍스트 상태에 대한 세부 정보를 가져옵니다.
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);Context Analysis
최적화 기회를 위해 컨텍스트를 분석합니다.
const analysis = agent.analyzeContext();
console.log({
compressionNeeded: analysis.compressionNeeded,
averageTokensPerMessage: analysis.averageTokensPerMessage,
suggestedCompressionRatio: analysis.suggestedCompressionRatio
});Response Types
컨텍스트 관리 메서드는 대화 컨텍스트를 모니터링하고 제어하기 위한 상세한 객체를 반환합니다.
Context Window Response
사용률 지표와 함께 현재 컨텍스트 윈도우를 가져옵니다.
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
}Context Analysis Response
현재 컨텍스트 사용량과 압축 필요 여부를 분석합니다.
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
}Compression Result Response
컨텍스트를 압축하고 상세한 압축 지표를 가져옵니다.
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"
}Context Summary Response
대화에 대한 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"
]
}Get Context Messages Response
모든 컨텍스트 메시지를 배열로 조회합니다.
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
]Export Context Response
컨텍스트 내보내기는 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/Clear Context Response
가져오기 및 초기화 작업은 void를 반환합니다.
// Import context
agent.importContext(jsonString);
// Returns: void
// Clear context
agent.clearContext();
// Returns: void마지막 업데이트: 2026년 7월 6일
이 섹션에서
소개
실제 작업을 효과적으로 해결하는 자율 시스템을 구축하기 위한 오픈소스 AI 에이전트 프레임워크입니다. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.
설치
npm, yarn, pnpm을 사용해 Astreus를 설치하고, 필요한 Node.js 버전을 확인한 다음 프레임워크로 AI 에이전트를 구축할 로컬 프로젝트를 준비합니다.
빠른 시작
Astreus 문서에서 빠른 시작에 대해 알아보고, 에이전트 시스템을 구축하기 위한 설정 안내, API 패턴, 실용적인 예제를 확인하세요. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.
에이전트
Astreus 문서에서 에이전트에 대해 알아보고, 에이전트 시스템을 구축하기 위한 설정 안내, API 패턴, 실용적인 예제를 확인하세요. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.