Skip to content

Commit f11df7c

Browse files
authored
Merge pull request #17 from pamelafox/session2-tweaks
Tweak examples for session 2
2 parents 375d180 + e7bed60 commit f11df7c

20 files changed

Lines changed: 120 additions & 244 deletions

examples/agent_history_redis.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ async def example_persistent_session() -> None:
6363
session_id = str(uuid.uuid4())
6464

6565
# Phase 1: Start a conversation with a Redis-backed history provider
66-
print("[dim]--- Phase 1: Starting conversation ---[/dim]")
66+
print("[bold]--- Phase 1: Starting conversation ---[/bold]")
6767
redis_provider = RedisHistoryProvider(source_id="redis_chat", redis_url=REDIS_URL)
6868

6969
agent = Agent(
@@ -84,7 +84,7 @@ async def example_persistent_session() -> None:
8484
print(f"[green]Agent:[/green] {response.text}")
8585

8686
# Phase 2: Simulate an application restart — reconnect using the same session ID in Redis
87-
print("\n[dim]--- Phase 2: Resuming after 'restart' ---[/dim]")
87+
print("\n[bold]--- Phase 2: Resuming after 'restart' ---[/bold]")
8888
redis_provider2 = RedisHistoryProvider(source_id="redis_chat", redis_url=REDIS_URL)
8989

9090
agent2 = Agent(
@@ -99,7 +99,6 @@ async def example_persistent_session() -> None:
9999
print("[blue]User:[/blue] Which of the cities I asked about had better weather?")
100100
response = await agent2.run("Which of the cities I asked about had better weather?", session=session2)
101101
print(f"[green]Agent:[/green] {response.text}")
102-
print("[dim]Note: The agent remembered the conversation from Phase 1 via Redis persistence.[/dim]")
103102

104103

105104
async def main() -> None:
@@ -111,17 +110,15 @@ async def main() -> None:
111110
try:
112111
r.ping()
113112
except Exception as e:
114-
print(f"[red]Cannot connect to Redis at {REDIS_URL}: {e}[/red]")
115-
print(
116-
"[red]Ensure Redis is running (e.g. via the dev container"
117-
" or 'docker run -p 6379:6379 redis:7-alpine').[/red]"
113+
logger.error(f"Cannot connect to Redis at {REDIS_URL}: {e}")
114+
logger.error(
115+
"Ensure Redis is running (e.g. via the dev container"
116+
" or 'docker run -p 6379:6379 redis:7-alpine')."
118117
)
119118
return
120119
finally:
121120
r.close()
122121

123-
print("[dim]Redis connection verified.[/dim]")
124-
125122
await example_persistent_session()
126123

127124
if async_credential:

examples/agent_history_sqlite.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ async def main() -> None:
111111

112112
# Phase 1: Start a conversation with a SQLite-backed history provider
113113
print("\n[bold]=== Persistent SQLite Session ===[/bold]")
114-
print("[dim]--- Phase 1: Starting conversation ---[/dim]")
114+
print("[bold]--- Phase 1: Starting conversation ---[/bold]")
115115

116116
sqlite_provider = SQLiteHistoryProvider(db_path=db_path)
117117

@@ -132,12 +132,8 @@ async def main() -> None:
132132
response = await agent.run("How about Paris?", session=session)
133133
print(f"[green]Agent:[/green] {response.text}")
134134

135-
messages = await sqlite_provider.get_messages(session_id)
136-
print(f"[dim]Messages stored in SQLite: {len(messages)}[/dim]")
137-
sqlite_provider.close()
138-
139135
# Phase 2: Simulate an application restart — reconnect to the same session ID in SQLite
140-
print("\n[dim]--- Phase 2: Resuming after 'restart' ---[/dim]")
136+
print("\n[bold]--- Phase 2: Resuming after 'restart' ---[/bold]")
141137
sqlite_provider2 = SQLiteHistoryProvider(db_path=db_path)
142138

143139
agent2 = Agent(
@@ -152,7 +148,6 @@ async def main() -> None:
152148
print("[blue]User:[/blue] Which of the cities I asked about had better weather?")
153149
response = await agent2.run("Which of the cities I asked about had better weather?", session=session2)
154150
print(f"[green]Agent:[/green] {response.text}")
155-
print("[dim]Note: The agent remembered the conversation from Phase 1 via SQLite persistence.[/dim]")
156151

157152
sqlite_provider2.close()
158153

examples/agent_knowledge_pg_rewrite.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -411,9 +411,6 @@ async def main() -> None:
411411
like "protective jackets and boots for hiking in snow".
412412
"""
413413
print("\n[bold]=== Knowledge Retrieval with Query Rewriting ===[/bold]")
414-
print("[dim]In multi-turn conversations, the LLM rewrites the search query[/dim]")
415-
print("[dim]using full conversation context for better retrieval.[/dim]\n")
416-
417414
session = agent.create_session()
418415

419416
# Turn 1: User asks about rain protection on rocky paths

examples/agent_knowledge_postgres.py

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -342,24 +342,13 @@ def setup_db() -> psycopg.Connection:
342342
async def main() -> None:
343343
"""Demonstrate hybrid search RAG with several queries."""
344344
print("\n[bold]=== Knowledge Retrieval (RAG) with PostgreSQL Hybrid Search ===[/bold]")
345-
print("[dim]The agent uses pgvector (semantic) + tsvector (keyword) with RRF before each LLM call.[/dim]\n")
346345

347346
# Query 1: Should match hiking boots and trekking poles
348347
print("[blue]User:[/blue] I'm planning a hiking trip. What boots and poles do you recommend?")
349348
response = await agent.run("I'm planning a hiking trip. What boots and poles do you recommend?")
350349
print(f"[green]Agent:[/green] {response.text}\n")
351350

352-
# Query 2: Should match the down jacket
353-
print("[blue]User:[/blue] I need something warm for winter camping, maybe a jacket?")
354-
response = await agent.run("I need something warm for winter camping, maybe a jacket?")
355-
print(f"[green]Agent:[/green] {response.text}\n")
356-
357-
# Query 3: Should match the kayak paddle (semantic match — "water sports gear")
358-
print("[blue]User:[/blue] What water sports gear do you carry?")
359-
response = await agent.run("What water sports gear do you carry?")
360-
print(f"[green]Agent:[/green] {response.text}\n")
361-
362-
# Query 4: Semantic match — "gadgets for wildlife watching" → binoculars
351+
# Query 2: Semantic match — "gadgets for wildlife watching" → binoculars
363352
print("[blue]User:[/blue] I want gadgets for wildlife watching")
364353
response = await agent.run("I want gadgets for wildlife watching")
365354
print(f"[green]Agent:[/green] {response.text}\n")

examples/agent_knowledge_sqlite.py

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -294,23 +294,12 @@ async def main() -> None:
294294
"""Demonstrate the knowledge retrieval (RAG) pattern with several queries."""
295295
# Query 1: Should match hiking boots and trekking poles
296296
print("\n[bold]=== Knowledge Retrieval (RAG) Demo ===[/bold]")
297-
print("[dim]The agent searches a SQLite FTS5 knowledge base before each LLM call.[/dim]\n")
298297

299298
print("[blue]User:[/blue] I'm planning a hiking trip. What boots and poles do you recommend?")
300299
response = await agent.run("I'm planning a hiking trip. What boots and poles do you recommend?")
301300
print(f"[green]Agent:[/green] {response.text}\n")
302301

303-
# Query 2: Should match the down jacket
304-
print("[blue]User:[/blue] I need something warm for winter camping, maybe a jacket?")
305-
response = await agent.run("I need something warm for winter camping, maybe a jacket?")
306-
print(f"[green]Agent:[/green] {response.text}\n")
307-
308-
# Query 3: Should match the kayak paddle
309-
print("[blue]User:[/blue] Do you sell anything for kayaking?")
310-
response = await agent.run("Do you sell anything for kayaking?")
311-
print(f"[green]Agent:[/green] {response.text}\n")
312-
313-
# Query 4: No match expected — demonstrates graceful "no knowledge" handling
302+
# Query 2: No match expected — demonstrates graceful "no knowledge" handling
314303
print("[blue]User:[/blue] Do you have any surfboards?")
315304
response = await agent.run("Do you have any surfboards?")
316305
print(f"[green]Agent:[/green] {response.text}\n")

examples/agent_memory_mem0.py

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,31 @@ async def main() -> None:
110110
},
111111
},
112112
}
113+
elif API_HOST == "github":
114+
# Use GitHub Models for both Mem0's LLM and embedder
115+
mem0_config = {
116+
"llm": {
117+
"provider": "openai",
118+
"config": {
119+
"model": os.getenv("GITHUB_MODEL", "openai/gpt-4.1-mini"),
120+
"api_key": os.environ["GITHUB_TOKEN"],
121+
"openai_base_url": "https://models.github.ai/inference",
122+
},
123+
},
124+
"embedder": {
125+
"provider": "openai",
126+
"config": {
127+
"model": "openai/text-embedding-3-small",
128+
"api_key": os.environ["GITHUB_TOKEN"],
129+
"openai_base_url": "https://models.github.ai/inference",
130+
},
131+
},
132+
}
113133
elif os.getenv("OPENAI_API_KEY"):
114134
mem0_config = {} # Mem0 defaults to OpenAI via OPENAI_API_KEY
115135
else:
116-
print("[red]Mem0 OSS requires an LLM for memory extraction.[/red]")
117-
print("[red]Set API_HOST=azure (with Azure OpenAI) or set OPENAI_API_KEY.[/red]")
136+
logger.error("Mem0 OSS requires an LLM for memory extraction.")
137+
logger.error("Set API_HOST=azure (with Azure OpenAI) or set OPENAI_API_KEY.")
118138
return
119139

120140
mem0_client = await AsyncMemory.from_config(mem0_config)
@@ -132,27 +152,25 @@ async def main() -> None:
132152
)
133153

134154
# Step 1: Teach the agent user preferences
135-
print("\n[dim]--- Step 1: Teaching preferences ---[/dim]")
155+
print("\n[bold]--- Step 1: Teaching preferences ---[/bold]")
136156
print("[blue]User:[/blue] Remember that my favorite city is Tokyo and I prefer Celsius.")
137157
response = await agent.run("Remember that my favorite city is Tokyo and I prefer Celsius.")
138158
print(f"[green]Agent:[/green] {response.text}")
139159

140160
# Step 2: Start a new session — Mem0 should inject remembered facts
141-
print("\n[dim]--- Step 2: New session — recalling preferences ---[/dim]")
161+
print("\n[bold]--- Step 2: New session — recalling preferences ---[/bold]")
142162
print("[blue]User:[/blue] What's my favorite city?")
143163
response = await agent.run("What's my favorite city?")
144164
print(f"[green]Agent:[/green] {response.text}")
145-
print("[dim]Note: Mem0 extracted and stored facts, then injected them into the new session.[/dim]")
146165

147166
# Step 3: Use a tool, demonstrating memory with tool outputs
148-
print("\n[dim]--- Step 3: Tool use with memory ---[/dim]")
167+
print("\n[bold]--- Step 3: Tool use with memory ---[/bold]")
149168
print("[blue]User:[/blue] What's the weather in my favorite city?")
150169
response = await agent.run("What's the weather in my favorite city?")
151170
print(f"[green]Agent:[/green] {response.text}")
152-
print("[dim]Note: The agent used Mem0 memory to know which city to check.[/dim]")
153171

154172
# Show what Mem0 has stored
155-
print("\n[dim]--- Extracted memories ---[/dim]")
173+
print("\n[bold]--- Extracted memories ---[/bold]")
156174
memories = await mem0_client.get_all(user_id=user_id)
157175
for mem in memories.get("results", []):
158176
print(f" [cyan]•[/cyan] {mem.get('memory', '')}")

examples/agent_memory_redis.py

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -96,19 +96,19 @@ async def example_agent_with_memory() -> None:
9696
)
9797

9898
# Step 1: Teach the agent a user preference
99-
print("\n[dim]--- Step 1: Teaching a preference ---[/dim]")
99+
print("\n[bold]--- Step 1: Teaching a preference ---[/bold]")
100100
print("[blue]User:[/blue] Remember that my favorite city is Tokyo.")
101101
response = await agent.run("Remember that my favorite city is Tokyo.")
102102
print(f"[green]Agent:[/green] {response.text}")
103103

104104
# Step 2: Ask the agent to recall the preference from memory
105-
print("\n[dim]--- Step 2: Recalling a preference ---[/dim]")
105+
print("\n[bold]--- Step 2: Recalling a preference ---[/bold]")
106106
print("[blue]User:[/blue] What's my favorite city?")
107107
response = await agent.run("What's my favorite city?")
108108
print(f"[green]Agent:[/green] {response.text}")
109109

110110
# Step 3: Use a tool, then verify the agent remembers tool output details
111-
print("\n[dim]--- Step 3: Tool use with memory ---[/dim]")
111+
print("\n[bold]--- Step 3: Tool use with memory ---[/bold]")
112112
print("[blue]User:[/blue] What's the weather in Paris?")
113113
response = await agent.run("What's the weather in Paris?")
114114
print(f"[green]Agent:[/green] {response.text}")
@@ -119,21 +119,6 @@ async def example_agent_with_memory() -> None:
119119

120120

121121
async def main() -> None:
122-
"""Run the Redis memory example."""
123-
# Verify Redis has RediSearch module
124-
import redis as redis_client
125-
126-
r = redis_client.from_url(REDIS_URL)
127-
try:
128-
r.execute_command("FT._LIST")
129-
except Exception:
130-
print(f"[red]Redis at {REDIS_URL} does not have the RediSearch module.[/red]")
131-
return
132-
finally:
133-
r.close()
134-
135-
print("[dim]Redis Stack with RediSearch verified.[/dim]")
136-
137122
await example_agent_with_memory()
138123

139124
if async_credential:

examples/agent_session.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,13 @@ async def example_without_session() -> None:
6262
"""Without a session, each call is independent — the agent has no memory of prior messages."""
6363
print("\n[bold]=== Without Session (No Memory) ===[/bold]")
6464

65-
response = await agent.run("What's the weather like in Seattle?")
6665
print(f"[blue]User:[/blue] What's the weather like in Seattle?")
66+
response = await agent.run("What's the weather like in Seattle?")
6767
print(f"[green]Agent:[/green] {response.text}")
6868

69-
response = await agent.run("What was the last city I asked about?")
7069
print(f"\n[blue]User:[/blue] What was the last city I asked about?")
70+
response = await agent.run("What was the last city I asked about?")
7171
print(f"[green]Agent:[/green] {response.text}")
72-
print("[dim]Note: Each call creates a separate session, so the agent doesn't remember previous context.[/dim]")
73-
7472

7573
async def example_with_session() -> None:
7674
"""With a session, the agent maintains context across multiple messages."""
@@ -89,7 +87,6 @@ async def example_with_session() -> None:
8987
print(f"\n[blue]User:[/blue] Which of those cities has better weather?")
9088
response = await agent.run("Which of those cities has better weather?", session=session)
9189
print(f"[green]Agent:[/green] {response.text}")
92-
print("[dim]Note: The agent remembers context from previous messages in the same session.[/dim]")
9390

9491

9592
async def example_session_across_agents() -> None:
@@ -112,7 +109,6 @@ async def example_session_across_agents() -> None:
112109
print(f"\n[blue]User:[/blue] What was the last city I asked about?")
113110
response = await agent2.run("What was the last city I asked about?", session=session)
114111
print(f"[green]Agent 2:[/green] {response.text}")
115-
print("[dim]Note: The second agent continues the conversation using the session's message history.[/dim]")
116112

117113

118114
async def main() -> None:

examples/redis_viewer.py

Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import redis
99
from dotenv import load_dotenv
1010
from rich import print
11-
from rich.console import Group
1211
from rich.panel import Panel
1312
from rich.syntax import Syntax
1413
from rich.text import Text
@@ -57,34 +56,21 @@
5756

5857
elif key_type == "list":
5958
items = r.lrange(key, 0, -1)
60-
panels = []
61-
for i, item in enumerate(items):
59+
parts = []
60+
for item in items:
6261
raw = item.decode()
6362
try:
64-
parsed = json.loads(raw)
65-
role = parsed.get("role", {}).get("value", "unknown")
66-
contents = parsed.get("contents", [])
67-
# Extract display text
68-
parts = []
69-
for c in contents:
70-
if c.get("type") == "text":
71-
parts.append(c["text"])
72-
elif c.get("type") == "function_call":
73-
parts.append(f"[tool call] {c['name']}({c['arguments']})")
74-
elif c.get("type") == "function_result":
75-
parts.append(f"[tool result] {c['result']}")
76-
display = "\n".join(parts) if parts else json.dumps(parsed, indent=2)
77-
color = {"user": "blue", "assistant": "green", "tool": "yellow"}.get(role, "white")
78-
panels.append(
79-
Panel(display, title=f"[bold {color}]{role}[/bold {color}] [dim]({i + 1}/{len(items)})[/dim]")
80-
)
63+
formatted = json.dumps(json.loads(raw), indent=2)
8164
except json.JSONDecodeError:
82-
panels.append(Panel(raw, title=f"[dim]item {i + 1}/{len(items)}[/dim]"))
65+
formatted = raw
66+
parts.append(formatted)
67+
combined = "\n---\n".join(parts)
68+
content = Syntax(combined, "json", theme="monokai", word_wrap=True)
8369
print(
8470
Panel(
85-
Group(*panels),
71+
content,
8672
title=f"[bold cyan]{key}[/bold cyan] [dim]({key_type})[/dim]",
87-
subtitle=f"[dim]{len(items)} message(s)[/dim]",
73+
subtitle=f"[dim]{len(items)} item(s)[/dim]",
8874
)
8975
)
9076

examples/spanish/agent_history_redis.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ async def example_persistent_session() -> None:
6363
session_id = str(uuid.uuid4())
6464

6565
# Fase 1: Iniciar una conversación con un proveedor de historial en Redis
66-
print("[dim]--- Fase 1: Iniciando conversación ---[/dim]")
66+
print("[bold]--- Fase 1: Iniciando conversación ---[/bold]")
6767
redis_provider = RedisHistoryProvider(source_id="redis_chat", redis_url=REDIS_URL)
6868

6969
agent = Agent(
@@ -84,7 +84,7 @@ async def example_persistent_session() -> None:
8484
print(f"[green]Agente:[/green] {response.text}")
8585

8686
# Fase 2: Simular un reinicio de la app — reconectar usando el mismo session_id en Redis
87-
print("\n[dim]--- Fase 2: Reanudando después del 'reinicio' ---[/dim]")
87+
print("\n[bold]--- Fase 2: Reanudando después del 'reinicio' ---[/bold]")
8888
redis_provider2 = RedisHistoryProvider(source_id="redis_chat", redis_url=REDIS_URL)
8989

9090
agent2 = Agent(
@@ -99,7 +99,6 @@ async def example_persistent_session() -> None:
9999
print("[blue]Usuario:[/blue] ¿Cuál de las ciudades por las que pregunté tuvo mejor clima?")
100100
response = await agent2.run("¿Cuál de las ciudades por las que pregunté tuvo mejor clima?", session=session2)
101101
print(f"[green]Agente:[/green] {response.text}")
102-
print("[dim]Nota: El agente recordó la conversación de la Fase 1 gracias a la persistencia en Redis.[/dim]")
103102

104103

105104
async def main() -> None:
@@ -111,17 +110,15 @@ async def main() -> None:
111110
try:
112111
r.ping()
113112
except Exception as e:
114-
print(f"[red]No se puede conectar a Redis en {REDIS_URL}: {e}[/red]")
115-
print(
116-
"[red]Asegúrate de que Redis esté corriendo (por ejemplo, con el dev container"
117-
" o con 'docker run -p 6379:6379 redis:7-alpine').[/red]"
113+
logger.error(f"No se puede conectar a Redis en {REDIS_URL}: {e}")
114+
logger.error(
115+
"Asegúrate de que Redis esté corriendo (por ejemplo, con el dev container"
116+
" o con 'docker run -p 6379:6379 redis:7-alpine')."
118117
)
119118
return
120119
finally:
121120
r.close()
122121

123-
print("[dim]Conexión a Redis verificada.[/dim]")
124-
125122
await example_persistent_session()
126123

127124
if async_credential:

0 commit comments

Comments
 (0)