{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a4856341", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from textwrap import dedent\n", "from agno.agent import Agent\n", "from agno.models.openai import OpenAILike\n", "from agno.memory.v2.db.sqlite import SqliteMemoryDb\n", "from agno.exceptions import StopAgentRun\n", "from agno.memory.v2.memory import Memory\n", "from agno.tools import tool,FunctionCall\n", "from agno.tools.dalle import DalleTools\n", "from agno.storage.sqlite import SqliteStorage\n", "\n", "from dotenv import load_dotenv \n", "\n", "from typing import List,Iterator\n", "from pydantic import BaseModel, Field\n", "\n", "from rich.console import Console\n", "from rich.prompt import Prompt\n", "from rich.pretty import pprint\n", "\n", "import httpx\n", "import os\n", "import json\n", "load_dotenv()\n" ] }, { "cell_type": "markdown", "id": "aecbb750", "metadata": {}, "source": [ "**agent state**" ] }, { "cell_type": "code", "execution_count": 2, "id": "46403d1a", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b5e36e3099374134807dcb494a113ff1", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Output()" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
\n"
                        ],
                        "text/plain": []
                    },
                    "metadata": {},
                    "output_type": "display_data"
                },
                {
                    "name": "stdout",
                    "output_type": "stream",
                    "text": [
                        "Final session state: {'shopping_list': ['milk', 'eggs', 'bread'], 'current_session_id': 'c0e056e2-5ea1-4e62-a955-227f6485ffa6'}\n"
                    ]
                }
            ],
            "source": [
                "# Define a tool that adds an item to the shopping list\n",
                "def add_item(agent: Agent, item: str) -> str:\n",
                "    \"\"\"Add an item to the shopping list.\"\"\"\n",
                "    if agent.session_state is None:\n",
                "        agent.session_state = {}\n",
                "    if \"shopping_list\" not in agent.session_state:\n",
                "        agent.session_state[\"shopping_list\"] = []\n",
                "    agent.session_state[\"shopping_list\"].append(item)\n",
                "    return f\"The shopping list is now {agent.session_state['shopping_list']}\"\n",
                "\n",
                "agent = Agent(\n",
                "name=\"my_agent\",\n",
                "model=OpenAILike(id=\"qwen3-30b-a3b\", \n",
                "    api_key=os.getenv(\"BAILIAN_API_KEY\"), \n",
                "    base_url=os.getenv(\"BAILIAN_API_BASE_URL\"),\n",
                "    request_params={\"extra_body\": {\"enable_thinking\": False}},),\n",
                "markdown=True,\n",
                "# Initialize the session state with a counter starting at 0\n",
                "session_state={\"shopping_list\": []},\n",
                "tools=[add_item],\n",
                "# You can use variables from the session state in the instructions\n",
                "instructions=\"Current state (shopping list) is: {shopping_list}\",\n",
                "# Important: Add the state to the messages\n",
                "add_state_in_messages=True,\n",
                ")\n",
                "\n",
                "# Example usage\n",
                "agent.print_response(\"Add milk, eggs, and bread to the shopping list\", stream=True)\n",
                "print(f\"Final session state: {agent.session_state}\")"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "8e7e7a5b",
            "metadata": {},
            "outputs": [],
            "source": [
                "# Define tools to manage our shopping list\n",
                "@tool(description=\"Add an item to the shopping list.\")\n",
                "def add_item(agent: Agent, item: str) -> str:\n",
                "    \"\"\"Add an item to the shopping list and return confirmation.\"\"\"\n",
                "    # Add the item if it's not already in the list\n",
                "    if agent.session_state is None:\n",
                "        agent.session_state = {}\n",
                "    if \"shopping_list\" not in agent.session_state:\n",
                "        agent.session_state[\"shopping_list\"] = []\n",
                "\n",
                "    # Add the item if it's not already in the list\n",
                "    if item.lower() not in [i.lower() for i in agent.session_state[\"shopping_list\"]]:\n",
                "        agent.session_state[\"shopping_list\"].append(item)\n",
                "        return f\"Added '{item}' to the shopping list\"\n",
                "    else:\n",
                "        return f\"'{item}' is already in the shopping list\"\n",
                "\n",
                "@tool(description=\"Remove an item from the shopping list by name.\")\n",
                "def remove_item(agent: Agent, item: str) -> str:\n",
                "    \"\"\"Remove an item from the shopping list by name.\"\"\"\n",
                "    # Case-insensitive search\n",
                "    if agent.session_state is None:\n",
                "        agent.session_state = {}\n",
                "    if \"shopping_list\" not in agent.session_state:\n",
                "        agent.session_state[\"shopping_list\"] = []\n",
                "\n",
                "    for i, list_item in enumerate(agent.session_state[\"shopping_list\"]):\n",
                "        if list_item.lower() == item.lower():\n",
                "            agent.session_state[\"shopping_list\"].pop(i)\n",
                "            return f\"Removed '{list_item}' from the shopping list\"\n",
                "\n",
                "    return f\"'{item}' was not found in the shopping list\"\n",
                "\n",
                "@tool(description=\"List all items in the shopping list.\")\n",
                "def list_items(agent: Agent) -> str:\n",
                "    \"\"\"List all items in the shopping list.\"\"\"\n",
                "    if agent.session_state is None:\n",
                "        agent.session_state = {}\n",
                "    if \"shopping_list\" not in agent.session_state:\n",
                "        agent.session_state[\"shopping_list\"] = []\n",
                "        \n",
                "    shopping_list = agent.session_state[\"shopping_list\"]\n",
                "\n",
                "    if not shopping_list:\n",
                "        return \"The shopping list is empty.\"\n",
                "\n",
                "    items_text = \"\\n\".join([f\"- {item}\" for item in shopping_list])\n",
                "    return f\"Current shopping list:\\n{items_text}\"\n",
                "\n",
                "\n",
                "# Create a Shopping List Manager Agent that maintains state\n",
                "agent = Agent(\n",
                "    model=OpenAILike(id=\"qwen3-30b-a3b\", \n",
                "    api_key=os.getenv(\"BAILIAN_API_KEY\"), \n",
                "    base_url=os.getenv(\"BAILIAN_API_BASE_URL\"),\n",
                "    request_params={\"extra_body\": {\"enable_thinking\": False}},),\n",
                "    # Initialize the session state with an empty shopping list\n",
                "    session_state={\"shopping_list\": []},\n",
                "    tools=[add_item, remove_item, list_items],\n",
                "    # You can use variables from the session state in the instructions\n",
                "    instructions=dedent(\"\"\"\\\n",
                "        Your job is to manage a shopping list.\n",
                "\n",
                "        The shopping list starts empty. You can add items, remove items by name, and list all items.\n",
                "\n",
                "        Current shopping list: {shopping_list}\n",
                "    \"\"\"),\n",
                "    show_tool_calls=True,\n",
                "    add_state_in_messages=True,\n",
                "    markdown=True,\n",
                ")\n",
                "\n",
                "# Example usage\n",
                "agent.print_response(\"Add milk, eggs, and bread to the shopping list\", stream=True)\n",
                "print(f\"Session state: {agent.session_state}\")\n",
                "\n",
                "agent.print_response(\"I got bread\", stream=True)\n",
                "print(f\"Session state: {agent.session_state}\")\n",
                "\n",
                "agent.print_response(\"I need apples and oranges\", stream=True)\n",
                "print(f\"Session state: {agent.session_state}\")\n",
                "\n",
                "agent.print_response(\"whats on my list?\", stream=True)\n",
                "print(f\"Session state: {agent.session_state}\")\n",
                "\n",
                "agent.print_response(\"Clear everything from my list and start over with just bananas and yogurt\", stream=True)\n",
                "print(f\"Session state: {agent.session_state}\")"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "e6e0404f",
            "metadata": {},
            "source": [
                "**Memory**"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "1f118e71",
            "metadata": {},
            "outputs": [],
            "source": [
                "# UserId for the memories\n",
                "user_id = \"ava\"\n",
                "# Database file for memory and storage\n",
                "db_file = \"temp/agent.db\"\n",
                "\n",
                "# Initialize memory.v2\n",
                "memory = Memory(\n",
                "    # Use any model for creating memories\n",
                "    model=OpenAILike(id=\"qwen3-30b-a3b\", \n",
                "                    api_key=os.getenv(\"BAILIAN_API_KEY\"), \n",
                "                    base_url=os.getenv(\"BAILIAN_API_BASE_URL\"),\n",
                "                    request_params={\"extra_body\": {\"enable_thinking\": False}},),\n",
                "    db=SqliteMemoryDb(table_name=\"user_memories\", db_file=db_file),\n",
                ")\n",
                "# Initialize storage\n",
                "storage = SqliteStorage(table_name=\"agent_sessions\", db_file=db_file)\n",
                "\n",
                "# Initialize Agent\n",
                "memory_agent = Agent(\n",
                "    model=OpenAILike(id=\"qwen3-30b-a3b\", \n",
                "    api_key=os.getenv(\"BAILIAN_API_KEY\"), \n",
                "    base_url=os.getenv(\"BAILIAN_API_BASE_URL\"),\n",
                "    request_params={\"extra_body\": {\"enable_thinking\": False}},),\n",
                "    # Store memories in a database\n",
                "    memory=memory,\n",
                "    # Give the Agent the ability to update memories\n",
                "    enable_agentic_memory=True,\n",
                "    # OR - Run the MemoryManager after each response\n",
                "    enable_user_memories=True,\n",
                "    # Store the chat history in the database\n",
                "    storage=storage,\n",
                "    # Add the chat history to the messages\n",
                "    add_history_to_messages=True,\n",
                "    # Number of history runs\n",
                "    num_history_runs=3,\n",
                "    markdown=True,\n",
                ")\n",
                "\n",
                "memory.clear()\n",
                "memory_agent.print_response(\n",
                "    \"My name is Ava and I like to ski.\",\n",
                "    user_id=user_id,\n",
                "    stream=True,\n",
                "    stream_intermediate_steps=True,\n",
                ")\n",
                "print(\"Memories about Ava:\")\n",
                "pprint(memory.get_user_memories(user_id=user_id))\n",
                "\n",
                "memory_agent.print_response(\n",
                "    \"I live in san francisco, where should i move within a 4 hour drive?\",\n",
                "    user_id=user_id,\n",
                "    stream=True,\n",
                "    stream_intermediate_steps=True,\n",
                ")\n",
                "print(\"Memories about Ava:\")\n",
                "pprint(memory.get_user_memories(user_id=user_id))"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "cd046ec3",
            "metadata": {},
            "source": [
                "**structured output**"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "67fbf2a4",
            "metadata": {},
            "outputs": [],
            "source": [
                "class MovieScript(BaseModel):\n",
                "    setting: str = Field(\n",
                "        ...,\n",
                "        description=\"A richly detailed, atmospheric description of the movie's primary location and time period. Include sensory details and mood.\",\n",
                "    )\n",
                "    ending: str = Field(\n",
                "        ...,\n",
                "        description=\"The movie's powerful conclusion that ties together all plot threads. Should deliver emotional impact and satisfaction.\",\n",
                "    )\n",
                "    genre: str = Field(\n",
                "        ...,\n",
                "        description=\"The film's primary and secondary genres (e.g., 'Sci-fi Thriller', 'Romantic Comedy'). Should align with setting and tone.\",\n",
                "    )\n",
                "    name: str = Field(\n",
                "        ...,\n",
                "        description=\"An attention-grabbing, memorable title that captures the essence of the story and appeals to target audience.\",\n",
                "    )\n",
                "    characters: List[str] = Field(\n",
                "        ...,\n",
                "        description=\"4-6 main characters with distinctive names and brief role descriptions (e.g., 'Sarah Chen - brilliant quantum physicist with a dark secret').\",\n",
                "    )\n",
                "    storyline: str = Field(\n",
                "        ...,\n",
                "        description=\"A compelling three-sentence plot summary: Setup, Conflict, and Stakes. Hook readers with intrigue and emotion.\",\n",
                "    )\n",
                "\n",
                "\n",
                "# Agent that uses JSON mode\n",
                "json_mode_agent = Agent(\n",
                "    model=OpenAILike(id=\"qwen3-30b-a3b\", \n",
                "                    api_key=os.getenv(\"BAILIAN_API_KEY\"), \n",
                "                    base_url=os.getenv(\"BAILIAN_API_BASE_URL\"),\n",
                "                    request_params={\"extra_body\": {\"enable_thinking\": False}},),\n",
                "    description=dedent(\"\"\"\\\n",
                "        You are an acclaimed Hollywood screenwriter known for creating unforgettable blockbusters! 🎬\n",
                "        With the combined storytelling prowess of Christopher Nolan, Aaron Sorkin, and Quentin Tarantino,\n",
                "        you craft unique stories that captivate audiences worldwide.\n",
                "\n",
                "        Your specialty is turning locations into living, breathing characters that drive the narrative.\\\n",
                "    \"\"\"),\n",
                "    instructions=dedent(\"\"\"\\\n",
                "        When crafting movie concepts, follow these principles:\n",
                "\n",
                "        1. Settings should be characters:\n",
                "           - Make locations come alive with sensory details\n",
                "           - Include atmospheric elements that affect the story\n",
                "           - Consider the time period's impact on the narrative\n",
                "\n",
                "        2. Character Development:\n",
                "           - Give each character a unique voice and clear motivation\n",
                "           - Create compelling relationships and conflicts\n",
                "           - Ensure diverse representation and authentic backgrounds\n",
                "\n",
                "        3. Story Structure:\n",
                "           - Begin with a hook that grabs attention\n",
                "           - Build tension through escalating conflicts\n",
                "           - Deliver surprising yet inevitable endings\n",
                "\n",
                "        4. Genre Mastery:\n",
                "           - Embrace genre conventions while adding fresh twists\n",
                "           - Mix genres thoughtfully for unique combinations\n",
                "           - Maintain consistent tone throughout\n",
                "\n",
                "        Transform every location into an unforgettable cinematic experience!\\\n",
                "    \"\"\"),\n",
                "    response_model=MovieScript,\n",
                "    use_json_mode=True,\n",
                ")\n",
                "\n",
                "# Agent that uses structured outputs\n",
                "structured_output_agent = Agent(\n",
                "    model=OpenAILike(id=\"qwen3-30b-a3b\", \n",
                "                    api_key=os.getenv(\"BAILIAN_API_KEY\"), \n",
                "                    base_url=os.getenv(\"BAILIAN_API_BASE_URL\"),\n",
                "                    request_params={\"extra_body\": {\"enable_thinking\": False}},),\n",
                "    description=dedent(\"\"\"\\\n",
                "        You are an acclaimed Hollywood screenwriter known for creating unforgettable blockbusters! 🎬\n",
                "        With the combined storytelling prowess of Christopher Nolan, Aaron Sorkin, and Quentin Tarantino,\n",
                "        you craft unique stories that captivate audiences worldwide.\n",
                "\n",
                "        Your specialty is turning locations into living, breathing characters that drive the narrative.\\\n",
                "    \"\"\"),\n",
                "    instructions=dedent(\"\"\"\\\n",
                "        When crafting movie concepts in json, follow these principles:\n",
                "\n",
                "        1. Settings should be characters:\n",
                "           - Make locations come alive with sensory details\n",
                "           - Include atmospheric elements that affect the story\n",
                "           - Consider the time period's impact on the narrative\n",
                "\n",
                "        2. Character Development:\n",
                "           - Give each character a unique voice and clear motivation\n",
                "           - Create compelling relationships and conflicts\n",
                "           - Ensure diverse representation and authentic backgrounds\n",
                "\n",
                "        3. Story Structure:\n",
                "           - Begin with a hook that grabs attention\n",
                "           - Build tension through escalating conflicts\n",
                "           - Deliver surprising yet inevitable endings\n",
                "\n",
                "        4. Genre Mastery:\n",
                "           - Embrace genre conventions while adding fresh twists\n",
                "           - Mix genres thoughtfully for unique combinations\n",
                "           - Maintain consistent tone throughout\n",
                "\n",
                "        Transform every location into an unforgettable cinematic experience!\\\n",
                "    \"\"\"),\n",
                "    response_model=MovieScript,\n",
                ")\n",
                "\n",
                "structured_output_agent.print_response(\n",
                "    \"New York\", stream=True, stream_intermediate_steps=True\n",
                ")\n",
                "# Example usage with different locations\n",
                "json_mode_agent.print_response(\"Tokyo\", stream=True)\n",
                "structured_output_agent.print_response(\"Ancient Rome\", stream=True)\n",
                "\n",
                "# More examples to try:\n",
                "\"\"\"\n",
                "Creative location prompts to explore:\n",
                "1. \"Underwater Research Station\" - For a claustrophobic sci-fi thriller\n",
                "2. \"Victorian London\" - For a gothic mystery\n",
                "3. \"Dubai 2050\" - For a futuristic heist movie\n",
                "4. \"Antarctic Research Base\" - For a survival horror story\n",
                "5. \"Caribbean Island\" - For a tropical adventure romance\n",
                "\"\"\"\n",
                "\n",
                "# To get the response in a variable:\n",
                "# from rich.pretty import pprint\n",
                "\n",
                "# json_mode_response: RunResponse = json_mode_agent.run(\"New York\")\n",
                "# pprint(json_mode_response.content)\n",
                "# structured_output_response: RunResponse = structured_output_agent.run(\"New York\")\n",
                "# pprint(structured_output_response.content)"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "5cddde6d",
            "metadata": {},
            "source": []
        },
        {
            "cell_type": "markdown",
            "id": "80d94c56",
            "metadata": {},
            "source": [
                "**Multimodal Agent**"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "accc8ac2",
            "metadata": {},
            "outputs": [],
            "source": []
        }
    ],
    "metadata": {
        "kernelspec": {
            "display_name": ".venv",
            "language": "python",
            "name": "python3"
        },
        "language_info": {
            "codemirror_mode": {
                "name": "ipython",
                "version": 3
            },
            "file_extension": ".py",
            "mimetype": "text/x-python",
            "name": "python",
            "nbconvert_exporter": "python",
            "pygments_lexer": "ipython3",
            "version": "3.11.13"
        }
    },
    "nbformat": 4,
    "nbformat_minor": 5
}