![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
We value your privacy
We 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.
Customise Reject All Accept All
Customise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The 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
NecessaryAlways Active
Necessary 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.
  * Cookie
BCTempID
  * Duration
10 minutes
  * Description
No description available.


  * Cookie
__cf_bm
  * Duration
1 hour
  * Description
This cookie, set by Cloudflare, is used to support Cloudflare Bot Management. 


  * Cookie
AWSALBCORS
  * Duration
7 days
  * Description
Amazon Web Services set this cookie for load balancing.


  * Cookie
_cfuvid
  * Duration
session
  * Description
Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services


  * Cookie
li_gc
  * Duration
6 months
  * Description
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.


  * Cookie
__hssrc
  * Duration
session
  * Description
This 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.


  * Cookie
__hssc
  * Duration
1 hour
  * Description
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.


  * Cookie
wpEmojiSettingsSupports
  * Duration
session
  * Description
WordPress 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.


  * Cookie
BCSessionID
  * Duration
1 year 1 month 4 days
  * Description
Blueconic sets this cookie as a unique identifier for the BlueConic profile.


  * Cookie
_octo
  * Duration
1 year
  * Description
No description available.


  * Cookie
logged_in
  * Duration
1 year
  * Description
No description available.


  * Cookie
__Secure-YEC
  * Duration
past
  * Description
YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video


  * Cookie
__eoi
  * Duration
6 months
  * Description
Description is currently not available.


  * Cookie
AWSALBTGCORS
  * Duration
7 days
  * Description
No description available.


  * Cookie
login-status-p
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
AWSALBTG
  * Duration
7 days
  * Description
No description available.


  * Cookie
csrf_token
  * Duration
session
  * Description
No description available.


  * Cookie
token_v2
  * Duration
1 day
  * Description
Description is currently not available.


  * Cookie
D
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
PHPSESSID
  * Duration
session
  * Description
This 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.


  * Cookie
VISITOR_PRIVACY_METADATA
  * Duration
6 months
  * Description
YouTube sets this cookie to store the user's cookie consent state for the current domain. 


  * Cookie
cookietest
  * Duration
session
  * Description
The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.


  * Cookie
__Host-airtable-session
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
__Host-airtable-session.sig
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
m
  * Duration
1 year 1 month 4 days
  * Description
Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.


  * Cookie
BIGipServer*
  * Duration
session
  * Description
Marketo 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. 


  * Cookie
__cfruid
  * Duration
session
  * Description
Cloudflare sets this cookie to identify trusted web traffic.


  * Cookie
_GRECAPTCHA
  * Duration
6 months
  * Description
Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.


  * Cookie
__Secure-YNID
  * Duration
6 months
  * Description
Google cookie used to protect user security and prevent fraud, especially during the login process.


  * Cookie
cookieyes-consent
  * Duration
1 year
  * Description
CookieYes 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.


Functional
Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
  * Cookie
lidc
  * Duration
1 day
  * Description
LinkedIn sets the lidc cookie to facilitate data center selection.


  * Cookie
brw
  * Duration
1 year
  * Description
No description available.


  * Cookie
brwConsent
  * Duration
5 minutes
  * Description
Description is currently not available.


  * Cookie
WMF-Uniq
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
loom_anon_comment
  * Duration
1 year
  * Description
No description available.


  * Cookie
loom_referral_video
  * Duration
session
  * Description
Description is currently not available.


  * Cookie
VISITOR_INFO1_LIVE
  * Duration
6 months
  * Description
A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.


  * Cookie
yt-remote-connected-devices
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
ytidb::LAST_RESULT_ENTRY_KEY
  * Duration
Never Expires
  * Description
The 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.


  * Cookie
yt-remote-device-id
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
yt-remote-session-name
  * Duration
session
  * Description
The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.


  * Cookie
yt-remote-fast-check-period
  * Duration
session
  * Description
The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.


  * Cookie
yt-remote-session-app
  * Duration
session
  * Description
The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.


  * Cookie
yt-remote-cast-available
  * Duration
session
  * Description
The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.


  * Cookie
yt-remote-cast-installed
  * Duration
session
  * Description
The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.


  * Cookie
cp_session
  * Duration
3 months
  * Description
Codepen sets this cookie for Help systems found in the website.


  * Cookie
loid
  * Duration
1 year 1 month 4 days
  * Description
This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.


Analytics
Analytical 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.
  * Cookie
__hstc
  * Duration
6 months
  * Description
Hubspot 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).


  * Cookie
