Knowledge Filters

Filter knowledge base searches using static filters or agentic filters.

1"""
2Knowledge Filters
3=============================
4
5Filter knowledge base searches using static filters or agentic filters.
6
7Static filters are set at agent creation time and apply to every search.
8Agentic filters let the agent dynamically choose filter values at runtime.
9"""
10
11from kern.agent import Agent
12from kern.filters import EQ
13from kern.knowledge.embedder.openai import OpenAIEmbedder
14from kern.knowledge.knowledge import Knowledge
15from kern.models.openai import OpenAIResponses
16from kern.vectordb.pgvector import PgVector, SearchType
17
18db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
19knowledge = Knowledge(
20 vector_db=PgVector(
21 table_name="recipes_filters_demo",
22 db_url=db_url,
23 search_type=SearchType.hybrid,
24 embedder=OpenAIEmbedder(id="text-embedding-3-small"),
25 ),
26)
27
28# ---------------------------------------------------------------------------
29# Create Agent With Static Filters
30# ---------------------------------------------------------------------------
31# Static filters: only retrieve documents matching these criteria
32agent_static = Agent(
33 model=OpenAIResponses(id="gpt-5.2"),
34 knowledge=knowledge,
35 search_knowledge=True,
36 # Use FilterExpr objects for type-safe filtering
37 knowledge_filters=[EQ("cuisine", "thai")],
38 markdown=True,
39)
40
41# ---------------------------------------------------------------------------
42# Create Agent With Agentic Filters
43# ---------------------------------------------------------------------------
44# Agentic filters: the agent decides filter values dynamically
45agent_agentic = Agent(
46 model=OpenAIResponses(id="gpt-5.2"),
47 knowledge=knowledge,
48 search_knowledge=True,
49 # Let the agent choose filter values based on the user's query
50 enable_agentic_knowledge_filters=True,
51 markdown=True,
52)
53
54# ---------------------------------------------------------------------------
55# Run Agent
56# ---------------------------------------------------------------------------
57if __name__ == "__main__":
58 knowledge.insert(url="https://kern-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf")
59
60 print("--- Static filters (cuisine=thai) ---")
61 agent_static.print_response(
62 "What soup recipes do you have?",
63 stream=True,
64 )
65
66 print("\n--- Agentic filters ---")
67 agent_agentic.print_response(
68 "Find me a Thai dessert recipe.",
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
9# Optiona: Run PgVector (needs docker)
10./cookbook/scripts/run_pgvector.sh
11
12python knowledge_filters.py