pythonadvanced
Stream OpenAI Responses with Tool Calls
Handle streaming responses that include tool calls by accumulating delta chunks from the OpenAI API.
pythonPress ⌘/Ctrl + Shift + C to copy
from openai import OpenAI
import json
client = OpenAI()
tools = [{'type':'function','function':{'name':'search','description':'Search the web','parameters':{'type':'object','properties':{'query':{'type':'string'}},'required':['query']}}}]
stream = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role':'user','content':'Search for the latest Python news'}],
tools=tools,
stream=True,
)
collected_chunks = []
tool_call_args = ''
tool_call_name = ''
for chunk in stream:
delta = chunk.choices[0].delta
if delta.content:
print(delta.content, end='', flush=True)
if delta.tool_calls:
tc = delta.tool_calls[0]
if tc.function.name:
tool_call_name += tc.function.name
if tc.function.arguments:
tool_call_args += tc.function.arguments
if tool_call_name:
args = json.loads(tool_call_args)
print(f'\nTool call: {tool_call_name}({args})')
print('Simulated result: Latest Python news: Python 3.14 alpha released.')Use Cases
- streaming tool calls
- delta accumulation
- real-time agents
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
typescriptintermediate
Next.js AI Streaming Route Handler
Stream OpenAI responses from a Next.js App Router route handler using the Vercel AI SDK.
Best for: AI chatbot backend
#nextjs#openai
pythonintermediate
OpenAI Function Calling / Tool Use
Let GPT call your functions by defining tool schemas and handling responses.
Best for: AI agents
#ai#openai
pythonbeginner
Stream LLM Chat Responses
Stream OpenAI chat completions token-by-token for real-time UI updates.
Best for: Chat UIs
#ai#streaming