- Streaming function calls
- Passing multiple functions
- Executing function calls in parallel
Defining our functions
First, we will define two functions we want to execute in parallel:sleep and dream.
Our goal is to use the dream function to make an API call to the Telnyx chat completions endpoint while we sleep.
We will also re-use the func_to_tool helped function we defined in the previous tutorial to easily convert between our Python functions and the JSON we need to pass to the tools field for our chat completions API.
Make sure you have set the
TELNYX_API_KEY environment variableParsing Streaming Tools + Executing Tasks in Parallel
Next we will define a few functions to help us parse and execute tasks in parallel.handle_tool_calls
Thehandle_tool_calls function will iterate over streamed chunks from the chat completions endpoint. The language model may invoke multiple tool calls to be executed in parallel and will differentiate them using the index attribute on the chunk.
As we progress through the stream, we will build our local copy of this list of function calls in the tool_calls list.
The first chunk of a new tool call will contain the name of the function. This enables you to give early feedback to users that a function will be executed. In this example, we simply print the name of the function when it is detected.
As we build the arguments from the streamed chunks, we attempt to parse what we have built as JSON. Once we have a valid JSON object, we create an async task to be scheduled for execution (if we have not already done so).
NB: Telnyx guarantees valid JSON is returned for tool calls, so you don’t have to worry about lengthy retries or fuzzy matching.
execute_tasks
This function executes the tasks from the previous function and returns the results as they are completed, enabling users to receive feedback as soon as possible.func_wrapper
This is a trivial helper function that exposes the tool call ID and function name toexecute_tasks
Putting it all together
With our helper functions defined, we are ready to stream and execute multiple function calls in parallel. In this code, we:- Ask the language model to
sleepanddreamat the same time - Execute the returned tool calls in parallel
- Provide the results back to the language model and get a final response
sleep was detected and executed first, but dream still returned results first.