OpenAI recommends using the Responses API for all new projects. See the guide.
- Install prerequisite packages and set up the environment
- Overview of how OpenAI’s tool calling feature works
- Use Exa within an OpenAI tool call
Get Started
1
Pre-requisites and installation
Install the:
openailibrary to perform OpenAI API calls and completionsexa_pylibrary to perform Exa searchrichlibrary to make the output more readable
Python
2
Set up the environment variables
Create an
.env file in the root of your project and set the EXA_API_KEY and OPENAI_API_KEY environment variable to your API keys respectively. Visit the OpenAI playground and the Exa dashboard to generate your API keys.Get your Exa API key
Shell
3
What is OpenAI tool calling?
OpenAI LLMs can call a function you have defined in your code, this is called tool calling. To do this you first need to describe the function you want to call to OpenAI’s LLM. You can do this by defining a description object of the format:When this description is sent to OpenAI’s LLM, it returns an object with a string, which is the function name defined in your code, and the arguments that the function takes. This does not execute or call functions on OpenAI’s side; it only returns the function name and arguments which you will have to parse and call yourself in your code.We will use this object to - in this case - call the
JSON
Python
exa_search function we define with the arguments provided.4
Use Exa Search as an OpenAI tool
First, we import and initialise the OpenAI and Exa libraries and load the stored API keys.Next, we define the function and the function schema so that OpenAI knows how to use it and what arguments our local function takes:Finally, we’ll define the primer We can now start writing the code needed to perform the LLM calls and the search. We’ll create the Next, we create a function to process the tool calls:Lastly, we’ll create a The implementation creates a loop that continually prompts the user for search queries, uses OpenAI’s tool calling feature to determine when to perform a search, and then uses the Exa search results to provide an informed response to the user’s query.We also use the rich library to provide a more visually appealing console interface, including coloured output and markdown rendering for the responses.
Python
Python
SYSTEM_MESSAGE, which explains to OpenAI what it is supposed to do:Python
exa_search function that will call Exa’s search_and_contents function with the query:Python
Python
main function to bring it all together, and handle the user input and interaction with OpenAI:Python
5
Running the code
Save the code in a file, e.g. You should see a prompt:Let’s test it out.That’s it, enjoy your search agent!
openai_search.py, and make sure the .env file containing the API keys we previously created is in the same directory as the script.Then run the script using the following command from your terminal:Bash
Bash
Bash
Full code
Python

