Skip to main content
In the previous tutorial, we learned the basics for defining and executing functions using our chat completions API. In this tutorial, we will introduce more advanced use cases:
  • Streaming function calls
  • Passing multiple functions
  • Executing function calls in parallel
For low-latency contexts, streaming and parallel calls are especially helpful.

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 variable

Parsing 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

The handle_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 to execute_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 sleep and dream at the same time
  • Execute the returned tool calls in parallel
  • Provide the results back to the language model and get a final response
The output of the print statements in this script will look something like this. Notice that sleep was detected and executed first, but dream still returned results first.