hubspotutk
  * Duration
6 months
  * Description
HubSpot 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.


  * Cookie
_ga
  * Duration
1 year 1 month 4 days
  * Description
Google 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.


  * Cookie
_ga_*
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to store and count page views.


  * Cookie
__Host-psifi.analyticsTrace
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
__Host-psifi.analyticsTraceV2
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
_gh_sess
  * Duration
session
  * Description
GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.


  * Cookie
YSC
  * Duration
session
  * Description
YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.


  * Cookie
ajs_anonymous_id
  * Duration
1 year
  * Description
This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.


  * Cookie
vuid
  * Duration
1 year 1 month 4 days
  * Description
Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. 


Performance
Performance 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.
  * Cookie
AWSALB
  * Duration
7 days
  * Description
AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.


  * Cookie
acq
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
acq.sig
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
ptc
  * Duration
2 years
  * Description
No description available.


Advertisement
Advertisement 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.
  * Cookie
muc_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.


  * Cookie
guest_id_marketing
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
guest_id_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
personalization_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter 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.


  * Cookie
guest_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter 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.


  * Cookie
bcookie
  * Duration
1 year
  * Description
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.


  * Cookie
__Secure-ROLLOUT_TOKEN
  * Duration
6 months
  * Description
YouTube 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.


  * Cookie
yt.innertube::nextId
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
yt.innertube::requests
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
session_tracker
  * Duration
session
  * Description
This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.


  * Cookie
edgebucket
  * Duration
session
  * Description
Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.


  * Cookie
did
  * Duration
1 year
  * Description
Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.


Uncategorised
Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet.
No cookies to display.
Reject All Save My Preferences Accept All
Toggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[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/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
[Data Science](https://towardsdatascience.com/category/data-science/)
# Build Autonomous AI Agents with Function Calling
Transform your chatbot into an agent that can interact with external APIs
[Julian Yip](https://towardsdatascience.com/author/jyipkl/)
April 2, 202411 min read
Function 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!
With 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.
## **What is Function Calling for?**
Function 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:
  * **Autonomous decision making** : Models can intelligently choose tools to respond to questions.
  * **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.


It opens up numerous possibilities:
Learn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) roadmap.
  * **Autonomous AI assistants** : Bots can interact with internal systems for tasks like customer orders and returns, beyond providing answers to enquiries
  * **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.
  * **IoT voice commands** : Models can control devices or suggest actions based on detected intents, such as adjusting the AC temperature.


* * *
_(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!)_
> [**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)
Without further ado, let's explore what Function Calling is about!
## The Structure of Function Calling
Borrowing 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
![Image from Gemini&#039;s Function Calling documentation](../images/000.png)
Image from [Gemini's Function Calling documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling)
  1. User issues prompt to the application
  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
  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**
  4. & 5. Based on the response, the application invokes the relevant API
  5. & 7. The response from API is fed into the model again to output a human-readable response
  6. Application returns the final response to the user, then repeat from 1.


This might seem convuluted, but the concept will be illustrated in detail with example
## Architecture
Before diving into the code, a few words about the demo application's architecture
### **Solution**
Here 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.
  * `get_items`, `purchase_item`: Connect to product catalog stored in database via API, for retrieving item list and making a purchase respectively
  * `rag_pipeline_func`: Connect to document store with Retrieval Augmented Generation (RAG) to obtain information from unstructured texts e.g. hotel's brochures


![](../images/body-c1cc917801e07b42c0b8.png)
### **Tech stack**
  * **Embedding model** : [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2)
  * **Vector Database** : [Haystack's InMemoryDocumentStore](https://docs.haystack.deepset.ai/docs/inmemorydocumentstore)
  * **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
  * **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


Now let's begin!
## Sample Application
### Preparation
Head 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.
Please also create and activate a virtual environment, then `pip install -r requirements.txt` to install the required packages
### **Initialization**
We 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
python

```
import os
from dotenv import load_dotenv
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.utils import Secret
from haystack.dataclasses import ChatMessage
from haystack.components.generators.utils import print_streaming_chunk

# Set your API key as environment variable before executing this
load_dotenv()
OPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY')

chat_generator = OpenAIChatGenerator(api_key=Secret.from_env_var("OPENROUTER_API_KEY"),
  api_base_url="https://openrouter.ai/api/v1",
  model="openai/gpt-4-turbo-preview",
        streaming_callback=print_streaming_chunk)
```

Then we test can the `chat_generator` be successfully invoked
python

```
chat_generator.run(messages=[ChatMessage.from_user("Return this text: 'test'")])
```

text

```
---------- The response should look like this ----------
{'replies': [ChatMessage(content="'test'", role=<ChatRole.ASSISTANT: 'assistant'>, name=None, meta={'model': 'openai/gpt-4-turbo-preview', 'index': 0, 'finish_reason': 'stop', 'usage': {}})]}
```

### Step 1: Establish data store
Here we establish connection between our application and the two data sources: **Document store** for unstructured texts, and **application database** via API
**Index Documents with a Pipeline**
We 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
python

```
from haystack import Pipeline, Document
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.writers import DocumentWriter
from haystack.components.embedders import SentenceTransformersDocumentEmbedder

# Sample documents
documents = [
    Document(content="Coffee shop opens at 9am and closes at 5pm."),
    Document(content="Gym room opens at 6am and closes at 10pm.")
]

# Create the document store
document_store = InMemoryDocumentStore()

# Create a pipeline to turn the texts into embeddings and store them in the document store
indexing_pipeline = Pipeline()
indexing_pipeline.add_component(
    "doc_embedder", SentenceTransformersDocumentEmbedder(model="sentence-transformers/all-MiniLM-L6-v2")
)
indexing_pipeline.add_component("doc_writer", DocumentWriter(document_store=document_store))

indexing_pipeline.connect("doc_embedder.documents", "doc_writer.documents")

indexing_pipeline.run({"doc_embedder": {"documents": documents}})
```

It should output this, corresponding to the `documents` we created as sample
json

```
{'doc_writer': {'documents_written': 2}}
```

**Spin up API server**
An 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
![This would be shown in the terminal, if successfully executed](../images/001.png)
This would be shown in the terminal, if successfully executed
Also notice that some initial data has been added in `db_api.py`
![Sample data in the database](../images/002.png)
Sample data in the database
### Step 2: Define the functions
Here we prepare the actual functions for the model to invoke **AFTER** Function Calling (Step 4–5 as described in **The Structure of Function Calling**)
**RAG function**
Namely 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
python

```
from haystack.components.embedders import SentenceTransformersTextEmbedder
from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
from haystack.components.builders import PromptBuilder
from haystack.components.generators import OpenAIGenerator

template = """
Answer the questions based on the given context.

Context:
{% for document in documents %}
    {{ document.content }}
{% endfor %}
Question: {{ question }}
Answer:
"""
rag_pipe = Pipeline()
rag_pipe.add_component("embedder", SentenceTransformersTextEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"))
rag_pipe.add_component("retriever", InMemoryEmbeddingRetriever(document_store=document_store))
rag_pipe.add_component("prompt_builder", PromptBuilder(template=template))
# 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
rag_pipe.add_component("llm", OpenAIGenerator(api_key=Secret.from_env_var("OPENROUTER_API_KEY"),
  api_base_url="https://openrouter.ai/api/v1",
  model="openai/gpt-4-turbo-preview"))

rag_pipe.connect("embedder.embedding", "retriever.query_embedding")
rag_pipe.connect("retriever", "prompt_builder.documents")
rag_pipe.connect("prompt_builder", "llm")
```

Test if the function works
python

```
query = "When does the coffee shop open?"
rag_pipe.run({"embedder": {"text": query}, "prompt_builder": {"question": query}})
```

This should yield the following output. Notice the `replies` that the model gave is from the sample documents we provided before
json

```
{'llm': {'replies': ['The coffee shop opens at 9am.'],
  'meta': [{'model': 'openai/gpt-4-turbo-preview',
    'index': 0,
    'finish_reason': 'stop',
    'usage': {'completion_tokens': 9,
     'prompt_tokens': 60,
     'total_tokens': 69,
     'total_cost': 0.00087}}]}}
```

We can then turn the `rag_pipe` into a function, which provides the `replies` only without adding in the other details
python

```
def rag_pipeline_func(query: str):
    result = rag_pipe.run({"embedder": {"text": query}, "prompt_builder": {"question": query}})

    return {"reply": result["llm"]["replies"][0]}
```

**API calls**
We define the `get_items` and `purchase_item`functions for interacting with the database
python

```
# Flask's default local URL, change it if necessary
db_base_url = 'http://127.0.0.1:5000'

# Use requests to get the data from the database
import requests
import json

# get_categories is supplied as part of the prompt, it is not used as a tool
def get_categories():
    response = requests.get(f'{db_base_url}/category')
    data = response.json()
    return data

def get_items(ids=None,categories=None):
    params = {
        'id': ids,
        'category': categories,
    }
    response = requests.get(f'{db_base_url}/item', params=params)
    data = response.json()
    return data

def purchase_item(id,quantity):

    headers = {
    'Content-type':'application/json', 
    'Accept':'application/json'
    }

    data = {
        'id': id,
        'quantity': quantity,
    }
    response = requests.post(f'{db_base_url}/item/purchase', json=data, headers=headers)
    return response.json()
```

**Define the tool list**
Now 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.
Since 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)
python

```
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_items",
            "description": "Get a list of items from the database",
            "parameters": {
                "type": "object",
                "properties": {
                    "ids": {
                        "type": "string",
                        "description": "Comma separated list of item ids to fetch",
                    },
                    "categories": {
                        "type": "string",
                        "description": "Comma separated list of item categories to fetch",
                    },
                },
                "required": [],
            },
        }
    },
    {
        "type": "function",
        "function": {
            "name": "purchase_item",
            "description": "Purchase a particular item",
            "parameters": {
                "type": "object",
                "properties": {
                    "id": {
                        "type": "string",
                        "description": "The given product ID, product name is not accepted here. Please obtain the product ID from the database first.",
                    },
                    "quantity": {
                        "type": "integer",
                        "description": "Number of items to purchase",
                    },
                },
                "required": [],
            },
        }
    },
    {
        "type": "function",
        "function": {
            "name": "rag_pipeline_func",
            "description": "Get information from hotel brochure",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The query to use in the search. Infer this from the user's message. It should be a question or a statement",
                    }
                },
                "required": ["query"],
            },
        },
    }
]
```

### **Step 3: Putting it all together**
We now have the necessary inputs to test Function Calling! Here we do a few things:
  1. Provide the initial prompt to the model, to give it some context
  2. Provide a sample user-generated message
  3. Most importantly, we pass the tool list to the chat generator in `tools`


python

```
# 1. Initial prompt
context = f"""You are an assistant to tourists visiting a hotel.
You have access to a database of items (which includes {get_categories()}) that tourists can buy, you also have access to the hotel's brochure.
If the tourist's question cannot be answered from the database, you can refer to the brochure.
If the tourist's question cannot be answered from the brochure, you can ask the tourist to ask the hotel staff.
"""
messages = [
    ChatMessage.from_system(context),
    # 2. Sample message from user
    ChatMessage.from_user("Can I buy a coffee?"),
    ]

# 3. Passing the tools list and invoke the chat generator
response = chat_generator.run(messages=messages, generation_kwargs= {"tools": tools})
response
```

text

```
---------- Response ----------
{'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': {}})]}
```

Now 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.
python

```
function_call = json.loads(response["replies"][0].content)[0]
function_name = function_call["function"]["name"]
function_args = json.loads(function_call["function"]["arguments"])
print("Function Name:", function_name)
print("Function Arguments:", function_args)
```

text

```
---------- Response ----------
Function Name: get_items
Function Arguments: {'categories': 'Food and beverages'}
```

When presented with another question, the model will use another tool that is more relevant
python

```
# Another question
messages.append(ChatMessage.from_user("Where's the coffee shop?"))

# Invoke the chat generator, and passing the tools list
response = chat_generator.run(messages=messages, generation_kwargs= {"tools": tools})
function_call = json.loads(response["replies"][0].content)[0]
function_name = function_call["function"]["name"]
function_args = json.loads(function_call["function"]["arguments"])
print("Function Name:", function_name)
print("Function Arguments:", function_args)
```

text

```
---------- Response ----------
Function Name: rag_pipeline_func
Function Arguments: {'query': "Where's the coffee shop?"}
```

Again, notice that no actual function is invoked here, this is what we will do next!
**Calling the function**
We can then feed the arguments into the chosen function
python

```
## Find the correspoding function and call it with the given arguments
available_functions = {"get_items": get_items, "purchase_item": purchase_item,"rag_pipeline_func": rag_pipeline_func}
function_to_call = available_functions[function_name]
function_response = function_to_call(**function_args)
print("Function Response:", function_response)
```

text

```
---------- Response ----------
Function 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.'}
```

The 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
python

```
messages.append(ChatMessage.from_function(content=json.dumps(function_response), name=function_name))
response = chat_generator.run(messages=messages)
response_msg = response["replies"][0]

print(response_msg.content)
```

text

```
---------- Response ----------
For 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.
```

We now have completed the chat cycle!
### Step 4: Turn into an interactive chat
The code above shows how Function Calling can be done, but we want to go a step further by turning it into an interactive chat
Here 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
`**input()**`**loop**
The 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._
python

```
import json
from haystack.dataclasses import ChatMessage, ChatRole

response = None
messages = [
    ChatMessage.from_system(context)
]

while True:
    # if OpenAI response is a tool call
    if response and response["replies"][0].meta["finish_reason"] == "tool_calls":
        function_calls = json.loads(response["replies"][0].content)

        for function_call in function_calls:
            ## Parse function calling information
            function_name = function_call["function"]["name"]
            function_args = json.loads(function_call["function"]["arguments"])

            ## Find the correspoding function and call it with the given arguments
            function_to_call = available_functions[function_name]
            function_response = function_to_call(**function_args)

            ## Append function response to the messages list using `ChatMessage.from_function`
            messages.append(ChatMessage.from_function(content=json.dumps(function_response), name=function_name))

    # Regular Conversation
    else:
        # Append assistant messages to the messages list
        if not messages[-1].is_from(ChatRole.SYSTEM):
            messages.append(response["replies"][0])

        user_input = input("ENTER YOUR MESSAGE 👇  INFO: Type 'exit' or 'quit' to stopn")
        if user_input.lower() == "exit" or user_input.lower() == "quit":
            break
        else:
            messages.append(ChatMessage.from_user(user_input))

    response = chat_generator.run(messages=messages, generation_kwargs={"tools": tools})
```

![Running interactive chats in the IDE](../images/003.png)
Running interactive chats in the IDE
While it works, we might want to have something that looks nicer.
**Streamlit interface**
Streamlit 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
You can run it by:
  1. If you have not done so already, spin up the API server with `python db_api.py`
  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
  3. Navigate to the `streamlit` folder in the terminal with `cd streamlit`
  4. Run Streamlit with `streamlit run app.py`. A new tab should be automatically created in your browser running the application


That's basically it! I hope you enjoy this article.
![Streamlit UI](../images/004.png)
Streamlit UI
 _*Unless otherwise noted, all images are by the author_
## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.
Register for freeSign in to your account
* * *
![](../images/body-d6f10b7f094af8ff005c.jpeg)
Written By
## [Julian Yip](https://towardsdatascience.com/author/jyipkl/)
[See all from Julian Yip](https://towardsdatascience.com/author/jyipkl/)
[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/)
Share This Article
  * [](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)
  * [](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)
  * [](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)


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
[Write for TDS](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/005.jpeg)](https://towardsdatascience.com/chefboost-an-alternative-python-library-for-tree-based-models-f46af028a348/)
## [Chefboost - an alternative Python library for tree-based models](https://towardsdatascience.com/chefboost-an-alternative-python-library-for-tree-based-models-f46af028a348/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
An overview of key differences from scikit-learn
[Eryk Lewinson](https://towardsdatascience.com/author/eryk-lewinson/)
June 13, 20215 min read
  * [![](../images/006.jpg)](https://towardsdatascience.com/parse-the-folder-not-just-the-pdfs-the-relational-tables-rag-needs-on-a-case-file/)
## [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/)
[Large Language Model](https://towardsdatascience.com/category/large-language-model/)
Enterprise 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
[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)
August 23, 202620 min read
  * [![](../images/007.jpg)](https://towardsdatascience.com/the-best-interviews-ive-had-were-never-coding-challenges-95ec0cde765b/)
## [The Best Interviews I've Had Were Never Coding Challenges](https://towardsdatascience.com/the-best-interviews-ive-had-were-never-coding-challenges-95ec0cde765b/)
[Data Science](https://towardsdatascience.com/category/data-science/)
Different Styles of Interviews that You Can Try Out
[Rose Day](https://towardsdatascience.com/author/rjday/)
February 4, 20227 min read
  * [![](../images/008.jpeg)](https://towardsdatascience.com/5-chrome-extension-to-ease-up-your-life-as-a-data-scientist-c5c483605d0d/)
## [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/)
[Programming](https://towardsdatascience.com/category/programming/)
These extensions are must for a smooth workflow
[Sara A. Metwalli](https://towardsdatascience.com/author/saraametwalli/)
August 23, 20205 min read
  * [![](../images/009.png)](https://towardsdatascience.com/geovec-word-embeddings-for-geosciences-ac1e1e854e19/)
## [GeoVec: word embeddings for geosciences](https://towardsdatascience.com/geovec-word-embeddings-for-geosciences-ac1e1e854e19/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Analogies, categorisation, relatedness and spatial interpolation of word embeddings.
[José Padarian](https://towardsdatascience.com/author/spadarian/)
August 20, 20198 min read
  * [![](../images/010.jpg)](https://towardsdatascience.com/tsfresh-on-large-data-samples-part-ii-4d6843155dfc/)
## [tsfresh on Large Data Samples - Part II](https://towardsdatascience.com/tsfresh-on-large-data-samples-part-ii-4d6843155dfc/)
[Data Science](https://towardsdatascience.com/category/data-science/)
If big is not big enough In the last post, we have explored how tsfresh...
[Nils Braun](https://towardsdatascience.com/author/nils-braun/)
December 7, 202015 min read
  * [![](../images/011.jpeg)](https://towardsdatascience.com/mlops-level-1-continuous-training-b2a633e27d47/)
## [MLOps Level 1: Continuous Training](https://towardsdatascience.com/mlops-level-1-continuous-training-b2a633e27d47/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
In MLOps level 1 the machine learning pipeline is automated. By doing so you achieve...
[Marco Susilo](https://towardsdatascience.com/author/marco-susilo/)
May 9, 20215 min read
  * [![](../images/012.jpg)](https://towardsdatascience.com/roialign-explained-d30f6843da3a/)
## [RoIAlign Explained](https://towardsdatascience.com/roialign-explained-d30f6843da3a/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
With Python Implementation
[Alexey Kravets](https://towardsdatascience.com/author/alexml0123/)
December 29, 202210 min read
  * [![](../images/013.jpg)](https://towardsdatascience.com/how-to-make-your-deep-learning-experiments-reproducible-and-your-code-extendible-7ef56767dddb/)
## [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/)
[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)
Lessons learned from building an open-source deep learning for time series framework
[Isaac Godfried](https://towardsdatascience.com/author/igodfried/)
September 25, 20206 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.
Subscribe 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/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
####  Recommended Articles 
Close
  * [ ![](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")
  * [ ![](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")
  * [ ![](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")
  * [ ![](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?")


