pythonadvanced
Parallel Tool Calls with OpenAI
Execute multiple tool calls in parallel when OpenAI returns multiple function calls in one response.
pythonPress ⌘/Ctrl + Shift + C to copy
import asyncio
import json
from openai import AsyncOpenAI
client = AsyncOpenAI()
tools = [
{'type':'function','function':{'name':'get_weather','description':'Get weather for a city','parameters':{'type':'object','properties':{'city':{'type':'string'}},'required':['city']}}},
{'type':'function','function':{'name':'get_time','description':'Get current time in timezone','parameters':{'type':'object','properties':{'timezone':{'type':'string'}},'required':['timezone']}}},
]
async def execute_tool(name: str, args: dict) -> str:
if name == 'get_weather':
return f'Weather in {args["city"]}: 22°C, sunny'
elif name == 'get_time':
return f'Time in {args["timezone"]}: 14:30'
return 'Unknown tool'
async def run_with_parallel_tools(question: str) -> str:
resp = await client.chat.completions.create(model='gpt-4o-mini', messages=[{'role':'user','content':question}], tools=tools, tool_choice='auto')
msg = resp.choices[0].message
if not msg.tool_calls:
return msg.content
results = await asyncio.gather(*[execute_tool(tc.function.name, json.loads(tc.function.arguments)) for tc in msg.tool_calls])
tool_msgs = [{'role':'tool','tool_call_id':tc.id,'content':r} for tc, r in zip(msg.tool_calls, results)]
final = await client.chat.completions.create(model='gpt-4o-mini', messages=[{'role':'user','content':question}, msg, *tool_msgs])
return final.choices[0].message.content
print(asyncio.run(run_with_parallel_tools('What is the weather in Paris and the time in UTC?')))Use Cases
- parallel function calls
- multi-tool AI
- efficient agents
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Async OpenAI Client in Python
Use the AsyncOpenAI client with asyncio to run concurrent chat completions without blocking.
Best for: concurrent LLM calls
#openai#async
pythonintermediate
asyncio.gather Concurrent Tasks
Run multiple async operations concurrently with asyncio.gather and proper error handling.
Best for: Parallel API calls
#asyncio#concurrency
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming
typescriptbeginner
Generate Text Embeddings with OpenAI
Create vector embeddings for semantic search and similarity matching using text-embedding-3-small.
Best for: semantic search
#openai#embeddings