rag
БесплатноБез исполняемых скриптовНе проверенUse when building Retrieval-Augmented Generation systems - covers document ingestion, hybrid search retrieval, reranking results, and prompt augmentation for…
от majiayu000★ 31 звезда на GitHubОб этом скилле
LLMemory RAG Systems
Installation
uv add llmemory
# For reranking support
uv add "llmemory[reranker-local]" # Local cross-encoder models
# or configure OpenAI reranking (no extra install needed)
Overview
Retrieval-Augmented Generation (RAG) combines llmemory's document retrieval with LLM generation for accurate, grounded responses.
RAG Pipeline:
- Ingest: Add documents to llmemory
- Retrieve: Search for relevant chunks
- Rerank: Improve relevance ordering (optional but recommended)
- Augment: Build prompt with retrieved context
- Generate: Get LLM response
When to use RAG:
- Question answering over your documents
- Customer support with knowledge base
- Research assistance
- Code documentation search
- Any application needing accurate, source-backed answers
Quick Start
from llmemory import LLMemory, SearchType, DocumentType
from openai import AsyncOpenAI
async def rag_system():
# Initialize
memory = LLMemory(
connection_string="postgresql://localhost/mydb",
openai_api_key="sk-..."
)
await memory.initialize()
# 1. Ingest documents
await memory.add_document(
owner_id="workspace-1",
id_at_origin="kb",
document_name="product_guide.md",
document_type=DocumentType.MARKDOWN,
content="Your product documentation..."
)
# 2. Retrieve with reranking
results = await memory.search(
owner_id="workspace-1",
query_text="how to reset password",
search_type=SearchType.HYBRID,
query_expansion=True, # Better retrieval
rerank=True, # Better ranking
rerank_top_k=50, # Rerank top 50 candidates
rerank_return_k=10, # Prefer 10 best after reranking
limit=5 # Final result count (max of limit and rerank_return_k)
)
# 3. Build prompt with context
context = "\n\n".join([
f"Source: {r.metadata.get('source', 'unknown')}\n{r.content}"
for r in results
])
prompt = f"""Answer the question using only the provided context.
Context:
{context}
Question: how to reset password
Answer:"""
# 4. Generate response
client = AsyncOpenAI()
response = await client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}]
)
print(response.choices[0].message.content)
await memory.close()
import asyncio
asyncio.run(rag_system())
Query Routing for Production RAG
Production RAG systems should detect when queries cannot be answered from available documents.
When to use query routing:
- User queries may be unanswerable from your knowledge base
- Need to route to web search or external APIs
- Want to avoid hallucinated answers
- Building conversational assistants
Example:
from llmemory import LLMemory
async with LLMemory(connection_string="...") as memory:
# Search with automatic routing
result = await memory.search_with_routing(
owner_id="workspace-1",
query_text="What's the current weather in Paris?",
enable_routing=True,
limit=5
)
if result["route"] == "retrieval":
# Answer from documents
return generate_answer(result["results"])
elif result["route"] == "web_search":
# Route to web search
return fetch_from_web(query)
elif result["route"] == "unanswerable":
# Honest response
return "I don't have information to answer that question."
else: # clarification
return "Could you please provide more details?"
API Reference:
search_with_routing()
Route queries intelligently before searching.
Signature:
async def search_with_routing(
owner_id: str,
query_text: str,
enable_routing: bool = True,
routing_threshold: float = 0.7,
**search_kwargs
) -> Dict[str, Any]
Parameters:
owner_id(str): Owner identifierquery_text(str): Search queryenable_routing(bool, default: True): Enable automatic routingrouting_threshold(float, default: 0.7): Confidence threshold**search_kwargs: Additional arguments passed to search()
Returns: Dict with:
route(str): "retrieval", "web_search", "unanswerable", or "clarification"confidence(float): 0-1 confidence in routing decisionresults(List[SearchResult]): If route="retrieval"message(str): If route != "retrieval"reason(str): Explanation of routing decision
Example:
result = await memory.search_with_routing(
owner_id="support",
query_text="How do I reset my password?",
routing_threshold=0.8
)
if result["route"] == "retrieval":
answer = generate_rag_response(result["results"])
else:
answer = result["message"] # Pre-formatted response
Complete RAG Pipeline
Step 1: Document Ingestion
from llmemory import LLMemory, DocumentType, ChunkingConfig, LLMemoryConfi
Установить rag в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл rag?
Use when building Retrieval-Augmented Generation systems - covers document ingestion, hybrid search retrieval, reranking results, and prompt augmentation for accurate LLM responses grounded in your knowledge base
Как установить скилл rag?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл rag запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic