{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Julian Yip",
  "title_listed": "Build Autonomous AI Agents with Function Calling",
  "keywords": "",
  "domain": "大模型算法",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/build-autonomous-ai-agents-with-function-calling-0bb483753975/",
  "publish_date": "2024-04-02",
  "corpus_stage": "",
  "notes": "",
  "id": "9d6b4ccfd105",
  "collected_at": "2026-10-02T06:45:49",
  "title": "Build Autonomous AI Agents with Function Calling | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Build Autonomous AI Agents with Function Calling\nTransform your chatbot into an agent that can interact with external APIs\n[Julian Yip](https://towardsdatascience.com/author/jyipkl/)\nApril 2, 202411 min read\nFunction Calling is not something new. In July 2023, OpenAI introduced Function Calling for their GPT models, a feature now being adopted by competitors. Google's Gemini API recently supported it, and Anthropic is integrating it into Claude. Function Calling is becoming essential for large language models (LLMs), enhancing their capabilities. All the more useful to learn this technique!\nWith this in mind, I aim to write a comprehensive tutorial covering Function Calling beyond basic introductions (there are already plenty of tutorials for it). The focus will be on practical implementation, building a fully autonomous AI agent and integrating it with Streamlit for a ChatGPT-like interface. Although OpenAI is used for demonstration, this tutorial can be easily adapted for other LLMs supporting Function Calling, such as Gemini.\n## **What is Function Calling for?**\nFunction Calling enables developers to describe functions (aka tools, you can consider this as actions for the model to take, like performing calculation, or making an order), and have the model intelligently choose to output a JSON object containing arguments to call those functions. In simpler terms, it allows for:\n  * **Autonomous decision making** : Models can intelligently choose tools to respond to questions.\n  * **Reliable parsing** : Responses are in JSON format, instead of the more typical dialogue-like response. It might not seem much from the first look, but this is what allows LLM to connect to external systems, say via APIs with structured inputs.\n\n\nIt opens up numerous possibilities:\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) roadmap.\n  * **Autonomous AI assistants** : Bots can interact with internal systems for tasks like customer orders and returns, beyond providing answers to enquiries\n  * **Personal research assistants** : Say if you are planning for your travel, assistants can search the web, crawl content, compare options, and summarize results in Excel.\n  * **IoT voice commands** : Models can control devices or suggest actions based on detected intents, such as adjusting the AC temperature.\n\n\n* * *\n_(Sidetracking a bit: To realize such potentials, we must have a systematic way to design our prompts and to test them. I have written an article about this too!)_\n> [**Prompt Like a Data Scientist: Auto Prompt Optimization and Testing with DSPy**](https://towardsdatascience.com/prompt-like-a-data-scientist-auto-prompt-optimization-and-testing-with-dspy-ff699f030cb7)\nWithout further ado, let's explore what Function Calling is about!\n## The Structure of Function Calling\nBorrowing from [Gemini's Function Calling documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling), Function Calling has the below structure, which works the same in OpenAI\n![Image from Gemini&#039;s Function Calling documentation](../images/000.png)\nImage from [Gemini's Function Calling documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling)\n  1. User issues prompt to the application\n  2. Application passes the user-provided prompt, and the Function Declaration(s), which is a description of the tool(s) that the model could use\n  3. Based on the Function Declaration, the model suggests the tool to use, and the relevant request parameters. **Notice the model outputs the suggested tool and parameters only, WITHOUT actually calling the functions**\n  4. & 5. Based on the response, the application invokes the relevant API\n  5. & 7. The response from API is fed into the model again to output a human-readable response\n  6. Application returns the final response to the user, then repeat from 1.\n\n\nThis might seem convuluted, but the concept will be illustrated in detail with example\n## Architecture\nBefore diving into the code, a few words about the demo application's architecture\n### **Solution**\nHere we build an assistant for tourists visiting a hotel. The assistant has access to the following tools, which allows the assistant to access external applications.\n  * `get_items`, `purchase_item`: Connect to product catalog stored in database via API, for retrieving item list and making a purchase respectively\n  * `rag_pipeline_func`: Connect to document store with Retrieval Augmented Generation (RAG) to obtain information from unstructured texts e.g. hotel's brochures\n\n\n![](../images/body-c1cc917801e07b42c0b8.png)\n### **Tech stack**\n  * **Embedding model** : [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2)\n  * **Vector Database** : [Haystack's InMemoryDocumentStore](https://docs.haystack.deepset.ai/docs/inmemorydocumentstore)\n  * **LLM** : [GPT-4 Turbo accessed via OpenRouter](https://openrouter.ai/models/openai/gpt-4-1106-preview). With OpenRouter you can access different LLM APIs from Hong Kong without VPN. The flow can be adapted into using other LLMs with slight code change, provided they support Function Calling, say Gemini\n  * **LLM Framework** : [Haystack](https://haystack.deepset.ai/) for their ease of use, great documentation and transparency in pipeline construction. This tutorial is actually an extension to their [fantastic tutorial](https://haystack.deepset.ai/tutorials/40_building_chat_application_with_function_calling) for the same topic\n\n\nNow let's begin!\n## Sample Application\n### Preparation\nHead over to [Github](https://github.com/yip-kl/llm_function_calling_demo) to clone my code. The contents below can be found in the `function_calling_demo` Notebook.\nPlease also create and activate a virtual environment, then `pip install -r requirements.txt` to install the required packages\n### **Initialization**\nWe first connect to OpenRouter. Alternatively using the original `OpenAIChatGenerator` without overwritting the `api_base_url`would also work, provided you have an OpenAI API key\npython\n\n```\nimport os\nfrom dotenv import load_dotenv\nfrom haystack.components.generators.chat import OpenAIChatGenerator\nfrom haystack.utils import Secret\nfrom haystack.dataclasses import ChatMessage\nfrom haystack.components.generators.utils import print_streaming_chunk\n\n# Set your API key as environment variable before executing this\nload_dotenv()\nOPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY')\n\nchat_generator = OpenAIChatGenerator(api_key=Secret.from_env_var(\"OPENROUTER_API_KEY\"),\n  api_base_url=\"https://openrouter.ai/api/v1\",\n  model=\"openai/gpt-4-turbo-preview\",\n        streaming_callback=print_streaming_chunk)\n```\n\nThen we test can the `chat_generator` be successfully invoked\npython\n\n```\nchat_generator.run(messages=[ChatMessage.from_user(\"Return this text: 'test'\")])\n```\n\ntext\n\n```\n---------- The response should look like this ----------\n{'replies': [ChatMessage(content=\"'test'\", role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'openai/gpt-4-turbo-preview', 'index': 0, 'finish_reason': 'stop', 'usage': {}})]}\n```\n\n### Step 1: Establish data store\nHere we establish connection between our application and the two data sources: **Document store** for unstructured texts, and **application database** via API\n**Index Documents with a Pipeline**\nWe provide sample texts in `documents` for the model to perform Retrival Augmented Generation (RAG). The texts are turned into embeddings and stored in an in-memory document store\npython\n\n```\nfrom haystack import Pipeline, Document\nfrom haystack.document_stores.in_memory import InMemoryDocumentStore\nfrom haystack.components.writers import DocumentWriter\nfrom haystack.components.embedders import SentenceTransformersDocumentEmbedder\n\n# Sample documents\ndocuments = [\n    Document(content=\"Coffee shop opens at 9am and closes at 5pm.\"),\n    Document(content=\"Gym room opens at 6am and closes at 10pm.\")\n]\n\n# Create the document store\ndocument_store = InMemoryDocumentStore()\n\n# Create a pipeline to turn the texts into embeddings and store them in the document store\nindexing_pipeline = Pipeline()\nindexing_pipeline.add_component(\n    \"doc_embedder\", SentenceTransformersDocumentEmbedder(model=\"sentence-transformers/all-MiniLM-L6-v2\")\n)\nindexing_pipeline.add_component(\"doc_writer\", DocumentWriter(document_store=document_store))\n\nindexing_pipeline.connect(\"doc_embedder.documents\", \"doc_writer.documents\")\n\nindexing_pipeline.run({\"doc_embedder\": {\"documents\": documents}})\n```\n\nIt should output this, corresponding to the `documents` we created as sample\njson\n\n```\n{'doc_writer': {'documents_written': 2}}\n```\n\n**Spin up API server**\nAn API server made with Flask is created under `db_api.py` to connect to SQLite. Please spin it up by running `python db_api.py` in your terminal\n![This would be shown in the terminal, if successfully executed](../images/001.png)\nThis would be shown in the terminal, if successfully executed\nAlso notice that some initial data has been added in `db_api.py`\n![Sample data in the database](../images/002.png)\nSample data in the database\n### Step 2: Define the functions\nHere we prepare the actual functions for the model to invoke **AFTER** Function Calling (Step 4–5 as described in **The Structure of Function Calling**)\n**RAG function**\nNamely the `rag_pipeline_func`. This is for the model to provide an answer by searching through the texts stored in the Document Store. We first define the RAG retrieval as a Haystack pipeline\npython\n\n```\nfrom haystack.components.embedders import SentenceTransformersTextEmbedder\nfrom haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever\nfrom haystack.components.builders import PromptBuilder\nfrom haystack.components.generators import OpenAIGenerator\n\ntemplate = \"\"\"\nAnswer the questions based on the given context.\n\nContext:\n{% for document in documents %}\n    {{ document.content }}\n{% endfor %}\nQuestion: {{ question }}\nAnswer:\n\"\"\"\nrag_pipe = Pipeline()\nrag_pipe.add_component(\"embedder\", SentenceTransformersTextEmbedder(model=\"sentence-transformers/all-MiniLM-L6-v2\"))\nrag_pipe.add_component(\"retriever\", InMemoryEmbeddingRetriever(document_store=document_store))\nrag_pipe.add_component(\"prompt_builder\", PromptBuilder(template=template))\n# Note to llm: We are using OpenAIGenerator, not the OpenAIChatGenerator, because the latter only accepts List[str] as input and cannot accept prompt_builder's str output\nrag_pipe.add_component(\"llm\", OpenAIGenerator(api_key=Secret.from_env_var(\"OPENROUTER_API_KEY\"),\n  api_base_url=\"https://openrouter.ai/api/v1\",\n  model=\"openai/gpt-4-turbo-preview\"))\n\nrag_pipe.connect(\"embedder.embedding\", \"retriever.query_embedding\")\nrag_pipe.connect(\"retriever\", \"prompt_builder.documents\")\nrag_pipe.connect(\"prompt_builder\", \"llm\")\n```\n\nTest if the function works\npython\n\n```\nquery = \"When does the coffee shop open?\"\nrag_pipe.run({\"embedder\": {\"text\": query}, \"prompt_builder\": {\"question\": query}})\n```\n\nThis should yield the following output. Notice the `replies` that the model gave is from the sample documents we provided before\njson\n\n```\n{'llm': {'replies': ['The coffee shop opens at 9am.'],\n  'meta': [{'model': 'openai/gpt-4-turbo-preview',\n    'index': 0,\n    'finish_reason': 'stop',\n    'usage': {'completion_tokens': 9,\n     'prompt_tokens': 60,\n     'total_tokens': 69,\n     'total_cost': 0.00087}}]}}\n```\n\nWe can then turn the `rag_pipe` into a function, which provides the `replies` only without adding in the other details\npython\n\n```\ndef rag_pipeline_func(query: str):\n    result = rag_pipe.run({\"embedder\": {\"text\": query}, \"prompt_builder\": {\"question\": query}})\n\n    return {\"reply\": result[\"llm\"][\"replies\"][0]}\n```\n\n**API calls**\nWe define the `get_items` and `purchase_item`functions for interacting with the database\npython\n\n```\n# Flask's default local URL, change it if necessary\ndb_base_url = 'http://127.0.0.1:5000'\n\n# Use requests to get the data from the database\nimport requests\nimport json\n\n# get_categories is supplied as part of the prompt, it is not used as a tool\ndef get_categories():\n    response = requests.get(f'{db_base_url}/category')\n    data = response.json()\n    return data\n\ndef get_items(ids=None,categories=None):\n    params = {\n        'id': ids,\n        'category': categories,\n    }\n    response = requests.get(f'{db_base_url}/item', params=params)\n    data = response.json()\n    return data\n\ndef purchase_item(id,quantity):\n\n    headers = {\n    'Content-type':'application/json', \n    'Accept':'application/json'\n    }\n\n    data = {\n        'id': id,\n        'quantity': quantity,\n    }\n    response = requests.post(f'{db_base_url}/item/purchase', json=data, headers=headers)\n    return response.json()\n```\n\n**Define the tool list**\nNow that we have defined the fuctions, we need to let the model recognize those functions, and to instruct them how they are used, by providing descriptions for them.\nSince we are using OpenAI here, the `tools` is formatted as below following the [format required by Open AI](https://cookbook.openai.com/examples/function_calling_with_an_openapi_spec)\npython\n\n```\ntools = [\n    {\n        \"type\": \"function\",\n        \"function\": {\n            \"name\": \"get_items\",\n            \"description\": \"Get a list of items from the database\",\n            \"parameters\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"ids\": {\n                        \"type\": \"string\",\n                        \"description\": \"Comma separated list of item ids to fetch\",\n                    },\n                    \"categories\": {\n                        \"type\": \"string\",\n                        \"description\": \"Comma separated list of item categories to fetch\",\n                    },\n                },\n                \"required\": [],\n            },\n        }\n    },\n    {\n        \"type\": \"function\",\n        \"function\": {\n            \"name\": \"purchase_item\",\n            \"description\": \"Purchase a particular item\",\n            \"parameters\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"id\": {\n                        \"type\": \"string\",\n                        \"description\": \"The given product ID, product name is not accepted here. Please obtain the product ID from the database first.\",\n                    },\n                    \"quantity\": {\n                        \"type\": \"integer\",\n                        \"description\": \"Number of items to purchase\",\n                    },\n                },\n                \"required\": [],\n            },\n        }\n    },\n    {\n        \"type\": \"function\",\n        \"function\": {\n            \"name\": \"rag_pipeline_func\",\n            \"description\": \"Get information from hotel brochure\",\n            \"parameters\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"query\": {\n                        \"type\": \"string\",\n                        \"description\": \"The query to use in the search. Infer this from the user's message. It should be a question or a statement\",\n                    }\n                },\n                \"required\": [\"query\"],\n            },\n        },\n    }\n]\n```\n\n### **Step 3: Putting it all together**\nWe now have the necessary inputs to test Function Calling! Here we do a few things:\n  1. Provide the initial prompt to the model, to give it some context\n  2. Provide a sample user-generated message\n  3. Most importantly, we pass the tool list to the chat generator in `tools`\n\n\npython\n\n```\n# 1. Initial prompt\ncontext = f\"\"\"You are an assistant to tourists visiting a hotel.\nYou have access to a database of items (which includes {get_categories()}) that tourists can buy, you also have access to the hotel's brochure.\nIf the tourist's question cannot be answered from the database, you can refer to the brochure.\nIf the tourist's question cannot be answered from the brochure, you can ask the tourist to ask the hotel staff.\n\"\"\"\nmessages = [\n    ChatMessage.from_system(context),\n    # 2. Sample message from user\n    ChatMessage.from_user(\"Can I buy a coffee?\"),\n    ]\n\n# 3. Passing the tools list and invoke the chat generator\nresponse = chat_generator.run(messages=messages, generation_kwargs= {\"tools\": tools})\nresponse\n```\n\ntext\n\n```\n---------- Response ----------\n{'replies': [ChatMessage(content='[{\"index\": 0, \"id\": \"call_AkTWoiJzx5uJSgKW0WAI1yBB\", \"function\": {\"arguments\": \"{\"categories\":\"Food and beverages\"}\", \"name\": \"get_items\"}, \"type\": \"function\"}]', role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'openai/gpt-4-turbo-preview', 'index': 0, 'finish_reason': 'tool_calls', 'usage': {}})]}\n```\n\nNow let's inspect the response. Notice how the Function Calling returns both the function chosen by the model, and the arguments for invoking the chosen function.\npython\n\n```\nfunction_call = json.loads(response[\"replies\"][0].content)[0]\nfunction_name = function_call[\"function\"][\"name\"]\nfunction_args = json.loads(function_call[\"function\"][\"arguments\"])\nprint(\"Function Name:\", function_name)\nprint(\"Function Arguments:\", function_args)\n```\n\ntext\n\n```\n---------- Response ----------\nFunction Name: get_items\nFunction Arguments: {'categories': 'Food and beverages'}\n```\n\nWhen presented with another question, the model will use another tool that is more relevant\npython\n\n```\n# Another question\nmessages.append(ChatMessage.from_user(\"Where's the coffee shop?\"))\n\n# Invoke the chat generator, and passing the tools list\nresponse = chat_generator.run(messages=messages, generation_kwargs= {\"tools\": tools})\nfunction_call = json.loads(response[\"replies\"][0].content)[0]\nfunction_name = function_call[\"function\"][\"name\"]\nfunction_args = json.loads(function_call[\"function\"][\"arguments\"])\nprint(\"Function Name:\", function_name)\nprint(\"Function Arguments:\", function_args)\n```\n\ntext\n\n```\n---------- Response ----------\nFunction Name: rag_pipeline_func\nFunction Arguments: {'query': \"Where's the coffee shop?\"}\n```\n\nAgain, notice that no actual function is invoked here, this is what we will do next!\n**Calling the function**\nWe can then feed the arguments into the chosen function\npython\n\n```\n## Find the correspoding function and call it with the given arguments\navailable_functions = {\"get_items\": get_items, \"purchase_item\": purchase_item,\"rag_pipeline_func\": rag_pipeline_func}\nfunction_to_call = available_functions[function_name]\nfunction_response = function_to_call(**function_args)\nprint(\"Function Response:\", function_response)\n```\n\ntext\n\n```\n---------- Response ----------\nFunction Response: {'reply': 'The provided context does not specify a physical location for the coffee shop, only its operating hours. Therefore, I cannot determine where the coffee shop is located based on the given information.'}\n```\n\nThe response from `rag_pipeline_func` can then passed as a context to the chat by appending it under the `messages`, for the model to provide the final answer\npython\n\n```\nmessages.append(ChatMessage.from_function(content=json.dumps(function_response), name=function_name))\nresponse = chat_generator.run(messages=messages)\nresponse_msg = response[\"replies\"][0]\n\nprint(response_msg.content)\n```\n\ntext\n\n```\n---------- Response ----------\nFor the location of the coffee shop within the hotel, I recommend asking the hotel staff directly. They will be able to guide you to it accurately.\n```\n\nWe now have completed the chat cycle!\n### Step 4: Turn into an interactive chat\nThe code above shows how Function Calling can be done, but we want to go a step further by turning it into an interactive chat\nHere I showcase two methods to do it, from the more primitive `input()` that prints the dialogue into the notebook itself, to rendering it through **Streamlit** to provide it with an ChatGPT-like UI\n`**input()**`**loop**\nThe code is copied from [Haystack's tutorial](https://haystack.deepset.ai/tutorials/40_building_chat_application_with_function_calling), which allows us to quickly test the model. _Note: This application is created to demonstrate the idea of Function Calling, and is NOT meant to be perfectly robust e.g. supporting the order of multiple items at the same time, no hallucination, etc._\npython\n\n```\nimport json\nfrom haystack.dataclasses import ChatMessage, ChatRole\n\nresponse = None\nmessages = [\n    ChatMessage.from_system(context)\n]\n\nwhile True:\n    # if OpenAI response is a tool call\n    if response and response[\"replies\"][0].meta[\"finish_reason\"] == \"tool_calls\":\n        function_calls = json.loads(response[\"replies\"][0].content)\n\n        for function_call in function_calls:\n            ## Parse function calling information\n            function_name = function_call[\"function\"][\"name\"]\n            function_args = json.loads(function_call[\"function\"][\"arguments\"])\n\n            ## Find the correspoding function and call it with the given arguments\n            function_to_call = available_functions[function_name]\n            function_response = function_to_call(**function_args)\n\n            ## Append function response to the messages list using `ChatMessage.from_function`\n            messages.append(ChatMessage.from_function(content=json.dumps(function_response), name=function_name))\n\n    # Regular Conversation\n    else:\n        # Append assistant messages to the messages list\n        if not messages[-1].is_from(ChatRole.SYSTEM):\n            messages.append(response[\"replies\"][0])\n\n        user_input = input(\"ENTER YOUR MESSAGE 👇  INFO: Type 'exit' or 'quit' to stopn\")\n        if user_input.lower() == \"exit\" or user_input.lower() == \"quit\":\n            break\n        else:\n            messages.append(ChatMessage.from_user(user_input))\n\n    response = chat_generator.run(messages=messages, generation_kwargs={\"tools\": tools})\n```\n\n![Running interactive chats in the IDE](../images/003.png)\nRunning interactive chats in the IDE\nWhile it works, we might want to have something that looks nicer.\n**Streamlit interface**\nStreamlit turns data scripts into shareable web apps, which provides a neat UI for our application. The code shown above are adapted into a Streamlit application under the `streamlit` folder of my repo\nYou can run it by:\n  1. If you have not done so already, spin up the API server with `python db_api.py`\n  2. Set the OPENROUTER_API_KEY as environment variable e.g. `export OPENROUTER_API_KEY = '@REPLACE WITH YOUR API KEY'` assuming you are on Linux / executing with git bash\n  3. Navigate to the `streamlit` folder in the terminal with `cd streamlit`\n  4. Run Streamlit with `streamlit run app.py`. A new tab should be automatically created in your browser running the application\n\n\nThat's basically it! I hope you enjoy this article.\n![Streamlit UI](../images/004.png)\nStreamlit UI\n _*Unless otherwise noted, all images are by the author_\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-d6f10b7f094af8ff005c.jpeg)\nWritten By\n## [Julian Yip](https://towardsdatascience.com/author/jyipkl/)\n[See all from Julian Yip](https://towardsdatascience.com/author/jyipkl/)\n[AI](https://towardsdatascience.com/tag/ai/)[Chatbots](https://towardsdatascience.com/tag/chatbots/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Llm](https://towardsdatascience.com/tag/llm/)[OpenAI](https://towardsdatascience.com/tag/openai/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F&title=Build%20Autonomous%20AI%20Agents%20with%20Function%20Calling)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F&title=Build%20Autonomous%20AI%20Agents%20with%20Function%20Calling)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F&text=Build%20Autonomous%20AI%20Agents%20with%20Function%20Calling)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/005.jpeg)](https://towardsdatascience.com/chefboost-an-alternative-python-library-for-tree-based-models-f46af028a348/)\n## [Chefboost - an alternative Python library for tree-based models](https://towardsdatascience.com/chefboost-an-alternative-python-library-for-tree-based-models-f46af028a348/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAn overview of key differences from scikit-learn\n[Eryk Lewinson](https://towardsdatascience.com/author/eryk-lewinson/)\nJune 13, 20215 min read\n  * [![](../images/006.jpg)](https://towardsdatascience.com/parse-the-folder-not-just-the-pdfs-the-relational-tables-rag-needs-on-a-case-file/)\n## [Parse the Folder, Not Just the PDFs: The Relational Tables RAG Needs on a Case File](https://towardsdatascience.com/parse-the-folder-not-just-the-pdfs-the-relational-tables-rag-needs-on-a-case-file/)\n[Large Language Model](https://towardsdatascience.com/category/large-language-model/)\nEnterprise Document Intelligence [Vol.1 #14D] - The index lists what the case type demands before any folder is opened, and the two questions worth building for are not retrieval questions at all\n[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\nAugust 23, 202620 min read\n  * [![](../images/007.jpg)](https://towardsdatascience.com/the-best-interviews-ive-had-were-never-coding-challenges-95ec0cde765b/)\n## [The Best Interviews I've Had Were Never Coding Challenges](https://towardsdatascience.com/the-best-interviews-ive-had-were-never-coding-challenges-95ec0cde765b/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nDifferent Styles of Interviews that You Can Try Out\n[Rose Day](https://towardsdatascience.com/author/rjday/)\nFebruary 4, 20227 min read\n  * [![](../images/008.jpeg)](https://towardsdatascience.com/5-chrome-extension-to-ease-up-your-life-as-a-data-scientist-c5c483605d0d/)\n## [5 Chrome Extension to Ease up Your Life as a Data Scientist](https://towardsdatascience.com/5-chrome-extension-to-ease-up-your-life-as-a-data-scientist-c5c483605d0d/)\n[Programming](https://towardsdatascience.com/category/programming/)\nThese extensions are must for a smooth workflow\n[Sara A. Metwalli](https://towardsdatascience.com/author/saraametwalli/)\nAugust 23, 20205 min read\n  * [![](../images/009.png)](https://towardsdatascience.com/geovec-word-embeddings-for-geosciences-ac1e1e854e19/)\n## [GeoVec: word embeddings for geosciences](https://towardsdatascience.com/geovec-word-embeddings-for-geosciences-ac1e1e854e19/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAnalogies, categorisation, relatedness and spatial interpolation of word embeddings.\n[José Padarian](https://towardsdatascience.com/author/spadarian/)\nAugust 20, 20198 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/tsfresh-on-large-data-samples-part-ii-4d6843155dfc/)\n## [tsfresh on Large Data Samples - Part II](https://towardsdatascience.com/tsfresh-on-large-data-samples-part-ii-4d6843155dfc/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nIf big is not big enough In the last post, we have explored how tsfresh...\n[Nils Braun](https://towardsdatascience.com/author/nils-braun/)\nDecember 7, 202015 min read\n  * [![](../images/011.jpeg)](https://towardsdatascience.com/mlops-level-1-continuous-training-b2a633e27d47/)\n## [MLOps Level 1: Continuous Training](https://towardsdatascience.com/mlops-level-1-continuous-training-b2a633e27d47/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIn MLOps level 1 the machine learning pipeline is automated. By doing so you achieve...\n[Marco Susilo](https://towardsdatascience.com/author/marco-susilo/)\nMay 9, 20215 min read\n  * [![](../images/012.jpg)](https://towardsdatascience.com/roialign-explained-d30f6843da3a/)\n## [RoIAlign Explained](https://towardsdatascience.com/roialign-explained-d30f6843da3a/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWith Python Implementation\n[Alexey Kravets](https://towardsdatascience.com/author/alexml0123/)\nDecember 29, 202210 min read\n  * [![](../images/013.jpg)](https://towardsdatascience.com/how-to-make-your-deep-learning-experiments-reproducible-and-your-code-extendible-7ef56767dddb/)\n## [How to make your deep learning experiments reproducible and your code extendible](https://towardsdatascience.com/how-to-make-your-deep-learning-experiments-reproducible-and-your-code-extendible-7ef56767dddb/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nLessons learned from building an open-source deep learning for time series framework\n[Isaac Godfried](https://towardsdatascience.com/author/igodfried/)\nSeptember 25, 20206 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "Build Autonomous AI Agents with Function Calling | Towards Data Science",
    "description": "Transform your chatbot into an agent that can interact with external APIs",
    "keywords": null,
    "author": "Julian Yip",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Build Autonomous AI Agents with Function Calling",
    "og:description": "Transform your chatbot into an agent that can interact with external APIs",
    "og:url": "https://towardsdatascience.com/build-autonomous-ai-agents-with-function-calling-0bb483753975/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/0rrgnwWr7Hif3TfH_.png",
    "og:image:width": "516",
    "og:image:height": "566",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Julian Yip",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "11 min read",
    "article:published_time": "2024-04-02T10:03:19.000Z",
    "article:modified_time": "2024-04-02T10:03:19.000Z",
    "article:author": "https://towardsdatascience.com/author/jyipkl/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_000.txt",
      "chars": 621
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_001.txt",
      "chars": 81
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_002.txt",
      "chars": 249
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_003.txt",
      "chars": 984
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_004.txt",
      "chars": 41
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_005.txt",
      "chars": 1285
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_006.txt",
      "chars": 125
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_007.txt",
      "chars": 272
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_008.txt",
      "chars": 182
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_009.txt",
      "chars": 901
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_010.txt",
      "chars": 2050
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_011.txt",
      "chars": 735
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_012.txt",
      "chars": 383
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_013.txt",
      "chars": 262
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_014.txt",
      "chars": 113
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_015.txt",
      "chars": 491
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_016.txt",
      "chars": 122
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_017.txt",
      "chars": 344
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_018.txt",
      "chars": 263
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_019.txt",
      "chars": 218
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_020.txt",
      "chars": 179
    },
    {
      "language": "txt",
      "file": "attachments/9d6b4ccfd105/code/block_021.txt",
      "chars": 1551
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:07:57Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:07:57Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:07:57Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:07:57Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/jyipkl/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/prompt-like-a-data-scientist-auto-prompt-optimization-and-testing-with-dspy-ff699f030cb7"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/ai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/chatbots/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/llm/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/openai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/chefboost-an-alternative-python-library-for-tree-based-models-f46af028a348/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/eryk-lewinson/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/parse-the-folder-not-just-the-pdfs-the-relational-tables-rag-needs-on-a-case-file/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/large-language-model/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/angela.shi/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2"
    },
    {
      "type": "external",
      "href": "https://docs.haystack.deepset.ai/docs/inmemorydocumentstore"
    },
    {
      "type": "external",
      "href": "https://openrouter.ai/models/openai/gpt-4-1106-preview"
    },
    {
      "type": "external",
      "href": "https://haystack.deepset.ai/"
    },
    {
      "type": "external",
      "href": "https://haystack.deepset.ai/tutorials/40_building_chat_application_with_function_calling"
    },
    {
      "type": "external",
      "href": "https://github.com/yip-kl/llm_function_calling_demo"
    },
    {
      "type": "external",
      "href": "https://cookbook.openai.com/examples/function_calling_with_an_openapi_spec"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Build+Autonomous+AI+Agents+with+Function+Calling&u=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Build+Autonomous+AI+Agents+with+Function+Calling&url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Build+Autonomous+AI+Agents+with+Function+Calling&url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:33:17Z",
  "source_url": "https://towardsdatascience.com/build-autonomous-ai-agents-with-function-calling-0bb483753975/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Science](https://towardsdatascience.com/category/data-science/)\n# Build Autonomous AI Agents with Function Calling\nTransform your chatbot into an agent that can interact with external APIs\n[Julian Yip](https://towardsdatascience.com/author/jyipkl/)\nApril 2, 202411 min read\nFunction Calling is not something new. In July 2023, OpenAI introduced Function Calling for their GPT models, a feature now being adopted by competitors. Google's Gemini API recently supported it, and Anthropic is integrating it into Claude. Function Calling is becoming essential for large language models (LLMs), enhancing their capabilities. All the more useful to learn this technique!\nWith this in mind, I aim to write a comprehensive tutorial covering Function Calling beyond basic introductions (there are already plenty of tutorials for it). The focus will be on practical implementation, building a fully autonomous AI agent and integrating it with Streamlit for a ChatGPT-like interface. Although OpenAI is used for demonstration, this tutorial can be easily adapted for other LLMs supporting Function Calling, such as Gemini.\n## **What is Function Calling for?**\nFunction Calling enables developers to describe functions (aka tools, you can consider this as actions for the model to take, like performing calculation, or making an order), and have the model intelligently choose to output a JSON object containing arguments to call those functions. In simpler terms, it allows for:\n  * **Autonomous decision making** : Models can intelligently choose tools to respond to questions.\n  * **Reliable parsing** : Responses are in JSON format, instead of the more typical dialogue-like response. It might not seem much from the first look, but this is what allows LLM to connect to external systems, say via APIs with structured inputs.\n\n\nIt opens up numerous possibilities:\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) roadmap.\n  * **Autonomous AI assistants** : Bots can interact with internal systems for tasks like customer orders and returns, beyond providing answers to enquiries\n  * **Personal research assistants** : Say if you are planning for your travel, assistants can search the web, crawl content, compare options, and summarize results in Excel.\n  * **IoT voice commands** : Models can control devices or suggest actions based on detected intents, such as adjusting the AC temperature.\n\n\n* * *\n_(Sidetracking a bit: To realize such potentials, we must have a systematic way to design our prompts and to test them. I have written an article about this too!)_\n> [**Prompt Like a Data Scientist: Auto Prompt Optimization and Testing with DSPy**](https://towardsdatascience.com/prompt-like-a-data-scientist-auto-prompt-optimization-and-testing-with-dspy-ff699f030cb7)\nWithout further ado, let's explore what Function Calling is about!\n## The Structure of Function Calling\nBorrowing from [Gemini's Function Calling documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling), Function Calling has the below structure, which works the same in OpenAI\n![Image from Gemini&#039;s Function Calling documentation](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/0rrgnwWr7Hif3TfH_.png)\nImage from [Gemini's Function Calling documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling)\n  1. User issues prompt to the application\n  2. Application passes the user-provided prompt, and the Function Declaration(s), which is a description of the tool(s) that the model could use\n  3. Based on the Function Declaration, the model suggests the tool to use, and the relevant request parameters. **Notice the model outputs the suggested tool and parameters only, WITHOUT actually calling the functions**\n  4. & 5. Based on the response, the application invokes the relevant API\n  5. & 7. The response from API is fed into the model again to output a human-readable response\n  6. Application returns the final response to the user, then repeat from 1.\n\n\nThis might seem convuluted, but the concept will be illustrated in detail with example\n## Architecture\nBefore diving into the code, a few words about the demo application's architecture\n### **Solution**\nHere we build an assistant for tourists visiting a hotel. The assistant has access to the following tools, which allows the assistant to access external applications.\n  * `get_items`, `purchase_item`: Connect to product catalog stored in database via API, for retrieving item list and making a purchase respectively\n  * `rag_pipeline_func`: Connect to document store with Retrieval Augmented Generation (RAG) to obtain information from unstructured texts e.g. hotel's brochures\n\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/12aXhxSCJKyOVzkC0IJofiQ.png)\n### **Tech stack**\n  * **Embedding model** : [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2)\n  * **Vector Database** : [Haystack's InMemoryDocumentStore](https://docs.haystack.deepset.ai/docs/inmemorydocumentstore)\n  * **LLM** : [GPT-4 Turbo accessed via OpenRouter](https://openrouter.ai/models/openai/gpt-4-1106-preview). With OpenRouter you can access different LLM APIs from Hong Kong without VPN. The flow can be adapted into using other LLMs with slight code change, provided they support Function Calling, say Gemini\n  * **LLM Framework** : [Haystack](https://haystack.deepset.ai/) for their ease of use, great documentation and transparency in pipeline construction. This tutorial is actually an extension to their [fantastic tutorial](https://haystack.deepset.ai/tutorials/40_building_chat_application_with_function_calling) for the same topic\n\n\nNow let's begin!\n## Sample Application\n### Preparation\nHead over to [Github](https://github.com/yip-kl/llm_function_calling_demo) to clone my code. The contents below can be found in the `function_calling_demo` Notebook.\nPlease also create and activate a virtual environment, then `pip install -r requirements.txt` to install the required packages\n### **Initialization**\nWe first connect to OpenRouter. Alternatively using the original `OpenAIChatGenerator` without overwritting the `api_base_url`would also work, provided you have an OpenAI API key\npython\n\n```\nimport os\nfrom dotenv import load_dotenv\nfrom haystack.components.generators.chat import OpenAIChatGenerator\nfrom haystack.utils import Secret\nfrom haystack.dataclasses import ChatMessage\nfrom haystack.components.generators.utils import print_streaming_chunk\n\n# Set your API key as environment variable before executing this\nload_dotenv()\nOPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY')\n\nchat_generator = OpenAIChatGenerator(api_key=Secret.from_env_var(\"OPENROUTER_API_KEY\"),\n  api_base_url=\"https://openrouter.ai/api/v1\",\n  model=\"openai/gpt-4-turbo-preview\",\n        streaming_callback=print_streaming_chunk)\n```\n\nThen we test can the `chat_generator` be successfully invoked\npython\n\n```\nchat_generator.run(messages=[ChatMessage.from_user(\"Return this text: 'test'\")])\n```\n\ntext\n\n```\n---------- The response should look like this ----------\n{'replies': [ChatMessage(content=\"'test'\", role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'openai/gpt-4-turbo-preview', 'index': 0, 'finish_reason': 'stop', 'usage': {}})]}\n```\n\n### Step 1: Establish data store\nHere we establish connection between our application and the two data sources: **Document store** for unstructured texts, and **application database** via API\n**Index Documents with a Pipeline**\nWe provide sample texts in `documents` for the model to perform Retrival Augmented Generation (RAG). The texts are turned into embeddings and stored in an in-memory document store\npython\n\n```\nfrom haystack import Pipeline, Document\nfrom haystack.document_stores.in_memory import InMemoryDocumentStore\nfrom haystack.components.writers import DocumentWriter\nfrom haystack.components.embedders import SentenceTransformersDocumentEmbedder\n\n# Sample documents\ndocuments = [\n    Document(content=\"Coffee shop opens at 9am and closes at 5pm.\"),\n    Document(content=\"Gym room opens at 6am and closes at 10pm.\")\n]\n\n# Create the document store\ndocument_store = InMemoryDocumentStore()\n\n# Create a pipeline to turn the texts into embeddings and store them in the document store\nindexing_pipeline = Pipeline()\nindexing_pipeline.add_component(\n    \"doc_embedder\", SentenceTransformersDocumentEmbedder(model=\"sentence-transformers/all-MiniLM-L6-v2\")\n)\nindexing_pipeline.add_component(\"doc_writer\", DocumentWriter(document_store=document_store))\n\nindexing_pipeline.connect(\"doc_embedder.documents\", \"doc_writer.documents\")\n\nindexing_pipeline.run({\"doc_embedder\": {\"documents\": documents}})\n```\n\nIt should output this, corresponding to the `documents` we created as sample\njson\n\n```\n{'doc_writer': {'documents_written': 2}}\n```\n\n**Spin up API server**\nAn API server made with Flask is created under `db_api.py` to connect to SQLite. Please spin it up by running `python db_api.py` in your terminal\n![This would be shown in the terminal, if successfully executed](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/1S4Ty6XitWFrOHY5wWENaXg.png)\nThis would be shown in the terminal, if successfully executed\nAlso notice that some initial data has been added in `db_api.py`\n![Sample data in the database](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/1tASIXxNUJThtf0-HuPtISw.png)\nSample data in the database\n### Step 2: Define the functions\nHere we prepare the actual functions for the model to invoke **AFTER** Function Calling (Step 4–5 as described in **The Structure of Function Calling**)\n**RAG function**\nNamely the `rag_pipeline_func`. This is for the model to provide an answer by searching through the texts stored in the Document Store. We first define the RAG retrieval as a Haystack pipeline\npython\n\n```\nfrom haystack.components.embedders import SentenceTransformersTextEmbedder\nfrom haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever\nfrom haystack.components.builders import PromptBuilder\nfrom haystack.components.generators import OpenAIGenerator\n\ntemplate = \"\"\"\nAnswer the questions based on the given context.\n\nContext:\n{% for document in documents %}\n    {{ document.content }}\n{% endfor %}\nQuestion: {{ question }}\nAnswer:\n\"\"\"\nrag_pipe = Pipeline()\nrag_pipe.add_component(\"embedder\", SentenceTransformersTextEmbedder(model=\"sentence-transformers/all-MiniLM-L6-v2\"))\nrag_pipe.add_component(\"retriever\", InMemoryEmbeddingRetriever(document_store=document_store))\nrag_pipe.add_component(\"prompt_builder\", PromptBuilder(template=template))\n# Note to llm: We are using OpenAIGenerator, not the OpenAIChatGenerator, because the latter only accepts List[str] as input and cannot accept prompt_builder's str output\nrag_pipe.add_component(\"llm\", OpenAIGenerator(api_key=Secret.from_env_var(\"OPENROUTER_API_KEY\"),\n  api_base_url=\"https://openrouter.ai/api/v1\",\n  model=\"openai/gpt-4-turbo-preview\"))\n\nrag_pipe.connect(\"embedder.embedding\", \"retriever.query_embedding\")\nrag_pipe.connect(\"retriever\", \"prompt_builder.documents\")\nrag_pipe.connect(\"prompt_builder\", \"llm\")\n```\n\nTest if the function works\npython\n\n```\nquery = \"When does the coffee shop open?\"\nrag_pipe.run({\"embedder\": {\"text\": query}, \"prompt_builder\": {\"question\": query}})\n```\n\nThis should yield the following output. Notice the `replies` that the model gave is from the sample documents we provided before\njson\n\n```\n{'llm': {'replies': ['The coffee shop opens at 9am.'],\n  'meta': [{'model': 'openai/gpt-4-turbo-preview',\n    'index': 0,\n    'finish_reason': 'stop',\n    'usage': {'completion_tokens': 9,\n     'prompt_tokens': 60,\n     'total_tokens': 69,\n     'total_cost': 0.00087}}]}}\n```\n\nWe can then turn the `rag_pipe` into a function, which provides the `replies` only without adding in the other details\npython\n\n```\ndef rag_pipeline_func(query: str):\n    result = rag_pipe.run({\"embedder\": {\"text\": query}, \"prompt_builder\": {\"question\": query}})\n\n    return {\"reply\": result[\"llm\"][\"replies\"][0]}\n```\n\n**API calls**\nWe define the `get_items` and `purchase_item`functions for interacting with the database\npython\n\n```\n# Flask's default local URL, change it if necessary\ndb_base_url = 'http://127.0.0.1:5000'\n\n# Use requests to get the data from the database\nimport requests\nimport json\n\n# get_categories is supplied as part of the prompt, it is not used as a tool\ndef get_categories():\n    response = requests.get(f'{db_base_url}/category')\n    data = response.json()\n    return data\n\ndef get_items(ids=None,categories=None):\n    params = {\n        'id': ids,\n        'category': categories,\n    }\n    response = requests.get(f'{db_base_url}/item', params=params)\n    data = response.json()\n    return data\n\ndef purchase_item(id,quantity):\n\n    headers = {\n    'Content-type':'application/json', \n    'Accept':'application/json'\n    }\n\n    data = {\n        'id': id,\n        'quantity': quantity,\n    }\n    response = requests.post(f'{db_base_url}/item/purchase', json=data, headers=headers)\n    return response.json()\n```\n\n**Define the tool list**\nNow that we have defined the fuctions, we need to let the model recognize those functions, and to instruct them how they are used, by providing descriptions for them.\nSince we are using OpenAI here, the `tools` is formatted as below following the [format required by Open AI](https://cookbook.openai.com/examples/function_calling_with_an_openapi_spec)\npython\n\n```\ntools = [\n    {\n        \"type\": \"function\",\n        \"function\": {\n            \"name\": \"get_items\",\n            \"description\": \"Get a list of items from the database\",\n            \"parameters\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"ids\": {\n                        \"type\": \"string\",\n                        \"description\": \"Comma separated list of item ids to fetch\",\n                    },\n                    \"categories\": {\n                        \"type\": \"string\",\n                        \"description\": \"Comma separated list of item categories to fetch\",\n                    },\n                },\n                \"required\": [],\n            },\n        }\n    },\n    {\n        \"type\": \"function\",\n        \"function\": {\n            \"name\": \"purchase_item\",\n            \"description\": \"Purchase a particular item\",\n            \"parameters\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"id\": {\n                        \"type\": \"string\",\n                        \"description\": \"The given product ID, product name is not accepted here. Please obtain the product ID from the database first.\",\n                    },\n                    \"quantity\": {\n                        \"type\": \"integer\",\n                        \"description\": \"Number of items to purchase\",\n                    },\n                },\n                \"required\": [],\n            },\n        }\n    },\n    {\n        \"type\": \"function\",\n        \"function\": {\n            \"name\": \"rag_pipeline_func\",\n            \"description\": \"Get information from hotel brochure\",\n            \"parameters\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"query\": {\n                        \"type\": \"string\",\n                        \"description\": \"The query to use in the search. Infer this from the user's message. It should be a question or a statement\",\n                    }\n                },\n                \"required\": [\"query\"],\n            },\n        },\n    }\n]\n```\n\n### **Step 3: Putting it all together**\nWe now have the necessary inputs to test Function Calling! Here we do a few things:\n  1. Provide the initial prompt to the model, to give it some context\n  2. Provide a sample user-generated message\n  3. Most importantly, we pass the tool list to the chat generator in `tools`\n\n\npython\n\n```\n# 1. Initial prompt\ncontext = f\"\"\"You are an assistant to tourists visiting a hotel.\nYou have access to a database of items (which includes {get_categories()}) that tourists can buy, you also have access to the hotel's brochure.\nIf the tourist's question cannot be answered from the database, you can refer to the brochure.\nIf the tourist's question cannot be answered from the brochure, you can ask the tourist to ask the hotel staff.\n\"\"\"\nmessages = [\n    ChatMessage.from_system(context),\n    # 2. Sample message from user\n    ChatMessage.from_user(\"Can I buy a coffee?\"),\n    ]\n\n# 3. Passing the tools list and invoke the chat generator\nresponse = chat_generator.run(messages=messages, generation_kwargs= {\"tools\": tools})\nresponse\n```\n\ntext\n\n```\n---------- Response ----------\n{'replies': [ChatMessage(content='[{\"index\": 0, \"id\": \"call_AkTWoiJzx5uJSgKW0WAI1yBB\", \"function\": {\"arguments\": \"{\"categories\":\"Food and beverages\"}\", \"name\": \"get_items\"}, \"type\": \"function\"}]', role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'openai/gpt-4-turbo-preview', 'index': 0, 'finish_reason': 'tool_calls', 'usage': {}})]}\n```\n\nNow let's inspect the response. Notice how the Function Calling returns both the function chosen by the model, and the arguments for invoking the chosen function.\npython\n\n```\nfunction_call = json.loads(response[\"replies\"][0].content)[0]\nfunction_name = function_call[\"function\"][\"name\"]\nfunction_args = json.loads(function_call[\"function\"][\"arguments\"])\nprint(\"Function Name:\", function_name)\nprint(\"Function Arguments:\", function_args)\n```\n\ntext\n\n```\n---------- Response ----------\nFunction Name: get_items\nFunction Arguments: {'categories': 'Food and beverages'}\n```\n\nWhen presented with another question, the model will use another tool that is more relevant\npython\n\n```\n# Another question\nmessages.append(ChatMessage.from_user(\"Where's the coffee shop?\"))\n\n# Invoke the chat generator, and passing the tools list\nresponse = chat_generator.run(messages=messages, generation_kwargs= {\"tools\": tools})\nfunction_call = json.loads(response[\"replies\"][0].content)[0]\nfunction_name = function_call[\"function\"][\"name\"]\nfunction_args = json.loads(function_call[\"function\"][\"arguments\"])\nprint(\"Function Name:\", function_name)\nprint(\"Function Arguments:\", function_args)\n```\n\ntext\n\n```\n---------- Response ----------\nFunction Name: rag_pipeline_func\nFunction Arguments: {'query': \"Where's the coffee shop?\"}\n```\n\nAgain, notice that no actual function is invoked here, this is what we will do next!\n**Calling the function**\nWe can then feed the arguments into the chosen function\npython\n\n```\n## Find the correspoding function and call it with the given arguments\navailable_functions = {\"get_items\": get_items, \"purchase_item\": purchase_item,\"rag_pipeline_func\": rag_pipeline_func}\nfunction_to_call = available_functions[function_name]\nfunction_response = function_to_call(**function_args)\nprint(\"Function Response:\", function_response)\n```\n\ntext\n\n```\n---------- Response ----------\nFunction Response: {'reply': 'The provided context does not specify a physical location for the coffee shop, only its operating hours. Therefore, I cannot determine where the coffee shop is located based on the given information.'}\n```\n\nThe response from `rag_pipeline_func` can then passed as a context to the chat by appending it under the `messages`, for the model to provide the final answer\npython\n\n```\nmessages.append(ChatMessage.from_function(content=json.dumps(function_response), name=function_name))\nresponse = chat_generator.run(messages=messages)\nresponse_msg = response[\"replies\"][0]\n\nprint(response_msg.content)\n```\n\ntext\n\n```\n---------- Response ----------\nFor the location of the coffee shop within the hotel, I recommend asking the hotel staff directly. They will be able to guide you to it accurately.\n```\n\nWe now have completed the chat cycle!\n### Step 4: Turn into an interactive chat\nThe code above shows how Function Calling can be done, but we want to go a step further by turning it into an interactive chat\nHere I showcase two methods to do it, from the more primitive `input()` that prints the dialogue into the notebook itself, to rendering it through **Streamlit** to provide it with an ChatGPT-like UI\n`**input()**`**loop**\nThe code is copied from [Haystack's tutorial](https://haystack.deepset.ai/tutorials/40_building_chat_application_with_function_calling), which allows us to quickly test the model. _Note: This application is created to demonstrate the idea of Function Calling, and is NOT meant to be perfectly robust e.g. supporting the order of multiple items at the same time, no hallucination, etc._\npython\n\n```\nimport json\nfrom haystack.dataclasses import ChatMessage, ChatRole\n\nresponse = None\nmessages = [\n    ChatMessage.from_system(context)\n]\n\nwhile True:\n    # if OpenAI response is a tool call\n    if response and response[\"replies\"][0].meta[\"finish_reason\"] == \"tool_calls\":\n        function_calls = json.loads(response[\"replies\"][0].content)\n\n        for function_call in function_calls:\n            ## Parse function calling information\n            function_name = function_call[\"function\"][\"name\"]\n            function_args = json.loads(function_call[\"function\"][\"arguments\"])\n\n            ## Find the correspoding function and call it with the given arguments\n            function_to_call = available_functions[function_name]\n            function_response = function_to_call(**function_args)\n\n            ## Append function response to the messages list using `ChatMessage.from_function`\n            messages.append(ChatMessage.from_function(content=json.dumps(function_response), name=function_name))\n\n    # Regular Conversation\n    else:\n        # Append assistant messages to the messages list\n        if not messages[-1].is_from(ChatRole.SYSTEM):\n            messages.append(response[\"replies\"][0])\n\n        user_input = input(\"ENTER YOUR MESSAGE 👇  INFO: Type 'exit' or 'quit' to stopn\")\n        if user_input.lower() == \"exit\" or user_input.lower() == \"quit\":\n            break\n        else:\n            messages.append(ChatMessage.from_user(user_input))\n\n    response = chat_generator.run(messages=messages, generation_kwargs={\"tools\": tools})\n```\n\n![Running interactive chats in the IDE](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/1A5nwZCw3JO_553WiBEGaDg.png)\nRunning interactive chats in the IDE\nWhile it works, we might want to have something that looks nicer.\n**Streamlit interface**\nStreamlit turns data scripts into shareable web apps, which provides a neat UI for our application. The code shown above are adapted into a Streamlit application under the `streamlit` folder of my repo\nYou can run it by:\n  1. If you have not done so already, spin up the API server with `python db_api.py`\n  2. Set the OPENROUTER_API_KEY as environment variable e.g. `export OPENROUTER_API_KEY = '@REPLACE WITH YOUR API KEY'` assuming you are on Linux / executing with git bash\n  3. Navigate to the `streamlit` folder in the terminal with `cd streamlit`\n  4. Run Streamlit with `streamlit run app.py`. A new tab should be automatically created in your browser running the application\n\n\nThat's basically it! I hope you enjoy this article.\n![Streamlit UI](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/04/1EPp8ZNpthZi8ksU03vuCAg.png)\nStreamlit UI\n _*Unless otherwise noted, all images are by the author_\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657545973_9tepv8.jpeg)\nWritten By\n## [Julian Yip](https://towardsdatascience.com/author/jyipkl/)\n[See all from Julian Yip](https://towardsdatascience.com/author/jyipkl/)\n[AI](https://towardsdatascience.com/tag/ai/)[Chatbots](https://towardsdatascience.com/tag/chatbots/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Llm](https://towardsdatascience.com/tag/llm/)[OpenAI](https://towardsdatascience.com/tag/openai/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F&title=Build%20Autonomous%20AI%20Agents%20with%20Function%20Calling)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F&title=Build%20Autonomous%20AI%20Agents%20with%20Function%20Calling)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fbuild-autonomous-ai-agents-with-function-calling-0bb483753975%2F&text=Build%20Autonomous%20AI%20Agents%20with%20Function%20Calling)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/06/1tzAod2DzLo0nAOmakvaulQ-scaled.jpeg)](https://towardsdatascience.com/chefboost-an-alternative-python-library-for-tree-based-models-f46af028a348/)\n## [Chefboost - an alternative Python library for tree-based models](https://towardsdatascience.com/chefboost-an-alternative-python-library-for-tree-based-models-f46af028a348/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAn overview of key differences from scikit-learn\n[Eryk Lewinson](https://towardsdatascience.com/author/eryk-lewinson/)\nJune 13, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/08/binder_shelf_34293529_v3_card.jpg)](https://towardsdatascience.com/parse-the-folder-not-just-the-pdfs-the-relational-tables-rag-needs-on-a-case-file/)\n## [Parse the Folder, Not Just the PDFs: The Relational Tables RAG Needs on a Case File](https://towardsdatascience.com/parse-the-folder-not-just-the-pdfs-the-relational-tables-rag-needs-on-a-case-file/)\n[Large Language Model](https://towardsdatascience.com/category/large-language-model/)\nEnterprise Document Intelligence [Vol.1 #14D] - The index lists what the case type demands before any folder is opened, and the two questions worth building for are not retrieval questions at all\n[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\nAugust 23, 202620 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/02/0cGeMLypdJxN6PWyv-scaled.jpg)](https://towardsdatascience.com/the-best-interviews-ive-had-were-never-coding-challenges-95ec0cde765b/)\n## [The Best Interviews I've Had Were Never Coding Challenges](https://towardsdatascience.com/the-best-interviews-ive-had-were-never-coding-challenges-95ec0cde765b/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nDifferent Styles of Interviews that You Can Try Out\n[Rose Day](https://towardsdatascience.com/author/rjday/)\nFebruary 4, 20227 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/08/1BKasSImsqazJsyi3BZwHzg-scaled.jpeg)](https://towardsdatascience.com/5-chrome-extension-to-ease-up-your-life-as-a-data-scientist-c5c483605d0d/)\n## [5 Chrome Extension to Ease up Your Life as a Data Scientist](https://towardsdatascience.com/5-chrome-extension-to-ease-up-your-life-as-a-data-scientist-c5c483605d0d/)\n[Programming](https://towardsdatascience.com/category/programming/)\nThese extensions are must for a smooth workflow\n[Sara A. Metwalli](https://towardsdatascience.com/author/saraametwalli/)\nAugust 23, 20205 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/08/1yUrus7EH-GxwjszC2nQA9A.png)](https://towardsdatascience.com/geovec-word-embeddings-for-geosciences-ac1e1e854e19/)\n## [GeoVec: word embeddings for geosciences](https://towardsdatascience.com/geovec-word-embeddings-for-geosciences-ac1e1e854e19/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAnalogies, categorisation, relatedness and spatial interpolation of word embeddings.\n[José Padarian](https://towardsdatascience.com/author/spadarian/)\nAugust 20, 20198 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/0XSRgmcQanIX_0spm.jpg)](https://towardsdatascience.com/tsfresh-on-large-data-samples-part-ii-4d6843155dfc/)\n## [tsfresh on Large Data Samples - Part II](https://towardsdatascience.com/tsfresh-on-large-data-samples-part-ii-4d6843155dfc/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nIf big is not big enough In the last post, we have explored how tsfresh...\n[Nils Braun](https://towardsdatascience.com/author/nils-braun/)\nDecember 7, 202015 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/1r0oI6sac7YWMmcruIpeHcw-scaled.jpeg)](https://towardsdatascience.com/mlops-level-1-continuous-training-b2a633e27d47/)\n## [MLOps Level 1: Continuous Training](https://towardsdatascience.com/mlops-level-1-continuous-training-b2a633e27d47/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIn MLOps level 1 the machine learning pipeline is automated. By doing so you achieve...\n[Marco Susilo](https://towardsdatascience.com/author/marco-susilo/)\nMay 9, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/12/0lR4DV-NyB5XkkRJA.jpg)](https://towardsdatascience.com/roialign-explained-d30f6843da3a/)\n## [RoIAlign Explained](https://towardsdatascience.com/roialign-explained-d30f6843da3a/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWith Python Implementation\n[Alexey Kravets](https://towardsdatascience.com/author/alexml0123/)\nDecember 29, 202210 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/09/0is4UBs-VYy1lkDkK-scaled.jpg)](https://towardsdatascience.com/how-to-make-your-deep-learning-experiments-reproducible-and-your-code-extendible-7ef56767dddb/)\n## [How to make your deep learning experiments reproducible and your code extendible](https://towardsdatascience.com/how-to-make-your-deep-learning-experiments-reproducible-and-your-code-extendible-7ef56767dddb/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nLessons learned from building an open-source deep learning for time series framework\n[Isaac Godfried](https://towardsdatascience.com/author/igodfried/)\nSeptember 25, 20206 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/9d6b4ccfd105/pages/",
  "body_markdown_path": "attachments/9d6b4ccfd105/pages/archived-body.md",
  "local_html": "attachments/9d6b4ccfd105/pages/archived-body.html",
  "body_source": "prior_capture"
}