{ "cells": [ { "cell_type": "markdown", "id": "44c07650", "metadata": {}, "source": [] }, { "cell_type": "markdown", "id": "22cfa9c5", "metadata": {}, "source": [] }, { "cell_type": "code", "execution_count": 1, "id": "4a90eb53", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from dotenv import load_dotenv\n", "from agents import Agent, Runner, trace\n", "from agents.mcp import MCPServerStdio, create_static_tool_filter\n", "import os\n", "from pathlib import Path\n", "from datetime import datetime\n", "from IPython.display import Markdown, display\n", "\n", "load_dotenv(override=True)" ] }, { "cell_type": "code", "execution_count": 2, "id": "a8e3d0c8", "metadata": {}, "outputs": [], "source": [ "\n", "import functools\n", "import subprocess\n", "import agents.mcp.server\n", "\n", "agents.mcp.server.stdio_client = functools.partial(agents.mcp.server.stdio_client, errlog=subprocess.DEVNULL)" ] }, { "cell_type": "code", "execution_count": 3, "id": "d4a15b44", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[Tool(name='create_entities', title='Create Entities', description='Create multiple new entities in the knowledge graph', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'entities': {'type': 'array', 'items': {'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name of the entity'}, 'entityType': {'type': 'string', 'description': 'The type of the entity'}, 'observations': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of observation contents associated with the entity'}}, 'required': ['name', 'entityType', 'observations']}}}, 'required': ['entities']}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'entities': {'type': 'array', 'items': {'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name of the entity'}, 'entityType': {'type': 'string', 'description': 'The type of the entity'}, 'observations': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of observation contents associated with the entity'}}, 'required': ['name', 'entityType', 'observations'], 'additionalProperties': False}}}, 'required': ['entities'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden')),\n", " Tool(name='create_relations', title='Create Relations', description='Create multiple new relations between entities in the knowledge graph. Relations should be in active voice', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'relations': {'type': 'array', 'items': {'type': 'object', 'properties': {'from': {'type': 'string', 'description': 'The name of the entity where the relation starts'}, 'to': {'type': 'string', 'description': 'The name of the entity where the relation ends'}, 'relationType': {'type': 'string', 'description': 'The type of the relation'}}, 'required': ['from', 'to', 'relationType']}}}, 'required': ['relations']}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'relations': {'type': 'array', 'items': {'type': 'object', 'properties': {'from': {'type': 'string', 'description': 'The name of the entity where the relation starts'}, 'to': {'type': 'string', 'description': 'The name of the entity where the relation ends'}, 'relationType': {'type': 'string', 'description': 'The type of the relation'}}, 'required': ['from', 'to', 'relationType'], 'additionalProperties': False}}}, 'required': ['relations'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden')),\n", " Tool(name='add_observations', title='Add Observations', description='Add new observations to existing entities in the knowledge graph', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'observations': {'type': 'array', 'items': {'type': 'object', 'properties': {'entityName': {'type': 'string', 'description': 'The name of the entity to add the observations to'}, 'contents': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of observation contents to add'}}, 'required': ['entityName', 'contents']}}}, 'required': ['observations']}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'results': {'type': 'array', 'items': {'type': 'object', 'properties': {'entityName': {'type': 'string'}, 'addedObservations': {'type': 'array', 'items': {'type': 'string'}}}, 'required': ['entityName', 'addedObservations'], 'additionalProperties': False}}}, 'required': ['results'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden')),\n", " Tool(name='delete_entities', title='Delete Entities', description='Delete multiple entities and their associated relations from the knowledge graph', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'entityNames': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of entity names to delete'}}, 'required': ['entityNames']}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'success': {'type': 'boolean'}, 'message': {'type': 'string'}}, 'required': ['success', 'message'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=False, destructiveHint=True, idempotentHint=True, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden')),\n", " Tool(name='delete_observations', title='Delete Observations', description='Delete specific observations from entities in the knowledge graph', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'deletions': {'type': 'array', 'items': {'type': 'object', 'properties': {'entityName': {'type': 'string', 'description': 'The name of the entity containing the observations'}, 'observations': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of observations to delete'}}, 'required': ['entityName', 'observations']}}}, 'required': ['deletions']}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'success': {'type': 'boolean'}, 'message': {'type': 'string'}}, 'required': ['success', 'message'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=False, destructiveHint=True, idempotentHint=True, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden')),\n", " Tool(name='delete_relations', title='Delete Relations', description='Delete multiple relations from the knowledge graph', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'relations': {'type': 'array', 'items': {'type': 'object', 'properties': {'from': {'type': 'string', 'description': 'The name of the entity where the relation starts'}, 'to': {'type': 'string', 'description': 'The name of the entity where the relation ends'}, 'relationType': {'type': 'string', 'description': 'The type of the relation'}}, 'required': ['from', 'to', 'relationType']}, 'description': 'An array of relations to delete'}}, 'required': ['relations']}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'success': {'type': 'boolean'}, 'message': {'type': 'string'}}, 'required': ['success', 'message'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=False, destructiveHint=True, idempotentHint=True, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden')),\n", " Tool(name='read_graph', title='Read Graph', description='Read the entire knowledge graph', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {}}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'entities': {'type': 'array', 'items': {'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name of the entity'}, 'entityType': {'type': 'string', 'description': 'The type of the entity'}, 'observations': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of observation contents associated with the entity'}}, 'required': ['name', 'entityType', 'observations'], 'additionalProperties': False}}, 'relations': {'type': 'array', 'items': {'type': 'object', 'properties': {'from': {'type': 'string', 'description': 'The name of the entity where the relation starts'}, 'to': {'type': 'string', 'description': 'The name of the entity where the relation ends'}, 'relationType': {'type': 'string', 'description': 'The type of the relation'}}, 'required': ['from', 'to', 'relationType'], 'additionalProperties': False}}}, 'required': ['entities', 'relations'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden')),\n", " Tool(name='search_nodes', title='Search Nodes', description='Search for nodes in the knowledge graph based on a query', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The search query to match against entity names, types, and observation content'}}, 'required': ['query']}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'entities': {'type': 'array', 'items': {'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name of the entity'}, 'entityType': {'type': 'string', 'description': 'The type of the entity'}, 'observations': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of observation contents associated with the entity'}}, 'required': ['name', 'entityType', 'observations'], 'additionalProperties': False}}, 'relations': {'type': 'array', 'items': {'type': 'object', 'properties': {'from': {'type': 'string', 'description': 'The name of the entity where the relation starts'}, 'to': {'type': 'string', 'description': 'The name of the entity where the relation ends'}, 'relationType': {'type': 'string', 'description': 'The type of the relation'}}, 'required': ['from', 'to', 'relationType'], 'additionalProperties': False}}}, 'required': ['entities', 'relations'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden')),\n", " Tool(name='open_nodes', title='Open Nodes', description='Open specific nodes in the knowledge graph by their names', inputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'names': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of entity names to retrieve'}}, 'required': ['names']}, outputSchema={'$schema': 'http://json-schema.org/draft-07/schema#', 'type': 'object', 'properties': {'entities': {'type': 'array', 'items': {'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name of the entity'}, 'entityType': {'type': 'string', 'description': 'The type of the entity'}, 'observations': {'type': 'array', 'items': {'type': 'string'}, 'description': 'An array of observation contents associated with the entity'}}, 'required': ['name', 'entityType', 'observations'], 'additionalProperties': False}}, 'relations': {'type': 'array', 'items': {'type': 'object', 'properties': {'from': {'type': 'string', 'description': 'The name of the entity where the relation starts'}, 'to': {'type': 'string', 'description': 'The name of the entity where the relation ends'}, 'relationType': {'type': 'string', 'description': 'The type of the relation'}}, 'required': ['from', 'to', 'relationType'], 'additionalProperties': False}}}, 'required': ['entities', 'relations'], 'additionalProperties': False}, icons=None, annotations=ToolAnnotations(title=None, readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False), meta=None, execution=ToolExecution(taskSupport='forbidden'))]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "memory_path = os.path.abspath(\"memory/memory.json\")\n", "memory_params = {\"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-memory\"], \"env\": {\"MEMORY_FILE_PATH\": memory_path}}\n", "\n", "async with MCPServerStdio(params=memory_params, client_session_timeout_seconds=60) as server:\n", " memory_tools = await server.list_tools()\n", "\n", "memory_tools" ] }, { "cell_type": "code", "execution_count": 4, "id": "93f2c256", "metadata": {}, "outputs": [], "source": [ "instructions = \"You use your entity tools as a persistent memory to store and recall information about your conversations.\"\n", "request = \"My name's Mohan. I'm an LLM engineer. I'm teaching a course about AI Agents, including the incredible MCP protocol. MCP is a protocol for connecting agents with tools, resources and prompt templates, and makes it easy to integrate AI agents with capabilities.\"\n", "model = \"gpt-4o-mini\"" ] }, { "cell_type": "code", "execution_count": 5, "id": "787144ee", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "I've noted your information. If you need to add more details or have any specific requests, feel free to let me know!" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "async with MCPServerStdio(params=memory_params, client_session_timeout_seconds=30) as mcp_server:\n", " agent = Agent(name=\"agent\", instructions=instructions, model=model, mcp_servers=[mcp_server])\n", " with trace(\"conversation\"):\n", " result = await Runner.run(agent, request)\n", " display(Markdown(result.final_output))" ] }, { "cell_type": "code", "execution_count": 6, "id": "8c5c05dd", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "I've recorded your information:\n", "\n", "- **Name**: Mohan\n", " - **Role**: LLM engineer\n", " - **Activities**: Teaching a course about AI Agents and knowledgeable about the MCP protocol.\n", " \n", "- **MCP Protocol**:\n", " - Connects agents with tools, resources, and prompt templates.\n", " - Facilitates integration of AI agents with various capabilities.\n", "\n", "Let me know if you need any further assistance!" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "async with MCPServerStdio(params=memory_params, client_session_timeout_seconds=30) as mcp_server:\n", " agent = Agent(name=\"agent\", instructions=instructions, model=model, mcp_servers=[mcp_server])\n", " with trace(\"conversation\"):\n", " result = await Runner.run(agent, request)\n", " display(Markdown(result.final_output))" ] }, { "cell_type": "code", "execution_count": 7, "id": "6c199790", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "I know that you're Mohan, an LLM engineer. You are teaching a course about AI Agents, which includes the MCP protocol. If you'd like to share more or update any information, feel free to let me know!" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "async with MCPServerStdio(params=memory_params, client_session_timeout_seconds=30) as mcp_server:\n", " agent = Agent(name=\"agent\", instructions=instructions, model=model, mcp_servers=[mcp_server])\n", " with trace(\"conversation\"):\n", " result = await Runner.run(agent, \"My name's Mohan . What do you know about me?\")\n", " display(Markdown(result.final_output))" ] }, { "cell_type": "code", "execution_count": 8, "id": "d5ac80de", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[Tool(name='tavily_search', title=None, description='Search the web for current information on any topic. Use for news, facts, or data beyond your knowledge cutoff. Returns snippets and source URLs.', inputSchema={'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'Search query'}, 'search_depth': {'type': 'string', 'enum': ['basic', 'advanced', 'fast', 'ultra-fast'], 'description': \"The depth of the search. 'basic' for generic results, 'advanced' for more thorough search, 'fast' for optimized low latency with high relevance, 'ultra-fast' for prioritizing latency above all else\", 'default': 'basic'}, 'topic': {'type': 'string', 'enum': ['general'], 'description': 'The category of the search. This will determine which of our agents will be used for the search', 'default': 'general'}, 'time_range': {'type': 'string', 'description': 'The time range back from the current date to include in the search results', 'enum': ['day', 'week', 'month', 'year']}, 'start_date': {'type': 'string', 'description': 'Will return all results after the specified start date. Required to be written in the format YYYY-MM-DD.', 'default': ''}, 'end_date': {'type': 'string', 'description': 'Will return all results before the specified end date. Required to be written in the format YYYY-MM-DD', 'default': ''}, 'max_results': {'type': 'number', 'description': 'The maximum number of search results to return', 'default': 5, 'minimum': 5, 'maximum': 20}, 'include_images': {'type': 'boolean', 'description': 'Include a list of query-related images in the response', 'default': False}, 'include_image_descriptions': {'type': 'boolean', 'description': 'Include a list of query-related images and their descriptions in the response', 'default': False}, 'include_raw_content': {'type': 'boolean', 'description': 'Include the cleaned and parsed HTML content of each search result', 'default': False}, 'include_domains': {'type': 'array', 'items': {'type': 'string'}, 'description': 'A list of domains to specifically include in the search results, if the user asks to search on specific sites set this to the domain of the site', 'default': []}, 'exclude_domains': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of domains to specifically exclude, if the user asks to exclude a domain set this to the domain of the site', 'default': []}, 'country': {'type': 'string', 'description': \"Boost search results from a specific country. Must be a full country name (e.g., 'United States', 'Japan', 'Germany'). ISO country codes (e.g., 'us', 'jp') are not supported. Available only if topic is general. See https://docs.tavily.com/documentation/api-reference/search for the full list of supported countries.\", 'default': ''}, 'include_favicon': {'type': 'boolean', 'description': 'Whether to include the favicon URL for each result', 'default': False}, 'exact_match': {'type': 'boolean', 'description': 'Only return results containing the exact phrase(s) in quotes in your query'}}, 'required': ['query']}, outputSchema=None, icons=None, annotations=None, meta=None, execution=None),\n", " Tool(name='tavily_extract', title=None, description='Extract content from URLs. Returns raw page content in markdown or text format.', inputSchema={'type': 'object', 'properties': {'urls': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of URLs to extract content from'}, 'extract_depth': {'type': 'string', 'enum': ['basic', 'advanced'], 'description': \"Use 'advanced' for LinkedIn, protected sites, or tables/embedded content\", 'default': 'basic'}, 'include_images': {'type': 'boolean', 'description': 'Include images from pages', 'default': False}, 'format': {'type': 'string', 'enum': ['markdown', 'text'], 'description': 'Output format', 'default': 'markdown'}, 'include_favicon': {'type': 'boolean', 'description': 'Include favicon URLs', 'default': False}, 'query': {'type': 'string', 'description': 'Query to rerank content chunks by relevance'}}, 'required': ['urls']}, outputSchema=None, icons=None, annotations=None, meta=None, execution=None),\n", " Tool(name='tavily_crawl', title=None, description='Crawl a website starting from a URL. Extracts content from pages with configurable depth and breadth.', inputSchema={'type': 'object', 'properties': {'url': {'type': 'string', 'description': 'The root URL to begin the crawl'}, 'max_depth': {'type': 'integer', 'description': 'Max depth of the crawl. Defines how far from the base URL the crawler can explore.', 'default': 1, 'minimum': 1}, 'max_breadth': {'type': 'integer', 'description': 'Max number of links to follow per level of the tree (i.e., per page)', 'default': 20, 'minimum': 1}, 'limit': {'type': 'integer', 'description': 'Total number of links the crawler will process before stopping', 'default': 50, 'minimum': 1}, 'instructions': {'type': 'string', 'description': 'Natural language instructions for the crawler. Instructions specify which types of pages the crawler should return.'}, 'select_paths': {'type': 'array', 'items': {'type': 'string'}, 'description': 'Regex patterns to select only URLs with specific path patterns (e.g., /docs/.*, /api/v1.*)', 'default': []}, 'select_domains': {'type': 'array', 'items': {'type': 'string'}, 'description': 'Regex patterns to restrict crawling to specific domains or subdomains (e.g., ^docs\\\\.example\\\\.com$)', 'default': []}, 'allow_external': {'type': 'boolean', 'description': 'Whether to return external links in the final response', 'default': True}, 'extract_depth': {'type': 'string', 'enum': ['basic', 'advanced'], 'description': 'Advanced extraction retrieves more data, including tables and embedded content, with higher success but may increase latency', 'default': 'basic'}, 'format': {'type': 'string', 'enum': ['markdown', 'text'], 'description': 'The format of the extracted web page content. markdown returns content in markdown format. text returns plain text and may increase latency.', 'default': 'markdown'}, 'include_favicon': {'type': 'boolean', 'description': 'Whether to include the favicon URL for each result', 'default': False}}, 'required': ['url']}, outputSchema=None, icons=None, annotations=None, meta=None, execution=None),\n", " Tool(name='tavily_map', title=None, description=\"Map a website's structure. Returns a list of URLs found starting from the base URL.\", inputSchema={'type': 'object', 'properties': {'url': {'type': 'string', 'description': 'The root URL to begin the mapping'}, 'max_depth': {'type': 'integer', 'description': 'Max depth of the mapping. Defines how far from the base URL the crawler can explore', 'default': 1, 'minimum': 1}, 'max_breadth': {'type': 'integer', 'description': 'Max number of links to follow per level of the tree (i.e., per page)', 'default': 20, 'minimum': 1}, 'limit': {'type': 'integer', 'description': 'Total number of links the crawler will process before stopping', 'default': 50, 'minimum': 1}, 'instructions': {'type': 'string', 'description': 'Natural language instructions for the crawler'}, 'select_paths': {'type': 'array', 'items': {'type': 'string'}, 'description': 'Regex patterns to select only URLs with specific path patterns (e.g., /docs/.*, /api/v1.*)', 'default': []}, 'select_domains': {'type': 'array', 'items': {'type': 'string'}, 'description': 'Regex patterns to restrict crawling to specific domains or subdomains (e.g., ^docs\\\\.example\\\\.com$)', 'default': []}, 'allow_external': {'type': 'boolean', 'description': 'Whether to return external links in the final response', 'default': True}}, 'required': ['url']}, outputSchema=None, icons=None, annotations=None, meta=None, execution=None),\n", " Tool(name='tavily_research', title=None, description='Perform comprehensive research on a given topic or question. Use this tool when you need to gather information from multiple sources to answer a question or complete a task. Returns a detailed response based on the research findings. Rate limit: 20 requests per minute.', inputSchema={'type': 'object', 'properties': {'input': {'type': 'string', 'description': 'A comprehensive description of the research task'}, 'model': {'type': 'string', 'enum': ['mini', 'pro', 'auto'], 'description': \"Defines the degree of depth of the research. 'mini' is good for narrow tasks with few subtopics. 'pro' is good for broad tasks with many subtopics. 'auto' automatically selects the best model.\", 'default': 'auto'}}, 'required': ['input']}, outputSchema=None, icons=None, annotations=None, meta=None, execution=None)]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tavily_params = {\"command\": \"npx\", \"args\": [\"-y\", \"tavily-mcp@latest\"], \"env\": {\"TAVILY_API_KEY\": os.getenv(\"TAVILY_API_KEY\")}}\n", "\n", "async with MCPServerStdio(params=tavily_params, client_session_timeout_seconds=60) as server:\n", " tavily_tools = await server.list_tools()\n", "\n", "tavily_tools" ] }, { "cell_type": "code", "execution_count": 9, "id": "cd2a8029", "metadata": {}, "outputs": [], "source": [ "instructions = \"You search the web for information and briefly summarize the takeaways.\"\n", "request = f\"Please research the latest news on Amazon stock price and briefly summarize its outlook. For context, the current date is {datetime.now().strftime('%Y-%m-%d')}\"\n", "model = \"gpt-4o-mini\"\n", "search_only = create_static_tool_filter(allowed_tool_names=[\"tavily_search\"])" ] }, { "cell_type": "code", "execution_count": 10, "id": "d8e3e51a", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "As of July 23, 2026, Amazon's stock (AMZN) closed at **$233.66**, marking a **4.57% decline** in a single day. The shares saw a modest recovery in pre-market trading, rising to **$234.66**.\n", "\n", "### Key Factors for Price Movement:\n", "1. **Regulatory Scrutiny**: Amazon is under investigation by a U.S. Senate panel regarding potential undue Chinese influence on its marketplace. This has heightened investor concerns, further driven by ongoing antitrust lawsuits and allegations of deceptive business practices.\n", " \n", "2. **Operational Changes**: The company has announced job cuts aimed at streamlining operations within its Artificial General Intelligence (AGI) division, focusing on enhancing projects that deliver direct customer value.\n", "\n", "3. **Market Sentiment**: Despite the recent drop, analysts maintain a generally positive outlook. Major firms like Citi and KeyBanc recently reaffirmed their \"Buy\" ratings, with price targets ranging from **$325** to **$335**. The consensus average price target across analysts is around **$318.98**, indicating an anticipated upside of approximately **36.41%** from current levels.\n", "\n", "4. **Earnings Anticipation**: The upcoming Q2 earnings report on July 30 is another focal point for investors. Analysts suggest that strong growth in Amazon's business segments, including a notable increase in gross sales on the Amazon Business platform, supports a continued bullish sentiment.\n", "\n", "### Outlook:\n", "In summary, while Amazon faces regulatory and operational challenges that contributed to its recent stock decline, analysts remain optimistic about the company's long-term growth potential, particularly in AWS and AI infrastructure. The consensus is a \"Moderate Buy,\" with projections suggesting significant recovery potential." ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "async with MCPServerStdio(params=tavily_params, client_session_timeout_seconds=60, tool_filter=search_only) as mcp_server:\n", " agent = Agent(name=\"agent\", instructions=instructions, model=model, mcp_servers=[mcp_server])\n", " with trace(\"conversation\"):\n", " result = await Runner.run(agent, request)\n", " display(Markdown(result.final_output))" ] }, { "cell_type": "markdown", "id": "24d6a53c", "metadata": {}, "source": [ "### AGENTIC RAG INTEGRATION ####" ] }, { "cell_type": "code", "execution_count": 11, "id": "c3817fa9", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[Tool(name='qdrant-find', title=None, description='Look up memories in Qdrant. Use this tool when you need to: \\n - Find memories by their content \\n - Access memories for further analysis \\n - Get some personal information about the user', inputSchema={'properties': {'query': {'description': 'What to search for', 'title': 'Query', 'type': 'string'}}, 'required': ['query'], 'type': 'object'}, outputSchema=None, icons=None, annotations=None, meta=None, execution=None),\n", " Tool(name='qdrant-store', title=None, description='Keep the memory for later use, when you are asked to remember something.', inputSchema={'properties': {'information': {'description': 'Text to store', 'title': 'Information', 'type': 'string'}, 'metadata': {'anyOf': [{'additionalProperties': True, 'type': 'object'}, {'type': 'null'}], 'default': None, 'description': 'Extra metadata stored along with memorised information. Any json is accepted.', 'title': 'Metadata'}}, 'required': ['information'], 'type': 'object'}, outputSchema=None, icons=None, annotations=None, meta=None, execution=None)]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vectordb_path = Path(\"memory/qdrant\")\n", "vectorstore_params = {\n", " \"command\": \"uvx\",\n", " \"args\": [\"mcp-server-qdrant\"],\n", " \"env\": {\n", " \"QDRANT_LOCAL_PATH\": str(vectordb_path),\n", " \"COLLECTION_NAME\": \"knowledge\",\n", " },\n", "}\n", "\n", "async with MCPServerStdio(params=vectorstore_params, client_session_timeout_seconds=120) as server:\n", " vectorstore_tools = await server.list_tools()\n", "\n", "vectorstore_tools" ] }, { "cell_type": "code", "execution_count": 12, "id": "cd1c1b4a", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "I have researched the latest news on Nvidia and stored key facts in the knowledge base. Here are the key points:\n", "\n", "1. Nvidia CEO Jensen Huang predicts Marvell as the next AI trillion-dollar giant, TCS opens an NVIDIA-powered AI engineering lab, and Yotta Data Services invests in Nvidia's latest chips for an AI hub.\n", "\n", "2. Nvidia's DLSS 4.5 update with 6x frame generation is available, ePlane joins forces with Nvidia for aerospace innovation, and Uniphore raises $260 million in funding from Nvidia and others.\n", "\n", "3. BlackBerry's QNX software safeguards Nvidia's self-driving platform, Arm's CEO introduces a disruptive new CPU, and IITian Rishabh Agarwal launches an Nvidia-backed startup.\n", "\n", "4. Nvidia rewrites the AI storage rulebook at GTC 2026, partners with Microsoft for nuclear reactor deployment, and surpasses Tesla in global value creators ranking.\n", "\n", "5. Jensen Huang emphasizes the profitability of AI and auctions his signature leather jacket for a high price." ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "INSTRUCTIONS = \"\"\"You research topics on the web and build up a knowledge base for later.\n", "When you learn something worth keeping, store it in your knowledge base.\n", "When you are asked what you know, search your knowledge base and answer from it.\"\"\"\n", "\n", "model = \"gpt-3.5-turbo\"\n", "\n", "async with MCPServerStdio(params=tavily_params, client_session_timeout_seconds=60, tool_filter=search_only) as search_server:\n", " async with MCPServerStdio(params=vectorstore_params, client_session_timeout_seconds=120) as vector_server:\n", " agent = Agent(name=\"researcher\", instructions=INSTRUCTIONS, model=model, mcp_servers=[search_server, vector_server])\n", " with trace(\"research and store\"):\n", " result = await Runner.run(agent, \"Research the latest news on Nvidia and store the key facts in your knowledge base.\", max_turns=20)\n", " display(Markdown(result.final_output))" ] }, { "cell_type": "code", "execution_count": 13, "id": "f44d3a66", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "Here are some recent updates on Nvidia:\n", "\n", "1. Nvidia has rewritten the AI storage rulebook at GTC 2026 and partnered with Microsoft to create a digital ecosystem for accelerating nuclear reactor deployment.\n", "2. Nvidia has released the DLSS 4.5 update with 6x frame generation to boost gaming performance. They have also partnered with Indian eVTOL startup ePlane for aerospace innovation.\n", "3. Nvidia CEO Jensen Huang predicts Marvell as the next AI trillion-dollar giant and TCS has opened an NVIDIA-powered AI engineering lab in Bengaluru. Hiranandani Group-backed Yotta Data Services will spend over $2 billion on Nvidia's latest chips for an artificial intelligence hub.\n", "4. BlackBerry's QNX software will safeguard NVIDIA's self-driving platform. Arm's CEO claims the market needs his new CPU, which could disrupt the industry. IITian Rishabh Agarwal rejected Meta's offer to launch an NVIDIA-backed startup for AI scientists.\n", "5. Nvidia CEO Jensen Huang mentioned that AI is 'insanely profitable' as he engages with billionaire families. Additionally, Jensen Huang's signature leather jacket is up for auction, expected to sell for a significant price." ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "async with MCPServerStdio(params=vectorstore_params, client_session_timeout_seconds=120) as vector_server:\n", " agent = Agent(name=\"researcher\", instructions=INSTRUCTIONS, model=model, mcp_servers=[vector_server])\n", " with trace(\"retrieve\"):\n", " result = await Runner.run(agent, \"Based on your knowledge base, what's the latest on Nvidia?\")\n", " display(Markdown(result.final_output))" ] }, { "cell_type": "markdown", "id": "7cff511b", "metadata": {}, "source": [ "### INTEGRATION ###" ] }, { "cell_type": "code", "execution_count": 14, "id": "ca899a32", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[Tool(name='lookup_share_price', title=None, description='This tool provides the current price of the given stock symbol.\\n\\nArgs:\\n symbol: the symbol of the stock\\n', inputSchema={'properties': {'symbol': {'title': 'Symbol', 'type': 'string'}}, 'required': ['symbol'], 'title': 'lookup_share_priceArguments', 'type': 'object'}, outputSchema={'properties': {'result': {'title': 'Result', 'type': 'number'}}, 'required': ['result'], 'title': 'lookup_share_priceOutput', 'type': 'object'}, icons=None, annotations=None, meta=None, execution=None)]" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "massive_api_key = os.getenv(\"MASSIVE_API_KEY\")\n", "\n", "if massive_api_key:\n", " market_params = {\n", " \"command\": \"uvx\",\n", " \"args\": [\"--from\", \"git+https://github.com/massive-com/mcp_massive@v0.10.0\", \"mcp_massive\"],\n", " \"env\": {\"MASSIVE_API_KEY\": massive_api_key},\n", " }\n", "else:\n", " market_params = {\"command\": \"uv\", \"args\": [\"run\", \"-m\", \"backend.market_server\"]}\n", "\n", "async with MCPServerStdio(params=market_params, client_session_timeout_seconds=120) as server:\n", " market_tools = await server.list_tools()\n", "\n", "market_tools" ] }, { "cell_type": "code", "execution_count": 15, "id": "06922fe2", "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "The most recent price that Kawasaki Motosport traded at was $358.91." ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "instructions = \"You answer questions about the stock market.\"\n", "request = \"What was the most recent price that Kawasaki Motosport traded at?\"\n", "model = \"gpt-3.5-turbo\"\n", "\n", "async with MCPServerStdio(params=market_params, client_session_timeout_seconds=120) as mcp_server:\n", " agent = Agent(name=\"agent\", instructions=instructions, model=model, mcp_servers=[mcp_server])\n", " with trace(\"conversation\"):\n", " result = await Runner.run(agent, request)\n", " display(Markdown(result.final_output))" ] }, { "cell_type": "code", "execution_count": null, "id": "9add634a", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "7f00e9b6", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "30c960c3", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "dfb06936", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "25f35eca", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "57a1af3b", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "f9cac71c", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "bb68ce13", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "585a7db6", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.13" } }, "nbformat": 4, "nbformat_minor": 5 }