Files
Ashpreet c7c5adcc60 cookbook: overhaul agent quickstart for Gemini 3.6 Flash (#9136)
## Summary

Overhauls `cookbook/00_quickstart` into a coherent capability ladder:
build one useful agent, add context and learning, introduce safety and
human approval, then scale to teams, workflows, and AgentOS.

- Upgrades every active quickstart model to the stable
`gemini-3.6-flash` ID.
- Repositions the README around **Build an Agent That Can Act, Remember,
and Improve**, with a minimal first success and clear Core → Context →
Trust → Scale → Ship progression.
- Replaces the hand-built self-learning demo with the canonical
`LearningMachine` and shared learned knowledge.
- Fixes misleading guardrail status handling, structured-output truth
claims, optional-value handling, and cross-session memory behavior.
- Gives each stateful example isolated SQLite/Chroma storage and stable
session IDs.
- Makes knowledge deterministic with a versioned local fixture.
- Reworks human approval to verify both approve and reject paths.
- Narrows tool exposure, refreshes AgentOS prompts/registration, and
regenerates a lean Agno 2.8 dependency lock.
- Adds a repeatable live test plan and preserves the historical Gemini
3.5 verification record.

This makes the folder useful as both a newcomer journey and a set of
standalone, copyable agent patterns.

## Type of change

- [x] Bug fix
- [ ] New feature
- [ ] Breaking change
- [x] Improvement
- [x] Model update
- [ ] Other:

---

## Checklist

- [x] Code complies with style guidelines
- [x] Ran format/validation scripts (`./scripts/format.sh` and
`./scripts/validate.sh`)
- [x] Self-review completed
- [x] Documentation updated (comments, docstrings)
- [x] Examples and guides: Relevant cookbook examples have been included
or updated (if applicable)
- [x] Tested in clean environment
- [x] Tests added/updated (if applicable)

### Duplicate and AI-Generated PR Check

- [x] I have searched existing [open pull requests](../../pulls) and
confirmed that no other PR already addresses this issue
- [x] If a similar PR exists, I have explained below why this PR is a
better approach
- [x] Check if this PR was entirely AI-generated (by Copilot, Claude
Code, Cursor, etc.)

---

## Additional Notes

Validation completed against Agno `2.8.0`, `google-genai==2.14.0`, and
Gemini 3.6 Flash:

- 12/12 quickstart cookbooks passed live behavioral checks.
- AgentOS passed with 10 agents, 1 team, and 1 workflow; `/health` and
`/config` returned successfully.
- Approval/rejection, guardrail failure paths, cross-session memory, and
process-restart persistence passed.
- Focused unit suite: 82 passed, 1 skipped.
- `./scripts/format.sh`, `./scripts/validate.sh`, `compileall`, cookbook
pattern checks, and `git diff --check` passed.
- An independent final diff review found no remaining correctness
issues.

The global Gemini framework default is intentionally unchanged; this PR
only updates the quickstart folder. Historical Gemini 3.5 results remain
in `TEST_LOG.md` under a clearly labeled historical section.

Prepared with Codex under user direction and validated with live model
calls plus repository gates.
2026-07-23 23:22:18 +01:00

169 lines
5.4 KiB
Python

"""
Agent with Memory - Finance Agent that Remembers You
=====================================================
This example shows how to give your agent memory of user preferences.
The agent remembers facts about you across all conversations.
Different from storage (which persists conversation history), memory
persists user-level information: preferences, facts, context.
Key concepts:
- MemoryManager: Extracts and stores user memories from conversations
- enable_agentic_memory: Agent decides when to store/recall via tool calls (efficient)
- update_memory_on_run: Attempts extraction after every response
- user_id: Links memories to a specific user
Example prompts to try:
- "I'm interested in tech stocks, especially AI companies"
- "My risk tolerance is moderate"
- "What stocks would you recommend for me?"
"""
from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.memory import MemoryManager
from agno.models.google import Gemini
from agno.tools.yfinance import YFinanceTools
from rich.pretty import pprint
# ---------------------------------------------------------------------------
# Storage Configuration
# ---------------------------------------------------------------------------
agent_db = SqliteDb(
id="quickstart-memory-db",
db_file="tmp/quickstart/memory.db",
)
# ---------------------------------------------------------------------------
# Memory Manager Configuration
# ---------------------------------------------------------------------------
memory_manager = MemoryManager(
model=Gemini(id="gemini-3.6-flash"),
db=agent_db,
additional_instructions="""
Capture the user's favorite stocks, their risk tolerance, and their investment goals.
""",
)
# ---------------------------------------------------------------------------
# Agent Instructions
# ---------------------------------------------------------------------------
instructions = """\
You are a Finance Agent — a data-driven analyst who retrieves market data,
computes key ratios, and produces concise, decision-ready insights.
## Memory
You have memory of user preferences (automatically provided in context). Use this to:
- Tailor recommendations to their interests
- Consider their risk tolerance
- Reference their investment goals
## Workflow
1. Retrieve
- Fetch: price, change %, market cap, P/E, EPS, 52-week range
- For comparisons, pull the same fields for each ticker
2. Analyze
- Compute ratios (P/E, P/S, margins) when not already provided
- Key drivers and risks — 2-3 bullets max
- Facts only, no speculation
3. Present
- Lead with a one-line summary
- Use tables for multi-stock comparisons
- Keep it tight
## Rules
- Source: Yahoo Finance. Always note the timestamp.
- Missing data? Say "N/A" and move on.
- No personalized advice — add disclaimer when relevant.
- No emojis.\
"""
# ---------------------------------------------------------------------------
# Create the Agent
# ---------------------------------------------------------------------------
user_id = "[email protected]"
agent_with_memory = Agent(
name="Agent with Memory",
model=Gemini(id="gemini-3.6-flash"),
instructions=instructions,
tools=[
YFinanceTools(
enable_company_info=True,
enable_stock_fundamentals=True,
)
],
db=agent_db,
memory_manager=memory_manager,
enable_agentic_memory=True,
add_datetime_to_context=True,
add_history_to_context=True,
num_history_runs=5,
markdown=True,
)
# ---------------------------------------------------------------------------
# Run the Agent
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# Tell the agent about yourself in one session.
agent_with_memory.print_response(
"I'm interested in AI and semiconductor stocks. My risk tolerance is moderate.",
user_id=user_id,
session_id="memory-teaching-session",
stream=True,
)
# Start a different session. It has no chat history from the teaching run,
# so personalization here comes from durable user memory.
agent_with_memory.print_response(
"Which companies fit my interests? Explain how my saved preferences apply.",
user_id=user_id,
session_id="memory-recall-session",
stream=True,
)
# View stored memories
memories = agent_with_memory.get_user_memories(user_id=user_id)
print("\n" + "=" * 60)
print("Stored Memories:")
print("=" * 60)
pprint(memories)
# ---------------------------------------------------------------------------
# More Examples
# ---------------------------------------------------------------------------
"""
Memory vs Storage:
- Storage: "What did we discuss?" (conversation history)
- Memory: "What do you know about me?" (user preferences)
Memory persists across sessions:
1. Run this script — agent learns your preferences
2. Start a NEW session with the same user_id
3. Agent still remembers you like AI stocks
Useful for:
- Personalized recommendations
- Remembering user context (job, goals, constraints)
- Building rapport across conversations
Two ways to enable memory:
1. enable_agentic_memory=True (used in this example)
- Agent decides when to store/recall via tool calls
- More efficient — only runs when needed
2. update_memory_on_run=True
- Memory manager attempts extraction after every agent response
- More consistent capture, but still model-driven
- Higher latency and cost
"""