Guide · Code & SDK

DeepSeek API in Python: chat, streaming, JSON and functions

Python code examples for DeepSeek models: a first request, a conversation, streaming, JSON-schema output and function calling with the official openai SDK.

20 min time
Python 3.10+ stack
5 examples of code
Beginner level

DeepSeek models work through the official openai SDK for Python: only the API address, the key and the model name change. This guide collects five working examples, from a first request to function calling. You can copy each example into a file and run it, and every model from the DeepSeek API overview is called with the same code.

Install the SDK and save your key

You need Python 3.10 or newer and the openai package. Create an llmbox key in the cabinet, in the Keys section; the details are in the documentation page Quickstart. Keep the key in an environment variable, not in your code.

bash
pip install openai
export LLMBOX_API_KEY="sk-your-key"

Create a file with the client. The other examples import the client from it, so the address and key are set in one place.

client.py
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://llmbox.cc/v1",
    api_key=os.environ["LLMBOX_API_KEY"],
)

Choosing a model

The catalog has three main DeepSeek models. For a new project, start with DeepSeek V4.1 Flash: it is the newest DeepSeek model, accepts text and images as input and can answer by a JSON schema. Compare DeepSeek V4 Pro on tasks where the model needs to rely on its own knowledge. DeepSeek V4 Flash is handy where your prompts are already tuned on it.

The model is set by the model string in every request. To compare two models on your own data, just change this string; the key and the rest of the code stay the same.

First request

A request in the Chat Completions format is a list of messages. The system message sets the role and tone, and the user message contains the question. You can send the same request with curl, for example to check the key from a terminal.

from client import client

resp = client.chat.completions.create(
    model="deepseek/deepseek-v4.1-flash",
    messages=[
        {"role": "system", "content": "You are a developer assistant. Answer briefly."},
        {"role": "user", "content": "How is a list different from a tuple in Python?"},
    ],
)
print(resp.choices[0].message.content)
print(resp.usage)

The text of the answer is in choices[0].message.content, and the usage field shows how many tokens went to input and output. The same request, with its status, tokens and cost, appears in the Logs section of the cabinet.

The model doesn't remember earlier requests, so for a conversation you pass the whole history in every call. A simple terminal chat looks like this:

python
from client import client

history = [{"role": "system", "content": "You are a developer assistant. Answer briefly."}]

while True:
    question = input("> ")
    if not question:
        break
    history.append({"role": "user", "content": question})
    resp = client.chat.completions.create(
        model="deepseek/deepseek-v4.1-flash",
        messages=history,
    )
    answer = resp.choices[0].message.content
    history.append({"role": "assistant", "content": answer})
    print(answer)

Streaming

It is more convenient to show a long answer as it is generated. To do that, add stream=True: the SDK returns an iterator of chunks. The stream_options parameter with include_usage adds the token counts to the last chunk of the stream.

python
from client import client

stream = client.chat.completions.create(
    model="deepseek/deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Explain what a closure is in Python"}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print(f"\n\ninput: {chunk.usage.prompt_tokens}, output: {chunk.usage.completion_tokens}")

DeepSeek models have reasoning turned on by default, so there may be a pause before the first chunk of the answer. Set a generous client timeout, for example OpenAI(..., timeout=300). If the stream breaks with an error, repeat the whole request; the details are in the documentation page Streaming.

JSON-schema output

When a program reads the model's answer rather than a person, it helps to get it as JSON. The response_format parameter with the json_schema type sets a schema, and the model answers strictly by it. DeepSeek V4.1 Flash and DeepSeek V4 Pro have this mode.

python
import json
from client import client

schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "email": {"type": "string"},
        "topic": {"type": "string", "enum": ["payment", "delivery", "return", "other"]},
    },
    "required": ["name", "email", "topic"],
    "additionalProperties": False,
}

resp = client.chat.completions.create(
    model="deepseek/deepseek-v4.1-flash",
    messages=[
        {"role": "system", "content": "Extract the data from the customer's email."},
        {"role": "user", "content": "Hello, I'm Anna, anna@example.com. I was charged twice for my order."},
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {"name": "ticket", "schema": schema, "strict": True},
    },
)
ticket = json.loads(resp.choices[0].message.content)
print(ticket["topic"])

This is handy for triaging support requests, extracting details from emails and labeling reviews: you can write the result straight to a database or spreadsheet without parsing text by hand.

Function calling

Functions let the model request data or actions from your code. You describe a function in tools, the model decides when to call it and returns the name and arguments. Your code runs the function and sends the result back, and the model writes the answer for the user.

python
import json
from client import client

MODEL = "deepseek/deepseek-v4.1-flash"

def get_order_status(order_id: str) -> dict:
    # A query to your database could go here
    return {"order_id": order_id, "status": "handed to delivery"}

tools = [{
    "type": "function",
    "function": {
        "name": "get_order_status",
        "description": "Order status by its number",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "string", "description": "Order number"}},
            "required": ["order_id"],
        },
    },
}]

messages = [{"role": "user", "content": "Where is my order 10452?"}]
resp = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
msg = resp.choices[0].message

if msg.tool_calls:
    messages.append(msg)
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_order_status(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result, ensure_ascii=False),
        })
    resp = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)

print(resp.choices[0].message.content)

The model's response with a function call is added to the history in full, and the result of each function goes in a separate message with the tool role and the same tool_call_id. There can be several functions, and the model may call more than one in a single response; the loop over tool_calls handles that. Each such round needs a separate request, so an agent with functions uses more tokens than a single request without them.

Estimating usage

Cost is the sum of input and output tokens at the model's rates. Reasoning tokens count as output. According to DeepSeek's documentation, the reasoning depth for V4.1 Flash and V4 Pro is set with the levels low, high and max; in the request this is the reasoning_effort parameter. For bulk simple requests, low is a good fit: it can reduce the number of output tokens.

Enter the number of requests per day and the average request and answer size into the calculator. The usage data from your first test requests will give you a more accurate estimate.

Per month on DeepSeek V4.1 Flash ≈ $4.23 18M in · 9M out

Error handling

The openai SDK retries requests on 429 and 5xx responses by itself, and the number of attempts and the timeout are set when you create the client: OpenAI(..., max_retries=3, timeout=300). The errors listed below usually mean you need to fix the request:

  • 401 invalid_api_key: the key is missing or revoked, check the environment variable;
  • 404 model_not_found: a typo in the model identifier, compare it with the client.models.list() output;
  • 400 with a param field: the model didn't accept the parameter value, and the response names the parameter.

Every response has an x-request-id header. If a request behaves oddly, include this ID when you contact support so they can find that specific call. The full list of codes is in the documentation page Errors.

Questions

Do I need an account and key on the DeepSeek platform?

No. Requests use your llmbox key from the cabinet. The same key works with models from other vendors in the catalog.

How is this code different from regular OpenAI SDK code?

In only three values: base_url, the key and the model string with a DeepSeek model identifier from the catalog. The rest of the code, including streaming and functions, stays the same.

Which DeepSeek model answers strictly by a JSON schema?

DeepSeek V4.1 Flash and DeepSeek V4 Pro. For tasks that need schema-based output, choose one of them.

Can I send the model an image?

Yes, DeepSeek V4.1 Flash accepts images as input. Pass the image as an image_url part of the message, as a link or a data URL.

Is there an asynchronous version?

Yes, the same openai package has an AsyncOpenAI client with the same parameters. The calls are the same, just with await.

Published November 15, 2026

One key — every model

GPT, Gemini, DeepSeek, Qwen, video and audio. Pay as you go.

Create a key