Astreus

지식

Astreus 문서에서 지식에 대해 알아보고, 에이전트 시스템을 구축하기 위한 설정 안내, API 패턴, 실용적인 예제를 확인하세요. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.

문서 처리와 벡터 검색을 결합한 RAG 통합

Overview

지식(Knowledge) 시스템은 검색 증강 생성(RAG) 기능을 제공하여 에이전트가 응답에 외부 문서를 활용할 수 있게 합니다. 문서를 자동으로 처리하고, 벡터 임베딩을 생성하며, 관련 정보에 대한 시맨틱 검색을 가능하게 합니다. 지식 기능을 갖춘 에이전트는 여러분의 문서를 기반으로 더 정확하고 맥락에 맞는 응답을 제공할 수 있습니다.

Enabling Knowledge

knowledge 옵션을 true로 설정하여 에이전트의 지식 기능을 활성화하세요.

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

const agent = await Agent.create({
  name: 'KnowledgeAgent',
  model: 'gpt-4o',
  knowledge: true,  // Enable knowledge base access (default: false)
  embeddingModel: 'text-embedding-3-small' // Optional: specify embedding model
});

Adding Documents

1

Add Text Content

문자열로 직접 콘텐츠를 추가하세요.

await agent.addKnowledge(
  'Your important content here',
  'Document Title',
  { category: 'documentation' }
);
2

Add from File

지원되는 파일 타입에서 콘텐츠를 추가하세요.

// Add PDF file
await agent.addKnowledgeFromFile(
  '/path/to/document.pdf',
  { source: 'manual', version: '1.0' }
);

// Add text file
await agent.addKnowledgeFromFile('/path/to/notes.txt');
3

Add from Directory

디렉터리 내 지원되는 모든 파일을 처리하세요.

await agent.addKnowledgeFromDirectory(
  '/path/to/docs',
  { project: 'documentation' }
);

Supported File Types

  • 텍스트 파일: .txt, .md, .json
  • PDF 파일: .pdf (텍스트 추출 지원)

How It Works

지식 시스템은 정교한 처리 파이프라인을 따릅니다.

1

Document Processing

문서는 메타데이터와 함께 지식 데이터베이스에 저장되고 색인됩니다.

2

Text Chunking

콘텐츠는 최적의 검색을 위해 청크(1500자, 300자 오버랩)로 분할됩니다.

오버랩은 컨텍스트 연속성을 보장합니다. overlap ratio=3001500=0.2=20%\text{overlap ratio} = \frac{300}{1500} = 0.2 = 20\%

이는 중요한 정보가 청크 경계에서 분할되는 것을 방지합니다.

3

Vector Embeddings

각 청크는 OpenAI, Gemini, Ollama 임베딩 모델을 사용해 벡터 임베딩으로 변환됩니다.

일반적인 임베딩 차원:

  • text-embedding-3-small: 1536차원 (OpenAI)
  • text-embedding-3-large: 3072차원 (OpenAI)
  • text-embedding-ada-002: 1536차원 (OpenAI)
  • text-embedding-004: 768차원 (Gemini)

벡터 간의 유클리드 거리도 사용할 수 있습니다. d(p,q)=i=1n(piqi)2d(\vec{p}, \vec{q}) = \sqrt{\sum_{i=1}^{n}(p_i - q_i)^2}

4

에이전트가 쿼리를 받으면, 코사인 유사도 검색을 사용해 관련 청크를 검색합니다.

쿼리와 문서 벡터 간의 유사도는 다음과 같이 계산됩니다.

cosine similarity=cos(θ)=ABAB=i=1nAiBii=1nAi2i=1nBi2\text{cosine similarity} = \cos(\theta) = \frac{\vec{A} \cdot \vec{B}}{||\vec{A}|| \cdot ||\vec{B}||} = \frac{\sum_{i=1}^{n} A_i B_i}{\sqrt{\sum_{i=1}^{n} A_i^2} \cdot \sqrt{\sum_{i=1}^{n} B_i^2}}

