Skip to content
All guides

Capabilities & guides

Streaming & Function Calling

Implement low-latency SSE token streaming, reasoning trace parsing, and Function Calling workflows.

Updated 2026-11-26 · 2 min read

Why Enable Streaming in Production

For long completions or deep reasoning models such as DeepSeek R1 and Qwen3 235B-A22B Thinking, full generation can take tens of seconds. Setting stream: true delivers incremental tokens over Server-Sent Events (SSE):

  • Sub-second perceived responsiveness: Users see output start almost immediately instead of staring at a spinner.
  • Gateway timeout resilience: Continuous SSE frames prevent reverse proxies and load balancers from dropping long-running idle connections.

Consuming SSE Streams and Reasoning Traces

When iterating over streamed chunks, inspect chunk.choices[0].delta. Reasoning models may emit an additional reasoning trace attribute (commonly reasoning_content) before streaming final content tokens:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["API_KEY"],
    base_url=os.environ["API_BASE_URL"],
)

stream = client.chat.completions.create(
    model="deepseek-r1",
    messages=[
        {"role": "user", "content": "Design an idempotent message consumer workflow."}
    ],
    stream=True,
)

for chunk in stream:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    reasoning = getattr(delta, "reasoning_content", None)
    if reasoning:
        print(reasoning, end="", flush=True)
    if delta.content:
        print(delta.content, end="", flush=True)

Tip: In product UIs, render reasoning tokens inside a collapsible "Thought process" disclosure so the final answer remains clean and scannable.

End-to-End Function Calling Workflow

Function Calling lets a model request structured actions from your application (such as querying order status, checking live inventory, or invoking internal microservices) without granting the model direct network or database access:

  1. Declare tool schemas: Pass JSON Schema definitions in the tools parameter.
  2. Inspect tool_calls: When external data is needed, the model responds with finish_reason: "tool_calls" and structured arguments.
  3. Execute locally and return results: Validate authorization on your server, run the function, and send the output back in a role: "tool" message.
import json

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_service_health",
            "description": "Fetch live health status and error rate for an internal microservice",
            "parameters": {
                "type": "object",
                "properties": {
                    "service_name": {
                        "type": "string",
                        "description": "Canonical service name such as payment-gateway",
                    }
                },
                "required": ["service_name"],
            },
        },
    }
]

first = client.chat.completions.create(
    model="qwen3-coder-plus",
    messages=[{"role": "user", "content": "Check the current health of payment-gateway."}],
    tools=tools,
    tool_choice="auto",
)

msg = first.choices[0].message
if msg.tool_calls:
    call = msg.tool_calls[0]
    args = json.loads(call.function.arguments)
    tool_result = {"service": args["service_name"], "status": "healthy", "error_rate": "0.02%"}

    final = client.chat.completions.create(
        model="qwen3-coder-plus",
        messages=[
            {"role": "user", "content": "Check the current health of payment-gateway."},
            msg,
            {
                "role": "tool",
                "tool_call_id": call.id,
                "content": json.dumps(tool_result),
            },
        ],
        tools=tools,
    )
    print(final.choices[0].message.content)

Security and Reliability Checklist for Tool Use

  • Treat tool arguments as untrusted input: Always validate schemas, tenant scope, and user permissions on the server before executing queries or mutations.
  • Keep tool sets focused: Passing fewer than 15 well-differentiated tools per request yields higher selection accuracy than dumping dozens of overlapping endpoints. Pair with API Integration Guide for full client configuration details.