SoFunction
Updated on 2025-04-05

Complete operation guide for calling DeepSeek API in Python

Introduction

This article will introduce in detail how to use Python to call the DeepSeek API to implement streaming conversations and save conversation records. Compared with the Go version, Python implementation is more concise and elegant, suitable for rapid development and prototype verification./i/vnCCfVaQ

1. Environmental preparation

1.1 Dependency installation

pip install requests

1.2 Project Structure

deepseek-project/
├──            # Main Program└──   # Dialogue record file

2. Complete code implementation

import os
import json
import time
import requests
from datetime import datetime

def save_to_file(file, content, is_question=False):
    """Save conversation content to file"""
    timestamp = ().strftime("%Y-%m-%d %H:%M:%S")
    if is_question:
        (f"\n[{timestamp}] Question:\n{content}\n\n[{timestamp}] Answer:\n")
    else:
        (content)

def main():
    #Configuration    url = "/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer YOUR_API_KEY"  # Replace with your API Key    }

    # Open a file to save the conversation    with open("", "a", encoding="utf-8") as file:
        while True:
            # Get user input            question = input("\nPlease enter your question (enter q quit): ").strip()
            
            if () == 'q':
                print("Program Exited")
                break

            # Save the question            save_to_file(file, question, is_question=True)

            # Prepare to request data            data = {
                "model": "deepseek-ai/DeepSeek-V3",
                "messages": [
                    {
                        "role": "user",
                        "content": question
                    }
                ],
                "stream": True,
                "max_tokens": 2048,
                "temperature": 0.7,
                "top_p": 0.7,
                "top_k": 50,
                "frequency_penalty": 0.5,
                "n": 1,
                "response_format": {
                    "type": "text"
                }
            }

            try:
                # Send a streaming request                response = (url, json=data, headers=headers, stream=True)
                response.raise_for_status()  # Check the response status
                # Handle streaming responses                for line in response.iter_lines():
                    if line:
                        line = ('utf-8')
                        if ('data: '):
                            if line == 'data: [DONE]':
                                continue
                            
                            try:
                                content = (line[6:])  # Remove the 'data: ' prefix                                if content['choices'][0]['delta'].get('content'):
                                    chunk = content['choices'][0]['delta']['content']
                                    print(chunk, end='', flush=True)
                                    (chunk)
                                    ()
                            except :
                                continue

                # Add a separator                print("\n----------------------------------------")
                ("\n----------------------------------------\n")
                ()

            except  as e:
                error_msg = f"Request error: {str(e)}\n"
                print(error_msg)
                (error_msg)
                ()

if __name__ == "__main__":
    main()

3. Detailed code explanation

3.1 Core functions

File recording function

save_to_fileFunctions are responsible for:

  • Generate timestamp
  • Format save questions and answers
  • Automatically refresh the file buffer

API Configuration

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"  # Replace with your API Key}

Streaming request processing

Program usagerequestsThe library's streaming processing function:

  • usestream=TrueEnable streaming
  • Process response data row by line
  • Show and save content in real time

3.2 Configuration parameter description

API Request Parameters:

  • model: The name of the model used
  • stream: Enable streaming output
  • max_tokens: Maximum output length (2048)
  • temperature: Control randomness (0.7)
  • top_ptop_k: Sampling parameters
  • frequency_penalty: Repeat penalty coefficient

4. Error handling

The code contains a complete error handling mechanism:

  • Check HTTP response status
  • Capture network exceptions
  • Handling JSON parsing errors
  • File operation error handling

5. How to use

5.1 Modify the configuration

Replace YOUR_API_KEY in your code for your actual API Key.

5.2 Run the program

python 

5.3 Interaction method

  • Enter a question for a conversation
  • Enter ‘q’ to exit the program
  • View Get conversation history

6. Performance optimization suggestions

  1. File Operation

    • Use the appropriate buffer size
    • Flush file buffer periodically
    • Close the file handle correctly
  2. Network request

    • Set appropriate timeout
    • Multiplexing connections using Session
    • Handle network exceptions
  3. Memory management

    • Release resources in a timely manner
    • Avoid a large amount of data accumulation
    • Processing streaming data using generator

Summarize

The Python version of DeepSeek API calls are simple and intuitive, suitable for rapid development and testing. Provides a complete conversation experience through streaming and file recording.

This is the article about this complete operation guide for Python calling DeepSeek API. For more related content on Python calling DeepSeek API, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!