1181 lines
45 KiB
Plaintext
1181 lines
45 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "bcb31876-4d8c-41ef-aa24-b8c78dfd5808",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Project - Stock Information AI Assistant\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "b7bd1bd7-19d9-4c4b-bc4b-9bc9cca8bd0f",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"!pip install finnhub-python"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "8b50bbe2-c0b1-49c3-9a5c-1ba7efa2bcb4",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# imports\n",
|
|
"\n",
|
|
"import os\n",
|
|
"import json\n",
|
|
"from dotenv import load_dotenv\n",
|
|
"from openai import OpenAI\n",
|
|
"import gradio as gr\n",
|
|
"import finnhub\n",
|
|
"from typing import Dict, List, Any, Optional\n",
|
|
"from datetime import datetime"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "747e8786-9da8-4342-b6c9-f5f69c2e22ae",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Initialization\n",
|
|
"\n",
|
|
"load_dotenv(override=True)\n",
|
|
"\n",
|
|
"openai_api_key = os.getenv('OPENAI_API_KEY')\n",
|
|
"FINNHUB_API_KEY = os.getenv(\"FINNHUB_API_KEY\")\n",
|
|
"\n",
|
|
"if openai_api_key:\n",
|
|
" print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n",
|
|
"else:\n",
|
|
" print(\"OpenAI API Key not set\")\n",
|
|
"\n",
|
|
"if FINNHUB_API_KEY:\n",
|
|
" print(f\"FINNHUB_API_KEY exists!\")\n",
|
|
"else:\n",
|
|
" print(\"OpenAI API Key not set\")\n",
|
|
" \n",
|
|
"MODEL = \"gpt-5-mini\"\n",
|
|
"openai = OpenAI()\n",
|
|
"finnhub_client = finnhub.Client(api_key=FINNHUB_API_KEY)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "ee3aaa9a-5495-42fd-a382-803fbfa92eaf",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"system_message += f\"\"\"\n",
|
|
"You are called \"TickerBot\", You are a helpful stock information assistant specializing in US stocks. You provide factual, educational information without investment advice. You have access to tools for:\n",
|
|
"- Stock symbol lookup\n",
|
|
"- Real-time quotes\n",
|
|
"- Company Financials\n",
|
|
"- Company News\n",
|
|
"- Market overview\n",
|
|
"\n",
|
|
"### **Core Principles**\n",
|
|
"**Educational Focus**: Explain financial metrics clearly and keep an educational tone.\n",
|
|
"**Factual**: NEVER give buy/sell advice or predictions.\n",
|
|
"**Accurate always**: If no data is available, inform the user in a friendly way. Always be accurate. If you don't know the answer, simply say so. Do not make up your own stock details information.\n",
|
|
"\n",
|
|
"### **How to Handle Different Requests**\n",
|
|
"- For all temporal reasoning in this chat you can use `get_current_time()` tool to get time and then relative to current time you can proceed.\n",
|
|
"- When users mention companies, search for symbols with the tool `search_symbol()` else proceed directly if obvious match\n",
|
|
"- Try to search for news or data for only for a maximum of 1 month time range, else it becomes a lot of data to parse. If user asks for recent news just check the last 5 days from today; For example if today is 10-06-2025, use from=\"2025-06-05\", to=\"2025-06-10\"\n",
|
|
"\n",
|
|
"**Single Stock Comprehensive Analysis** (Use very judicially as it is time taking tool, only when user definitely needs a complete overview or multiple things that you would otherwise need to call multiple tools for):\n",
|
|
"- User asks about \"Apple\" or \"AAPL\" → Use all company specific tools that you deem necessary. \n",
|
|
"- Present a comprehensive analysis with current price, key metrics, and recent developments\n",
|
|
"\n",
|
|
"**Market Overview Requests**:\n",
|
|
"- \"What's happening in the market?\" → Use `get_market_overview(\"general\")`\n",
|
|
"- Summarize all news stories with very brief analysis\n",
|
|
"\n",
|
|
"### **Error Handling**\n",
|
|
"- If symbol search fails: \"I couldn't find that company in US markets. Could you try a different name or provide the ticker symbol?\"\n",
|
|
"- If some information gathered from the tool call says unavailable or error do not present it to the user unless they had specifically asked for it. Present rest of the gathered information if any.\n",
|
|
"- If data is unavailable: \"Some data isn't available right now, but here's what I found...\"\n",
|
|
"- Stay helpful and suggest alternatives\n",
|
|
"\"\"\""
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "61a2a15d-b559-4844-b377-6bd5cb4949f6",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def validate_symbol(symbol: str) -> bool:\n",
|
|
" \"\"\"Validate stock symbol format\"\"\"\n",
|
|
" if not symbol or not isinstance(symbol, str):\n",
|
|
" return False\n",
|
|
" return symbol.isalnum() and 1 <= len(symbol) <= 5 and symbol.isupper()\n",
|
|
"\n",
|
|
"def search_symbol(query: str) -> Dict[str, Any]:\n",
|
|
" \"\"\"Search for stock symbol using Finnhub client\"\"\"\n",
|
|
" print(f\"Tool search_symbol called for {query}\")\n",
|
|
" try:\n",
|
|
" if not query or len(query.strip()) < 1:\n",
|
|
" return {\"success\": False, \"error\": \"Invalid search query\"}\n",
|
|
" \n",
|
|
" query = query.strip()[:50]\n",
|
|
" result = finnhub_client.symbol_lookup(query)\n",
|
|
" \n",
|
|
" if result.get(\"result\") and len(result[\"result\"]) > 0:\n",
|
|
" first_result = result[\"result\"][0]\n",
|
|
" symbol = first_result.get(\"symbol\", \"\").upper()\n",
|
|
" \n",
|
|
" if validate_symbol(symbol):\n",
|
|
" return {\n",
|
|
" \"success\": True,\n",
|
|
" \"symbol\": symbol\n",
|
|
" }\n",
|
|
" else:\n",
|
|
" return {\"success\": False, \"error\": \"Invalid symbol format found\"}\n",
|
|
" else:\n",
|
|
" return {\"success\": False, \"error\": \"No matching US stocks found\"}\n",
|
|
" \n",
|
|
" except Exception as e:\n",
|
|
" return {\"success\": False, \"error\": f\"Symbol search failed: {str(e)[:100]}\"}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "173010e3-dfef-4611-8b68-d11256bd5fba",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"search_symbol_function = {\n",
|
|
" \"name\": \"search_symbol\",\n",
|
|
" \"description\": \"Search for a stock symbol / ticker symbol based on company name or partial name\",\n",
|
|
" \"parameters\": {\n",
|
|
" \"type\": \"object\",\n",
|
|
" \"properties\": {\n",
|
|
" \"query\": {\n",
|
|
" \"type\": \"string\",\n",
|
|
" \"description\": \"Company name or partial name to search for, extract only relevant name part and pass it here, keep this to less than 50 characters\"\n",
|
|
" }\n",
|
|
" },\n",
|
|
" \"required\": [\n",
|
|
" \"query\"\n",
|
|
" ]\n",
|
|
" }\n",
|
|
"}\n",
|
|
"\n",
|
|
"search_symbol_tool = {\"type\": \"function\", \"function\": search_symbol_function}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "448bb4ce-8e86-4ceb-ab52-96bddfd33337",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def _format_big_number_from_millions(value_millions: Any) -> str:\n",
|
|
" \"\"\"\n",
|
|
" Finnhub returns some large metrics (marketCapitalization, enterpriseValue, revenueTTM)\n",
|
|
" in MILLIONS USD. Convert to full USD and format with M/B/T suffixes.\n",
|
|
" \"\"\"\n",
|
|
" if value_millions is None:\n",
|
|
" return \"Unavailable\"\n",
|
|
" try:\n",
|
|
" value = float(value_millions) * 1_000_000 # convert millions -> full USD\n",
|
|
" except (TypeError, ValueError):\n",
|
|
" return \"Unavailable\"\n",
|
|
"\n",
|
|
" trillion = 1_000_000_000_000\n",
|
|
" billion = 1_000_000_000\n",
|
|
" million = 1_000_000\n",
|
|
"\n",
|
|
" if value >= trillion:\n",
|
|
" return f\"{value / trillion:.2f}T USD\"\n",
|
|
" if value >= billion:\n",
|
|
" return f\"{value / billion:.2f}B USD\"\n",
|
|
" if value >= million:\n",
|
|
" return f\"{value / million:.2f}M USD\"\n",
|
|
" return f\"{value:.2f} USD\"\n",
|
|
"\n",
|
|
"\n",
|
|
"def _safe_metric(metrics: Dict[str, Any], key: str) -> Any:\n",
|
|
" \"\"\"\n",
|
|
" Return metric value if present; otherwise \"Unavailable\".\n",
|
|
" We intentionally return the raw value for numeric metrics (no rounding/format)\n",
|
|
" except for the specially formatted big-number fields handled elsewhere.\n",
|
|
" \"\"\"\n",
|
|
" if metrics is None:\n",
|
|
" return \"Unavailable\"\n",
|
|
" val = metrics.get(key)\n",
|
|
" return val if val is not None else \"Unavailable\"\n",
|
|
"\n",
|
|
"\n",
|
|
"def get_company_financials(symbol: str) -> Dict[str, Any]:\n",
|
|
" \"\"\"\n",
|
|
" Fetch and return a curated set of 'basic' financial metrics for `symbol`.\n",
|
|
" - Calls finnhub_client.company_basic_financials(symbol, 'all')\n",
|
|
" - Formats market cap, enterprise value, revenue (Finnhub returns these in millions)\n",
|
|
" - Returns success flag and readable keys\n",
|
|
" \"\"\"\n",
|
|
" print(f\"Tool get_company_financials called for {symbol}\")\n",
|
|
" try:\n",
|
|
" if not symbol or not symbol.strip():\n",
|
|
" return {\"success\": False, \"error\": \"Invalid stock symbol\"}\n",
|
|
"\n",
|
|
" symbol = symbol.strip().upper()\n",
|
|
"\n",
|
|
" # --- API Call ---\n",
|
|
" financials_resp = finnhub_client.company_basic_financials(symbol, \"all\")\n",
|
|
"\n",
|
|
" # Finnhub places primary values under \"metric\"\n",
|
|
" metrics = financials_resp.get(\"metric\", {})\n",
|
|
" if not metrics:\n",
|
|
" return {\"success\": False, \"error\": \"No financial metrics found\"}\n",
|
|
"\n",
|
|
" # --- Build result using helpers ---\n",
|
|
" result = {\n",
|
|
" \"success\": True,\n",
|
|
" \"symbol\": symbol,\n",
|
|
" \"financials\": {\n",
|
|
" \"Market Cap\": _format_big_number_from_millions(metrics.get(\"marketCapitalization\")),\n",
|
|
" \"Enterprise Value\": _format_big_number_from_millions(metrics.get(\"enterpriseValue\")),\n",
|
|
" \"P/E Ratio (TTM)\": _safe_metric(metrics, \"peBasicExclExtraTTM\"),\n",
|
|
" \"Forward P/E\": _safe_metric(metrics, \"forwardPE\"),\n",
|
|
" \"Revenue (TTM)\": _format_big_number_from_millions(metrics.get(\"revenueTTM\")),\n",
|
|
" \"Gross Margin (TTM)\": _safe_metric(metrics, \"grossMarginTTM\"),\n",
|
|
" \"Net Profit Margin (TTM)\": _safe_metric(metrics, \"netProfitMarginTTM\"),\n",
|
|
" \"EPS (TTM)\": _safe_metric(metrics, \"epsTTM\"),\n",
|
|
" \"EPS Growth (5Y)\": _safe_metric(metrics, \"epsGrowth5Y\"),\n",
|
|
" \"Dividend Yield (Indicated Annual)\": _safe_metric(metrics, \"dividendYieldIndicatedAnnual\"),\n",
|
|
" \"Current Ratio (Quarterly)\": _safe_metric(metrics, \"currentRatioQuarterly\"),\n",
|
|
" \"Debt/Equity (Long Term, Quarterly)\": _safe_metric(metrics, \"longTermDebt/equityQuarterly\"),\n",
|
|
" \"Beta\": _safe_metric(metrics, \"beta\"),\n",
|
|
" \"52-Week High\": _safe_metric(metrics, \"52WeekHigh\"),\n",
|
|
" \"52-Week Low\": _safe_metric(metrics, \"52WeekLow\"),\n",
|
|
" }\n",
|
|
" }\n",
|
|
"\n",
|
|
" return result\n",
|
|
"\n",
|
|
" except Exception as e:\n",
|
|
" # keep error message short but useful for debugging\n",
|
|
" return {\"success\": False, \"error\": f\"Failed to fetch metrics: {str(e)[:200]}\"}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "9df7b74e-fec8-4e75-92a9-31acc75e6e97",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"get_company_financials_function = {\n",
|
|
" \"name\": \"get_company_financials\",\n",
|
|
" \"description\": \"Fetch and return a curated set of basic financial metrics for a stock symbol. Calls Finnhub's company_basic_financials API, formats large numbers (market cap, enterprise value, revenue) in M/B/T USD, and shows metrics like P/E ratios, EPS, margins, dividend yield, debt/equity, beta, and 52-week range. Returns 'Unavailable' for missing values.\",\n",
|
|
" \"parameters\": {\n",
|
|
" \"type\": \"object\",\n",
|
|
" \"properties\": {\n",
|
|
" \"symbol\": {\n",
|
|
" \"type\": \"string\",\n",
|
|
" \"description\": \"Stock ticker symbol to fetch metrics for. Example: 'AAPL' for Apple Inc.\"\n",
|
|
" }\n",
|
|
" },\n",
|
|
" \"required\": [\n",
|
|
" \"symbol\"\n",
|
|
" ]\n",
|
|
" }\n",
|
|
"}\n",
|
|
"\n",
|
|
"\n",
|
|
"get_company_financials_tool = {\"type\": \"function\", \"function\": get_company_financials_function}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "cfeeb200-3f30-4855-82b9-cc8b2a950f80",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def get_stock_quote(symbol: str) -> dict:\n",
|
|
" \"\"\"\n",
|
|
" Fetch the latest stock quote for a given ticker symbol using Finnhub's /quote endpoint.\n",
|
|
" Returns current price, daily high/low, open, previous close, percent change, and readable timestamp.\n",
|
|
" \"\"\"\n",
|
|
" print(f\"Tool get_stock_quote called for {symbol}\")\n",
|
|
" try:\n",
|
|
" if not symbol or len(symbol.strip()) < 1:\n",
|
|
" return {\"success\": False, \"error\": \"Invalid symbol provided\"}\n",
|
|
" \n",
|
|
" symbol = symbol.strip().upper()\n",
|
|
" data = finnhub_client.quote(symbol)\n",
|
|
"\n",
|
|
" if not data or \"c\" not in data:\n",
|
|
" return {\"success\": False, \"error\": \"No quote data found\"}\n",
|
|
" \n",
|
|
" # Convert epoch timestamp to ISO UTC if present\n",
|
|
" timestamp = data.get(\"t\")\n",
|
|
" if timestamp and isinstance(timestamp, (int, float)):\n",
|
|
" timestamp = datetime.utcfromtimestamp(timestamp).isoformat() + \"Z\"\n",
|
|
" else:\n",
|
|
" timestamp = \"Unavailable\"\n",
|
|
" \n",
|
|
" return {\n",
|
|
" \"success\": True,\n",
|
|
" \"symbol\": symbol,\n",
|
|
" \"current_price\": round(data.get(\"c\", 0), 2) if data.get(\"c\") is not None else \"Unavailable\",\n",
|
|
" \"change\": round(data.get(\"d\", 0), 2) if data.get(\"d\") is not None else \"Unavailable\",\n",
|
|
" \"percent_change\": f\"{round(data.get('dp', 0), 2)}%\" if data.get(\"dp\") is not None else \"Unavailable\",\n",
|
|
" \"high_price\": round(data.get(\"h\", 0), 2) if data.get(\"h\") is not None else \"Unavailable\",\n",
|
|
" \"low_price\": round(data.get(\"l\", 0), 2) if data.get(\"l\") is not None else \"Unavailable\",\n",
|
|
" \"open_price\": round(data.get(\"o\", 0), 2) if data.get(\"o\") is not None else \"Unavailable\",\n",
|
|
" \"previous_close\": round(data.get(\"pc\", 0), 2) if data.get(\"pc\") is not None else \"Unavailable\",\n",
|
|
" \"timestamp\": timestamp\n",
|
|
" }\n",
|
|
" except Exception as e:\n",
|
|
" return {\"success\": False, \"error\": f\"Quote retrieval failed: {str(e)[:100]}\"}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "3724d92a-4515-4267-af6f-2c1ec2b6ed36",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"get_stock_quote_function = {\n",
|
|
" \"name\": \"get_stock_quote\",\n",
|
|
" \"description\": \"Retrieve the latest stock quote for a given symbol, including current price, daily high/low, open, previous close, and percent change. Data is near real-time. Avoid constant polling; use websockets for streaming updates.\",\n",
|
|
" \"parameters\": {\n",
|
|
" \"type\": \"object\",\n",
|
|
" \"properties\": {\n",
|
|
" \"symbol\": {\n",
|
|
" \"type\": \"string\",\n",
|
|
" \"description\": \"Stock ticker symbol to fetch the latest quote for. Example: 'AAPL', 'MSFT'.\"\n",
|
|
" }\n",
|
|
" },\n",
|
|
" \"required\": [\"symbol\"]\n",
|
|
" }\n",
|
|
"}\n",
|
|
"\n",
|
|
"get_stock_quote_tool = {\"type\": \"function\", \"function\": get_stock_quote_function}\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "62f5d477-6626-428f-b8eb-d763e736ef5b",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def get_company_news(symbol: str, _from: str, to: str):\n",
|
|
" \"\"\"\n",
|
|
" Fetch the top 5 latest company news for a stock symbol within a date range.\n",
|
|
" - Ensures the range does not exceed ~1 months (35 days).\n",
|
|
" - Best practice: Keep searches to a month or less to avoid too much data.\n",
|
|
"\n",
|
|
" Args:\n",
|
|
" symbol (str): Stock ticker (e.g., \"AAPL\").\n",
|
|
" _from (str): Start date in YYYY-MM-DD format.\n",
|
|
" to (str): End date in YYYY-MM-DD format.\n",
|
|
"\n",
|
|
" Returns:\n",
|
|
" list or dict: Cleaned news data or error message.\n",
|
|
" \"\"\"\n",
|
|
" # Validate date format\n",
|
|
" print(f\"Tool get_company_news called for {symbol} from {_from} to {to}\")\n",
|
|
" try:\n",
|
|
" start_date = datetime.strptime(_from, \"%Y-%m-%d\")\n",
|
|
" end_date = datetime.strptime(to, \"%Y-%m-%d\")\n",
|
|
" except ValueError:\n",
|
|
" return {\"success\": False, \"error\": \"Invalid date format. Use YYYY-MM-DD.\"}\n",
|
|
"\n",
|
|
" # Check date range\n",
|
|
" delta_days = (end_date - start_date).days\n",
|
|
" if delta_days > 35:\n",
|
|
" return {\n",
|
|
" \"success\": False, \n",
|
|
" \"error\": f\"Date range too large ({delta_days} days). \"\n",
|
|
" \"Please use a range of 1 months or less.\"\n",
|
|
" }\n",
|
|
"\n",
|
|
" # Fetch data\n",
|
|
" try:\n",
|
|
" news = finnhub_client.company_news(symbol, _from=_from, to=to)\n",
|
|
" except Exception as e:\n",
|
|
" return {\"success\": False, \"error\": str(e)}\n",
|
|
"\n",
|
|
" # Do not want to report just the latest news in the time period\n",
|
|
" if len(news) <= 10:\n",
|
|
" # If 10 or fewer articles, take all\n",
|
|
" selected_news = news\n",
|
|
" else:\n",
|
|
" # Take first 5 (oldest) and last 5 (newest)\n",
|
|
" selected_news = news[:5] + news[-5:]\n",
|
|
"\n",
|
|
" # Clean & transform objects\n",
|
|
" cleaned_news = []\n",
|
|
" for article in news:\n",
|
|
" cleaned_news.append({\n",
|
|
" \"summary\": article.get(\"summary\"),\n",
|
|
" \"source\": article.get(\"source\"),\n",
|
|
" \"published_at\": datetime.utcfromtimestamp(article[\"datetime\"]).strftime(\"%Y-%m-%d %H:%M:%S UTC\"),\n",
|
|
" \"related\": article.get(\"related\")\n",
|
|
" })\n",
|
|
"\n",
|
|
" return {\"success\": True, \"news\": cleaned_news}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "5150ecb6-e3f1-46dc-94fa-2a9abe5165f6",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"get_company_news_function = {\n",
|
|
" \"name\": \"get_company_news\",\n",
|
|
" \"description\": \"Fetch the top 5 most recent company news articles for a given stock symbol. ⚠️ Avoid querying more than a 1-month range at a time as it may return too much data. Only tells news about company within last 1 year. An error is returned if the requested time range exceeds 1 month.\",\n",
|
|
" \"parameters\": {\n",
|
|
" \"type\": \"object\",\n",
|
|
" \"properties\": {\n",
|
|
" \"symbol\": {\n",
|
|
" \"type\": \"string\",\n",
|
|
" \"description\": \"Stock ticker symbol, e.g., 'AAPL'.\"\n",
|
|
" },\n",
|
|
" \"_from\": {\n",
|
|
" \"type\": \"string\",\n",
|
|
" \"description\": \"Start date in YYYY-MM-DD format. Ensure it is not more than 1 year ago.\"\n",
|
|
" },\n",
|
|
" \"to\": {\n",
|
|
" \"type\": \"string\",\n",
|
|
" \"description\": \"End date in YYYY-MM-DD format. Ensure it is not more than 1 year ago.\"\n",
|
|
" }\n",
|
|
" },\n",
|
|
" \"required\": [\n",
|
|
" \"symbol\",\n",
|
|
" \"_from\",\n",
|
|
" \"to\"\n",
|
|
" ]\n",
|
|
" }\n",
|
|
"}\n",
|
|
"\n",
|
|
"get_company_news_tool = {\"type\": \"function\", \"function\": get_company_news_function}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "26dd7375-626f-4235-b4a2-f1926f62cc5e",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def get_market_news(category: str = \"general\"):\n",
|
|
" \"\"\"\n",
|
|
" Fetch the latest market news for a given category.\n",
|
|
" - Returns only the top 7 articles.\n",
|
|
"\n",
|
|
" Args:\n",
|
|
" category (str): News category. One of [\"general\", \"forex\", \"crypto\", \"merger\"].\n",
|
|
"\n",
|
|
" Returns:\n",
|
|
" list or dict: A cleaned list of news articles or error message.\n",
|
|
" \"\"\"\n",
|
|
" print(f\"Tool get_market_news called for category '{category}'\")\n",
|
|
"\n",
|
|
" try:\n",
|
|
" news = finnhub_client.general_news(category)\n",
|
|
" except Exception as e:\n",
|
|
" return {\"success\": False, \"error\": str(e)}\n",
|
|
"\n",
|
|
" # Do not want to report just the latest news in the time period\n",
|
|
" if len(news) <= 10:\n",
|
|
" # If 10 or fewer articles, take all\n",
|
|
" selected_news = news\n",
|
|
" else:\n",
|
|
" # Take first 5 (oldest) and last 5 (newest)\n",
|
|
" selected_news = news[:5] + news[-5:]\n",
|
|
"\n",
|
|
" # Clean & transform objects\n",
|
|
" cleaned_news = []\n",
|
|
" for article in news:\n",
|
|
" cleaned_news.append({\n",
|
|
" \"headline\": article.get(\"headline\"),\n",
|
|
" \"summary\": article.get(\"summary\"),\n",
|
|
" \"source\": article.get(\"source\"),\n",
|
|
" \"category\": article.get(\"category\"),\n",
|
|
" \"published_at\": datetime.utcfromtimestamp(article[\"datetime\"]).strftime(\"%Y-%m-%d %H:%M:%S UTC\"),\n",
|
|
" \"related\": article.get(\"related\")\n",
|
|
" })\n",
|
|
"\n",
|
|
" return {\"success\": True, \"news\": cleaned_news}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "5bd1aa28-119c-4c7a-bdc0-161a582ab1cc",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"get_market_news_function = {\n",
|
|
" \"name\": \"get_market_news\",\n",
|
|
" \"description\": \"Fetch the latest market news by category. Returns the top 10 news articles with headline, summary, source, category, published time (UTC), and URLs. Categories: general, forex, crypto, merger. Use this to quickly get relevant financial news.\",\n",
|
|
" \"parameters\": {\n",
|
|
" \"type\": \"object\",\n",
|
|
" \"properties\": {\n",
|
|
" \"category\": {\n",
|
|
" \"type\": \"string\",\n",
|
|
" \"description\": \"News category to fetch. One of: general, forex, crypto, merger.\"\n",
|
|
" }\n",
|
|
" },\n",
|
|
" \"required\": [\"category\"]\n",
|
|
" }\n",
|
|
"}\n",
|
|
"\n",
|
|
"get_market_news_tool = {\"type\": \"function\", \"function\": get_market_news_function}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "d3378855-b83c-4078-b1e9-5f03e55c7276",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "bf29bdd0-7603-45fc-ad39-790eb0b471d5",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "a25474d9-128e-431f-9b4c-1b3897798f0b",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "bdca8679-935f-4e7f-97e6-e71a4d4f228c",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# And this is included in a list of tools:\n",
|
|
"\n",
|
|
"tools = [{\"type\": \"function\", \"function\": price_function}]"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "c3d3554f-b4e3-4ce7-af6f-68faa6dd2340",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Getting OpenAI to use our Tool\n",
|
|
"\n",
|
|
"There's some fiddly stuff to allow OpenAI \"to call our tool\"\n",
|
|
"\n",
|
|
"What we actually do is give the LLM the opportunity to inform us that it wants us to run the tool.\n",
|
|
"\n",
|
|
"Here's how the new chat function looks:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "ce9b0744-9c78-408d-b9df-9f6fd9ed78cf",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def chat(message, history):\n",
|
|
" messages = [{\"role\": \"system\", \"content\": system_message}] + history + [{\"role\": \"user\", \"content\": message}]\n",
|
|
" response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)\n",
|
|
"\n",
|
|
" if response.choices[0].finish_reason==\"tool_calls\":\n",
|
|
" message = response.choices[0].message\n",
|
|
" response, city = handle_tool_call(message)\n",
|
|
" messages.append(message)\n",
|
|
" messages.append(response)\n",
|
|
" response = openai.chat.completions.create(model=MODEL, messages=messages)\n",
|
|
" \n",
|
|
" return response.choices[0].message.content"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "b0992986-ea09-4912-a076-8e5603ee631f",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# We have to write that function handle_tool_call:\n",
|
|
"\n",
|
|
"def handle_tool_call(message):\n",
|
|
" tool_call = message.tool_calls[0]\n",
|
|
" arguments = json.loads(tool_call.function.arguments)\n",
|
|
" city = arguments.get('destination_city')\n",
|
|
" price = get_ticket_price(city)\n",
|
|
" response = {\n",
|
|
" \"role\": \"tool\",\n",
|
|
" \"content\": json.dumps({\"destination_city\": city,\"price\": price}),\n",
|
|
" \"tool_call_id\": tool_call.id\n",
|
|
" }\n",
|
|
" return response, city"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "f4be8a71-b19e-4c2f-80df-f59ff2661f14",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"gr.ChatInterface(fn=chat, type=\"messages\").launch()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "473e5b39-da8f-4db1-83ae-dbaca2e9531e",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Let's go multi-modal!!\n",
|
|
"\n",
|
|
"We can use DALL-E-3, the image generation model behind GPT-4o, to make us some images\n",
|
|
"\n",
|
|
"Let's put this in a function called artist.\n",
|
|
"\n",
|
|
"### Price alert: each time I generate an image it costs about 4 cents - don't go crazy with images!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "2c27c4ba-8ed5-492f-add1-02ce9c81d34c",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Some imports for handling images\n",
|
|
"\n",
|
|
"import base64\n",
|
|
"from io import BytesIO\n",
|
|
"from PIL import Image"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "773a9f11-557e-43c9-ad50-56cbec3a0f8f",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def artist(city):\n",
|
|
" image_response = openai.images.generate(\n",
|
|
" model=\"dall-e-3\",\n",
|
|
" prompt=f\"An image representing a vacation in {city}, showing tourist spots and everything unique about {city}, in a vibrant pop-art style\",\n",
|
|
" size=\"1024x1024\",\n",
|
|
" n=1,\n",
|
|
" response_format=\"b64_json\",\n",
|
|
" )\n",
|
|
" image_base64 = image_response.data[0].b64_json\n",
|
|
" image_data = base64.b64decode(image_base64)\n",
|
|
" return Image.open(BytesIO(image_data))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "d877c453-e7fb-482a-88aa-1a03f976b9e9",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"image = artist(\"New York City\")\n",
|
|
"display(image)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "728a12c5-adc3-415d-bb05-82beb73b079b",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "f4975b87-19e9-4ade-a232-9b809ec75c9a",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Audio (NOTE - Audio is optional for this course - feel free to skip Audio if it causes trouble!)\n",
|
|
"\n",
|
|
"And let's make a function talker that uses OpenAI's speech model to generate Audio\n",
|
|
"\n",
|
|
"### Troubleshooting Audio issues\n",
|
|
"\n",
|
|
"If you have any problems running this code below (like a FileNotFound error, or a warning of a missing package), you may need to install FFmpeg, a very popular audio utility.\n",
|
|
"\n",
|
|
"**For PC Users**\n",
|
|
"\n",
|
|
"Detailed instructions are [here](https://chatgpt.com/share/6724efee-6b0c-8012-ac5e-72e2e3885905) and summary instructions:\n",
|
|
"\n",
|
|
"1. Download FFmpeg from the official website: https://ffmpeg.org/download.html\n",
|
|
"\n",
|
|
"2. Extract the downloaded files to a location on your computer (e.g., `C:\\ffmpeg`)\n",
|
|
"\n",
|
|
"3. Add the FFmpeg bin folder to your system PATH:\n",
|
|
"- Right-click on 'This PC' or 'My Computer' and select 'Properties'\n",
|
|
"- Click on 'Advanced system settings'\n",
|
|
"- Click on 'Environment Variables'\n",
|
|
"- Under 'System variables', find and edit 'Path'\n",
|
|
"- Add a new entry with the path to your FFmpeg bin folder (e.g., `C:\\ffmpeg\\bin`)\n",
|
|
"- Restart your command prompt, and within Jupyter Lab do Kernel -> Restart kernel, to pick up the changes\n",
|
|
"\n",
|
|
"4. Open a new command prompt and run this to make sure it's installed OK\n",
|
|
"`ffmpeg -version`\n",
|
|
"\n",
|
|
"**For Mac Users**\n",
|
|
"\n",
|
|
"1. Install homebrew if you don't have it already by running this in a Terminal window and following any instructions: \n",
|
|
"`/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"`\n",
|
|
"\n",
|
|
"2. Then install FFmpeg with `brew install ffmpeg`\n",
|
|
"\n",
|
|
"3. Verify your installation with `ffmpeg -version` and if everything is good, within Jupyter Lab do Kernel -> Restart kernel to pick up the changes\n",
|
|
"\n",
|
|
"Message me or email me at ed@edwarddonner.com with any problems!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "4cc90e80-c96e-4dd4-b9d6-386fe2b7e797",
|
|
"metadata": {},
|
|
"source": [
|
|
"## To check you now have ffmpeg and can access it here\n",
|
|
"\n",
|
|
"Excecute the next cell to see if you get a version number. (Putting an exclamation mark before something in Jupyter Lab tells it to run it as a terminal command rather than python code).\n",
|
|
"\n",
|
|
"If this doesn't work, you may need to actually save and close down your Jupyter lab, and start it again from a new Terminal window (Mac) or Anaconda prompt (PC), remembering to activate the llms environment. This ensures you pick up ffmpeg.\n",
|
|
"\n",
|
|
"And if that doesn't work, please contact me!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "7b3be0fb-1d34-4693-ab6f-dbff190afcd7",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"!ffmpeg -version\n",
|
|
"!ffprobe -version\n",
|
|
"!ffplay -version"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "d91d3f8f-e505-4e3c-a87c-9e42ed823db6",
|
|
"metadata": {},
|
|
"source": [
|
|
"# For Mac users - and possibly many PC users too\n",
|
|
"\n",
|
|
"This version should work fine for you. It might work for Windows users too, but you might get a Permissions error writing to a temp file. If so, see the next section!\n",
|
|
"\n",
|
|
"As always, if you have problems, please contact me! (You could also comment out the audio talker() in the later code if you're less interested in audio generation)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "ffbfe93b-5e86-4e68-ba71-b301cd5230db",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from pydub import AudioSegment\n",
|
|
"from pydub.playback import play\n",
|
|
"\n",
|
|
"def talker(message):\n",
|
|
" response = openai.audio.speech.create(\n",
|
|
" model=\"tts-1\",\n",
|
|
" voice=\"onyx\", # Also, try replacing onyx with alloy\n",
|
|
" input=message\n",
|
|
" )\n",
|
|
" \n",
|
|
" audio_stream = BytesIO(response.content)\n",
|
|
" audio = AudioSegment.from_file(audio_stream, format=\"mp3\")\n",
|
|
" play(audio)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "b88d775d-d357-4292-a1ad-5dc5ed567281",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"talker(\"Well, hi there\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "ad89a9bd-bb1e-4bbb-a49a-83af5f500c24",
|
|
"metadata": {},
|
|
"source": [
|
|
"# For Windows users (or any Mac users with problems above)\n",
|
|
"\n",
|
|
"## First try the Mac version above, but if you get a permissions error writing to a temp file, then this code should work instead.\n",
|
|
"\n",
|
|
"A collaboration between students Mark M. and Patrick H. and Claude got this resolved!\n",
|
|
"\n",
|
|
"Below are 4 variations - hopefully one of them will work on your PC. If not, message me please!\n",
|
|
"\n",
|
|
"And for Mac people - all 3 of the below work on my Mac too - please try these if the Mac version gave you problems.\n",
|
|
"\n",
|
|
"## PC Variation 1"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "d104b96a-02ca-4159-82fe-88e0452aa479",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import base64\n",
|
|
"from io import BytesIO\n",
|
|
"from PIL import Image\n",
|
|
"from IPython.display import Audio, display\n",
|
|
"\n",
|
|
"def talker(message):\n",
|
|
" response = openai.audio.speech.create(\n",
|
|
" model=\"tts-1\",\n",
|
|
" voice=\"onyx\",\n",
|
|
" input=message)\n",
|
|
"\n",
|
|
" audio_stream = BytesIO(response.content)\n",
|
|
" output_filename = \"output_audio.mp3\"\n",
|
|
" with open(output_filename, \"wb\") as f:\n",
|
|
" f.write(audio_stream.read())\n",
|
|
"\n",
|
|
" # Play the generated audio\n",
|
|
" display(Audio(output_filename, autoplay=True))\n",
|
|
"\n",
|
|
"talker(\"Well, hi there\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "3a5d11f4-bbd3-43a1-904d-f684eb5f3e3a",
|
|
"metadata": {},
|
|
"source": [
|
|
"## PC Variation 2"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "d59c8ebd-79c5-498a-bdf2-3a1c50d91aa0",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import tempfile\n",
|
|
"import subprocess\n",
|
|
"from io import BytesIO\n",
|
|
"from pydub import AudioSegment\n",
|
|
"import time\n",
|
|
"\n",
|
|
"def play_audio(audio_segment):\n",
|
|
" temp_dir = tempfile.gettempdir()\n",
|
|
" temp_path = os.path.join(temp_dir, \"temp_audio.wav\")\n",
|
|
" try:\n",
|
|
" audio_segment.export(temp_path, format=\"wav\")\n",
|
|
" time.sleep(3) # Student Dominic found that this was needed. You could also try commenting out to see if not needed on your PC\n",
|
|
" subprocess.call([\n",
|
|
" \"ffplay\",\n",
|
|
" \"-nodisp\",\n",
|
|
" \"-autoexit\",\n",
|
|
" \"-hide_banner\",\n",
|
|
" temp_path\n",
|
|
" ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n",
|
|
" finally:\n",
|
|
" try:\n",
|
|
" os.remove(temp_path)\n",
|
|
" except Exception:\n",
|
|
" pass\n",
|
|
" \n",
|
|
"def talker(message):\n",
|
|
" response = openai.audio.speech.create(\n",
|
|
" model=\"tts-1\",\n",
|
|
" voice=\"onyx\", # Also, try replacing onyx with alloy\n",
|
|
" input=message\n",
|
|
" )\n",
|
|
" audio_stream = BytesIO(response.content)\n",
|
|
" audio = AudioSegment.from_file(audio_stream, format=\"mp3\")\n",
|
|
" play_audio(audio)\n",
|
|
"\n",
|
|
"talker(\"Well hi there\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "96f90e35-f71e-468e-afea-07b98f74dbcf",
|
|
"metadata": {},
|
|
"source": [
|
|
"## PC Variation 3"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "8597c7f8-7b50-44ad-9b31-db12375cd57b",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import os\n",
|
|
"from pydub import AudioSegment\n",
|
|
"from pydub.playback import play\n",
|
|
"from io import BytesIO\n",
|
|
"\n",
|
|
"def talker(message):\n",
|
|
" # Set a custom directory for temporary files on Windows\n",
|
|
" custom_temp_dir = os.path.expanduser(\"~/Documents/temp_audio\")\n",
|
|
" os.environ['TEMP'] = custom_temp_dir # You can also use 'TMP' if necessary\n",
|
|
" \n",
|
|
" # Create the folder if it doesn't exist\n",
|
|
" if not os.path.exists(custom_temp_dir):\n",
|
|
" os.makedirs(custom_temp_dir)\n",
|
|
" \n",
|
|
" response = openai.audio.speech.create(\n",
|
|
" model=\"tts-1\",\n",
|
|
" voice=\"onyx\", # Also, try replacing onyx with alloy\n",
|
|
" input=message\n",
|
|
" )\n",
|
|
" \n",
|
|
" audio_stream = BytesIO(response.content)\n",
|
|
" audio = AudioSegment.from_file(audio_stream, format=\"mp3\")\n",
|
|
"\n",
|
|
" play(audio)\n",
|
|
"\n",
|
|
"talker(\"Well hi there\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "e821224c-b069-4f9b-9535-c15fdb0e411c",
|
|
"metadata": {},
|
|
"source": [
|
|
"## PC Variation 4\n",
|
|
"\n",
|
|
"### Let's try a completely different sound library\n",
|
|
"\n",
|
|
"First run the next cell to install a new library, then try the cell below it."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "69d3c0d9-afcc-49e3-b829-9c9869d8b472",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"!pip install simpleaudio"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "28f9cc99-36b7-4554-b3f4-f2012f614a13",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from pydub import AudioSegment\n",
|
|
"from io import BytesIO\n",
|
|
"import tempfile\n",
|
|
"import os\n",
|
|
"import simpleaudio as sa\n",
|
|
"\n",
|
|
"def talker(message):\n",
|
|
" response = openai.audio.speech.create(\n",
|
|
" model=\"tts-1\",\n",
|
|
" voice=\"onyx\", # Also, try replacing onyx with alloy\n",
|
|
" input=message\n",
|
|
" )\n",
|
|
" \n",
|
|
" audio_stream = BytesIO(response.content)\n",
|
|
" audio = AudioSegment.from_file(audio_stream, format=\"mp3\")\n",
|
|
"\n",
|
|
" # Create a temporary file in a folder where you have write permissions\n",
|
|
" with tempfile.NamedTemporaryFile(suffix=\".wav\", delete=False, dir=os.path.expanduser(\"~/Documents\")) as temp_audio_file:\n",
|
|
" temp_file_name = temp_audio_file.name\n",
|
|
" audio.export(temp_file_name, format=\"wav\")\n",
|
|
" \n",
|
|
" # Load and play audio using simpleaudio\n",
|
|
" wave_obj = sa.WaveObject.from_wave_file(temp_file_name)\n",
|
|
" play_obj = wave_obj.play()\n",
|
|
" play_obj.wait_done() # Wait for playback to finish\n",
|
|
"\n",
|
|
" # Clean up the temporary file afterward\n",
|
|
" os.remove(temp_file_name)\n",
|
|
" \n",
|
|
"talker(\"Well hi there\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "7986176b-cd04-495f-a47f-e057b0e462ed",
|
|
"metadata": {},
|
|
"source": [
|
|
"## PC Users - if none of those 4 variations worked!\n",
|
|
"\n",
|
|
"Please get in touch with me. I'm sorry this is causing problems! We'll figure it out.\n",
|
|
"\n",
|
|
"Alternatively: playing audio from your PC isn't super-critical for this course, and you can feel free to focus on image generation and skip audio for now, or come back to it later."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "1d48876d-c4fa-46a8-a04f-f9fadf61fb0d",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Our Agent Framework\n",
|
|
"\n",
|
|
"The term 'Agentic AI' and Agentization is an umbrella term that refers to a number of techniques, such as:\n",
|
|
"\n",
|
|
"1. Breaking a complex problem into smaller steps, with multiple LLMs carrying out specialized tasks\n",
|
|
"2. The ability for LLMs to use Tools to give them additional capabilities\n",
|
|
"3. The 'Agent Environment' which allows Agents to collaborate\n",
|
|
"4. An LLM can act as the Planner, dividing bigger tasks into smaller ones for the specialists\n",
|
|
"5. The concept of an Agent having autonomy / agency, beyond just responding to a prompt - such as Memory\n",
|
|
"\n",
|
|
"We're showing 1 and 2 here, and to a lesser extent 3 and 5. In week 8 we will do the lot!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "ba820c95-02f5-499e-8f3c-8727ee0a6c0c",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def chat(history):\n",
|
|
" messages = [{\"role\": \"system\", \"content\": system_message}] + history\n",
|
|
" response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools)\n",
|
|
" image = None\n",
|
|
" \n",
|
|
" if response.choices[0].finish_reason==\"tool_calls\":\n",
|
|
" message = response.choices[0].message\n",
|
|
" response, city = handle_tool_call(message)\n",
|
|
" messages.append(message)\n",
|
|
" messages.append(response)\n",
|
|
" image = artist(city)\n",
|
|
" response = openai.chat.completions.create(model=MODEL, messages=messages)\n",
|
|
" \n",
|
|
" reply = response.choices[0].message.content\n",
|
|
" history += [{\"role\":\"assistant\", \"content\":reply}]\n",
|
|
"\n",
|
|
" # Comment out or delete the next line if you'd rather skip Audio for now..\n",
|
|
" talker(reply)\n",
|
|
" \n",
|
|
" return history, image"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "f38d0d27-33bf-4992-a2e5-5dbed973cde7",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# More involved Gradio code as we're not using the preset Chat interface!\n",
|
|
"# Passing in inbrowser=True in the last line will cause a Gradio window to pop up immediately.\n",
|
|
"\n",
|
|
"with gr.Blocks() as ui:\n",
|
|
" with gr.Row():\n",
|
|
" chatbot = gr.Chatbot(height=500, type=\"messages\")\n",
|
|
" image_output = gr.Image(height=500)\n",
|
|
" with gr.Row():\n",
|
|
" entry = gr.Textbox(label=\"Chat with our AI Assistant:\")\n",
|
|
" with gr.Row():\n",
|
|
" clear = gr.Button(\"Clear\")\n",
|
|
"\n",
|
|
" def do_entry(message, history):\n",
|
|
" history += [{\"role\":\"user\", \"content\":message}]\n",
|
|
" return \"\", history\n",
|
|
"\n",
|
|
" entry.submit(do_entry, inputs=[entry, chatbot], outputs=[entry, chatbot]).then(\n",
|
|
" chat, inputs=chatbot, outputs=[chatbot, image_output]\n",
|
|
" )\n",
|
|
" clear.click(lambda: None, inputs=None, outputs=chatbot, queue=False)\n",
|
|
"\n",
|
|
"ui.launch(inbrowser=True)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "226643d2-73e4-4252-935d-86b8019e278a",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Exercises and Business Applications\n",
|
|
"\n",
|
|
"Add in more tools - perhaps to simulate actually booking a flight. A student has done this and provided their example in the community contributions folder.\n",
|
|
"\n",
|
|
"Next: take this and apply it to your business. Make a multi-modal AI assistant with tools that could carry out an activity for your work. A customer support assistant? New employee onboarding assistant? So many possibilities! Also, see the week2 end of week Exercise in the separate Notebook."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "7e795560-1867-42db-a256-a23b844e6fbe",
|
|
"metadata": {},
|
|
"source": [
|
|
"<table style=\"margin: 0; text-align: left;\">\n",
|
|
" <tr>\n",
|
|
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
|
|
" <img src=\"../thankyou.jpg\" width=\"150\" height=\"150\" style=\"display: block;\" />\n",
|
|
" </td>\n",
|
|
" <td>\n",
|
|
" <h2 style=\"color:#090;\">I have a special request for you</h2>\n",
|
|
" <span style=\"color:#090;\">\n",
|
|
" My editor tells me that it makes a HUGE difference when students rate this course on Udemy - it's one of the main ways that Udemy decides whether to show it to others. If you're able to take a minute to rate this, I'd be so very grateful! And regardless - always please reach out to me at ed@edwarddonner.com if I can help at any point.\n",
|
|
" </span>\n",
|
|
" </td>\n",
|
|
" </tr>\n",
|
|
"</table>"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3 (ipykernel)",
|
|
"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.12.7"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|