Let the model use a tool

Let the model use a tool

OpenAI LLM Interview Question

An agent is a loop, not a model. OpenAI assistants answer some questions outright and reach for a tool for the rest, and the code around the call is what decides which of the two just happened.

Write a function run_agent(question, tools, max_calls) that runs that loop. Start the conversation with the question, and read each reply off response.choices[0].message.content. A reply that starts with ANSWER: ends the loop, and the text after that prefix is what you return. A reply that starts with TOOL: names a tool: look that name up in the tools dictionary, add what it gives you to the conversation, and call again. Return None when the model names a tool the dictionary does not hold, and None when it has not answered within the number of calls allowed.

Asked of

  • AI Engineer
  • ML Engineer
  • Data Scientist

Example 1

Input

question = "What is the weather in Oslo?", tools = {"weather": "Oslo: sunny, 21C"}, max_calls = 4

The model says

call 1 -> "TOOL: weather"
call 2 -> "ANSWER: It's currently sunny in Oslo, at 21C."

Output

"It's currently sunny in Oslo, at 21C."

Example 2

Input

question = "What is two plus two?", tools = {}, max_calls = 4

The model says

call 1 -> "ANSWER: Two plus two is four."

Output

"Two plus two is four."

Example 3

Input

question = "What is the share price?", tools = {"weather": "Oslo: sunny, 21C"}, max_calls = 4

The model says

call 1 -> "TOOL: prices"

Output

None

Explanation

In the first example the model asks for the weather tool, is given what it returns, and answers on the second call. In the third it asks for a tool that was never offered, so the loop stops with nothing.

Submit also runs 3 hidden test cases that check edge cases.

Similar questions