### First Request: Few-shot Learning Example Source: https://deepseek.apifox.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E7%A1%AC%E7%9B%98%E7%BC%93%E5%AD%98-5903990m0 An example demonstrating Few-shot learning in the first request. It includes multiple question-answer pairs to guide the model, forming a substantial prefix for caching. ```json messages: [ {"role": "system", "content": "你是一位历史学专家,用户将提供一系列问题,你的回答应当简明扼要,并以`Answer:`开头"}, {"role": "user", "content": "请问秦始皇统一六国是在哪一年?"}, {"role": "assistant", "content": "Answer:公元前221年"}, {"role": "user", "content": "请问汉朝的建立者是谁?"}, {"role": "assistant", "content": "Answer:刘邦"}, {"role": "user", "content": "请问唐朝最后一任皇帝是谁"}, {"role": "assistant", "content": "Answer:李柷"}, {"role": "user", "content": "请问明朝的开国皇帝是谁?"}, {"role": "assistant", "content": "Answer:朱元璋"}, {"role": "user", "content": "请问清朝的开国皇帝是谁?"} ] ``` -------------------------------- ### Python Example for JSON Output Source: https://deepseek.apifox.cn/json-output-5903985m0 Demonstrates how to use the OpenAI client library with DeepSeek to get a JSON-formatted response. Ensure your system or user prompt includes the word 'json' and a sample of the desired output format. Adjust max_tokens to prevent truncation. ```python import json from openai import OpenAI client = OpenAI( api_key="", base_url="https://api.deepseek.com", ) system_prompt = """ The user will provide some exam text. Please parse the "question" and "answer" and output them in JSON format. EXAMPLE INPUT: Which is the highest mountain in the world? Mount Everest. EXAMPLE JSON OUTPUT: { "question": "Which is the highest mountain in the world?", "answer": "Mount Everest" } """ user_prompt = "Which is the longest river in the world? The Nile River." messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}] response = client.chat.completions.create( model="deepseek-chat", messages=messages, response_format={ 'type': 'json_object' } ) print(json.loads(response.choices[0].message.content)) ``` -------------------------------- ### Python Example for JSON Output Source: https://deepseek.apifox.cn/json-output-5903985m0 This snippet demonstrates how to configure and use the DeepSeek API to get JSON output. It includes setting the response format, crafting system and user prompts with JSON examples, and parsing the response. ```APIDOC ## Using JSON Output with DeepSeek API ### Description This example shows how to enable and utilize the JSON Output feature for the DeepSeek API using Python. It ensures that the model's response is a valid JSON string by setting the `response_format` parameter and providing clear instructions and examples within the prompts. ### Method POST ### Endpoint `/v1/chat/completions` (Assumed based on `openai` library usage) ### Parameters #### Request Body - **model** (string) - Required - The model to use (e.g., "deepseek-chat"). - **messages** (array) - Required - A list of message objects representing the conversation. - **role** (string) - Required - The role of the message sender ('system' or 'user'). - **content** (string) - Required - The content of the message. - **response_format** (object) - Required - Specifies the desired output format. - **type** (string) - Required - Must be set to 'json_object' to enable JSON output. - **max_tokens** (integer) - Optional - Maximum number of tokens to generate. Recommended to set appropriately to avoid truncation. ### Request Example ```python import json from openai import OpenAI client = OpenAI( api_key="", base_url="https://api.deepseek.com", ) system_prompt = """ The user will provide some exam text. Please parse the "question" and "answer" and output them in JSON format. EXAMPLE INPUT: Which is the highest mountain in the world? Mount Everest. EXAMPLE JSON OUTPUT: { "question": "Which is the highest mountain in the world?", "answer": "Mount Everest" } """ user_prompt = "Which is the longest river in the world? The Nile River." messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}] response = client.chat.completions.create( model="deepseek-chat", messages=messages, response_format={ 'type': 'json_object' } ) print(json.loads(response.choices[0].message.content)) ``` ### Response #### Success Response (200) - **choices** (array) - Contains the model's response. - **message** (object) - The message object from the model. - **content** (string) - The JSON formatted string output by the model. #### Response Example ```json { "question": "Which is the longest river in the world?", "answer": "The Nile River" } ``` ### Notes - Ensure the `system` or `user` prompt contains the word `json` and provides a clear JSON example. - Be aware that API might return an empty `content` in some cases. Modifying the prompt can help mitigate this. ``` -------------------------------- ### Second Request: Few-shot Learning Example Source: https://deepseek.apifox.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E7%A1%AC%E7%9B%98%E7%BC%93%E5%AD%98-5903990m0 The second request in a Few-shot learning scenario. It shares a significant prefix with the first request, allowing for substantial cache hits on the provided examples. ```json messages: [ {"role": "system", "content": "你是一位历史学专家,用户将提供一系列问题,你的回答应当简明扼要,并以`Answer:`开头"}, {"role": "user", "content": "请问秦始皇统一六国是在哪一年?"}, {"role": "assistant", "content": "Answer:公元前221年"}, {"role": "user", "content": "请问汉朝的建立者是谁?"}, {"role": "assistant", "content": "Answer:刘邦"}, {"role": "user", "content": "请问唐朝最后一任皇帝是谁"}, {"role": "assistant", "content": "Answer:李柷"}, {"role": "user", "content": "请问明朝的开国皇帝是谁?"}, {"role": "assistant", "content": "Answer:朱元璋"}, {"role": "user", "content": "请问商朝是什么时候灭亡的"} ] ``` -------------------------------- ### Install OpenAI SDK Source: https://deepseek.apifox.cn/%E6%8E%A8%E7%90%86%E6%A8%A1%E5%9E%8B-deepseek-reasoner-5903960m0 Upgrade the OpenAI SDK to the latest version to support new parameters for the DeepSeek Reasoner model. ```bash pip3 install -U openai ``` -------------------------------- ### 查询余额 OpenAPI 规范 Source: https://deepseek.apifox.cn/%E6%9F%A5%E8%AF%A2%E4%BD%99%E9%A2%9D-257846763e0 OpenAPI 3.0.1 规范,定义了查询用户余额的 GET 请求。包含响应体结构和示例。 ```yaml openapi: 3.0.1 info: title: '' description: '' version: 1.0.0 paths: /user/balance: get: summary: 查询余额 deprecated: false description: '' tags: - API 文档 parameters: [] responses: '200': description: '' content: application/json: schema: type: object properties: is_available: type: boolean balance_infos: type: array items: type: object properties: currency: type: string total_balance: type: string granted_balance: type: string topped_up_balance: type: string x-apifox-orders: - currency - total_balance - granted_balance - topped_up_balance required: - is_available - balance_infos x-apifox-orders: - is_available - balance_infos example: is_available: true balance_infos: - currency: CNY total_balance: '110.00' granted_balance: '10.00' topped_up_balance: '100.00' headers: {} x-apifox-name: 成功 security: [] x-apifox-folder: API 文档 x-apifox-status: released x-run-in-apifox: https://app.apifox.com/web/project/5813541/apis/api-257846763-run components: schemas: {} securitySchemes: bearer: type: bearer scheme: bearer servers: - url: https://api.deepseek.com description: 正式环境 security: - bearer: [] x-apifox: schemeGroups: - id: DOp0WuT-c0vg6PnvNSIS- schemeIds: - bearer required: true use: id: DOp0WuT-c0vg6PnvNSIS- ``` -------------------------------- ### Node.js Request to DeepSeek Chat API Source: https://deepseek.apifox.cn/%E9%A6%96%E6%AC%A1%E8%B0%83%E7%94%A8-api-5903654m0 This Node.js example shows how to call the DeepSeek chat API using the OpenAI SDK. Install the SDK with 'npm install openai'. Remember to substitute '' with your key. ```javascript // Please install OpenAI SDK first: `npm install openai` import OpenAI from "openai"; const openai = new OpenAI({ baseURL: 'https://api.deepseek.com', apiKey: '' }); async function main() { const completion = await openai.chat.completions.create({ messages: [{ role: "system", content: "You are a helpful assistant." }], model: "deepseek-chat", }); console.log(completion.choices[0].message.content); } main(); ``` -------------------------------- ### Python FIM Completion Example Source: https://deepseek.apifox.cn/fim-%E8%A1%A5%E5%85%A8beta-5903983m0 This Python snippet demonstrates how to use the Deepseek API for FIM completion. Ensure you set the correct base_url to 'https://api.deepseek.com/beta' to enable beta features. Replace '' with your actual API key. ```python from openai import OpenAI client = OpenAI( api_key="", base_url="https://api.deepseek.com/beta", ) response = client.completions.create( model="deepseek-chat", prompt="def fib(a):", suffix=" return fib(a-1) + fib(a-2)", max_tokens=128 ) print(response.choices[0].text) ``` -------------------------------- ### Streaming Chat Completion Response Example Source: https://deepseek.apifox.cn/%E5%AF%B9%E8%AF%9D%E8%A1%A5%E5%85%A8-257835379e0 This example demonstrates the format of a streaming chat completion response. It shows a series of 'chat completion chunk' objects, each containing partial content and metadata, streamed over `text/event-stream`. ```json data: { "id": "1f633d8bfc032625086f14113c411638", "choices": [ { "index": 0, "delta": { "content": "", "role": "assistant" }, "finish_reason": null, "logprobs": null } ], "created": 1718345013, "model": "deepseek-chat", "system_fingerprint": "fp_a49d71b8a1", "object": "chat.completion.chunk", "usage": null } data: { "choices": [ { "delta": { "content": "Hello", "role": "assistant" }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1718345013, "id": "1f633d8bfc032625086f14113c411638", "model": "deepseek-chat", "object": "chat.completion.chunk", "system_fingerprint": "fp_a49d71b8a1" } data: { "choices": [ { "delta": { "content": "!", "role": "assistant" }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1718345013, "id": "1f633d8bfc032625086f14113c411638", "model": "deepseek-chat", "object": "chat.completion.chunk", "system_fingerprint": "fp_a49d71b8a1" } data: { "choices": [ { "delta": { "content": " How", "role": "assistant" }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1718345013, "id": "1f633d8bfc032625086f14113c411638", "model": "deepseek-chat", "object": "chat.completion.chunk", "system_fingerprint": "fp_a49d71b8a1" } data: { "choices": [ { "delta": { "content": " can", "role": "assistant" }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1718345013, "id": "1f633d8bfc032625086f14113c411638", "model": "deepseek-chat", "object": "chat.completion.chunk", "system_fingerprint": "fp_a49d71b8a1" } data: { "choices": [ { "delta": { "content": " I", "role": "assistant" }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1718345013, "id": "1f633d8bfc032625086f14113c411638", "model": "deepseek-chat", "object": "chat.completion.chunk", "system_fingerprint": "fp_a49d71b8a1" } data: { "choices": [ { "delta": { "content": " assist", "role": "assistant" }, "finish_reason": null, "index": 0, "logprobs": null } ], "created": 1718345013, "id": "1f633d8bfc032625086f14113c411638", "model": "deepseek-chat", "object": "chat.completion.chunk", "system_fingerprint": "fp_a49d71b8a1" } data: { "choices": [ { "delta": { "content": "", "role": "assistant" }, "finish_reason": "stop", "index": 0, "logprobs": null } ], "created": 1718345013, "id": "1f633d8bfc032625086f14113c411638", "model": "deepseek-chat", "object": "chat.completion.chunk", "system_fingerprint": "fp_a49d71b8a1" } ``` -------------------------------- ### Chat Completion Response Example Source: https://deepseek.apifox.cn/%E5%AF%B9%E8%AF%9D%E8%A1%A5%E5%85%A8-257835379e0 This example shows the structure of a typical non-streaming chat completion response. It includes metadata like ID, creation timestamp, model used, and usage statistics, along with the assistant's message. ```json { "id": "e137bb42-7580-4cb8-88ba-825209cf966b", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I assist you today? 😊" }, "logprobs": null, "finish_reason": "stop" } ], "created": 1739112811, "model": "deepseek-chat", "system_fingerprint": "fp_3a5790e1b4", "object": "chat.completion", "usage": { "prompt_tokens": 9, "completion_tokens": 11, "total_tokens": 20, "prompt_tokens_details": { "cached_tokens": 0 }, "prompt_cache_hit_tokens": 0, "prompt_cache_miss_tokens": 9 } } ``` -------------------------------- ### Python Example: Function Calling for Weather Information Source: https://deepseek.apifox.cn/function-calling-5903987m0 This Python snippet demonstrates a complete workflow for using Function Calling to retrieve weather information. It requires the 'openai' library and a Deepseek API key. The 'get_weather' function is a placeholder for the actual tool implementation. ```python from openai import OpenAI def send_messages(messages): response = client.chat.completions.create( model="deepseek-chat", messages=messages, tools=tools ) return response.choices[0].message client = OpenAI( api_key="", base_url="https://api.deepseek.com", ) tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get weather of an location, the user shoud supply a location first", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", } }, "required": ["location"] }, } }, ] messages = [{"role": "user", "content": "How's the weather in Hangzhou?"}] message = send_messages(messages) print(f"User>\t {messages[0]['content']}") tool = message.tool_calls[0] messages.append(message) messages.append({"role": "tool", "tool_call_id": tool.id, "content": "24℃"}) message = send_messages(messages) print(f"Model>\t {message.content}") ``` -------------------------------- ### Use Deepseek API for Code Explanation Source: https://deepseek.apifox.cn/%E4%BB%A3%E7%A0%81%E8%A7%A3%E9%87%8A-5904041m0 This Python script demonstrates how to use the Deepseek API to get an explanation for a given code snippet. Replace '' with your actual API key. The 'deepseek-chat' model is used for generating the explanation. ```python from openai import OpenAI client = OpenAI( base_url="https://api.deepseek.com/", api_key="" ) completion = client.chat.completions.create( model="deepseek-chat", messages=[ { "role": "user", "content": "请解释下面这段代码的逻辑,并说明完成了什么功能:\n```\n// weight数组的大小 就是物品个数\nfor(int i = 1; i < weight.size(); i++) { // 遍历物品\n for(int j = 0; j <= bagweight; j++) { // 遍历背包容量\n if (j < weight[i]) dp[i][j] = dp[i - 1][j];\n else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);\n }\n}\n```" } ] ) print(completion.choices[0].message.content) ``` -------------------------------- ### Chat Completions API - Streaming Source: https://deepseek.apifox.cn/%E6%8E%A8%E7%90%86%E6%A8%A1%E5%9E%8B-deepseek-reasoner-5903960m0 This example demonstrates how to use the DeepSeek Reasoner model for chat completions with streaming enabled. It shows how to process chunks of the response to reconstruct the reasoning content and the final answer, and how to manage context for multi-round conversations. ```APIDOC ## POST /v1/chat/completions (Streaming) ### Description Generates a chat completion response using the deepseek-reasoner model with streaming enabled. The response is delivered in chunks, allowing for real-time display of the reasoning content and the final answer. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use, e.g., "deepseek-reasoner". - **messages** (array) - Required - A list of message objects representing the conversation history. - **role** (string) - Required - The role of the author of the message (e.g., "user", "assistant"). - **content** (string) - Required - The content of the message. - **stream** (boolean) - Required - Set to `true` to enable streaming. - **max_tokens** (integer) - Optional - The maximum length of the final answer (excluding reasoning content). Defaults to 4K, maximum 8K. ### Request Example ```json { "model": "deepseek-reasoner", "messages": [ {"role": "user", "content": "9.11 and 9.8, which is greater?"} ], "stream": true } ``` ### Response #### Success Response (200) - **choices** (array) - Contains the completion choices. - **delta** (object) - Contains the incremental update. - **reasoning_content** (string) - The incremental reasoning content. - **content** (string) - The incremental final answer content. #### Response Example (Chunk 1) ```json { "choices": [ { "delta": { "reasoning_content": "To compare 9.11 and 9.8, we look at the digits after the decimal point." } } ] } ``` #### Response Example (Chunk 2) ```json { "choices": [ { "delta": { "reasoning_content": "The first decimal place in 9.11 is 1, and in 9.8 it is 8." } } ] } ``` #### Response Example (Final Chunk) ```json { "choices": [ { "delta": { "content": " Therefore, 9.11 is greater than 9.8." } } ] } ``` ``` -------------------------------- ### Python Chat Prefix Completion Example Source: https://deepseek.apifox.cn/%E5%AF%B9%E8%AF%9D%E5%89%8D%E7%BC%80%E7%BB%AD%E5%86%99beta-5903980m0 Use this snippet to enable Beta features for chat prefix completion. Ensure the last message in `messages` has `role` set to `assistant` and `prefix` set to `True`. Configure `base_url` to `https://api.deepseek.com/beta`. ```python from openai import OpenAI client = OpenAI( api_key="", base_url="https://api.deepseek.com/beta", ) messages = [ {"role": "user", "content": "Please write quick sort code"}, {"role": "assistant", "content": "```python\n", "prefix": True} ] response = client.chat.completions.create( model="deepseek-chat", messages=messages, stop=["```"], ) print(response.choices[0].message.content) ``` -------------------------------- ### Chat Completions API - Non-Streaming Source: https://deepseek.apifox.cn/%E6%8E%A8%E7%90%86%E6%A8%A1%E5%9E%8B-deepseek-reasoner-5903960m0 This example demonstrates how to use the DeepSeek Reasoner model for chat completions without streaming. It shows how to retrieve both the reasoning content and the final answer, and how to manage context for multi-round conversations. ```APIDOC ## POST /v1/chat/completions ### Description Generates a chat completion response using the deepseek-reasoner model, providing a chain-of-thought output before the final answer. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use, e.g., "deepseek-reasoner". - **messages** (array) - Required - A list of message objects representing the conversation history. - **role** (string) - Required - The role of the author of the message (e.g., "user", "assistant"). - **content** (string) - Required - The content of the message. - **max_tokens** (integer) - Optional - The maximum length of the final answer (excluding reasoning content). Defaults to 4K, maximum 8K. ### Request Example ```json { "model": "deepseek-reasoner", "messages": [ {"role": "user", "content": "9.11 and 9.8, which is greater?"} ] } ``` ### Response #### Success Response (200) - **choices** (array) - Contains the completion choices. - **message** (object) - The message object. - **reasoning_content** (string) - The chain-of-thought reasoning content. - **content** (string) - The final answer content. #### Response Example ```json { "choices": [ { "message": { "reasoning_content": "The user is asking to compare two numbers: 9.11 and 9.8. To determine which is greater, we compare them directly. 9.11 has a '1' in the tenths place, while 9.8 has an '8'. Since 1 is greater than 8 in the tenths place, 9.11 is greater than 9.8.", "content": "9.11 is greater than 9.8." } } ] } ``` ``` -------------------------------- ### Python Request to DeepSeek Chat API Source: https://deepseek.apifox.cn/%E9%A6%96%E6%AC%A1%E8%B0%83%E7%94%A8-api-5903654m0 This Python script demonstrates how to use the OpenAI SDK to interact with the DeepSeek chat API. Install the SDK using 'pip3 install openai'. Replace '' with your key. ```python # Please install OpenAI SDK first: `pip3 install openai` from openai import OpenAI client = OpenAI(api_key="", base_url="https://api.deepseek.com") response = client.chat.completions.create( model="deepseek-chat", messages=[ {"role": "system", "content": "You are a helpful assistant"}, {"role": "user", "content": "Hello"}, ], stream=False ) print(response.choices[0].message.content) ``` -------------------------------- ### Python Example for Multi-turn Conversation Source: https://deepseek.apifox.cn/%E5%A4%9A%E8%BD%AE%E5%AF%B9%E8%AF%9D-5903977m0 This Python code demonstrates how to manage message history for multi-turn conversations using the DeepSeek API. It shows appending both user queries and assistant responses to the messages list before each API call. ```python from openai import OpenAI client = OpenAI(api_key="", base_url="https://api.deepseek.com") # Round 1 messages = [{"role": "user", "content": "What's the highest mountain in the world?"}] response = client.chat.completions.create( model="deepseek-chat", messages=messages ) messages.append(response.choices[0].message) print(f"Messages Round 1: {messages}") # Round 2 messages.append({"role": "user", "content": "What is the second?"}) response = client.chat.completions.create( model="deepseek-chat", messages=messages ) messages.append(response.choices[0].message) print(f"Messages Round 2: {messages}") ``` -------------------------------- ### 生成 Linux 助手提示词 Source: https://deepseek.apifox.cn/%E6%A8%A1%E5%9E%8B%E6%8F%90%E7%A4%BA%E8%AF%8D%E7%94%9F%E6%88%90-5904110m0 使用 OpenAI API 的 Python 客户端生成一个针对 Linux 助手的提示词。需要替换 "" 为您的实际 API 密钥。 ```python from openai import OpenAI client = OpenAI( base_url="https://api.deepseek.com/", api_key="" ) completion = client.chat.completions.create( model="deepseek-chat", messages=[ { "role": "system", "content": "你是一位大模型提示词生成专家,请根据用户的需求编写一个智能助手的提示词,来指导大模型进行内容生成,要求:\n1. 以 Markdown 格式输出\n2. 贴合用户需求,描述智能助手的定位、能力、知识储备\n3. 提示词应清晰、精确、易于理解,在保持质量的同时,尽可能简洁\n4. 只输出提示词,不要输出多余解释" }, { "role": "user", "content": "请帮我生成一个“Linux 助手”的提示词" } ] ) print(completion.choices[0].message.content) ``` -------------------------------- ### Chat Completion with Deepseek API Source: https://deepseek.apifox.cn/%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90-5904047m0 This Python snippet shows how to perform a chat completion using the Deepseek API. Ensure you have the 'openai' library installed and replace '' with your actual API key. ```python from openai import OpenAI client = OpenAI( base_url="https://api.deepseek.com/", api_key="" ) completion = client.chat.completions.create( model="deepseek-chat", messages=[ { "role": "user", "content": "请帮我用 HTML 生成一个五子棋游戏,所有代码都保存在一个 HTML 中。" } ] ) print(completion.choices[0].message.content) ``` -------------------------------- ### List Models Source: https://deepseek.apifox.cn/llms.txt Lists available models and their basic information. Refer to the pricing page for the current list of supported models. ```APIDOC ## GET /models ### Description Lists available models and their basic information. Refer to the pricing page for the current list of supported models. ### Method GET ### Endpoint /models ### Response #### Success Response (200) - **data** (array) - A list of available models. - **id** (string) - The model identifier. - **object** (string) - Type of object, e.g., `model`. - **created** (integer) - Unix timestamp of when the model was created. - **owned_by** (string) - The entity that owns the model. #### Response Example ```json { "data": [ { "id": "deepseek-coder", "object": "model", "created": 1677652288, "owned_by": "deepseek" }, { "id": "deepseek-chat", "object": "model", "created": 1677652288, "owned_by": "deepseek" } ] } ``` ``` -------------------------------- ### Access Reasoning Content (Non-Streaming) Source: https://deepseek.apifox.cn/%E6%8E%A8%E7%90%86%E6%A8%A1%E5%9E%8B-deepseek-reasoner-5903960m0 Example of accessing reasoning content and final answer in a non-streaming API call. For subsequent rounds, append the assistant's content to the messages and remove the reasoning_content field from previous responses. ```python from openai import OpenAI client = OpenAI(api_key="", base_url="https://api.deepseek.com") # Round 1 messages = [{"role": "user", "content": "9.11 and 9.8, which is greater?"}] response = client.chat.completions.create( model="deepseek-reasoner", messages=messages ) reasoning_content = response.choices[0].message.reasoning_content content = response.choices[0].message.content # Round 2 messages.append({'role': 'assistant', 'content': content}) messages.append({'role': 'user', 'content': "How many Rs are there in the word 'strawberry'?"}) response = client.chat.completions.create( model="deepseek-reasoner", messages=messages ) # ... ``` -------------------------------- ### Python调用DeepSeek API进行角色扮演对话 Source: https://deepseek.apifox.cn/%E8%A7%92%E8%89%B2%E6%89%AE%E6%BC%94%E6%83%85%E6%99%AF%E7%BB%AD%E5%86%99-5904068m0 使用Python SDK调用DeepSeek API,模拟诸葛亮和刘备在地府的对话。需要替换""为您的实际API密钥。 ```python from openai import OpenAI client = OpenAI( base_url="https://api.deepseek.com/", api_key="" ) completion = client.chat.completions.create( model="deepseek-chat", messages=[ { "role": "user", "content": "假设诸葛亮死后在地府遇到了刘备,请模拟两个人展开一段对话。" } ] ) print(completion.choices[0].message.content) ``` -------------------------------- ### Explain 0/1 Knapsack DP Logic Source: https://deepseek.apifox.cn/%E4%BB%A3%E7%A0%81%E8%A7%A3%E9%87%8A-5904041m0 This C++ code implements the 0/1 knapsack problem using dynamic programming. It calculates the maximum value that can be obtained within a given backpack capacity by selecting items with specific weights and values. Ensure 'weight', 'value', and 'bagweight' are properly defined before execution. ```cpp // weight数组的大小 就是物品个数 for(int i = 1; i < weight.size(); i++) { // 遍历物品 for(int j = 0; j <= bagweight; j++) { // 遍历背包容量 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); } } ``` -------------------------------- ### Access Reasoning Content (Streaming) Source: https://deepseek.apifox.cn/%E6%8E%A8%E7%90%86%E6%A8%A1%E5%9E%8B-deepseek-reasoner-5903960m0 Example of accessing reasoning content and final answer in a streaming API call. For subsequent rounds, append the assistant's content to the messages and remove the reasoning_content field from previous responses. ```python from openai import OpenAI client = OpenAI(api_key="", base_url="https://api.deepseek.com") # Round 1 messages = [{"role": "user", "content": "9.11 and 9.8, which is greater?"}] response = client.chat.completions.create( model="deepseek-reasoner", messages=messages, stream=True ) reasoning_content = "" content = "" for chunk in response: if chunk.choices[0].delta.reasoning_content: reasoning_content += chunk.choices[0].delta.reasoning_content else: content += chunk.choices[0].delta.content # Round 2 messages.append({"role": "assistant", "content": content}) messages.append({'role': 'user', 'content': "How many Rs are there in the word 'strawberry'?"}) response = client.chat.completions.create( model="deepseek-reasoner", messages=messages, stream=True ) # ... ``` -------------------------------- ### 对话补全 Source: https://deepseek.apifox.cn/%E5%AF%B9%E8%AF%9D%E8%A1%A5%E5%85%A8-257835379e0 根据输入的上下文,来让模型补全对话内容。 ```APIDOC ## POST /chat/completions ### Description 根据输入的上下文,来让模型补全对话内容。 ### Method POST ### Endpoint /chat/completions ### Parameters #### Request Body - **messages** (array) - Required - 对话的消息列表 - Each item in the array can be one of the following: - **System message**: - **content** (string) - Required - system 消息的内容 - **role** (string) - Required - 该消息的发起角色,其值为 `system` - **name** (string) - Optional - 可以选填的参与者的名称,为模型提供信息以区分相同角色的参与者 - **User message**: - **content** (string) - Required - user 消息的内容 - **role** (string) - Required - 该消息的发起角色,其值为 `user` - **name** (string) - Optional - 可以选填的参与者的名称,为模型提供信息以区分相同角色的参与者 - **Assistant message**: - **content** (string) - Required - assistant 消息的内容 - **role** (string) - Required - 该消息的发起角色,其值为 `assistant` - **name** (string) - Optional - 可以选填的参与者的名称,为模型提供信息以区分相同角色的参与者。 - **Tool message**: - **role** (string) - Required - 该消息的发起角色,其值为 `tool` - **content** (string) - Required - tool 消息的内容 - **tool_call_id** (string) - Required - 此消息所响应的 tool call 的 ID - **model** (string) - Required - 使用的 AI 模型. Enum: `deepseek-chat`, `deepseek-reasoner` - **frequency_penalty** (number) - Optional - **max_tokens** (integer) - Optional - **presence_penalty** (number) - Optional - **response_format** (object) - Optional - **type** (string) - Optional ### Request Example { "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Who won the world series in 2020?" } ], "model": "deepseek-chat" } ### Response #### Success Response (200) - **content** (string) - The content of the assistant's reply. - **role** (string) - The role of the assistant. - **stop_reason** (string) - The reason the assistant stopped generating tokens. - **usage** (object) - Usage statistics for the request. - **prompt_tokens** (integer) - Number of tokens in the prompt. - **completion_tokens** (integer) - Number of tokens in the completion. - **total_tokens** (integer) - Total number of tokens. #### Response Example { "choices": [ { "message": { "role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 30, "completion_tokens": 15, "total_tokens": 45 } } ``` -------------------------------- ### List Models Source: https://deepseek.apifox.cn/%E5%88%97%E5%87%BA%E6%A8%A1%E5%9E%8B-257840922e0 Retrieves a list of available models and their basic information. Refer to the [Models & Pricing](https://api-docs.deepseek.com/zh-cn/quick_start/pricing) page for the current list of supported models. ```APIDOC ## GET /models ### Description Lists available models and provides basic information about each model. ### Method GET ### Endpoint /models ### Parameters ### Request Example ### Response #### Success Response (200) - **object** (string) - Indicates the type of the returned object, expected to be 'list'. - **data** (array) - An array of model objects. - **id** (string) - The unique identifier for the model. - **object** (string) - The type of the object, expected to be 'model'. - **owned_by** (string) - The owner of the model. #### Response Example ```json { "object": "list", "data": [ { "id": "deepseek-chat", "object": "model", "owned_by": "deepseek" }, { "id": "deepseek-reasoner", "object": "model", "owned_by": "deepseek" } ] } ``` ``` -------------------------------- ### FIM Completion (Beta) Source: https://deepseek.apifox.cn/fim-%E8%A1%A5%E5%85%A8beta-257837815e0 The FIM (Fill-In-the-Middle) Completion API allows users to generate text by providing a prompt and optionally a suffix. Users need to set the base_url to "https://api.deepseek.com/beta" to use this feature. ```APIDOC ## POST /beta/completions ### Description FIM(Fill-In-the-Middle)补全 API。 用户需要设置 base_url="https://api.deepseek.com/beta" 来使用此功能。 ### Method POST ### Endpoint /beta/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use for completion. - **prompt** (string) - Required - The prompt to generate text from. - **echo** (boolean) - Optional - Whether to echo the prompt in the response. - **frequency_penalty** (number) - Optional - Controls the repetition of generated tokens based on their frequency. - **logprobs** (integer) - Optional - The number of log probabilities to return. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate. - **presence_penalty** (number) - Optional - Controls the repetition of generated tokens based on their presence. - **stop** (null) - Optional - Sequences where the API will stop generating further tokens. - **stream** (boolean) - Optional - Whether to stream the response. - **stream_options** (null) - Optional - Options for streaming. - **suffix** (string) - Optional - The suffix to append to the prompt. - **temperature** (number) - Optional - Controls the randomness of the generated text. - **top_p** (number) - Optional - Controls the diversity of the generated text via nucleus sampling. ### Request Example ```json { "model": "deepseek-chat", "prompt": "Once upon a time, ", "echo": false, "frequency_penalty": 0, "logprobs": 0, "max_tokens": 1024, "presence_penalty": 0, "stop": null, "stream": false, "stream_options": null, "suffix": null, "temperature": 1, "top_p": 1 } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the completion. - **choices** (array) - A list of completion choices. - **finish_reason** (string) - The reason the completion finished. - **index** (integer) - The index of the choice. - **logprobs** (object) - Log probabilities for the completion. - **text_offset** (array) - Offset of the text. - **token_logprobs** (array) - Log probabilities of the tokens. - **tokens** (array) - The generated tokens. - **top_logprobs** (array) - Top log probabilities of the tokens. - **text** (string) - The generated text. - **created** (integer) - The timestamp of when the completion was created. - **model** (string) - The model used for the completion. - **system_fingerprint** (string) - A system fingerprint. - **object** (string) - The object type. - **usage** (object) - Usage statistics for the completion. - **completion_tokens** (integer) - The number of tokens in the completion. - **prompt_tokens** (integer) - The number of tokens in the prompt. #### Response Example { "example": "response body" } ``` -------------------------------- ### Call DeepSeek API with LangChain Source: https://deepseek.apifox.cn/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98-5904006m0 This Python script demonstrates how to use the DeepSeek API with LangChain. Replace 'YOUR_API_KEY' with your actual API key. ```python from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="deepseek-chat", openai_api_key="YOUR_API_KEY", openai_api_base="https://api.deepseek.com", temperature=0.7, top_p=0.7, max_tokens=1024, ) response = llm.invoke("Hello, world!") print(response) ``` -------------------------------- ### First Request: Long Text Q&A Source: https://deepseek.apifox.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E7%A1%AC%E7%9B%98%E7%BC%93%E5%AD%98-5903990m0 This is the initial request in a long text question-answering scenario. The system message and the first part of the user's content form the prefix for potential caching in subsequent requests. ```json messages: [ {"role": "system", "content": "你是一位资深的财报分析师..."} {"role": "user", "content": "<财报内容>\n\n请总结一下这份财报的关键信息。"} ] ```