Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you provide an example of using asyncio with the DeepSeek R1 API


Can you provide an example of using asyncio with the DeepSeek R1 API


To use the DeepSeek R1 API with `asyncio` in Python, you can follow the example below. This code demonstrates how to asynchronously interact with the API to extract structured data from a message.

Example Code

python
import os
import asyncio
from openai import AsyncOpenAI
from pydantic import BaseModel
import instructor

# Initialize the DeepSeek client
client = instructor.from_openai(
    AsyncOpenAI(
        api_key=os.getenv("DEEPSEEK_API_KEY"),
        base_url="https://api.deepseek.com"
    )
)

# Define a Pydantic model for structured output
class User(BaseModel):
    name: str
    age: int

# Asynchronous function to extract user information
async def extract_user():
    user = await client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "user", "content": "Extract: Jason is 25 years old"},
        ],
        response_model=User,
    )
    return user

# Run the async function
if __name__ == "__main__":
    user = asyncio.run(extract_user())
    print(user)

Explanation of the Code

1. Imports: The required libraries are imported, including `os`, `asyncio`, and `instructor`, which is used to interact with the DeepSeek API.

2. Client Initialization: The `client` is initialized using `instructor.from_openai()` with the asynchronous OpenAI client, which requires an API key and base URL.

3. Data Model Definition: A Pydantic model named `User` is defined to structure the expected output, which includes fields for `name` and `age`.

4. Asynchronous Function: The `extract_user()` function sends a message to the DeepSeek API and awaits a response. It specifies the model to use and formats the input message appropriately.

5. Execution: The script runs the asynchronous function using `asyncio.run()`, capturing and printing the extracted user information.

This example showcases how to leverage asynchronous programming with the DeepSeek R1 API effectively, allowing for efficient handling of API calls without blocking execution.

Citations:
[1] https://python.useinstructor.com/integrations/deepseek/
[2] https://github.com/getasterisk/deepclaude
[3] https://thinhdanggroup.github.io/blog-on-chat-deepseek-r1-api/
[4] https://drlee.io/control-openai-model-behavior-with-seed-step-by-step-with-code-9bba4e137a63?gi=0c99fdfebc8d
[5] https://devblogs.microsoft.com/semantic-kernel/using-deepseek-models-in-semantic-kernel/
[6] https://deepinfra.com/deepseek-ai/DeepSeek-R1/api
[7] https://dev.to/sadiqsaleem/automating-dubai-centric-seo-with-ai-a-developers-guide-to-deepseek-r1-4ko
[8] https://www.reddit.com/r/LocalLLaMA/comments/1ibgoba/deepseekr1_how_can_we_use_it_via_api/