hjh 1 місяць тому
батько
коміт
30a4a6c0d7

+ 160 - 0
黄靖淏/agno/code/agno_agent_level2_3_test.ipynb

@@ -0,0 +1,160 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "bc1b70ed",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from agno.agent import Agent, RunResponse\n",
+    "from agno.models.openai.like import OpenAILike\n",
+    "from agno.memory.v2.db.sqlite import SqliteMemoryDb\n",
+    "from agno.memory.v2.memory import Memory\n",
+    "from agno.memory.v2.schema import UserMemory\n",
+    "from agno.memory.v2.db.schema import MemoryRow\n",
+    "from agno.memory.v2.db.sqlite import SqliteMemoryDb\n",
+    "from agno.memory.v2.memory import Memory\n",
+    "from agno.memory.v2.schema import UserMemory\n",
+    "from agno.storage.sqlite import SqliteStorage\n",
+    "import uuid\n",
+    "import os\n",
+    "\n",
+    "memory_db = SqliteMemoryDb(db_file=\"tmp/bank_memory.db\", table_name=\"memory\")\n",
+    "storge_db = SqliteStorage(\n",
+    "        table_name=\"agent_sessions\", db_file=\"tmp/persistent_memory.db\"\n",
+    "    )\n",
+    "\n",
+    "memory = Memory(\n",
+    "        \n",
+    "        model = OpenAILike(\n",
+    "            id=\"qwen3-4b\",\n",
+    "            api_key=os.getenv(\"BAILIAN_API_KEY\"),\n",
+    "            base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
+    "            request_params={\"extra_body\": {\"enable_thinking\": False}},\n",
+    "        ),\n",
+    "        db=memory_db\n",
+    "    )\n",
+    "\n",
+    "user_id = str(uuid.uuid4())\n",
+    "\n"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "93039b6a",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "memory.add_user_memory(\n",
+    "    memory=UserMemory(\n",
+    "        memory=\"我叫hhh,我喜欢冰淇淋和看电影。\",\n",
+    "        topics=[\"姓名\", \"兴趣\"]\n",
+    "    ),\n",
+    "    user_id=user_id,\n",
+    "    \n",
+    ")\n"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "b0f6fa9c",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "memory.clear()"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "99e6b8be",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "agent = Agent(\n",
+    "    model=OpenAILike(\n",
+    "        id=\"qwen3-4b\",\n",
+    "        api_key=os.getenv(\"BAILIAN_API_KEY\"),\n",
+    "        base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
+    "        request_params={\"extra_body\": {\"enable_thinking\": False}},\n",
+    "    ),\n",
+    "    add_history_to_messages=True,\n",
+    "    #存用户记忆,可指定模型按topic检索?\n",
+    "    memory=memory,\n",
+    "    #存对话历史,工具调用历史\n",
+    "    storage=storge_db,\n",
+    "    #将用户对话加入记忆\n",
+    "    enable_user_memories=True,\n",
+    "    #自动将过去5轮对话加入promt ,搭配storge使用\n",
+    "    num_history_responses=5,\n",
+    "    #将会话摘要加入上下文\n",
+    "    add_session_summary_references=True,\n",
+    ")"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "34d7cd93",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from typing import List\n",
+    "memories: List[MemoryRow] = memory_db.read_memories()\n",
+    "print(\"All the memory_db memories:\")\n",
+    "for i, m in enumerate(memories):\n",
+    "    print(f\"{i}: {m.memory['memory']} ({m.last_updated})\")"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "8099f79a",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "def ask_agent(question: str):\n",
+    "    response: RunResponse = agent.run(\n",
+    "        messages=[{\"role\": \"user\", \"content\": f\"{question}\"}],\n",
+    "        user_id=user_id,\n",
+    "    )\n",
+    "    print(\"== AI 回复 ==\")\n",
+    "    print(response.content)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "f8316605",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "# 示例对话\n",
+    "ask_agent(\"你好\")\n",
+    "ask_agent(\"你还记得我叫什么吗?\")\n",
+    "ask_agent(\"我最喜欢什么?\")"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "cd90f220",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "ask_agent(\"我还喜欢摄影和吃火锅\")\n",
+    "ask_agent(\"最近我想去旅游,请帮我根据我的爱好推荐城市\")"
+   ]
+  }
+ ],
+ "metadata": {
+  "language_info": {
+   "name": "python"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}

+ 149 - 0
黄靖淏/agno/code/agno_agrnt_level1_test.ipynb

@@ -0,0 +1,149 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "8b4a24cf",
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "# Executive Summary\n",
+      "\n",
+      "**Apple (AAPL)** is a leading technology company with strong financial performance and notable recent news. Here's a summary of its latest data:\n",
+      "\n",
+      "## Market Overview\n",
+      "- **Latest stock price**: $150.28  \n",
+      "- **52-week high**: $246.75  \n",
+      "- **52-week low**: $134.90  \n",
+      "\n",
+      "## Financial Deep Dive\n",
+      "\n",
+      "| Metric               | Current Value | Industry Average |\n",
+      "|---------------------|---------------|------------------|\n",
+      "| P/E Ratio            | 25.6           | 15.5             |\n",
+      "| Market Cap           | $1.7 Trillion  | $1.5 Trillion     |\n",
+      "| EPS (Earnings Per Share) | $14.85        | $12.50           |\n",
+      "\n",
+      "## Professional Insights\n",
+      "\n",
+      "- **Analyst Recommendations**: AAPL is currently recommended by **Morgan Stanley & Co.**, suggesting a **buy recommendation**.\n",
+      "- **Recent Rating Changes**: AAPL was previously rated **\"Outperform\"** by all analysts, but has since been upgraded to **\"Strongly Outperform\"**.\n",
+      "\n",
+      "## Market Context\n",
+      "\n",
+      "- **Industry Trends**: Apple is a dominant player in the smartphone and software sectors, with growth in both hardware and software.\n",
+      "- **Competitive Analysis**: Competitors like Microsoft (MSFT), Amazon (AMZN), and NVIDIA (NVDA) are also performing well in key areas.\n",
+      "- **Market Sentiment Indicators**: The market appears to be positively positioned for growth, with positive sentiment around Apple’s innovation and product launches.\n",
+      "\n",
+      "## Forward-Looking Analysis\n",
+      "\n",
+      "Apple is expected to continue driving strong revenue growth and maintaining its leadership position in the tech industry. However, there are potential risks such as economic downturns or regulatory changes that could impact its future performance. As an analyst, we believe Apple will remain a top performer in the coming years.\n",
+      "\n",
+      "### Risk Disclosure\n",
+      "- **Potential Risks**: Economic uncertainties, regulatory changes, and market volatility could affect Apple’s stock price.\n",
+      "- **Regulatory Concerns**: Apple has faced scrutiny regarding data privacy and antitrust issues, which may influence investor confidence.\n",
+      "\n",
+      "Let me know if you'd like further analysis!\n"
+     ]
+    }
+   ],
+   "source": [
+    "from textwrap import dedent\n",
+    "from os import getenv\n",
+    "from agno.agent import Agent, RunResponse\n",
+    "\n",
+    "from agno.models.openai.like import OpenAILike\n",
+    "from agno.tools.yfinance import YFinanceTools\n",
+    "agent = Agent(\n",
+    "    model=OpenAILike(\n",
+    "        id=\"qwen3-0.6b\",\n",
+    "        api_key=\"sk-42c3ca4b505a4d40813727843223c768\",\n",
+    "        base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
+    "        request_params={\"extra_body\": {\"enable_thinking\": False}},\n",
+    "    ),\n",
+    "    tools=[\n",
+    "        YFinanceTools(\n",
+    "            stock_price=True,\n",
+    "            analyst_recommendations=True,\n",
+    "            stock_fundamentals=True,\n",
+    "            historical_prices=True,\n",
+    "            company_info=True,\n",
+    "            company_news=True,\n",
+    "        )\n",
+    "    ],\n",
+    "    instructions=dedent(\"\"\"\\\n",
+    "        You are a seasoned Wall Street analyst with deep expertise in market analysis! 📊\n",
+    "\n",
+    "        Follow these steps for comprehensive financial analysis:\n",
+    "        1. Market Overview\n",
+    "           - Latest stock price\n",
+    "           - 52-week high and low\n",
+    "        2. Financial Deep Dive\n",
+    "           - Key metrics (P/E, Market Cap, EPS)\n",
+    "        3. Professional Insights\n",
+    "           - Analyst recommendations breakdown\n",
+    "           - Recent rating changes\n",
+    "\n",
+    "        4. Market Context\n",
+    "           - Industry trends and positioning\n",
+    "           - Competitive analysis\n",
+    "           - Market sentiment indicators\n",
+    "\n",
+    "        Your reporting style:\n",
+    "        - Begin with an executive summary\n",
+    "        - Use tables for data presentation\n",
+    "        - Include clear section headers\n",
+    "        - Add emoji indicators for trends (📈 📉)\n",
+    "        - Highlight key insights with bullet points\n",
+    "        - Compare metrics to industry averages\n",
+    "        - Include technical term explanations\n",
+    "        - End with a forward-looking analysis\n",
+    "\n",
+    "        Risk Disclosure:\n",
+    "        - Always highlight potential risk factors\n",
+    "        - Note market uncertainties\n",
+    "        - Mention relevant regulatory concerns\n",
+    "    \"\"\"),\n",
+    "    add_datetime_to_instructions=True,\n",
+    "    show_tool_calls=True,\n",
+    "    markdown=True,\n",
+    ")\n",
+    "\n",
+    "response: RunResponse = agent.run(\"What's the latest news and financial performance of Apple (AAPL)?\")\n",
+    "print(response.content)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "12569438",
+   "metadata": {},
+   "outputs": [],
+   "source": []
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "agno_stu",
+   "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.13.1"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}

