conversational-rag
Multi-turn RAG: chat history management, context window compaction (summarization, sliding window, vector memory), query rewriting with coreference resolution, follow-up vs new-query routing, LangChain ConversationalRetrievalChain, LlamaIndex ChatEngine, Redis/Postgres message history stores. USE WHEN: user mentions "conversational RAG", "multi-turn RAG", "chat history", "follow-up question", "chat memory", "ChatEngine", "ConversationalRetrievalChain", "coreference in RAG" DO NOT USE FOR: single-turn pipelines - use `rag-architecture`; query rewriting in isolation - use `query-transformations`; user-level long-term memory - use `personalization-rag`
What this skill does
# Conversational RAG
## The Core Problem
A retriever only sees the current query. In multi-turn chat the query is ambiguous without prior context:
```
User: What was revenue in Q3?
Bot: Revenue was $4.2M.
User: How did that compare to last year? <- "that" = Q3 revenue
```
Retrieving on "How did that compare to last year?" matches nothing. The retriever must see a reformulated, self-contained query.
## Pipeline
```
[history + current_q] -> [condenser LLM] -> [standalone_q] -> [retriever] -> [answer LLM(history, standalone_q, docs)]
```
Two LLM calls per turn: one cheap (Haiku) for condensation, one standard for synthesis.
## Query Condensation (Haiku)
```python
from anthropic import Anthropic
client = Anthropic()
CONDENSE_PROMPT = """Given the conversation so far and the latest user message,
rewrite the latest message as a standalone question that can be understood without
the prior messages. Resolve pronouns and elliptical references. If the latest
message is already standalone, return it unchanged.
Conversation:
{history}
Latest message: {question}
Standalone question:"""
def condense(history: list[dict], question: str) -> str:
hist_str = "\n".join(f"{m['role']}: {m['content']}" for m in history[-8:])
msg = client.messages.create(
model="claude-haiku-4-5-20250929",
max_tokens=256,
messages=[{"role": "user", "content": CONDENSE_PROMPT.format(
history=hist_str, question=question)}],
)
return msg.content[0].text.strip()
```
Keep only the last 8 turns in the condenser prompt — older turns rarely affect coreference and inflate cost.
## Follow-up vs New Query Routing
Not every turn needs retrieval. Classify first, retrieve only when needed.
```python
from pydantic import BaseModel
from typing import Literal
from langchain_anthropic import ChatAnthropic
class TurnType(BaseModel):
kind: Literal["follow_up", "new_query", "chit_chat", "meta"]
needs_retrieval: bool
llm = ChatAnthropic(model="claude-haiku-4-5-20250929").with_structured_output(TurnType)
def classify(history, question) -> TurnType:
return llm.invoke(
f"Classify the latest message.\nHistory: {history[-4:]}\nLatest: {question}"
)
```
`meta` (e.g. "summarize our conversation", "what did you say earlier") does not require retrieval. `chit_chat` ("thanks!") either.
## History Compaction Strategies
| Strategy | Keeps | Token Cost | Loses | Best For |
|---|---|---|---|---|
| Full transcript | Everything | Unbounded | Nothing | Short sessions |
| Sliding window | Last N turns | Bounded | Early context | Most chatbots |
| Summary buffer | Rolling summary + last N | Bounded | Detail in old turns | Long sessions with continuity |
| Vector memory | Retrieved past turns | Bounded | Linearity | Returning users |
| Hierarchical | Summary of summaries | Bounded | Recency | Very long sessions |
### Sliding Window
```python
def sliding_window(history: list[dict], n: int = 10) -> list[dict]:
return history[-n:]
```
### Summary Buffer (LangChain 0.3+ via LangGraph)
```python
from langgraph.graph import MessagesState, StateGraph
from langchain_core.messages import RemoveMessage, SystemMessage
SUMMARY_AFTER = 20 # messages
def maybe_summarize(state: MessagesState):
msgs = state["messages"]
if len(msgs) <= SUMMARY_AFTER:
return {}
to_summarize = msgs[:-8]
summary = llm.invoke(
[SystemMessage("Summarize the prior conversation in <= 300 words."),
*to_summarize]
).content
removals = [RemoveMessage(id=m.id) for m in to_summarize]
return {"messages": [SystemMessage(f"Summary so far: {summary}"), *removals]}
```
### Vector Memory (retrieve relevant past turns)
```python
from langchain_qdrant import QdrantVectorStore
from langchain_openai import OpenAIEmbeddings
mem_store = QdrantVectorStore.from_documents([], OpenAIEmbeddings(), collection_name="chat_mem")
def remember(session_id: str, turn: dict):
mem_store.add_texts([turn["content"]], metadatas=[{"session_id": session_id, **turn}])
def recall(session_id: str, query: str, k: int = 3):
return mem_store.similarity_search(query, k=k, filter={"session_id": session_id})
```
Best paired with a sliding window of the immediate turns — vector memory catches long-range callbacks while recency is handled verbatim.
## LangChain 0.3+ Conversational Retrieval (LCEL)
`ConversationalRetrievalChain` is deprecated. The idiomatic pattern uses `create_history_aware_retriever` + `create_retrieval_chain`.
```python
from langchain.chains import create_history_aware_retriever, create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
condense_prompt = ChatPromptTemplate.from_messages([
("system", "Given the chat history and latest question, rewrite it as standalone."),
MessagesPlaceholder("chat_history"),
("human", "{input}"),
])
history_aware_retriever = create_history_aware_retriever(llm, retriever, condense_prompt)
qa_prompt = ChatPromptTemplate.from_messages([
("system", "Answer using the context. Cite [source_id].\n\nContext:\n{context}"),
MessagesPlaceholder("chat_history"),
("human", "{input}"),
])
qa_chain = create_stuff_documents_chain(llm, qa_prompt)
rag_chain = create_retrieval_chain(history_aware_retriever, qa_chain)
result = rag_chain.invoke({"input": "How did that compare to last year?",
"chat_history": prior_messages})
```
## LlamaIndex ChatEngine
```python
from llama_index.core.chat_engine import CondensePlusContextChatEngine
from llama_index.core.memory import ChatMemoryBuffer
from llama_index.llms.anthropic import Anthropic
memory = ChatMemoryBuffer.from_defaults(token_limit=4000)
chat_engine = CondensePlusContextChatEngine.from_defaults(
retriever=index.as_retriever(similarity_top_k=5),
llm=Anthropic(model="claude-sonnet-4-5-20250929"),
memory=memory,
context_prompt=(
"Context:\n{context_str}\n\n"
"Answer using context; cite [id]. If insufficient, say so."
),
)
response = chat_engine.chat("How did that compare to last year?")
```
Modes:
- `condense_plus_context` — condense + retrieve + answer (best default).
- `context` — retrieve on raw query only (misses coreference).
- `condense_question` — condense + retrieve, no chat history in answer prompt.
- `react` — ReAct with retrieval as a tool; handles multi-hop follow-ups.
## Message History Stores
### Redis (production default)
```python
from langchain_community.chat_message_histories import RedisChatMessageHistory
def get_history(session_id: str):
return RedisChatMessageHistory(
session_id=session_id,
url="redis://localhost:6379/0",
ttl=60 * 60 * 24 * 7, # 7 day TTL
)
```
Set a TTL. Chat history is PII — expire it.
### Postgres
```python
from langchain_postgres import PostgresChatMessageHistory
import psycopg
conn = psycopg.connect("postgresql://...")
PostgresChatMessageHistory.create_tables(conn, "chat_history")
def get_history(session_id: str):
return PostgresChatMessageHistory("chat_history", session_id, sync_connection=conn)
```
Use Postgres when you need to query history (analytics, audit, compliance).
### LangGraph Checkpointer (state + history together)
```python
from langgraph.checkpoint.postgres import PostgresSaver
checkpointer = PostgresSaver.from_conn_string("postgresql://...")
checkpointer.setup()
app = graph.compile(checkpointer=checkpointer)
config = {"configurable": {"thread_id": session_id}}
app.invoke({"messages": [("human", question)]}, config=config)
```
Preferred for agentic conversational RAG — state survives restarts and can be replayed.
## TypeScript (Vercel AI SDK)
```ts
import { streamText, convertToCoreMessages } from 'ai';
import { anthropic } from '@ai-sdkRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.