Custom Retriever

Use knowledge_retriever to provide a custom retrieval function.

1"""
2Custom Retriever
3=============================
4
5Use knowledge_retriever to provide a custom retrieval function.
6
7Instead of using a Knowledge instance, you can supply your own callable
8that returns documents. The agent will use it as its search_knowledge_base tool.
9"""
10
11from typing import List, Optional
12
13from kern.agent import Agent
14from kern.models.openai import OpenAIResponses
15
16# ---------------------------------------------------------------------------
17# Custom Retriever Function
18# ---------------------------------------------------------------------------
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]
35
36
37def my_retriever(
38 query: str, num_documents: Optional[int] = None, **kwargs
39) -> Optional[List[dict]]:
40 """Search documents by simple keyword matching."""
41 query_lower = query.lower()
42 results = [
43 doc
44 for doc in DOCUMENTS
45 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 None
50
51
52# ---------------------------------------------------------------------------
53# Create Agent
54# ---------------------------------------------------------------------------
55agent = Agent(
56 model=OpenAIResponses(id="gpt-5.2"),
57 # Use a custom retriever instead of a Knowledge instance
58 knowledge_retriever=my_retriever,
59 # search_knowledge is True by default when knowledge_retriever is set
60 markdown=True,
61)
62
63# ---------------------------------------------------------------------------
64# Run Agent
65# ---------------------------------------------------------------------------
66if __name__ == "__main__":
67 agent.print_response(
68 "Tell me about Python.",
69 stream=True,
70 )

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/07_knowledge
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python custom_retriever.py