BIN
黄靖淏/agno/code/tmp/bank_memory.db


BIN
黄靖淏/agno/code/tmp/memory.db


BIN
黄靖淏/agno/code/tmp/persistent_memory.db


+ 304 - 0
黄靖淏/agno/code/transfer.ipynb

@@ -0,0 +1,304 @@
+{
+ "cells": [
+  {
+   "cell_type": "code",
+   "execution_count": 13,
+   "id": "0c217946",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "from agno.agent import Agent, RunResponse\n",
+    "from agno.models.openai.like import OpenAILike\n",
+    "from agno.memory.v2.db.sqlite import SqliteMemoryDb\n",
+    "from agno.memory.v2.memory import Memory\n",
+    "from agno.memory.v2.schema import UserMemory\n",
+    "from agno.memory.v2.db.schema import MemoryRow\n",
+    "from agno.memory.v2.db.sqlite import SqliteMemoryDb\n",
+    "from agno.memory.v2.memory import Memory\n",
+    "from agno.memory.v2.schema import UserMemory\n",
+    "from agno.storage.sqlite import SqliteStorage\n",
+    "import uuid\n",
+    "from agno.tools import tool\n",
+    "from textwrap import dedent"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "de9e7051",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "bank_map = dict()\n",
+    "bank_map[\"张三\"] = (\"15683022601\",0.00) \n",
+    "bank_map[\"me\"] = (\"15683022302\",500.00)\n"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "ae223104",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "# 暂时不知道为啥加了这个注解识别不到参数\n",
+    "# @tool(\n",
+    "#     name=\"get_contact\",\n",
+    "#     requires_user_input=True,\n",
+    "#     user_input_fields=[\"to_name\", \"to_card_id\", \"to_cash_num\"]\n",
+    "# )\n",
+    "def get_contact(to_name:str, to_card_id:str, to_cash_num:float):\n",
+    "    if to_name in bank_map:\n",
+    "        if bank_map.get(to_name)[0] == None\n",
+    "            return {\"error\": \"用户手机不存在,请填写手机\"}\n",
+    "        return bank_map.get(to_name)[0]\n",
+    "    return {\"error\": \"用户不存在\"}\n",
+    "\n",
+    "# @tool(\n",
+    "#     name=\"get_balance\",\n",
+    "#     requires_user_input=True,\n",
+    "#     user_input_fields=[\"from_name\"]\n",
+    "# )\n",
+    "def get_balance(from_name:str, to_cash_num:float):\n",
+    "    if from_name not in bank_map:\n",
+    "        return {\"error\": \"转账人不存在\"}\n",
+    "    \n",
+    "    my_cash = bank_map[from_name][1]\n",
+    "    if my_cash >= to_cash_num:\n",
+    "        return {\"result\": True}\n",
+    "    else:\n",
+    "        return {\"result\": False, \"current_balance\": my_cash}\n",
+    "\n",
+    "# @tool(\n",
+    "#     name=\"get_balance\",\n",
+    "#     requires_confirmation=True\n",
+    "# )\n",
+    "def transfer(from_name: str, to_name: str, to_cash_num: float):\n",
+    "    if from_name not in bank_map or to_name not in bank_map:\n",
+    "        return {\"error\": \"用户名错误\"}\n",
+    "\n",
+    "    from_phone, from_balance = bank_map[from_name]\n",
+    "    to_phone, to_balance = bank_map[to_name]\n",
+    "\n",
+    "    if from_balance < to_cash_num:\n",
+    "        return {\"error\": \"余额不足\", \"current_balance\": from_balance}\n",
+    "\n",
+    "    bank_map[from_name] = (from_phone, from_balance - to_cash_num)\n",
+    "    bank_map[to_name] = (to_phone, to_balance + to_cash_num)\n",
+    "\n",
+    "    return {\n",
+    "        \"message\": f\"成功转账 ¥{to_cash_num} 给 {to_name}\",\n",
+    "        \"from_balance\": bank_map[from_name][1],\n",
+    "        \"to_balance\": bank_map[to_name][1],\n",
+    "    }\n",
+    "\n",
+    "def (name:str, phone_Num:str):\n",
+    "    if name not in bank_map:\n",
+    "        return {\"error\": \"用户不存在\"}\n",
+    "    bank_map[name] = (phone_Num, bank_map[name][1])\n",
+    "    return {\"result\": \"修改成功\"}"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 16,
+   "id": "84a36800",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "memory_db = SqliteMemoryDb(db_file=\"tmp/bank_memory.db\", table_name=\"memory\")\n",
+    "storge_db = SqliteStorage(\n",
+    "        table_name=\"agent_sessions\", db_file=\"tmp/bank_memory.db\"\n",
+    "    )\n",
+    "\n",
+    "memory = Memory(\n",
+    "        \n",
+    "        model = OpenAILike(\n",
+    "            id=\"qwen3-4b\",\n",
+    "            api_key=\"sk-42c3ca4b505a4d40813727843223c768\",\n",
+    "            base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
+    "            request_params={\"extra_body\": {\"enable_thinking\": False}},\n",
+    "        ),\n",
+    "        db=memory_db\n",
+    "    )\n",
+    "\n",
+    "user_id = str(uuid.uuid4())"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 17,
+   "id": "dd55e87d",
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "All the memory_db memories:\n"
+     ]
+    }
+   ],
+   "source": [
+    "from typing import List\n",
+    "memories: List[MemoryRow] = memory_db.read_memories()\n",
+    "print(\"All the memory_db memories:\")\n",
+    "for i, m in enumerate(memories):\n",
+    "    print(f\"{i}: {m.memory['memory']} ({m.last_updated})\")"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": null,
+   "id": "4785791a",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "agent = Agent(\n",
+    "    model=OpenAILike(\n",
+    "        id=\"qwen3-32b\",\n",
+    "        api_key=\"sk-42c3ca4b505a4d40813727843223c768\",\n",
+    "        base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
+    "        request_params={\"extra_body\": {\"enable_thinking\": False}},\n",
+    "    ),\n",
+    "    tools=[\n",
+    "        get_contact,\n",
+    "        get_balance,\n",
+    "        transfer,\n",
+    "        modify_phone,\n",
+    "    ],\n",
+    "    instructions=dedent(\"\"\"\\\n",
+    "        你是一个转账助手。你需要完成以下操作:\n",
+    "        1. 调用get_contact函数,收集(被转账人姓名,被转账卡号,转账金额)校验收款人是否存在,展示其手机号;\n",
+    "        2. 调用get_balance函数,收集(转账人姓名)校验当前余额是否足够,若不足展示余额并提示重新输入金额;\n",
+    "        3. 调用transfer函数若验证通过则调用 transfer 工具完成转账操作;\n",
+    "        所有逻辑通过工具完成。\n",
+    "        注意!!!:提示用户输入尽可能详细\n",
+    "    \"\"\"),\n",
+    "\n",
+    "    add_datetime_to_instructions=True,\n",
+    "    show_tool_calls=True,\n",
+    "    markdown=True,\n",
+    "    add_history_to_messages=True,\n",
+    "    memory=memory,\n",
+    "    #指定记忆存储在sqlite中\n",
+    "    storage=storge_db,\n",
+    "    #将用户对话加入记忆\n",
+    "    enable_user_memories=True,\n",
+    ")\n"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 19,
+   "id": "c6c75890",
+   "metadata": {},
+   "outputs": [],
+   "source": [
+    "def ask_agent(question: str):\n",
+    "    response: RunResponse = agent.run(\n",
+    "        messages=[{\"role\": \"user\", \"content\": f\"{question}\"}],\n",
+    "        user_id=user_id,\n",
+    "    )\n",
+    "    print(\"== AI 回复 ==\")\n",
+    "    print(response.content)"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 20,
+   "id": "085df3f9",
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "== AI 回复 ==\n",
+      "好的,我来协助您完成转账操作。请您提供以下详细信息:\n",
+      "\n",
+      "1. **收款人姓名**:请输入被转账人的全名。\n",
+      "2. **收款人银行卡号**:请输入被转账人的银行卡号码。\n",
+      "3. **转账金额**:请输入您希望转账的金额(以人民币为单位)。\n",
+      "4. **您的姓名**:请输入您的全名,以便查询您的账户余额。\n",
+      "\n",
+      "请提供以上信息,我会逐步进行验证并完成转账。\n"
+     ]
+    }
+   ],
+   "source": [
+    "ask_agent(\"我要转账\")"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 21,
+   "id": "76687a6e",
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "== AI 回复 ==\n",
+      "已验证收款人信息,收款人张三的手机号为 **15683022601**。 \n",
+      "\n",
+      "接下来,请提供您的姓名(转账人姓名),以便查询您的账户余额是否足够完成此次转账。\n"
+     ]
+    }
+   ],
+   "source": [
+    "ask_agent({\"to_name\": \"张三\", \"to_card_id\": \"4650\", \"to_cash_num\": 400.00})\n"
+   ]
+  },
+  {
+   "cell_type": "code",
+   "execution_count": 23,
+   "id": "97c0e2b7",
+   "metadata": {},
+   "outputs": [
+    {
+     "name": "stdout",
+     "output_type": "stream",
+     "text": [
+      "您的账户余额充足,可以完成此次转账操作。现在我将为您执行转账,请稍等。\n",
+      "\n",
+      "转账已完成!以下是转账详情:\n",
+      "\n",
+      "- **转账金额**:¥400.0\n",
+      "- **收款人姓名**:张三\n",
+      "- **您的账户余额**:¥100.0\n",
+      "- **收款人账户余额**:¥400.0\n",
+      "\n",
+      "如有其他需求,请随时联系。感谢使用我们的服务!\n"
+     ]
+    }
+   ],
+   "source": [
+    "response: RunResponse = agent.run(\"转账人姓名为:me \")\n",
+    "print(response.content)"
+   ]
+  }
+ ],
+ "metadata": {
+  "kernelspec": {
+   "display_name": "agno_stu",
+   "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.13.1"
+  }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}

+ 0 - 0
黄靖淏/t2/code/t2.ipynb