Saturday, March 15, 2025

#5 - Structured-Output

 Example 5: Structured Output 

Step 1: Create structured_ouput.py

from agno.agent import Agent
from pydantic import BaseModel, Field
from rich.pretty import pprint  # noqa
from agno.models.ollama import Ollama
from ollama import Client as OllamaClient

class MovieScript(BaseModel):
    setting: str = Field(
        ..., description="Provide a nice setting for a blockbuster movie."
    )
    ending: str = Field(
        ...,
        description="Ending of the movie. If not available, provide a happy ending.",
    )
    genre: str = Field(
        ...,
        description="Genre of the movie. If not available, select action, thriller or romantic comedy.",
    )
    name: str = Field(..., description="Give a name to this movie")
    characters: list[str] = Field(..., description="Name of characters for this movie.")
    storyline: str = Field(
        ..., description="3 sentence storyline for the movie. Make it exciting!"
    )


# Agent that uses JSON mode
json_mode_agent = Agent(
    # model=OpenAIChat(id="gpt-4o"),
    model=Ollama(id="llama3.2", client=OllamaClient()),
    description="You write movie scripts.",
    response_model=MovieScript,
)

# Agent that uses structured outputs
structured_output_agent = Agent(
    # model=OpenAIChat(id="gpt-4o-2024-08-06"),
    model=Ollama(id="llama3.2", client=OllamaClient()),
    description="You write movie scripts.",
    response_model=MovieScript,
    structured_outputs=True,
)


# Get the response in a variable
# json_mode_response: RunResponse = json_mode_agent.run("New York")
# pprint(json_mode_response.content)
# structured_output_response: RunResponse = structured_
output_agent.run("New York")
# pprint(structured_output_response.content)

json_mode_agent.print_response("New York")
structured_output_agent.print_response("New York")

Expected Response

┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                                                                                                ┃
┃ New York                                                                                                                                       ┃
┃                                                                                                                                                ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Response (26.6s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                                                                                                ┃
┃ {                                                                                                                                              ┃
┃   "setting": {                                                                                                                                 ┃
┃     "description": "Provide a nice setting for a blockbuster movie.",                                                                          ┃
┃     "type": "string"                                                                                                                           ┃
┃   },                                                                                                                                           ┃
┃   "ending": {                                                                                                                                  ┃
┃     "description": "Ending of the movie. If not available, provide a happy ending.",                                                           ┃
┃     "type": "string"                                                                                                                           ┃
┃   },                                                                                                                                           ┃
┃   "genre": {                                                                                                                                   ┃
┃     "description": "Genre of the movie. If not available, select action, thriller or romantic comedy.",                                        ┃
┃     "type": "string"                                                                                                                           ┃
┃   },                                                                                                                                           ┃
┃   "name": {                                                                                                                                    ┃
┃     "description": "Give a name to this movie",                                                                                                ┃
┃     "type": "string"                                                                                                                           ┃
┃   },                                                                                                                                           ┃
┃   "characters": {                                                                                                                              ┃
┃     "description": "Name of characters for this movie.",                                                                                       ┃
┃     "items": {                                                                                                                                 ┃
┃       "type": "string"                                                                                                                         ┃
┃     },                                                                                                                                         ┃
┃     "type": "array"                                                                                                                            ┃
┃   },                                                                                                                                           ┃
┃   "storyline": {                                                                                                                               ┃
┃     "description": "3 sentence storyline for the movie. Make it exciting!",                                                                    ┃
┃     "type": "string"                                                                                                                           ┃
┃   }                                                                                                                                            ┃
┃ }                                                                                                                                              ┃
┃                                                                                                                                                ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                                                                                                ┃
┃ New York                                                                                                                                       ┃
┃                                                                                                                                                ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
┏━ Response (11.0s) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                                                                                                                                                ┃
┃ {                                                                                                                                              ┃
┃   "setting": "A bustling New York City street, with towering skyscrapers and endless energy. The sound of car horns, chatter, and wailing sire ┃
┃   "ending": "The sun sets over the Manhattan skyline, casting a golden glow over the city's concrete jungle as our protagonist walks alone int ┃
┃   "genre": "Drama/Mystery",                                                                                                                    ┃
┃   "name": "City of Secrets",                                                                                                                   ┃
┃   "characters": [                                                                                                                              ┃
┃     "Jen",                                                                                                                                     ┃
┃     "Mike"                                                                                                                                     ┃
┃   ],                                                                                                                                           ┃
┃   "storyline": "A young journalist discovers a hidden world of corruption and deceit in New York City, leading her on a perilous journey to un ┃
┃ }                                                                                                                                              ┃
┃                                                                                                                                                ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

....2 b continued....

#4 -Basic-Stream Agent

 Example 4:  Basic Streaming 

Step 1: Create basic_stream.py

from typing import Iterator  
from agno.agent import Agent, RunResponse
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.models.ollama import Ollama
from ollama import Client as OllamaClient

agent = Agent(
    model=Ollama(id="llama3.2", client=OllamaClient()),
)

# Get the response in a variable
run_response: Iterator[RunResponse] = agent.run("Share a 2
sentence about Quantum Computing", stream=True)
for chunk in run_response:
    print(chunk.content)

# Print the response in the terminal
agent.print_response("Share a 2 sentence about Quantum computing",
stream=True)

Expected Response

Quantum computing is a revolutionary technology that uses the principles of quantum 
mechanics to perform calculations exponentially faster than classical computers. 
By harnessing qubits and quantum gates, quantum computers can process vast amounts 
of information in parallel, leading to breakthroughs in cryptography, optimization, 
and simulation.

#3 - Agent [Tool_Usage]

Example 3: Using DuckDuckGo Search Tool

Step 1: Create tool_usage.py

from agno.agent import Agent
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.agent import Agent
from agno.models.ollama import Ollama
from ollama import Client as OllamaClient

agent = Agent(
    model=Ollama(id="llama3.2", client=OllamaClient()),
    tools=[DuckDuckGoTools()],
    show_tool_calls=True,
    markdown=True,
)
   
agent.print_response("What's happening in India?", stream=True)

Step 2: Install Dependencies

pip install duckduckgo duckduckgo-search

python.exe -m pip install --upgrade pip

Expected Response

Running: duckduckgo_search(max_results=5, query=India news)
Current Events in India:

- Latest India news can be found on websites such as Times of India, Hindustan Times, 
India Today, and Indian Express.
- Breaking news updates are available on various news portals and online platforms.


#2 - Basic Agent

 Example 2: Creating a Basic Agent with Metrics

Step 1: Create basic_agent.py

Create a new file named basic_agent.py and add the following code:

from agno.agent import Agent, RunResponse  # noqa
from agno.models.ollama import Ollama
from agno.tools.yfinance import YFinanceTools
from ollama import Client as OllamaClient

agent = Agent(
    model=Ollama(id="llama3.2", client=OllamaClient()),
    tools=[YFinanceTools(stock_price=True)],
    markdown=True,
)

# Print the response in the terminal
agent.print_response("Share a 2 sentence joke on quantum computing")
print(agent.run_response.metrics)


Step 2: Run the Script

python basic_agent.py

Expected Response

Response:

It seems like the previous response didn't quite work out as expected. Here's another attempt at a 2-sentence joke about quantum computing:    

Why did the qubit go to therapy? It was struggling to stay in its superposition of emotions! 

{'input_tokens': [193, 116], 'output_tokens': [152, 51], 'total_tokens': [345, 167], 'prompt_tokens': [0, 0], 'completion_tokens': [0, 0], 'additional_metrics': [{'total_duration': 15560175500, 'load_duration': 19980900, 'prompt_eval_duration': 4270000000, 'eval_duration': 11266000000}, {'total_duration': 5288854300, 'load_duration': 24048600, 'prompt_eval_duration': 1524000000, 'eval_duration': 3737000000}], 'time': [15.564438400000654, 5.28971300000012]}

Understanding the Metrics

  • Input and Output Tokens: The number of tokens processed.
  • Total Tokens: The sum of input and output tokens.
  • Additional Metrics: Execution duration in nanoseconds.
  • Time: Execution time in seconds.

Conclusion

These examples provide a solid foundation for working with Agno agents. You can build upon these scripts by adding more tools, modifying prompts, or integrating additional AI capabilities. Happy coding!

Stay tuned for more tutorials on AI-driven automation!

#1 - Client Agent

Agents Tutorial: Building an AI Agent with Agnos

Introduction

In this tutorial, we will explore how to build an AI agent using Agnos and integrate it with the Llama 3.2 model. We will also use YFinanceTools to fetch stock prices. By the end of this guide, you will have a working AI agent that can generate responses and fetch stock market data.

References

Hands-On Implementation

Step 1: Create a Workspace

First, create a new folder for your project:

mkdir agents && cd agents

Step 2: Create the Python Script

Inside the workspace, create a new file named client.py and add the following code:

from agno.agent import Agent, RunResponse  # noqa
from agno.models.ollama import Ollama
from agno.tools.yfinance import YFinanceTools
from ollama import Client as OllamaClient

agent = Agent(
    model=Ollama(id="llama3.2", client=OllamaClient()),
    tools=[YFinanceTools(stock_price=True)],
    markdown=True,
)

# Print the response in the terminal
agent.print_response("Share a 2 sentence joke on quantum computing")

Step 3: Set Up the Virtual Environment

To keep dependencies organized, create a virtual environment:

python3 -m venv .venv
source .venv/bin/activate  # On Windows, use `.venv\Scripts\activate`

Step 4: Install Dependencies

Install the required libraries using:

pip install -U ollama yfinance agno

Step 5: Download the Llama 3.2 Model

Before running the agent, download the Llama 3.2 model:

ollama pull llama3.2

Step 6: Run the AI Agent

Execute the script to see the agent in action:

python client.py

Expected Response

Response:

I see what happened! It looks like the "tell_joke" function is not available in this context. Let me try again:

Why did the qubit go to therapy? Because it was feeling a little "entangled"!

Conclusion

In this tutorial, we successfully: ✅ Set up an AI agent using Agnos
✅ Integrated the Llama 3.2 model
✅ Added a stock market tool with YFinanceTools
✅ Ran a test command to generate a response

For more details, visit the official Agnos Documentation. 🚀

#5 - Structured-Output

 Example 5: Structured Output  Step 1: Create structured_ouput.py from agno . agent import Agent from pydantic import BaseModel , Fiel...