Where:

  • A\vec{A}는 쿼리 임베딩 벡터입니다
  • B\vec{B}는 문서 청크 임베딩 벡터입니다
  • 값이 클수록 (1에 가까울수록) 유사도가 높습니다
5

Context Integration

검색된 정보는 향상된 응답을 위해 에이전트의 컨텍스트에 자동으로 추가됩니다.

Example Usage

에이전트와 함께 지식 기능을 사용하는 완전한 예제입니다.

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

// Create agent with knowledge enabled
const agent = await Agent.create({
  name: 'DocumentAssistant',
  model: 'gpt-4o',
  knowledge: true,
  embeddingModel: 'text-embedding-3-small', // Optional: specify embedding model
  systemPrompt: 'You are a helpful assistant with access to company documentation.'
});

// Add documentation
await agent.addKnowledgeFromFile('./company-handbook.pdf', {
  type: 'handbook',
  department: 'hr'
});

await agent.addKnowledge(`
Our API uses REST principles with JSON responses.
Authentication is done via Bearer tokens.
Rate limiting is 1000 requests per hour.
`, 'API Documentation', {
  type: 'api-docs',
  version: '2.0'
});

// Query with automatic knowledge retrieval
const response = await agent.ask('What is our API rate limit?');
console.log(response);
// The agent will automatically search the knowledge base and include relevant context

// Manual knowledge search
const results = await agent.searchKnowledge('API authentication', 5, 0.7);
results.forEach(result => {
  console.log(`Similarity: ${result.similarity}`);
  console.log(`Content: ${result.content}`);
});

Managing Knowledge

Available Methods

// List all documents with metadata
const documents = await agent.getKnowledgeDocuments();
// Returns: Array<{ id: string; title: string; created_at: string }>

// Delete specific document by ID (documentId is UUID string)
const success = await agent.deleteKnowledgeDocument(documentId);
// Returns: boolean indicating success

// Delete specific chunk by ID (chunkId is UUID string)
const success = await agent.deleteKnowledgeChunk(chunkId);
// Returns: boolean indicating success

// Clear all knowledge for this agent
await agent.clearKnowledge();
// Returns: void

// Search with custom parameters
const results = await agent.searchKnowledge(
  'search query',
  10,    // limit: max results (default: 5)
  0.8    // threshold: similarity threshold (0-1, default: 0.7)
);
// Returns: Array<{ content: string; metadata: MetadataObject; similarity: number }>

// Get relevant context for a query
const context = await agent.getKnowledgeContext(
  'query text',
  5      // limit: max chunks to include (default: 5)
);
// Returns: string with concatenated relevant content

// Expand context around a specific chunk
const expandedChunks = await agent.expandKnowledgeContext(
  documentId,   // Document ID (UUID string)
  chunkIndex,   // Chunk index within document
  2,            // expandBefore: chunks to include before (default: 1)
  2             // expandAfter: chunks to include after (default: 1)
);
// Returns: Array<string> with expanded chunk content

Configuration

Environment Variables

# Database (required)
KNOWLEDGE_DB_URL=postgresql://user:password@host:port/database

# API key for embeddings
OPENAI_API_KEY=your_openai_key
# Or use dedicated embedding keys:
OPENAI_EMBEDDING_API_KEY=your_embedding_key
OPENAI_EMBEDDING_BASE_URL=https://api.openai.com/v1  # Optional: custom endpoint for embeddings
GEMINI_API_KEY=your_gemini_key
GEMINI_EMBEDDING_API_KEY=your_gemini_embedding_key

# For Ollama embeddings (local)
OLLAMA_BASE_URL=http://localhost:11434

Embedding Model Configuration

에이전트 설정에서 직접 임베딩 모델을 지정하세요.

