{"id":7896,"date":"2025-10-21T04:57:04","date_gmt":"2025-10-21T04:57:04","guid":{"rendered":"https:\/\/techtrendfeed.com\/?p=7896"},"modified":"2025-10-21T04:57:04","modified_gmt":"2025-10-21T04:57:04","slug":"methods-to-construct-an-ai-agent-with-operate-calling-and-gpt-5","status":"publish","type":"post","link":"https:\/\/techtrendfeed.com\/?p=7896","title":{"rendered":"Methods to Construct An AI Agent with Operate Calling and GPT-5"},"content":{"rendered":"<p> <br \/>\n<\/p>\n<div>\n<h2 class=\"wp-block-heading\"> and Giant Language Fashions (LLMs)<\/h2>\n<p class=\"wp-block-paragraph\"><strong>Giant language fashions (LLMs)<\/strong>\u00a0are superior AI programs constructed on deep neural community comparable to transformers and educated on huge quantities of textual content to generate human-like language. LLMs like ChatGPT, Claude, Gemini and Grok can deal with many difficult duties and are used throughout fields comparable to science, healthcare, training, and finance.<\/p>\n<p class=\"wp-block-paragraph\">An AI agent extends the capabilites of LLMs to unravel duties which can be past their pre-trained data. An LLM can write a Python tutorial from what it discovered throughout coaching. When you ask it to ebook a flight, the duty requires entry to your calendar, net search and the flexibility to take actions, these fall past the LLM\u2019s pre-trained data. A few of the frequent actions embrace:<\/p>\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\"><em><strong>Climate forecast:<\/strong>\u00a0<\/em>The LLM connects to an online search software to fetch the newest climate forecast.<\/li>\n<li class=\"wp-block-list-item\"><em><strong>Reserving agent:\u00a0<\/strong><\/em>An AI agent that may verify a consumer\u2019s calendar, search the net to go to a reserving web site like Expedia to search out out there choices for flights and accommodations, current them to the consumer for affirmation, and full the reserving on behalf of the consumer.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">How an AI Agent Works<\/h2>\n<p class=\"wp-block-paragraph\">AI brokers type a system that makes use of a Giant Language Mannequin to plan, purpose, and take steps to work together with its atmosphere utilizing instruments prompt from the mannequin\u2019s reasoning to unravel a selected process.<\/p>\n<h3 class=\"wp-block-heading\">Fundamental Construction of an AI Agent<\/h3>\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/contributor.insightmediagroup.io\/wp-content\/uploads\/2025\/10\/agent.webp\" alt=\"\" class=\"wp-image-624142\"\/><figcaption class=\"wp-element-caption\">Picture Generated By Gemini<\/figcaption><\/figure>\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\"><em><strong>A Giant Language Mannequin (LLM):<\/strong><\/em>\u00a0the LLM is the\u00a0<em><strong>mind<\/strong><\/em>\u00a0of an AI agent. It takes a consumer\u2019s immediate, plans and causes via the request and breaks the issue into steps that decide which instruments it ought to use to finish the duty.<\/li>\n<li class=\"wp-block-list-item\"><em><strong>A software\u00a0<\/strong><\/em>is the framework that the agent makes use of to carry out an motion primarily based on the plan and reasoning from the Giant Language Mannequin. When you ask an LLM to ebook a desk for you at a restaurant, doable instruments that can be used embrace calendar to verify your availability and an online search software to entry the restaurant web site and make a reservation for you.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">Ilustrated Resolution Making of a Reserving AI Agent<\/h3>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/contributor.insightmediagroup.io\/wp-content\/uploads\/2025\/10\/booking-1024x683.webp\" alt=\"\" class=\"wp-image-624143\"\/><figcaption class=\"wp-element-caption\">Picture Generated By ChatGPT<\/figcaption><\/figure>\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">AI brokers can entry completely different instruments relying on the duty. A software is likely to be an information retailer, comparable to a database. For instance, a customer-support agent might entry a buyer\u2019s account particulars and buy historical past and determine when to retrieve that data to assist resolve a difficulty.<\/p>\n<\/blockquote>\n<p class=\"wp-block-paragraph\">AI brokers are used to unravel a variety of duties, and there are numerous highly effective brokers out there. Coding brokers, significantly agentic IDEs comparable to Cursor, Windsurf, and GitHub Copilot assist engineers write and debug code quicker and construct tasks rapidly. CLI Coding brokers like Claude Code and Codex CLI can work together with a consumer\u2019s desktop and terminal to hold out coding duties. ChatGPT helps brokers that may carry out actions comparable to reserving reservations on a consumer\u2019s behalf. Brokers are additionally built-in into buyer help workflows to speak with clients and resolve their points.<\/p>\n<h2 class=\"wp-block-heading\">Operate Calling<\/h2>\n<p class=\"wp-block-paragraph\">Operate calling is a way for connecting a big language mannequin (LLM) to exterior instruments comparable to APIs or databases. It&#8217;s utilized in creating AI brokers to attach LLMs to instruments. In perform calling, every software is outlined as a code perform (for instance, a climate API to fetch the newest forecast) together with a JSON Schema that specifies the perform\u2019s parameters and instructs the LLM on when and  name the perform for a given process.<\/p>\n<p class=\"wp-block-paragraph\">The kind of perform outlined is dependent upon the duty the agent is designed to carry out. For instance, for a buyer help agent we will outline a perform that may extract data from unstructured information, comparable to PDFs containing particulars a couple of enterprise\u2019s merchandise.<\/p>\n<p class=\"wp-block-paragraph\">On this submit I&#8217;ll exhibit  use perform calling to construct a easy net search agent utilizing GPT-5 as the massive language mannequin.<\/p>\n<h2 class=\"wp-block-heading\">Fundamental Construction of a Internet Search Agent<\/h2>\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/contributor.insightmediagroup.io\/wp-content\/uploads\/2025\/10\/functioncall.webp\" alt=\"\" class=\"wp-image-624144\"\/><figcaption class=\"wp-element-caption\">Picture Generated By Gemini<\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">The primary logic behind the net search agent:<\/h2>\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\">Outline a code perform to deal with the net search.<\/li>\n<li class=\"wp-block-list-item\">Outline customized directions that information the massive language mannequin in figuring out when to name the net search perform primarily based on the question. For instance, if the question asks concerning the present climate, the net search agent will acknowledge the necessity to search the web to get the newest climate reviews. Nonetheless, if the question asks it to jot down a tutorial a couple of programming language like Python, one thing it will possibly reply from its pre-trained data it won&#8217;t name the net search perform and can reply immediately as an alternative.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Prerequisite<\/h2>\n<p class=\"wp-block-paragraph\"><strong>Create an OpenAI account and generate an API key<\/strong><br \/>1:<strong>\u00a0<\/strong>Create an\u00a0<a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/auth.openai.com\/create-account\">OpenAI Account<\/a>\u00a0when you don\u2019t have one<br \/>2:\u00a0<a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/platform.openai.com\/account\/api-keys\">Generate an API Key<\/a><\/p>\n<p class=\"wp-block-paragraph\"><strong>Arrange and Activate Surroundings<\/strong><\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-bash\">python3 -m venv env\nsupply env\/bin\/activate<\/code><\/pre>\n<p class=\"wp-block-paragraph\"><strong>Export OpenAI API Key<\/strong><\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-bash\">export OPENAI_API_KEY=\"Your Openai API Key\"<\/code><\/pre>\n<p class=\"wp-block-paragraph\"><strong>Setup Tavily for Internet Search<\/strong><br \/>Tavily is a specialised web-search software for AI brokers. Create an account on\u00a0<a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/www.tavily.com\/\">Tavily.com<\/a>, and as soon as your profile is ready up, an API key can be generated that you would be able to copy into your atmosphere. New accounta obtain 1000 free credit that can be utilized for as much as 1000 net searches.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Export TAVILY API Key<\/strong><\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-bash\">export TAVILY_API_KEY=\"Your Tavily API Key\"<\/code><\/pre>\n<p class=\"wp-block-paragraph\"><strong>Set up Packages<\/strong><\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-bash\">pip3 set up openai\npip3 set up tavily-python<\/code><\/pre>\n<h2 class=\"wp-block-heading\">Constructing a Internet Search Agent with Operate Calling Step by Step<\/h2>\n<h3 class=\"wp-block-heading\">Step 1: Create Internet Search Operate with Tavily<\/h3>\n<p class=\"wp-block-paragraph\">An online search perform is applied utilizing Tavily, serving because the software for perform calling within the net search agent.<\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-python\">from tavily import TavilyClient\nimport os\n\ntavily = TavilyClient(api_key=os.getenv(\"TAVILY_API_KEY\"))\n\ndef web_search(question: str, num_results: int = 10):\n    strive:\n        consequence = tavily.search(\n            question=question,\n            search_depth=\"primary\",\n            max_results=num_results,\n            include_answer=False,       \n            include_raw_content=False,\n            include_images=False\n        )\n\n        outcomes = consequence.get(\"outcomes\", [])\n\n        return {\n            \"question\": question,\n            \"outcomes\": outcomes, \n            \"sources\": [\n                {\"title\": r.get(\"title\", \"\"), \"url\": r.get(\"url\", \"\")}\n                for r in results\n            ]\n        }\n\n    besides Exception as e:\n        return {\n            \"error\": f\"Search error: {e}\",\n            \"question\": question,\n            \"outcomes\": [],\n            \"sources\": [],\n        }<\/code><\/pre>\n<p class=\"wp-block-paragraph\"><strong>Internet perform code breakdown<\/strong><\/p>\n<p class=\"wp-block-paragraph\">Tavily is initialized with its API key. Within the\u00a0<code>web_search<\/code>\u00a0perform, the next steps are carried out:<\/p>\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\">Tavily search perform is known as to look the web and retrieve the highest 10 outcomes.<\/li>\n<li class=\"wp-block-list-item\">The search outcomes and their corresponding sources are returned.<\/li>\n<\/ul>\n<p class=\"wp-block-paragraph\">This returned output will function related context for the net search agent: which we are going to outline later on this article, to fetch up-to-date data for queries (prompts) that require real-time information comparable to climate forecasts.<\/p>\n<h3 class=\"wp-block-heading\">Step 2: Create Software Schema<\/h3>\n<p class=\"wp-block-paragraph\">The software schema defines customized directions for an AI mannequin on when it ought to name a software, on this case the software that can be utilized in an online search perform. It additionally specifies the situations and actions to be taken when the mannequin calls a software. A json software schema is outlined under primarily based on the\u00a0<a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/platform.openai.com\/docs\/guides\/structured-outputs?context=with_parse#supported-schemas\">OpenAI software schema construction<\/a>.<\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-yaml\">tool_schema = [\n    {\n        \"type\": \"function\",\n        \"name\": \"web_search\",\n\n        \"description\": \"\"\"Execute a web search to fetch up to date information. Synthesize a concise, \n        self-contained answer from the content of the results of the visited pages.\n        Fetch pages, extract text, and provide the best available result while citing 1-3 sources (title + URL). \n        If sources conflict, surface the uncertainty and prefer the most recent evidence.\n        \"\"\",\n\n        \"strict\": True,\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"query\": {\n                    \"type\": \"string\",\n                    \"description\": \"Query to be searched on the web.\",\n                },\n            },\n            \"required\": [\"query\"],\n            \"additionalProperties\": False\n        },\n    },\n]\n<\/code><\/pre>\n<h4 class=\"wp-block-heading\">Software schema\u2019s Properties<\/h4>\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\"><em><strong>kind:<\/strong><\/em>\u00a0Specifies that the kind of software is a perform.<\/li>\n<li class=\"wp-block-list-item\"><em><strong>identify:<\/strong><\/em>\u00a0the identify of the perform that can be used for software name, which is\u00a0<em><strong>web_search<\/strong><\/em>.<\/li>\n<li class=\"wp-block-list-item\"><em><strong>description:<\/strong><\/em>\u00a0Describes what the AI mannequin ought to do when calling the net search software. It instructs the mannequin to look the web utilizing the\u00a0<em><strong>web_search<\/strong><\/em>\u00a0perform to fetch up-to-date data and extract related particulars to generate the most effective response.<\/li>\n<li class=\"wp-block-list-item\"><em><strong>strict:\u00a0<\/strong><\/em>It&#8217;s set to true, this property instructs the LLM to strictly comply with the software schema\u2019s directions.<\/li>\n<li class=\"wp-block-list-item\"><em><strong>parameters:\u00a0<\/strong><\/em>Defines the parameters that can be handed into the\u00a0<em><strong>web_search<\/strong><\/em>\u00a0perform. On this case, there is just one parameter:\u00a0<em><strong>question<\/strong><\/em>\u00a0which represents the search time period to search for on the web.<\/li>\n<li class=\"wp-block-list-item\"><em><strong>required:\u00a0<\/strong><\/em>Instructs the LLM that question is a compulsory parameter for the\u00a0<em><strong>web_search<\/strong><\/em>\u00a0perform.<\/li>\n<li class=\"wp-block-list-item\"><em><strong>additionalProperties:<\/strong><\/em>\u00a0it&#8217;s set to false, that means that the software\u2019s\u00a0<em>arguments object<\/em>\u00a0can&#8217;t embrace any parameters apart from these outlined below\u00a0<em><strong>parameters.properties.<\/strong><\/em><\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">Step 3: Create the Internet Search Agent Utilizing GPT-5 and Operate Calling<\/h3>\n<p class=\"wp-block-paragraph\">Lastly I&#8217;ll construct an agent that we will chat with, which might search the net when it wants up-to-date data. I&#8217;ll use\u00a0<strong>GPT-5-mini<\/strong>, a quick and correct mannequin from OpenAI, together with perform calling to invoke the\u00a0<em><strong>software schema\u00a0<\/strong><\/em>and the\u00a0<em><strong>net search perform\u00a0<\/strong><\/em>already outlined.<\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-python\">from datetime import datetime, timezone\nimport json\nfrom openai import OpenAI\nimport os \n\nconsumer = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\n\n# tracker for the final mannequin's response id to take care of dialog's state \nprev_response_id = None\n\n# an inventory for storing software's outcomes from the perform name \ntool_results = []\n\nwhereas True:\n    # if the software outcomes is empty immediate message \n    if len(tool_results) == 0:\n        user_message = enter(\"Person: \")\n\n        \"\"\" instructions for exiting chat \"\"\"\n        if isinstance(user_message, str) and user_message.strip().decrease() in {\"exit\", \"q\"}:\n            print(\"Exiting chat. Goodbye!\")\n            break\n\n    else:\n        user_message = tool_results.copy()\n    \n        # clear the software outcomes for the subsequent name \n        tool_results = []\n\n    # get hold of present's date to be handed into the mannequin as an instruction to help in resolution making\n    today_date = datetime.now(timezone.utc).date().isoformat()     \n\n    response = consumer.responses.create(\n        mannequin = \"gpt-5-mini\",\n        enter = user_message,\n        directions=f\"Present date is {today_date}.\",\n        instruments = tool_schema,\n        previous_response_id=prev_response_id,\n        textual content = {\"verbosity\": \"low\"},\n        reasoning={\n            \"effort\": \"low\",\n        },\n        retailer=True,\n        )\n    \n    prev_response_id = response.id\n\n    # Handles mannequin response's output \n    for output in response.output:\n        \n        if output.kind == \"reasoning\":\n            print(\"Assistant: \",\"Reasoning ....\")\n\n            for reasoning_summary in output.abstract:\n                print(\"Assistant: \",reasoning_summary)\n\n        elif output.kind == \"message\":\n            for merchandise in output.content material:\n                print(\"Assistant: \",merchandise.textual content)\n\n        elif output.kind == \"function_call\":\n            # get hold of perform identify \n            function_name = globals().get(output.identify)\n            # masses perform arguments \n            args = json.masses(output.arguments)\n            function_response = function_name(**args)\n            tool_results.append(\n                {\n                    \"kind\": \"function_call_output\",\n                    \"call_id\": output.call_id,\n                    \"output\": json.dumps(function_response)\n                }\n            )<\/code><\/pre>\n<p class=\"wp-block-paragraph\"><strong>Step by Step Code Breakdown<\/strong><\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-python\">from openai import OpenAI\nimport os \n\nconsumer = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\nprev_response_id = None\ntool_results = []<\/code><\/pre>\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\">Initialized the OpenAI mannequin API with an API key.<\/li>\n<li class=\"wp-block-list-item\">Initialized two variables\u00a0<em><strong>prev_response_id<\/strong><\/em>\u00a0and\u00a0<em><strong>tool_results<\/strong><\/em>.\u00a0<em><strong>prev_response_id\u00a0<\/strong><\/em>retains observe of the mannequin\u2019s response to take care of dialog state, and\u00a0<em><strong>tool_results\u00a0<\/strong><\/em>is an inventory that shops outputs returned from the\u00a0<em><strong>web_search\u00a0<\/strong><\/em>perform name.<\/li>\n<\/ul>\n<p class=\"wp-block-paragraph\">The chat runs contained in the<em><strong>\u00a0loop<\/strong><\/em>. A consumer enters a message and the mannequin referred to as with software schema accepts the message, causes over it, decides whether or not to name the net search software, after which the software\u2019s output is handed again to the mannequin. The mannequin generates a context-aware response. This continues till the consumer exits the chat.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Code Walkthrough of the Loop<\/strong><\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-python\">if len(tool_results) == 0:\n    user_message = enter(\"Person: \")\n    if isinstance(user_message, str) and user_message.strip().decrease() in {\"exit\", \"q\"}:\n        print(\"Exiting chat. Goodbye!\")\n        break\n\nelse:\n    user_message = tool_results.copy()\n    tool_results = []\n\ntoday_date = datetime.now(timezone.utc).date().isoformat()     \n\nresponse = consumer.responses.create(\n    mannequin = \"gpt-5-mini\",\n    enter = user_message,\n    directions=f\"Present date is {today_date}.\",\n    instruments = tool_schema,\n    previous_response_id=prev_response_id,\n    textual content = {\"verbosity\": \"low\"},\n    reasoning={\n        \"effort\": \"low\",\n    },\n    retailer=True,\n    )\n\nprev_response_id = response.id<\/code><\/pre>\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\">Checks if the\u00a0<em><strong>tool_results<\/strong><\/em>\u00a0is empty. Whether it is, the consumer can be prompted to kind in a message, with an choice to stop utilizing\u00a0<em><strong>exit<\/strong><\/em>\u00a0or\u00a0<em><strong>q<\/strong><\/em>.<\/li>\n<li class=\"wp-block-list-item\">If the\u00a0<em><strong>tool_results<\/strong><\/em>\u00a0just isn&#8217;t empty,\u00a0<em><strong>user_message\u00a0<\/strong><\/em>can be set to the collected software outputs to be despatched to the mannequin.\u00a0<em><strong>tool_results<\/strong><\/em>\u00a0is cleared to keep away from resending the identical\u00a0<em><strong>software outputs\u00a0<\/strong><\/em>on the subsequent loop iteration.<\/li>\n<li class=\"wp-block-list-item\">The present date (<em><strong>today_date<\/strong><\/em>) is obtained for use by the mannequin to make time-aware selections.<\/li>\n<li class=\"wp-block-list-item\">Calls\u00a0<em><strong>consumer.responses.create<\/strong><\/em>\u00a0to generate the mannequin\u2019s response and it accepts the next parameters:\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\">mannequin: set to\u00a0<em><strong>gpt-5-mini<\/strong><\/em>.<\/li>\n<li class=\"wp-block-list-item\">enter: accepts the consumer\u2019s message.<\/li>\n<li class=\"wp-block-list-item\">directions: set to present\u2019s date (today_date).<\/li>\n<li class=\"wp-block-list-item\">instruments: set to the software schema that was outlined earlier.<\/li>\n<li class=\"wp-block-list-item\">previous_response_id: set to the earlier response\u2019s id so the mannequin can keep dialog state.<\/li>\n<li class=\"wp-block-list-item\">textual content: verbosity is ready to low to maintain mannequin\u2019s response concise.<\/li>\n<li class=\"wp-block-list-item\">reasoning: GPT-5-mini is a reasoning mannequin, set the reasoning\u2019s effort to low for quicker\u2019s response. For extra complicated duties we will set it to excessive.<\/li>\n<li class=\"wp-block-list-item\">retailer: tells the mannequin to retailer the present\u2019s response so it may be retrieved later and helps with dialog continuity.<\/li>\n<\/ul>\n<\/li>\n<li class=\"wp-block-list-item\"><em><strong>prev_response_id<\/strong><\/em><code>\u00a0<\/code>is ready to present\u2019s response id so the subsequent perform name can thread onto the identical dialog.<\/li>\n<\/ul>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-python\">for output in response.output:\n    if output.kind == \"reasoning\":\n        print(\"Assistant: \",\"Reasoning ....\")\n\n        for reasoning_summary in output.abstract:\n            print(\"Assistant: \",reasoning_summary)\n\n    elif output.kind == \"message\":\n        for merchandise in output.content material:\n            print(\"Assistant: \",merchandise.textual content)\n\n    elif output.kind == \"function_call\":\n        # get hold of perform identify \n        function_name = globals().get(output.identify)\n        # masses perform arguments \n        args = json.masses(output.arguments)\n        function_response = function_name(**args)\n        # append software outcomes checklist with the the perform name's id and performance's response \n        tool_results.append(\n            {\n                \"kind\": \"function_call_output\",\n                \"call_id\": output.call_id,\n                \"output\": json.dumps(function_response)\n            }\n        )<\/code><\/pre>\n<p class=\"wp-block-paragraph\">This processes the mannequin\u2019s response output and does the next;<\/p>\n<ul class=\"wp-block-list\">\n<li class=\"wp-block-list-item\">If the output kind is reasoning, print every merchandise within the reasoning abstract.<\/li>\n<li class=\"wp-block-list-item\">If the output kind is message, iterate via the content material and print every textual content merchandise.<\/li>\n<li class=\"wp-block-list-item\">If the output kind is a perform name, get hold of the perform\u2019s identify, parse its arguments, and cross them to the perform (<em><strong>web_search<\/strong><\/em>) to generate a response. On this case, the net search response incorporates up-to-date data related to the consumer\u2019s message. Lastly appends the perform name\u2019s response and performance name id to\u00a0<em><strong>tool_results<\/strong><\/em>. This lets the subsequent loop ship the software consequence again to the mannequin.<\/li>\n<\/ul>\n<h3 class=\"wp-block-heading\">Full Code for the Internet Search Agent<\/h3>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-python\">from datetime import datetime, timezone\nimport json\nfrom openai import OpenAI\nimport os \nfrom tavily import TavilyClient\n\ntavily = TavilyClient(api_key=os.getenv(\"TAVILY_API_KEY\"))\n\ndef web_search(question: str, num_results: int = 10):\n    strive:\n        consequence = tavily.search(\n            question=question,\n            search_depth=\"primary\",\n            max_results=num_results,\n            include_answer=False,       \n            include_raw_content=False,\n            include_images=False\n        )\n\n        outcomes = consequence.get(\"outcomes\", [])\n\n        return {\n            \"question\": question,\n            \"outcomes\": outcomes, \n            \"sources\": [\n                {\"title\": r.get(\"title\", \"\"), \"url\": r.get(\"url\", \"\")}\n                for r in results\n            ]\n        }\n\n    besides Exception as e:\n        return {\n            \"error\": f\"Search error: {e}\",\n            \"question\": question,\n            \"outcomes\": [],\n            \"sources\": [],\n        }\n\n\ntool_schema = [\n    {\n        \"type\": \"function\",\n        \"name\": \"web_search\",\n        \"description\": \"\"\"Execute a web search to fetch up to date information. Synthesize a concise, \n        self-contained answer from the content of the results of the visited pages.\n        Fetch pages, extract text, and provide the best available result while citing 1-3 sources (title + URL). \"\n        If sources conflict, surface the uncertainty and prefer the most recent evidence.\n        \"\"\",\n        \"strict\": True,\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"query\": {\n                    \"type\": \"string\",\n                    \"description\": \"Query to be searched on the web.\",\n                },\n            },\n            \"required\": [\"query\"],\n            \"additionalProperties\": False\n        },\n    },\n]\n\nconsumer = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\n\n# tracker for the final mannequin's response id to take care of dialog's state \nprev_response_id = None\n\n# an inventory for storing software's outcomes from the perform name \ntool_results = []\n\nwhereas True:\n    # if the software outcomes is empty immediate message \n    if len(tool_results) == 0:\n        user_message = enter(\"Person: \")\n\n        \"\"\" instructions for exiting chat \"\"\"\n        if isinstance(user_message, str) and user_message.strip().decrease() in {\"exit\", \"q\"}:\n            print(\"Exiting chat. Goodbye!\")\n            break\n\n    else:\n        # set the consumer's messages to the software outcomes to be despatched to the mannequin \n        user_message = tool_results.copy()\n    \n        # clear the software outcomes for the subsequent name \n        tool_results = []\n\n    # get hold of present's date to be handed into the mannequin as an instruction to help in resolution making\n    today_date = datetime.now(timezone.utc).date().isoformat()     \n\n    response = consumer.responses.create(\n        mannequin = \"gpt-5-mini\",\n        enter = user_message,\n        directions=f\"Present date is {today_date}.\",\n        instruments = tool_schema,\n        previous_response_id=prev_response_id,\n        textual content = {\"verbosity\": \"low\"},\n        reasoning={\n            \"effort\": \"low\",\n        },\n        retailer=True,\n        )\n    \n    prev_response_id = response.id\n\n\n    # Handles mannequin response's output \n    for output in response.output:\n        \n        if output.kind == \"reasoning\":\n            print(\"Assistant: \",\"Reasoning ....\")\n\n            for reasoning_summary in output.abstract:\n                print(\"Assistant: \",reasoning_summary)\n\n        elif output.kind == \"message\":\n            for merchandise in output.content material:\n                print(\"Assistant: \",merchandise.textual content)\n\n        # checks if the output kind is a perform name and append the perform name's outcomes to the software outcomes checklist\n        elif output.kind == \"function_call\":\n            # get hold of perform identify \n            function_name = globals().get(output.identify)\n            # masses perform arguments \n            args = json.masses(output.arguments)\n            function_response = function_name(**args)\n            # append software outcomes checklist with the the perform name's id and performance's response \n            tool_results.append(\n                {\n                    \"kind\": \"function_call_output\",\n                    \"call_id\": output.call_id,\n                    \"output\": json.dumps(function_response)\n                }\n            )<\/code><\/pre>\n<p class=\"wp-block-paragraph\">Once you run the code, you&#8217;ll be able to simply chat with the agent to ask questions that require the newest data, comparable to the present climate or the newest product releases. The agent responds with up-to-date data together with the corresponding sources from the web. Under is a pattern output from the terminal.<\/p>\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"language-markup\">Person: What's the climate like in London at present?\nAssistant:  Reasoning ....\nAssistant:  Reasoning ....\nAssistant:  Proper now in London: overcast, about 18\u00b0C (64\u00b0F), humidity ~88%, mild SW wind ~16 km\/h, no precipitation reported. Supply: WeatherAPI (present situations) \u2014 https:\/\/www.weatherapi.com\/\n\nPerson: What's the newest iPhone mannequin?\nAssistant:  Reasoning ....\nAssistant:  Reasoning ....\nAssistant:  The most recent iPhone fashions are the iPhone 17 lineup (together with iPhone 17, iPhone 17 Professional, iPhone 17 Professional Max) and the brand new iPhone Air \u2014 introduced by Apple on Sept 9, 2025. Supply: Apple Newsroom \u2014 https:\/\/www.apple.com\/newsroom\/2025\/09\/apple-debuts-iphone-17\/\n\nPerson: Multiply 500 by 12.           \nAssistant:  Reasoning ....\nAssistant:  6000\nPerson: exit   \nExiting chat. Goodbye!<\/code><\/pre>\n<p class=\"wp-block-paragraph\">You possibly can see the outcomes with their corresponding net sources. Once you ask it to carry out a process that doesn\u2019t require up-to-date data, comparable to maths calculations or writing code the agent responds immediately with none net search.<\/p>\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Notice: The online search agent is a straightforward, single-tool agent. Superior agentic programs orchestrate a number of specialised instruments and use environment friendly reminiscence to take care of context, plan, and clear up extra complicated duties.<\/p>\n<\/blockquote>\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\">On this submit I defined how an AI agent works and the way it extends the capabilities of a big language mannequin to work together with its atmosphere, carry out actions and clear up duties via using instruments. I additionally defined perform calling and the way it allows LLMs to name instruments. I demonstrated  create a software schema for perform calling that defines when and the way an LLM ought to name a software to carry out an motion. I outlined an online search perform utilizing Tavily to fetch data from the net after which confirmed step-by-step  construct an online search agent utilizing perform calling and GPT-5-mini because the LLM. In the long run, we constructed an online search agent able to retrieving up-to-date data from the web to reply consumer queries.<\/p>\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Try my GitHub repo,\u00a0<em><a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/github.com\/ayoolaolafenwa\/GenAI-Courses\/tree\/main\">GenAI-Programs<\/a>\u00a0<\/em>the place I&#8217;ve printed extra programs on varied Generative AI subjects. It additionally features a information on constructing an\u00a0<a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/github.com\/ayoolaolafenwa\/GenAI-Courses\/blob\/main\/AI%20Agents\/Agentic_RAG.md\">Agentic RAG utilizing perform calling.<\/a><\/p>\n<\/blockquote>\n<h2 class=\"wp-block-heading\">Attain out to me through:<\/h2>\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">E mail:\u00a0<a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/mail.google.com\/mail\/u\/0\/#inbox\"><span class=\"__cf_email__\" data-cfemail=\"147b787572717a6375756d7b7b7875547379757d783a777b79\">[email\u00a0protected]<\/span><\/a><\/p>\n<p class=\"wp-block-paragraph\">Linkedin:\u00a0<a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/www.linkedin.com\/in\/ayoola-olafenwa-003b901a9\/\">https:\/\/www.linkedin.com\/in\/ayoola-olafenwa-003b901a9\/<\/a><\/p>\n<\/blockquote>\n<h2 class=\"wp-block-heading\">References<\/h2>\n<p class=\"wp-block-paragraph\"><a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/platform.openai.com\/docs\/guides\/function-calling?api-mode=responses\">https:\/\/platform.openai.com\/docs\/guides\/function-calling?api-mode=responses<\/a><\/p>\n<p class=\"wp-block-paragraph\"><a rel=\"nofollow\" target=\"_blank\" href=\"https:\/\/docs.tavily.com\/documentation\/api-reference\/endpoint\/search\">https:\/\/docs.tavily.com\/documentation\/api-reference\/endpoint\/search<\/a><\/p>\n<\/div>\n\n","protected":false},"excerpt":{"rendered":"<p>and Giant Language Fashions (LLMs) Giant language fashions (LLMs)\u00a0are superior AI programs constructed on deep neural community comparable to transformers and educated on huge quantities of textual content to generate human-like language. LLMs like ChatGPT, Claude, Gemini and Grok can deal with many difficult duties and are used throughout fields comparable to science, healthcare, training, [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":7898,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[55],"tags":[75,73,1052,2193,4484],"class_list":["post-7896","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-machine-learning","tag-agent","tag-build","tag-calling","tag-function","tag-gpt5"],"_links":{"self":[{"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=\/wp\/v2\/posts\/7896","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=7896"}],"version-history":[{"count":1,"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=\/wp\/v2\/posts\/7896\/revisions"}],"predecessor-version":[{"id":7897,"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=\/wp\/v2\/posts\/7896\/revisions\/7897"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=\/wp\/v2\/media\/7898"}],"wp:attachment":[{"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=7896"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=7896"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techtrendfeed.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=7896"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}<!-- This website is optimized by Airlift. Learn more: https://airlift.net. Template:. Learn more: https://airlift.net. Template: 69d9690a190636c2e0989534. Config Timestamp: 2026-04-10 21:18:02 UTC, Cached Timestamp: 2026-06-21 05:58:50 UTC -->