Custom Retriever
Use knowledge_retriever to provide a custom retrieval function.
1"""2Custom Retriever3=============================45Use knowledge_retriever to provide a custom retrieval function.67Instead of using a Knowledge instance, you can supply your own callable8that returns documents. The agent will use it as its search_knowledge_base tool.9"""1011from typing import List, Optional1213from kern.agent import Agent14from kern.models.openai import OpenAIResponses1516# ---------------------------------------------------------------------------17# Custom Retriever Function18# ---------------------------------------------------------------------------19# A simple in-memory retriever for demonstration.20# In production, this could call an external API, database, or search engine.21DOCUMENTS = [22 {23 "title": "Python Basics",24 "content": "Python is a high-level programming language known for its readability.",25 },26 {27 "title": "TypeScript Intro",28 "content": "TypeScript adds static typing to JavaScript.",29 },30 {31 "title": "Rust Overview",32 "content": "Rust is a systems language focused on safety and performance.",33 },34]353637def my_retriever(38 query: str, num_documents: Optional[int] = None, **kwargs39) -> Optional[List[dict]]:40 """Search documents by simple keyword matching."""41 query_lower = query.lower()42 results = [43 doc44 for doc in DOCUMENTS45 if query_lower in doc["content"].lower() or query_lower in doc["title"].lower()46 ]47 if num_documents:48 results = results[:num_documents]49 return results if results else None505152# ---------------------------------------------------------------------------53# Create Agent54# ---------------------------------------------------------------------------55agent = Agent(56 model=OpenAIResponses(id="gpt-5.2"),57 # Use a custom retriever instead of a Knowledge instance58 knowledge_retriever=my_retriever,59 # search_knowledge is True by default when knowledge_retriever is set60 markdown=True,61)6263# ---------------------------------------------------------------------------64# Run Agent65# ---------------------------------------------------------------------------66if __name__ == "__main__":67 agent.print_response(68 "Tell me about Python.",69 stream=True,70 )Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/07_knowledge45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python custom_retriever.py