const agent = await Agent.create({
  name: 'KnowledgeAgent',
  model: 'gpt-4o',
  embeddingModel: 'text-embedding-3-small',  // Specify embedding model here
  knowledge: true
});

Response Types

지식 메서드의 응답을 이해하면 데이터를 효과적으로 다룰 수 있습니다.

Add Knowledge Response

지식을 추가하면 생성된 문서의 UUID를 반환합니다.

const documentId = await agent.addKnowledge(
  "TypeScript is a typed superset of JavaScript...",
  "TypeScript Overview",
  { source: "documentation", version: "5.0" }
);

// Response: "550e8400-e29b-41d4-a716-446655440000" (UUID string)

Search Knowledge Response

검색은 콘텐츠, 메타데이터, 유사도 점수를 포함한 청크 배열을 반환합니다.

const results = await agent.searchKnowledge("TypeScript types", 5, 0.7);

// Response structure:
[
  {
    content: "TypeScript provides static typing which helps catch errors at compile time...",
    metadata: {
      title: "TypeScript Overview",
      source: "documentation",
      version: "5.0"
    },
    similarity: 0.95
  },
  {
    content: "Types in TypeScript include primitives like string, number, boolean...",
    metadata: {
      title: "Type System",
      source: "tutorial"
    },
    similarity: 0.87
  },
  {
    content: "Advanced types like generics and conditional types provide powerful abstractions...",
    metadata: {
      title: "Advanced Types",
      source: "documentation"
    },
    similarity: 0.79
  }
]

Get Knowledge Context Response

컨텍스트 조회는 관련 청크를 이어붙인 문자열을 반환합니다.

const context = await agent.getKnowledgeContext("TypeScript", 3);

// Response: concatenated string with separator
"TypeScript is a typed superset of JavaScript...\n\n---\n\nTypes help catch errors at compile time...\n\n---\n\nAdvanced types provide powerful abstractions..."

Get Knowledge Documents Response

문서 목록 조회는 저장된 모든 문서의 메타데이터를 반환합니다.

const documents = await agent.getKnowledgeDocuments();

// Response structure:
[
  {
    id: "doc-uuid-1",                      // UUID string
    title: "TypeScript Overview",
    created_at: "2024-01-15T10:30:00Z"    // ISO 8601 timestamp
  },
  {
    id: "doc-uuid-2",
    title: "Advanced Types",
    created_at: "2024-01-16T14:20:00Z"
  },
  {
    id: "doc-uuid-3",
    title: "Best Practices",
    created_at: "2024-01-17T09:15:00Z"
  }
]

Expand Knowledge Context Response

컨텍스트 확장은 청크 문자열의 배열을 반환합니다.

const chunks = await agent.expandKnowledgeContext("doc-uuid", 5, 2, 2);

// Response structure (plain chunk content):
[
  "Earlier context before the target chunk...",
  "More context leading to the target...",
  "This is the target chunk with the main content...",
  "Following context after the target...",
  "Additional context for full understanding..."
]

Delete Responses

삭제 작업은 성공 여부를 나타내는 불리언 값을 반환합니다.

// Delete specific document
const docDeleted = await agent.deleteKnowledgeDocument("doc-uuid");
// Returns: true or false

// Delete specific chunk
const chunkDeleted = await agent.deleteKnowledgeChunk("chunk-uuid");
// Returns: true or false

Clear Knowledge Response

모든 지식을 삭제하면 void를 반환합니다 (반환 값 없음).

await agent.clearKnowledge();
// Returns: void (undefined)

File Operations Response

파일 기반 지식 작업은 성공 시 void를 반환하고, 오류 시 예외를 던집니다.

// Add from file
await agent.addKnowledgeFromFile('./document.pdf', { source: 'manual' });
// Returns: void

// Add from directory
await agent.addKnowledgeFromDirectory('./docs', { project: 'main' });
// Returns: void

마지막 업데이트: 2026년 7월 6일