Wissen
RAG-Integration mit Dokumentenverarbeitung und Vektorsuche Lerne die Einrichtungsmuster, APIs und praktischen Beispiele kennen, die du zum Aufbau...
RAG-Integration mit Dokumentenverarbeitung und Vektorsuche
Übersicht
Das Knowledge-System bietet Retrieval-Augmented-Generation-Funktionen (RAG), mit denen Agenten auf externe Dokumente zugreifen und diese in ihren Antworten nutzen können. Es verarbeitet Dokumente automatisch, erstellt Vektor-Embeddings und ermöglicht semantische Suche nach relevanten Informationen. Agenten mit Knowledge können genauere, kontextbezogene Antworten auf Basis deiner Dokumente liefern.
Knowledge aktivieren
Aktiviere Knowledge für einen Agenten, indem du die Option knowledge auf true setzt:
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
});Dokumente hinzufügen
Textinhalt hinzufügen
Füge Inhalte direkt als String hinzu:
await agent.addKnowledge(
'Your important content here',
'Document Title',
{ category: 'documentation' }
);Aus Datei hinzufügen
Füge Inhalte aus unterstützten Dateitypen hinzu:
// 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');Aus Verzeichnis hinzufügen
Verarbeite alle unterstützten Dateien in einem Verzeichnis:
await agent.addKnowledgeFromDirectory(
'/path/to/docs',
{ project: 'documentation' }
);Unterstützte Dateitypen
- Textdateien:
.txt,.md,.json - PDF-Dateien:
.pdf(mit Textextraktion)
Funktionsweise
Das Knowledge-System folgt einer ausgeklügelten Verarbeitungspipeline:
Dokumentenverarbeitung
Dokumente werden mit Metadaten in der Knowledge-Datenbank gespeichert und indiziert.
Text-Chunking
Inhalte werden für optimales Retrieval in Abschnitte (1500 Zeichen mit 300 Zeichen Überlappung) unterteilt.
Die Überlappung sorgt für Kontextkontinuität:
Dies verhindert, dass wichtige Informationen über Chunk-Grenzen hinweg aufgeteilt werden.
Vektor-Embeddings
Jeder Chunk wird mithilfe von OpenAI-, Gemini- oder Ollama-Embedding-Modellen in Vektor-Embeddings umgewandelt.
Gängige Embedding-Dimensionen:
text-embedding-3-small: 1536 Dimensionen (OpenAI)text-embedding-3-large: 3072 Dimensionen (OpenAI)text-embedding-ada-002: 1536 Dimensionen (OpenAI)text-embedding-004: 768 Dimensionen (Gemini)
Die euklidische Distanz zwischen Vektoren kann ebenfalls verwendet werden:
Semantische Suche
Wenn Agenten Anfragen erhalten, werden relevante Chunks mittels Cosine-Similarity-Suche abgerufen.
Die Ähnlichkeit zwischen Query- und Dokumentvektoren wird wie folgt berechnet:
Dabei gilt:
- ist der Query-Embedding-Vektor
- ist der Embedding-Vektor des Dokumenten-Chunks
- Höhere Werte (näher an 1) zeigen größere Ähnlichkeit an
Kontextintegration
Abgerufene Informationen werden automatisch dem Kontext des Agenten hinzugefügt, um bessere Antworten zu ermöglichen.
Beispiel für die Verwendung
Hier ist ein vollständiges Beispiel für die Verwendung von Knowledge mit einem Agenten:
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}`);
});Knowledge verwalten
Verfügbare Methoden
// 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 contentKonfiguration
Umgebungsvariablen
# 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:11434Konfiguration des Embedding-Modells
Gib das Embedding-Modell direkt in der Agent-Konfiguration an:
const agent = await Agent.create({
name: 'KnowledgeAgent',
model: 'gpt-4o',
embeddingModel: 'text-embedding-3-small', // Specify embedding model here
knowledge: true
});Antworttypen
Das Verständnis der Antworten von Knowledge-Methoden hilft dir, effektiv mit den Daten zu arbeiten.
Add-Knowledge-Antwort
Das Hinzufügen von Knowledge gibt die UUID des erstellten Dokuments zurück:
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-Antwort
Die Suche gibt ein Array von Chunks mit Inhalt, Metadaten und Ähnlichkeitswerten zurück:
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-Antwort
Der Kontextabruf gibt einen verketteten String relevanter Chunks zurück:
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-Antwort
Das Auflisten von Dokumenten gibt Metadaten für alle gespeicherten Dokumente zurück:
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-Antwort
Die Kontexterweiterung gibt ein Array von Chunk-Strings zurück:
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..."
]Lösch-Antworten
Löschoperationen geben boolesche Werte zurück, die den Erfolg anzeigen:
// 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 falseClear-Knowledge-Antwort
Das Löschen des gesamten Knowledge-Bestands gibt void zurück (kein Rückgabewert):
await agent.clearKnowledge();
// Returns: void (undefined)Antwort auf Dateioperationen
Dateibasierte Knowledge-Operationen geben bei Erfolg void zurück oder werfen bei einem Fehler eine Exception:
// Add from file
await agent.addKnowledgeFromFile('./document.pdf', { source: 'manual' });
// Returns: void
// Add from directory
await agent.addKnowledgeFromDirectory('./docs', { project: 'main' });
// Returns: voidZuletzt aktualisiert: 6. Juli 2026
In diesem Abschnitt
Einführung
Open-Source-KI-Agent-Framework zum Erstellen autonomer Systeme, die reale Aufgaben effektiv lösen.
Installation
Installiere Astreus mit npm, yarn oder pnpm, überprüfe die erforderliche Node.js-Version und bereite ein lokales Projekt für die Entwicklung von KI-Agenten...
Schnellstart
Erstelle deinen ersten KI-Agenten mit Astreus in unter 2 Minuten Lerne die Einrichtungsmuster, APIs und praktischen Beispiele kennen, die du zum Aufbau...
Agent
Zentrale KI-Entität mit modularen Fähigkeiten und dekoratorbasierter Komposition Lerne die Einrichtungsmuster, APIs und praktischen Beispiele kennen, die du...