{ "cells": [ { "cell_type": "markdown", "id": "0ae64ac8-c461-469e-88b0-8e485a0c8439", "metadata": {}, "source": [ "# DeepSeek API 输出解析 - OpenAI SDK\n", "\n", "> 指导文章:[DeepSeek API 输出解析 - OpenAI SDK](https://github.com/Hoper-J/AI-Guide-and-Demos-zh_CN/blob/master/Guide/DeepSeek%20API%20输出解析%20-%20OpenAI%20SDK.md)\n", "\n", "从下方选择平台开始,替换 `your-api-key` 后点击 `►` 或使用 `Shift + 回车` 运行代码块。\n", "\n", "在线链接:[Kaggle](https://www.kaggle.com/code/aidemos/deepseek-api-guide-2) | [Colab](https://colab.research.google.com/drive/12mS7nUNnvrhzdvSbG8sMV7t4mF06_mAX?usp=sharing)" ] }, { "cell_type": "markdown", "id": "3091b9c4-ab24-451e-9c13-c49b863e4c7c", "metadata": {}, "source": [ "# 环境依赖" ] }, { "cell_type": "code", "execution_count": null, "id": "5a2beceb-535d-40c8-a2d5-a49d693f511b", "metadata": {}, "outputs": [], "source": [ "%pip install openai" ] }, { "cell_type": "markdown", "id": "bcdc8f41-c3d1-4398-988b-2349e0b2c293", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# DeepSeek" ] }, { "cell_type": "markdown", "id": "1bc379cb-6848-469c-bbda-6b5e14ffdd84", "metadata": {}, "source": [ "## 认识输出" ] }, { "cell_type": "markdown", "id": "2e1eb298-ca95-466b-a2ef-aa73c88b375e", "metadata": {}, "source": [ "> 现在 V4 默认开启思考,下文以非思考开头是因为早期 DeepSeek 分为对话模型 V3 和思考模型 R1,所以这里保留顺序演示。\n", "\n", "### 非思考模式" ] }, { "cell_type": "code", "execution_count": 2, "id": "201e4f42-074e-4876-9eea-8e66f01f6253", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:19.735864Z", "iopub.status.busy": "2026-07-06T15:26:19.735593Z", "iopub.status.idle": "2026-07-06T15:26:22.610612Z", "shell.execute_reply": "2026-07-06T15:26:22.609665Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "client = OpenAI(\n", " api_key=\"your-api-key\", # 1:替换成对应的 API_Key,可以使用环境变量而非明文填写,即 api_key=os.getenv(\"DEEPSEEK_API_KEY\")\n", " base_url=\"https://api.deepseek.com/v1\", # 2:每个平台的 base_url 不同\n", ")\n", "\n", "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\", # 3:模型标识(model_id)可能存在差异\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 3, "id": "f1765ca0-cdcf-4165-826e-518b6bb0d2d9", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:22.613760Z", "iopub.status.busy": "2026-07-06T15:26:22.613586Z", "iopub.status.idle": "2026-07-06T15:26:22.617543Z", "shell.execute_reply": "2026-07-06T15:26:22.616761Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是 '\n", " 'DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你解答问题、处理信息、分析数据等等。虽然我不支持多模态识别(比如直接识别图片内容),但我可以读取你上传的文件(如PDF、Word、Excel、PPT等)中的文字信息,并帮你处理这些内容。\\n'\n", " '\\n'\n", " '我的上下文长度可达1M,相当于可以一次性处理像《三体》三部曲这样体量的书籍。而且我完全免费使用,支持联网搜索(不过需要你手动开启)。有什么我可以帮你的吗?😊',\n", " 'function_call': None,\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351581,\n", " 'id': 'd0f1fb99-b1e2-4499-9615-5a83ecb695f8',\n", " 'model': 'deepseek-v4-flash',\n", " 'object': 'chat.completion',\n", " 'service_tier': None,\n", " 'system_fingerprint': 'fp_8b330d02d0_prod0820_fp8_kvcache_20260402',\n", " 'usage': {'completion_tokens': 120,\n", " 'completion_tokens_details': None,\n", " 'prompt_cache_hit_tokens': 0,\n", " 'prompt_cache_miss_tokens': 12,\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0},\n", " 'total_tokens': 132}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "373b0d94-46e9-4487-913b-e8af8467b9ad", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 4, "id": "b6dbef5e-f4c0-4f93-8f08-82debb1b3fc1", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:22.620413Z", "iopub.status.busy": "2026-07-06T15:26:22.620215Z", "iopub.status.idle": "2026-07-06T15:26:22.623193Z", "shell.execute_reply": "2026-07-06T15:26:22.622522Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是 DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你解答问题、处理信息、分析数据等等。虽然我不支持多模态识别(比如直接识别图片内容),但我可以读取你上传的文件(如PDF、Word、Excel、PPT等)中的文字信息,并帮你处理这些内容。\n", "\n", "我的上下文长度可达1M,相当于可以一次性处理像《三体》三部曲这样体量的书籍。而且我完全免费使用,支持联网搜索(不过需要你手动开启)。有什么我可以帮你的吗?😊\n" ] } ], "source": [ "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "87174746-cc3b-4e7c-88f1-0e64008b8583", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 5, "id": "72c3c7b4-e01c-4229-b713-9bbaa2fda7ac", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:22.625404Z", "iopub.status.busy": "2026-07-06T15:26:22.625254Z", "iopub.status.idle": "2026-07-06T15:26:22.629553Z", "shell.execute_reply": "2026-07-06T15:26:22.628713Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens [缓存命中: 0 | 未命中: 12]\n", "输出: 120 tokens\n", "总消耗: 132 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0002 元\n", "预估总成本: ¥0.0003 元\n" ] } ], "source": [ "def print_chat_usage(completion):\n", " stats = completion.usage\n", " hit = stats.prompt_cache_hit_tokens\n", " miss = stats.prompt_cache_miss_tokens\n", " \n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", " \n", " # 按 DeepSeek v4-flash 定价计算成本(单位:元,思考/非思考同价)\n", " # - 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", "\t# - 输出: 2元/百万 tokens\n", " # 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " input_cost = (hit * 0.02 + miss * 1) / 1_000_000\n", " output_cost = stats.completion_tokens * 2 / 1_000_000\n", " total_cost = input_cost + output_cost\n", " \n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_chat_usage(completion)" ] }, { "cell_type": "markdown", "id": "f4035819-f0e4-4fc4-a596-c941df3608aa", "metadata": {}, "source": [ "### 思考模式" ] }, { "cell_type": "code", "execution_count": 6, "id": "212843ec-d21d-4402-a6b8-c2919432df6e", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:22.631288Z", "iopub.status.busy": "2026-07-06T15:26:22.631196Z", "iopub.status.idle": "2026-07-06T15:26:25.125620Z", "shell.execute_reply": "2026-07-06T15:26:25.124948Z" }, "scrolled": true }, "outputs": [], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\", # 3:思考模式(V4 默认开启,无需更换模型)\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 7, "id": "58e3ab1f-89e8-4c6a-a42e-b0f974c41890", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:25.127357Z", "iopub.status.busy": "2026-07-06T15:26:25.127235Z", "iopub.status.idle": "2026-07-06T15:26:25.130723Z", "shell.execute_reply": "2026-07-06T15:26:25.129817Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你回答问题、处理信息、进行创作等等。我支持阅读链接、上传文件(图片、PDF、Word、Excel等),还能联网搜索(需要手动开启)。我的上下文容量高达1M,能一次性处理像《三体》三部曲那样的大体量内容。最重要的是,我完全免费使用,没有任何收费计划!有什么我可以帮你的吗?😊',\n", " 'function_call': None,\n", " 'reasoning_content': '嗯,用户问“你是谁”,这是一个非常基础的自我介绍问题。用户可能是第一次接触我,或者想确认我的身份和功能。\\n'\n", " '\\n'\n", " '我需要简洁清晰地说明自己的名称、创造者、基本能力特点,以及友好的服务态度。想到了直接说“我是DeepSeek”,然后提到创造者深度求索公司,再列举几个关键特性:免费、长上下文、文件处理、联网搜索等,最后用一句友好的询问结尾,邀请用户提出需求。\\n'\n", " '\\n'\n", " '这个回答结构应该能全面覆盖用户可能想了解的信息,同时保持亲切自然。',\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351583,\n", " 'id': '01da138c-d195-495c-9ec9-b33242b7eccf',\n", " 'model': 'deepseek-v4-flash',\n", " 'object': 'chat.completion',\n", " 'service_tier': None,\n", " 'system_fingerprint': 'fp_8b330d02d0_prod0820_fp8_kvcache_20260402',\n", " 'usage': {'completion_tokens': 212,\n", " 'completion_tokens_details': {'accepted_prediction_tokens': None,\n", " 'audio_tokens': None,\n", " 'reasoning_tokens': 112,\n", " 'rejected_prediction_tokens': None},\n", " 'prompt_cache_hit_tokens': 0,\n", " 'prompt_cache_miss_tokens': 12,\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0},\n", " 'total_tokens': 224}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "5e66576f-0e8a-40bd-ab31-70499c460a61", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 8, "id": "246cc1f4-f310-4449-b98d-48d28ba45c3d", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:25.132795Z", "iopub.status.busy": "2026-07-06T15:26:25.132689Z", "iopub.status.idle": "2026-07-06T15:26:25.135710Z", "shell.execute_reply": "2026-07-06T15:26:25.135238Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "嗯,用户问“你是谁”,这是一个非常基础的自我介绍问题。用户可能是第一次接触我,或者想确认我的身份和功能。\n", "\n", "我需要简洁清晰地说明自己的名称、创造者、基本能力特点,以及友好的服务态度。想到了直接说“我是DeepSeek”,然后提到创造者深度求索公司,再列举几个关键特性:免费、长上下文、文件处理、联网搜索等,最后用一句友好的询问结尾,邀请用户提出需求。\n", "\n", "这个回答结构应该能全面覆盖用户可能想了解的信息,同时保持亲切自然。\n", "===== 模型回复 =====\n", "你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你回答问题、处理信息、进行创作等等。我支持阅读链接、上传文件(图片、PDF、Word、Excel等),还能联网搜索(需要手动开启)。我的上下文容量高达1M,能一次性处理像《三体》三部曲那样的大体量内容。最重要的是,我完全免费使用,没有任何收费计划!有什么我可以帮你的吗?😊\n" ] } ], "source": [ "# 获取推理思考过程(Reasoner特有字段)\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\")\n", "\n", "# 获取模型回复内容(与之前相同)\n", "content = completion.choices[0].message.content\n", "print(f\"===== 模型回复 =====\\n{content}\")" ] }, { "cell_type": "markdown", "id": "3870783c-3eb7-456d-9c60-63366167d3aa", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 9, "id": "6c624853-3e3c-4341-ae30-5332b59d6393", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:25.137757Z", "iopub.status.busy": "2026-07-06T15:26:25.137646Z", "iopub.status.idle": "2026-07-06T15:26:25.143075Z", "shell.execute_reply": "2026-07-06T15:26:25.141919Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens [缓存命中: 0 | 未命中: 12]\n", "输出: 212 tokens\n", "├─ 推理过程: 112 tokens\n", "└─ 最终回答: 100 tokens\n", "总消耗: 224 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0004 元\n", "预估总成本: ¥0.0004 元\n" ] } ], "source": [ "def print_reasoner_usage(completion):\n", " stats = completion.usage\n", " hit = stats.prompt_cache_hit_tokens\n", " miss = stats.prompt_cache_miss_tokens\n", " \n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", "\n", " # 推理模型的token分解\n", " if details := stats.completion_tokens_details:\n", " reasoning = details.reasoning_tokens\n", " final = stats.completion_tokens - reasoning\n", " print(f\"├─ 推理过程: {reasoning} tokens\")\n", " print(f\"└─ 最终回答: {final} tokens\")\n", " \n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", " \n", " # 按 DeepSeek v4-flash 定价计算成本(单位:元,思考/非思考同价)\n", " # - 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", "\t# - 输出: 2元/百万 tokens\n", " # 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " input_cost = (hit * 0.02 + miss * 1) / 1_000_000\n", " output_cost = stats.completion_tokens * 2 / 1_000_000\n", " total_cost = input_cost + output_cost\n", " \n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_reasoner_usage(completion)" ] }, { "cell_type": "markdown", "id": "aedcdfed-70a7-4ec8-9764-da8a13da1755", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# 硅基流动" ] }, { "cell_type": "markdown", "id": "1e94d5c4-45fc-4d36-9fe2-491ab9cfa2f9", "metadata": {}, "source": [ "## 认识输出" ] }, { "cell_type": "markdown", "id": "86f3cb9d-a2da-4936-8dc0-a93439be1226", "metadata": {}, "source": [ "### 非思考模式" ] }, { "cell_type": "code", "execution_count": 10, "id": "8ceedf55-5208-472b-a696-1087839314c3", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:26:25.146182Z", "iopub.status.busy": "2026-07-06T15:26:25.145977Z", "iopub.status.idle": "2026-07-06T15:27:09.005342Z", "shell.execute_reply": "2026-07-06T15:27:09.002462Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "client = OpenAI(\n", " api_key=\"your-api-key\", # 1:替换成对应的 API_Key,可以使用环境变量而非明文填写,即 api_key=os.getenv(\"SILICONFLOW_API_KEY\")\n", " base_url=\"https://api.siliconflow.cn/v1\", # 2:每个平台的 base_url 不同\n", ")\n", "\n", "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\", # 3:模型标识(model_id)可能存在差异\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 11, "id": "d1812b04-0d73-48ad-8327-459256c5efd2", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:09.009507Z", "iopub.status.busy": "2026-07-06T15:27:09.009343Z", "iopub.status.idle": "2026-07-06T15:27:09.013585Z", "shell.execute_reply": "2026-07-06T15:27:09.012937Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,能够帮你解答问题、提供信息、进行对话等。我支持中文、英文等多种语言,并且可以处理长文本(上下文高达1M)。虽然我不支持多模态识别,但你可以上传图片、PDF、Word等文件,我会从中读取文字信息来帮助你。\\n'\n", " '\\n'\n", " '我的知识截止日期是2025年5月,目前是免费使用的。有什么我可以帮你的吗?😊',\n", " 'function_call': None,\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351586,\n", " 'id': '019f3809ad3d1bd505e366096e788369',\n", " 'model': 'deepseek-ai/DeepSeek-V4-Flash',\n", " 'object': 'chat.completion',\n", " 'service_tier': None,\n", " 'system_fingerprint': '',\n", " 'usage': {'completion_tokens': 102,\n", " 'completion_tokens_details': {'accepted_prediction_tokens': None,\n", " 'audio_tokens': None,\n", " 'reasoning_tokens': 0,\n", " 'rejected_prediction_tokens': None},\n", " 'prompt_cache_hit_tokens': 0,\n", " 'prompt_cache_miss_tokens': 12,\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0},\n", " 'total_tokens': 114}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "8ddde14f-04e9-43fa-8ffb-36474b4f7958", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 12, "id": "58e666f7-7be0-40fb-99fb-d4ef836b87ea", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:09.015885Z", "iopub.status.busy": "2026-07-06T15:27:09.015794Z", "iopub.status.idle": "2026-07-06T15:27:09.018986Z", "shell.execute_reply": "2026-07-06T15:27:09.017699Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,能够帮你解答问题、提供信息、进行对话等。我支持中文、英文等多种语言,并且可以处理长文本(上下文高达1M)。虽然我不支持多模态识别,但你可以上传图片、PDF、Word等文件,我会从中读取文字信息来帮助你。\n", "\n", "我的知识截止日期是2025年5月,目前是免费使用的。有什么我可以帮你的吗?😊\n" ] } ], "source": [ "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "e5e04b3b-6a7d-4685-ac15-40405194883e", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 13, "id": "482daee3-382c-4188-9095-fad357fa3016", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:09.021430Z", "iopub.status.busy": "2026-07-06T15:27:09.021275Z", "iopub.status.idle": "2026-07-06T15:27:09.029591Z", "shell.execute_reply": "2026-07-06T15:27:09.028270Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens [缓存命中: 0 | 未命中: 12]\n", "输出: 102 tokens\n", "总消耗: 114 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0002 元\n", "预估总成本: ¥0.0002 元\n" ] } ], "source": [ "def print_chat_usage(completion, input_cost=1.0, output_cost=2.0, cache_hit_cost=0.02):\n", " \"\"\"\n", " 参数:\n", " input_cost: 输入价格(元/百万 tokens)\n", " output_cost: 输出价格(元/百万 tokens)\n", " cache_hit_cost: 缓存命中价格(当平台不支持时自动退化到全价模式)\n", "\n", " 按 DeepSeek 聊天模型定价设定默认成本(单位:元):\n", " - 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", "\t- 输出: 2元/百万 tokens\n", " 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " \"\"\"\n", " stats = completion.usage\n", "\n", " # 尝试获取字段(兼容其他平台)\n", " hit = getattr(stats, 'prompt_cache_hit_tokens', None) # 无缓存机制的平台没有该字段\n", " has_cache = hit is not None # 注意:命中 0 个时字段仍存在,值为 0\n", " if not has_cache:\n", " hit = 0 # 后续统一按数字处理\n", " miss = getattr(stats, 'prompt_cache_miss_tokens', \n", " stats.prompt_tokens - hit if hasattr(stats, 'prompt_tokens') else 0)\n", "\n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " # 仅在平台提供缓存字段时显示细节\n", " if has_cache:\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " else:\n", " print(f\"输入: {stats.prompt_tokens} tokens\")\n", "\n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", "\n", " # 动态成本计算\n", " input_cost = (hit * cache_hit_cost + miss * input_cost) / 1_000_000\n", " output_cost = stats.completion_tokens * output_cost / 1_000_000\n", " total_cost = input_cost + output_cost\n", "\n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_chat_usage(completion)" ] }, { "cell_type": "markdown", "id": "81780ee6-3d27-4cc4-a702-66ec3c48007c", "metadata": {}, "source": [ "### 思考模式" ] }, { "cell_type": "code", "execution_count": 14, "id": "e13adbfc-3543-4e9e-9245-87e5540b60c6", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:09.032114Z", "iopub.status.busy": "2026-07-06T15:27:09.031968Z", "iopub.status.idle": "2026-07-06T15:27:16.826833Z", "shell.execute_reply": "2026-07-06T15:27:16.825809Z" }, "scrolled": true }, "outputs": [], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\", # 3:无需更换模型\n", " extra_body={\"thinking\": {\"type\": \"enabled\"}}, # 硅基流动上偶尔不默认思考,所以这里显式开启\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 15, "id": "ded0a469-32af-47d6-ad10-dcaea53c09dc", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:16.830266Z", "iopub.status.busy": "2026-07-06T15:27:16.830068Z", "iopub.status.idle": "2026-07-06T15:27:16.833995Z", "shell.execute_reply": "2026-07-06T15:27:16.833190Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是DeepSeek,由深度求索公司创造的AI助手。我可以帮你解答问题、提供信息、进行对话交流等。我的知识截止于2025年5月,支持处理文本、阅读链接和上传的文件(如图片、PDF、Word、Excel等)。目前我是免费使用的,欢迎随时向我提问!有什么我可以帮你的吗?😊',\n", " 'function_call': None,\n", " 'reasoning_content': '嗯,用户问“你是谁”,这是一个简单的自我介绍问题。用户可能是初次接触,需要了解我的身份和功能。我可以直接、清晰地说明我是DeepSeek,由深度求索公司创造,并简要介绍我的核心能力,比如知识范围、文件处理、长上下文和免费使用。最后用友好的语气询问是否需要帮助,这样既回答了问题,也开启了进一步对话。',\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351630,\n", " 'id': '019f380a56932f25b566a2f9ff08862a',\n", " 'model': 'deepseek-ai/DeepSeek-V4-Flash',\n", " 'object': 'chat.completion',\n", " 'service_tier': None,\n", " 'system_fingerprint': '',\n", " 'usage': {'completion_tokens': 157,\n", " 'completion_tokens_details': {'accepted_prediction_tokens': None,\n", " 'audio_tokens': None,\n", " 'reasoning_tokens': 80,\n", " 'rejected_prediction_tokens': None},\n", " 'prompt_cache_hit_tokens': 0,\n", " 'prompt_cache_miss_tokens': 12,\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0},\n", " 'total_tokens': 169}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "6bbdf093-015f-40b2-bc0f-1a53d7314c6f", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 16, "id": "323d6c16-8c0a-46ea-bc1e-ddb4cd368e67", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:16.836314Z", "iopub.status.busy": "2026-07-06T15:27:16.836146Z", "iopub.status.idle": "2026-07-06T15:27:16.839408Z", "shell.execute_reply": "2026-07-06T15:27:16.838888Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "嗯,用户问“你是谁”,这是一个简单的自我介绍问题。用户可能是初次接触,需要了解我的身份和功能。我可以直接、清晰地说明我是DeepSeek,由深度求索公司创造,并简要介绍我的核心能力,比如知识范围、文件处理、长上下文和免费使用。最后用友好的语气询问是否需要帮助,这样既回答了问题,也开启了进一步对话。\n", "===== 模型回复 =====\n", "你好!我是DeepSeek,由深度求索公司创造的AI助手。我可以帮你解答问题、提供信息、进行对话交流等。我的知识截止于2025年5月,支持处理文本、阅读链接和上传的文件(如图片、PDF、Word、Excel等)。目前我是免费使用的,欢迎随时向我提问!有什么我可以帮你的吗?😊\n" ] } ], "source": [ "# 获取推理思考过程(Reasoner特有字段)\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\")\n", "\n", "# 获取模型回复内容(与之前相同)\n", "content = completion.choices[0].message.content\n", "print(f\"===== 模型回复 =====\\n{content}\")" ] }, { "cell_type": "markdown", "id": "448878e0-094a-46ad-aa38-663af46417e3", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 17, "id": "1508ae2c-f673-4aea-a8db-92a1f5b51d30", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:16.841527Z", "iopub.status.busy": "2026-07-06T15:27:16.841399Z", "iopub.status.idle": "2026-07-06T15:27:16.849443Z", "shell.execute_reply": "2026-07-06T15:27:16.848828Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens [缓存命中: 0 | 未命中: 12]\n", "输出: 157 tokens\n", "├─ 推理过程: 80 tokens\n", "└─ 最终回答: 77 tokens\n", "总消耗: 169 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0003 元\n", "预估总成本: ¥0.0003 元\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/var/folders/cv/p24b2d5j4hjg9ndjzbbwgplh0000gn/T/ipykernel_73850/3423767371.py:37: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.12/migration/\n", " details = getattr(details, 'dict', lambda: {})()\n" ] } ], "source": [ "def print_reasoner_usage(completion, input_cost=1.0, output_cost=2.0, cache_hit_cost=0.02):\n", " \"\"\"\n", " 参数:\n", " input_cost: 输入价格(元/百万 tokens)\n", " output_cost: 输出价格(元/百万 tokens)\n", " cache_hit_cost: 缓存命中价格(当平台不支持时自动退化到全价模式)\n", "\n", " 按 DeepSeek 推理模型定价设定默认成本(单位:元):\n", " - 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", " - 输出: 2元/百万 tokens\n", " 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " \"\"\"\n", " stats = completion.usage\n", " \n", " # 尝试获取字段(兼容其他平台)\n", " hit = getattr(stats, 'prompt_cache_hit_tokens', None) # 无缓存机制的平台没有该字段\n", " has_cache = hit is not None # 注意:命中 0 个时字段仍存在,值为 0\n", " if not has_cache:\n", " hit = 0 # 后续统一按数字处理\n", " miss = getattr(stats, 'prompt_cache_miss_tokens', \n", " stats.prompt_tokens - hit if hasattr(stats, 'prompt_tokens') else 0)\n", " \n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " # 仅在平台提供缓存字段时显示细节\n", " if has_cache:\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " else:\n", " print(f\"输入: {stats.prompt_tokens} tokens\")\n", " \n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", "\n", " # 尝试获取推理过程详情\n", " details = getattr(stats, 'completion_tokens_details', None)\n", " reasoning = 0\n", " if details:\n", " if not isinstance(details, dict):\n", " details = getattr(details, 'dict', lambda: {})()\n", " # 尝试获取 reasoning_tokens\n", " reasoning = details.get('reasoning_tokens', 0)\n", " \n", " # 仅在存在推理tokens数量字段时处理\n", " if reasoning > 0:\n", " final = stats.completion_tokens - reasoning\n", " print(f\"├─ 推理过程: {reasoning} tokens\")\n", " print(f\"└─ 最终回答: {final} tokens\")\n", " \n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", " \n", " # 动态成本计算\n", " input_cost_total = (hit * cache_hit_cost + miss * input_cost) / 1_000_000\n", " output_cost_total = stats.completion_tokens * output_cost / 1_000_000\n", " total_cost = input_cost_total + output_cost_total\n", " \n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost_total:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost_total:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_reasoner_usage(completion)" ] }, { "cell_type": "markdown", "id": "40de9f59-ae1b-4377-83c2-31de5b6cd669", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# 阿里云百炼" ] }, { "cell_type": "markdown", "id": "d6b599e5-18ff-431b-b0ae-3282e65cb081", "metadata": {}, "source": [ "## 认识输出" ] }, { "cell_type": "markdown", "id": "2071d7d0-9cdc-470b-a8c3-0ed76f3137e1", "metadata": {}, "source": [ "### 非思考模式" ] }, { "cell_type": "code", "execution_count": 18, "id": "fc954701-c1ff-4563-ba92-0c36669339b7", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:16.851652Z", "iopub.status.busy": "2026-07-06T15:27:16.851549Z", "iopub.status.idle": "2026-07-06T15:27:19.410977Z", "shell.execute_reply": "2026-07-06T15:27:19.409763Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "client = OpenAI(\n", " api_key=\"your-api-key\", # 1:替换成对应的 API_Key,可以使用环境变量而非明文填写,即 api_key=os.getenv(\"SILICONFLOW_API_KEY\")\n", " base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\", # 2:每个平台的 base_url 不同\n", ")\n", "\n", "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\", # 3:模型标识(model_id)可能存在差异\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 19, "id": "28cb7bff-0933-4a2f-9f90-3b16a1f418b9", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:19.414131Z", "iopub.status.busy": "2026-07-06T15:27:19.413906Z", "iopub.status.idle": "2026-07-06T15:27:19.418305Z", "shell.execute_reply": "2026-07-06T15:27:19.417100Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是 DeepSeek,一个由深度求索公司(DeepSeek)创造的 AI '\n", " '助手。我是一个纯文本模型,擅长回答各种问题、提供信息和帮助解决问题。我支持处理多种文件,比如图片、PDF、Word、Excel '\n", " '等,并且可以一次性处理超长文本(上下文窗口高达 '\n", " '1M)。虽然我不能直接识别图片内容,但可以读取图片中的文字信息。有什么我可以帮你的吗?😊',\n", " 'function_call': None,\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351640,\n", " 'id': 'chatcmpl-95087a5f-3fbf-95a4-83bd-c20d7fd091ec',\n", " 'model': 'deepseek-v4-flash',\n", " 'object': 'chat.completion',\n", " 'service_tier': None,\n", " 'system_fingerprint': None,\n", " 'usage': {'completion_tokens': 93,\n", " 'completion_tokens_details': None,\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0},\n", " 'total_tokens': 105}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "8277530a-81a2-434b-8f41-b51d242d8ce8", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 20, "id": "dfe8e595-420e-4d33-be4e-19f25c271edc", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:19.421402Z", "iopub.status.busy": "2026-07-06T15:27:19.421227Z", "iopub.status.idle": "2026-07-06T15:27:19.423818Z", "shell.execute_reply": "2026-07-06T15:27:19.423322Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是 DeepSeek,一个由深度求索公司(DeepSeek)创造的 AI 助手。我是一个纯文本模型,擅长回答各种问题、提供信息和帮助解决问题。我支持处理多种文件,比如图片、PDF、Word、Excel 等,并且可以一次性处理超长文本(上下文窗口高达 1M)。虽然我不能直接识别图片内容,但可以读取图片中的文字信息。有什么我可以帮你的吗?😊\n" ] } ], "source": [ "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "2fcb48d4-e06b-4888-8b3d-e17f8a591a17", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 21, "id": "a44d4230-b450-4a53-91e6-b129991c93f1", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:19.425874Z", "iopub.status.busy": "2026-07-06T15:27:19.425735Z", "iopub.status.idle": "2026-07-06T15:27:19.430771Z", "shell.execute_reply": "2026-07-06T15:27:19.430085Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens\n", "输出: 93 tokens\n", "总消耗: 105 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0002 元\n", "预估总成本: ¥0.0002 元\n" ] } ], "source": [ "def print_chat_usage(completion, input_cost=1.0, output_cost=2.0, cache_hit_cost=0.02):\n", " \"\"\"\n", " 参数:\n", " input_cost: 输入价格(元/百万 tokens)\n", " output_cost: 输出价格(元/百万 tokens)\n", " cache_hit_cost: 缓存命中价格(当平台不支持时自动退化到全价模式)\n", "\n", " 按 DeepSeek 聊天模型定价设定默认成本(单位:元):\n", " - 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", "\t- 输出: 2元/百万 tokens\n", " 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " \"\"\"\n", " stats = completion.usage\n", "\n", " # 尝试获取字段(兼容其他平台)\n", " hit = getattr(stats, 'prompt_cache_hit_tokens', None) # 无缓存机制的平台没有该字段\n", " has_cache = hit is not None # 注意:命中 0 个时字段仍存在,值为 0\n", " if not has_cache:\n", " hit = 0 # 后续统一按数字处理\n", " miss = getattr(stats, 'prompt_cache_miss_tokens', \n", " stats.prompt_tokens - hit if hasattr(stats, 'prompt_tokens') else 0)\n", "\n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " # 仅在平台提供缓存字段时显示细节\n", " if has_cache:\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " else:\n", " print(f\"输入: {stats.prompt_tokens} tokens\")\n", "\n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", "\n", " # 动态成本计算\n", " input_cost = (hit * cache_hit_cost + miss * input_cost) / 1_000_000\n", " output_cost = stats.completion_tokens * output_cost / 1_000_000\n", " total_cost = input_cost + output_cost\n", "\n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_chat_usage(completion)" ] }, { "cell_type": "markdown", "id": "e439e8ba-6329-4337-8a5a-3871d60ab20d", "metadata": {}, "source": [ "### 思考模式" ] }, { "cell_type": "markdown", "id": "0868871f-d587-4cf6-a3df-c2af062bb495", "metadata": {}, "source": [ "> 阿里云百炼的 deepseek-r1 API 可能会出现预期外的输出:重复/没有思维链或不解析 `` 标签。" ] }, { "cell_type": "code", "execution_count": 22, "id": "da018abb-4ea6-42e8-85e3-bf297c67e951", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:19.432506Z", "iopub.status.busy": "2026-07-06T15:27:19.432381Z", "iopub.status.idle": "2026-07-06T15:27:23.228310Z", "shell.execute_reply": "2026-07-06T15:27:23.227105Z" }, "scrolled": true }, "outputs": [], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\", # 3:思考模式(V4 默认开启,无需更换模型)\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 23, "id": "9b452d52-8eb5-4f47-9ff5-e4803c974fad", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:23.230465Z", "iopub.status.busy": "2026-07-06T15:27:23.230297Z", "iopub.status.idle": "2026-07-06T15:27:23.234278Z", "shell.execute_reply": "2026-07-06T15:27:23.233562Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是 DeepSeek,由深度求索公司创造的 AI '\n", " '助手。我在这里帮你解答问题、提供信息、聊天或者完成各种任务。我是纯文本模型,支持阅读链接和上传文件(图片、PDF、Word、Excel '\n", " '等),还可以一次性处理超长文本(上下文 '\n", " '1M,相当于三体三部曲的体量)。有什么我可以帮你的吗?😊',\n", " 'function_call': None,\n", " 'reasoning_content': '嗯,用户问了一个简单的自我介绍问题:“你是谁?”\\n'\n", " '\\n'\n", " '这是一个非常基础的问题,用户可能是第一次接触我,想了解我的身份和功能。我需要清晰、友好地介绍自己,说明我是谁、由谁创造、以及我能提供什么帮助。\\n'\n", " '\\n'\n", " '想到了可以这样回答:先直接表明身份——我是DeepSeek,由深度求索公司创造。然后简要说明我的核心能力,比如文本处理、支持文件上传、长上下文等,并强调是免费服务。最后以开放式的邀请结束,询问用户是否需要帮助。\\n'\n", " '\\n'\n", " '这样既回答了用户的问题,也为后续对话创造了自然的切入点。',\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351644,\n", " 'id': 'chatcmpl-92ce28cf-4c54-93d2-b713-a9a7fa8953ba',\n", " 'model': 'deepseek-v4-flash',\n", " 'object': 'chat.completion',\n", " 'service_tier': None,\n", " 'system_fingerprint': None,\n", " 'usage': {'completion_tokens': 208,\n", " 'completion_tokens_details': {'accepted_prediction_tokens': None,\n", " 'audio_tokens': None,\n", " 'reasoning_tokens': 123,\n", " 'rejected_prediction_tokens': None},\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0},\n", " 'total_tokens': 220}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "8ac0e42c-b019-49d4-99cb-66d8996db804", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 24, "id": "183a35bb-59cb-4285-8fd0-24629a62be9a", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:23.236737Z", "iopub.status.busy": "2026-07-06T15:27:23.236597Z", "iopub.status.idle": "2026-07-06T15:27:23.241470Z", "shell.execute_reply": "2026-07-06T15:27:23.240988Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "嗯,用户问了一个简单的自我介绍问题:“你是谁?”\n", "\n", "这是一个非常基础的问题,用户可能是第一次接触我,想了解我的身份和功能。我需要清晰、友好地介绍自己,说明我是谁、由谁创造、以及我能提供什么帮助。\n", "\n", "想到了可以这样回答:先直接表明身份——我是DeepSeek,由深度求索公司创造。然后简要说明我的核心能力,比如文本处理、支持文件上传、长上下文等,并强调是免费服务。最后以开放式的邀请结束,询问用户是否需要帮助。\n", "\n", "这样既回答了用户的问题,也为后续对话创造了自然的切入点。\n", "\n", "===== 最终回复 =====\n", "你好!我是 DeepSeek,由深度求索公司创造的 AI 助手。我在这里帮你解答问题、提供信息、聊天或者完成各种任务。我是纯文本模型,支持阅读链接和上传文件(图片、PDF、Word、Excel 等),还可以一次性处理超长文本(上下文 1M,相当于三体三部曲的体量)。有什么我可以帮你的吗?😊\n" ] } ], "source": [ "import re\n", "\n", "def parse_reasoner_response(completion):\n", " \"\"\"\n", " 参数:\n", " completion (object): API 返回的对象\n", " \n", " 返回:\n", " (reasoning_content, reply_content)\n", " \n", " 处理两种平台格式:\n", " 1. 有独立 reasoning_content 字段的平台:DeepSeek 官方,硅基流动,百度智能云...\n", " 2. 可能需要从 content 解析 标签的平台:阿里云百炼(偶尔会没有 reasoning_content)...\n", " \"\"\"\n", " message = completion.choices[0].message\n", " \n", " # 尝试直接获取 reasoning_content 字段\n", " reasoning = getattr(message, 'reasoning_content', None)\n", " \n", " # 有 reasoning_content 时直接获取最终回复\n", " if reasoning:\n", " final_content = getattr(message, 'content', '')\n", " else:\n", " # 如果没有,则尝试从 content 解析\n", " content = getattr(message, 'content', '')\n", " \n", " # 使用非贪婪模式匹配 标签\n", " reasoning_match = re.search(\n", " r'(.*?)', \n", " content, \n", " re.DOTALL # 允许跨行匹配\n", " )\n", " \n", " if reasoning_match:\n", " reasoning = reasoning_match.group(1).strip()\n", " # 从原始内容移除推理部分\n", " final_content = re.sub(\n", " r'.*?', \n", " '', \n", " content, \n", " flags=re.DOTALL\n", " ).strip()\n", " else:\n", " reasoning = ''\n", " final_content = content\n", " \n", " return reasoning, final_content\n", "\n", "reasoning_content, content = parse_reasoner_response(completion)\n", "\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\")\n", "print(f\"\\n===== 最终回复 =====\\n{content}\")" ] }, { "cell_type": "markdown", "id": "b121ab5b-3273-4481-9197-993cff97eb25", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 25, "id": "66fcdbea-faa7-4455-9f53-712172dd1a37", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:23.243588Z", "iopub.status.busy": "2026-07-06T15:27:23.243468Z", "iopub.status.idle": "2026-07-06T15:27:23.253047Z", "shell.execute_reply": "2026-07-06T15:27:23.252234Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens\n", "输出: 208 tokens\n", "├─ 推理过程: 123 tokens\n", "└─ 最终回答: 85 tokens\n", "总消耗: 220 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0004 元\n", "预估总成本: ¥0.0004 元\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/var/folders/cv/p24b2d5j4hjg9ndjzbbwgplh0000gn/T/ipykernel_73850/1154722965.py:37: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.12/migration/\n", " details = getattr(details, 'dict', lambda: {})()\n" ] } ], "source": [ "def print_reasoner_usage(completion, input_cost=1.0, output_cost=2.0, cache_hit_cost=0.02):\n", " \"\"\"\n", " 参数:\n", " input_cost: 输入价格(元/百万 tokens)\n", " output_cost: 输出价格(元/百万 tokens)\n", " cache_hit_cost: 缓存命中价格(当平台不支持时自动退化到全价模式)\n", "\n", " 按 DeepSeek 推理模型定价设定默认成本(单位:元):\n", " 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", " 输出: 2元/百万 tokens\n", " 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " \"\"\"\n", " stats = completion.usage\n", " \n", " # 尝试获取字段(兼容其他平台)\n", " hit = getattr(stats, 'prompt_cache_hit_tokens', None) # 无缓存机制的平台没有该字段\n", " has_cache = hit is not None # 注意:命中 0 个时字段仍存在,值为 0\n", " if not has_cache:\n", " hit = 0 # 后续统一按数字处理\n", " miss = getattr(stats, 'prompt_cache_miss_tokens', \n", " stats.prompt_tokens - hit if hasattr(stats, 'prompt_tokens') else 0)\n", " \n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " # 仅在平台提供缓存字段时显示细节\n", " if has_cache:\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " else:\n", " print(f\"输入: {stats.prompt_tokens} tokens\")\n", " \n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", "\n", " # 尝试获取推理过程详情\n", " details = getattr(stats, 'completion_tokens_details', None)\n", " reasoning = 0\n", " if details:\n", " if not isinstance(details, dict):\n", " details = getattr(details, 'dict', lambda: {})()\n", " # 尝试获取 reasoning_tokens\n", " reasoning = details.get('reasoning_tokens', 0)\n", " \n", " # 仅在存在推理tokens数量字段时处理\n", " if reasoning > 0:\n", " final = stats.completion_tokens - reasoning\n", " print(f\"├─ 推理过程: {reasoning} tokens\")\n", " print(f\"└─ 最终回答: {final} tokens\")\n", " \n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", " \n", " # 动态成本计算\n", " input_cost_total = (hit * cache_hit_cost + miss * input_cost) / 1_000_000\n", " output_cost_total = stats.completion_tokens * output_cost / 1_000_000\n", " total_cost = input_cost_total + output_cost_total\n", " \n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost_total:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost_total:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_reasoner_usage(completion)" ] }, { "cell_type": "markdown", "id": "6b1a5f80-bc05-4796-81a9-ccda08b2a9ac", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# 百度智能云" ] }, { "cell_type": "markdown", "id": "902a0a47-8e24-4130-be11-abe9f5751249", "metadata": {}, "source": [ "## 认识输出" ] }, { "cell_type": "markdown", "id": "1a029e69-968f-4385-baf6-03653f1ed074", "metadata": {}, "source": [ "### 非思考模式" ] }, { "cell_type": "code", "execution_count": 26, "id": "acd60c76-161c-4793-8576-215b485afec9", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:23.255187Z", "iopub.status.busy": "2026-07-06T15:27:23.255071Z", "iopub.status.idle": "2026-07-06T15:27:26.200275Z", "shell.execute_reply": "2026-07-06T15:27:26.199375Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "client = OpenAI(\n", " api_key=\"your-api-key\", # 1:替换成对应的 API_Key,可以使用环境变量而非明文填写,即 api_key=os.getenv(\"SILICONFLOW_API_KEY\")\n", " base_url=\"https://qianfan.baidubce.com/v2\" # 2:每个平台的 base_url 不同\n", ")\n", "\n", "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\", # 3:模型标识(model_id)可能存在差异\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 27, "id": "921e0103-84b6-4401-ad5b-3cbedb810820", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:26.203158Z", "iopub.status.busy": "2026-07-06T15:27:26.202977Z", "iopub.status.idle": "2026-07-06T15:27:26.207219Z", "shell.execute_reply": "2026-07-06T15:27:26.206513Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'flag': 0,\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '我是DeepSeek,由深度求索公司创造的AI助手!😊\\n'\n", " '\\n'\n", " '我是一个纯文本模型,擅长回答各种问题、提供信息、进行对话交流。虽然我不支持多模态识别(比如直接“看”图片),但我可以处理上传的文件(图像、txt、pdf、ppt、word、excel等),从中读取文字信息来帮你分析。\\n'\n", " '\\n'\n", " '我的知识截止日期是2025年5月,拥有1M的上下文长度,可以一次性处理像《三体》三部曲那样体量的书籍。而且我是完全免费的,无论是网页版还是App版都可以使用,App还支持语音输入哦!\\n'\n", " '\\n'\n", " '有什么我可以帮你的吗?无论是学习、工作还是日常生活中的问题,我都很乐意协助你!💪',\n", " 'function_call': None,\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351643,\n", " 'id': 'as-y1vepfsu2b',\n", " 'model': 'deepseek-v4-flash',\n", " 'object': 'chat.completion',\n", " 'service_tier': None,\n", " 'system_fingerprint': None,\n", " 'usage': {'completion_tokens': 154,\n", " 'completion_tokens_details': None,\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': None,\n", " 'total_tokens': 166}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "1c6ebf29-e261-43cf-be7d-c67e38780a3d", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 28, "id": "1a7c199d-9bd1-4b6f-825f-a3522661d603", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:26.210343Z", "iopub.status.busy": "2026-07-06T15:27:26.209737Z", "iopub.status.idle": "2026-07-06T15:27:26.213698Z", "shell.execute_reply": "2026-07-06T15:27:26.212911Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "我是DeepSeek,由深度求索公司创造的AI助手!😊\n", "\n", "我是一个纯文本模型,擅长回答各种问题、提供信息、进行对话交流。虽然我不支持多模态识别(比如直接“看”图片),但我可以处理上传的文件(图像、txt、pdf、ppt、word、excel等),从中读取文字信息来帮你分析。\n", "\n", "我的知识截止日期是2025年5月,拥有1M的上下文长度,可以一次性处理像《三体》三部曲那样体量的书籍。而且我是完全免费的,无论是网页版还是App版都可以使用,App还支持语音输入哦!\n", "\n", "有什么我可以帮你的吗?无论是学习、工作还是日常生活中的问题,我都很乐意协助你!💪\n" ] } ], "source": [ "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "edcc439c-485e-4941-a39c-09c3cb059e3a", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 29, "id": "20087743-44e9-4976-a23a-f903d58f1b19", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:26.215405Z", "iopub.status.busy": "2026-07-06T15:27:26.215282Z", "iopub.status.idle": "2026-07-06T15:27:26.220512Z", "shell.execute_reply": "2026-07-06T15:27:26.219893Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens\n", "输出: 154 tokens\n", "总消耗: 166 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0003 元\n", "预估总成本: ¥0.0003 元\n" ] } ], "source": [ "def print_chat_usage(completion, input_cost=1.0, output_cost=2.0, cache_hit_cost=0.02):\n", " \"\"\"\n", " 参数:\n", " input_cost: 输入价格(元/百万 tokens)\n", " output_cost: 输出价格(元/百万 tokens)\n", " cache_hit_cost: 缓存命中价格(当平台不支持时自动退化到全价模式)\n", "\n", " 按 DeepSeek 聊天模型定价设定默认成本(单位:元):\n", " 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", "\t- 输出: 2元/百万 tokens\n", " 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " \"\"\"\n", " stats = completion.usage\n", "\n", " # 尝试获取字段(兼容其他平台)\n", " hit = getattr(stats, 'prompt_cache_hit_tokens', None) # 无缓存机制的平台没有该字段\n", " has_cache = hit is not None # 注意:命中 0 个时字段仍存在,值为 0\n", " if not has_cache:\n", " hit = 0 # 后续统一按数字处理\n", " miss = getattr(stats, 'prompt_cache_miss_tokens', \n", " stats.prompt_tokens - hit if hasattr(stats, 'prompt_tokens') else 0)\n", "\n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " # 仅在平台提供缓存字段时显示细节\n", " if has_cache:\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " else:\n", " print(f\"输入: {stats.prompt_tokens} tokens\")\n", "\n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", "\n", " # 动态成本计算\n", " input_cost = (hit * cache_hit_cost + miss * input_cost) / 1_000_000\n", " output_cost = stats.completion_tokens * output_cost / 1_000_000\n", " total_cost = input_cost + output_cost\n", "\n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_chat_usage(completion)" ] }, { "cell_type": "markdown", "id": "11b4845a-2920-47d5-9ecf-2cee311444ab", "metadata": {}, "source": [ "### 思考模式" ] }, { "cell_type": "code", "execution_count": 30, "id": "9ce09efe-a8a3-4a3a-be08-e34958958fde", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:26.222320Z", "iopub.status.busy": "2026-07-06T15:27:26.222179Z", "iopub.status.idle": "2026-07-06T15:27:29.598082Z", "shell.execute_reply": "2026-07-06T15:27:29.597457Z" }, "scrolled": true }, "outputs": [], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\", # 3:思考模式(V4 默认开启,无需更换模型)\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 31, "id": "e93c7d4a-66df-4b0f-97ab-6fcab74ad229", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:29.600857Z", "iopub.status.busy": "2026-07-06T15:27:29.600676Z", "iopub.status.idle": "2026-07-06T15:27:29.604379Z", "shell.execute_reply": "2026-07-06T15:27:29.603712Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'flag': 0,\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是DeepSeek,一个由深度求索公司开发的AI助手。我是纯文本模型,可以回答问题、提供信息、协助处理各种任务。我支持文件上传(图像、TXT、PDF、PPT、Word、Excel等),能够从中读取文字信息处理。我的知识截止日期是2025年5月,上下文长度达1M,可以一次性处理超长文本(比如《三体》三部曲)。而且我是完全免费的!如果需要联网搜索,记得在Web或App上手动打开联网功能。有什么我可以帮你的吗?😊',\n", " 'function_call': None,\n", " 'reasoning_content': '嗯,用户问的是“你是谁”,这是一个非常基础的身份询问问题。我需要简单直接地介绍自己,说明我是谁、由谁创造、能做什么,以及我的核心特点。用户可能刚接触我,或者想确认我的功能边界。\\n'\n", " '\\n'\n", " '想到了可以明确名称、创造者、文本模型属性、免费使用、文件处理、知识截止时间、上下文长度和联网搜索支持这些关键信息。回复结构可以自然流畅,最后以友好语气结尾,保持开放帮助的态度。',\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351646,\n", " 'id': 'as-5wenhubdhj',\n", " 'model': 'deepseek-v4-flash',\n", " 'object': 'chat.completion',\n", " 'service_tier': None,\n", " 'system_fingerprint': None,\n", " 'usage': {'completion_tokens': 221,\n", " 'completion_tokens_details': {'accepted_prediction_tokens': None,\n", " 'audio_tokens': None,\n", " 'reasoning_tokens': 100,\n", " 'rejected_prediction_tokens': None},\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': None,\n", " 'total_tokens': 233}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "303550b9-95d6-4ec2-a114-432cbe79de9e", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 32, "id": "9facdcd7-95e8-40d5-ab6c-38c8785db50d", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:29.606324Z", "iopub.status.busy": "2026-07-06T15:27:29.606205Z", "iopub.status.idle": "2026-07-06T15:27:29.609421Z", "shell.execute_reply": "2026-07-06T15:27:29.608715Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "嗯,用户问的是“你是谁”,这是一个非常基础的身份询问问题。我需要简单直接地介绍自己,说明我是谁、由谁创造、能做什么,以及我的核心特点。用户可能刚接触我,或者想确认我的功能边界。\n", "\n", "想到了可以明确名称、创造者、文本模型属性、免费使用、文件处理、知识截止时间、上下文长度和联网搜索支持这些关键信息。回复结构可以自然流畅,最后以友好语气结尾,保持开放帮助的态度。\n", "===== 模型回复 =====\n", "你好!我是DeepSeek,一个由深度求索公司开发的AI助手。我是纯文本模型,可以回答问题、提供信息、协助处理各种任务。我支持文件上传(图像、TXT、PDF、PPT、Word、Excel等),能够从中读取文字信息处理。我的知识截止日期是2025年5月,上下文长度达1M,可以一次性处理超长文本(比如《三体》三部曲)。而且我是完全免费的!如果需要联网搜索,记得在Web或App上手动打开联网功能。有什么我可以帮你的吗?😊\n" ] } ], "source": [ "# 获取推理思考过程(Reasoner特有字段)\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\")\n", "\n", "# 获取模型回复内容(与之前相同)\n", "content = completion.choices[0].message.content\n", "print(f\"===== 模型回复 =====\\n{content}\")" ] }, { "cell_type": "markdown", "id": "f48cc16d-d179-417b-80a7-a4a70c550ccf", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 33, "id": "06600d31-6f52-405d-ac22-674d5adc047e", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:29.612267Z", "iopub.status.busy": "2026-07-06T15:27:29.612109Z", "iopub.status.idle": "2026-07-06T15:27:29.617824Z", "shell.execute_reply": "2026-07-06T15:27:29.617383Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens\n", "输出: 221 tokens\n", "├─ 推理过程: 100 tokens\n", "└─ 最终回答: 121 tokens\n", "总消耗: 233 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0004 元\n", "预估总成本: ¥0.0005 元\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/var/folders/cv/p24b2d5j4hjg9ndjzbbwgplh0000gn/T/ipykernel_73850/1154722965.py:37: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.12/migration/\n", " details = getattr(details, 'dict', lambda: {})()\n" ] } ], "source": [ "def print_reasoner_usage(completion, input_cost=1.0, output_cost=2.0, cache_hit_cost=0.02):\n", " \"\"\"\n", " 参数:\n", " input_cost: 输入价格(元/百万 tokens)\n", " output_cost: 输出价格(元/百万 tokens)\n", " cache_hit_cost: 缓存命中价格(当平台不支持时自动退化到全价模式)\n", "\n", " 按 DeepSeek 推理模型定价设定默认成本(单位:元):\n", " 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", " 输出: 2元/百万 tokens\n", " 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " \"\"\"\n", " stats = completion.usage\n", " \n", " # 尝试获取字段(兼容其他平台)\n", " hit = getattr(stats, 'prompt_cache_hit_tokens', None) # 无缓存机制的平台没有该字段\n", " has_cache = hit is not None # 注意:命中 0 个时字段仍存在,值为 0\n", " if not has_cache:\n", " hit = 0 # 后续统一按数字处理\n", " miss = getattr(stats, 'prompt_cache_miss_tokens', \n", " stats.prompt_tokens - hit if hasattr(stats, 'prompt_tokens') else 0)\n", " \n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " # 仅在平台提供缓存字段时显示细节\n", " if has_cache:\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " else:\n", " print(f\"输入: {stats.prompt_tokens} tokens\")\n", " \n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", "\n", " # 尝试获取推理过程详情\n", " details = getattr(stats, 'completion_tokens_details', None)\n", " reasoning = 0\n", " if details:\n", " if not isinstance(details, dict):\n", " details = getattr(details, 'dict', lambda: {})()\n", " # 尝试获取 reasoning_tokens\n", " reasoning = details.get('reasoning_tokens', 0)\n", " \n", " # 仅在存在推理tokens数量字段时处理\n", " if reasoning > 0:\n", " final = stats.completion_tokens - reasoning\n", " print(f\"├─ 推理过程: {reasoning} tokens\")\n", " print(f\"└─ 最终回答: {final} tokens\")\n", " \n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", " \n", " # 动态成本计算\n", " input_cost_total = (hit * cache_hit_cost + miss * input_cost) / 1_000_000\n", " output_cost_total = stats.completion_tokens * output_cost / 1_000_000\n", " total_cost = input_cost_total + output_cost_total\n", " \n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost_total:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost_total:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_reasoner_usage(completion)" ] }, { "cell_type": "markdown", "id": "d7306ffe-e8a6-495b-b93a-6c442b859150", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# 字节火山引擎" ] }, { "cell_type": "markdown", "id": "965f4726-25bd-47e0-8076-c62dcc24915b", "metadata": {}, "source": [ "## 认识输出" ] }, { "cell_type": "markdown", "id": "12d0d828-1ca6-4e60-9d63-3275e381a9a0", "metadata": {}, "source": [ "### 非思考模式" ] }, { "cell_type": "code", "execution_count": 34, "id": "99952546-851c-41df-8526-cd6fb0456fe8", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:29.620099Z", "iopub.status.busy": "2026-07-06T15:27:29.619991Z", "iopub.status.idle": "2026-07-06T15:27:31.965838Z", "shell.execute_reply": "2026-07-06T15:27:31.964746Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "client = OpenAI(\n", " api_key=\"your-api-key\", # 1:替换成对应的 API_Key,可以使用环境变量而非明文填写,即 api_key=os.getenv(\"SILICONFLOW_API_KEY\")\n", " base_url=\"https://ark.cn-beijing.volces.com/api/v3\" # 2:每个平台的 base_url 不同\n", ")\n", "\n", "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\", # 3:模型标识(model_id)可能存在差异\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 35, "id": "18326f43-c920-4f80-b0b1-16feb9087bcc", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:31.968027Z", "iopub.status.busy": "2026-07-06T15:27:31.967813Z", "iopub.status.idle": "2026-07-06T15:27:31.971939Z", "shell.execute_reply": "2026-07-06T15:27:31.971166Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你解答问题、处理信息、进行对话等。我支持阅读链接、上传文件(图像、txt、pdf、ppt、word、excel等),还能联网搜索(需要手动开启)。我知识截止于2025年5月,版本是DeepSeek最新版。有什么我可以帮你的吗?😊',\n", " 'function_call': None,\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351652,\n", " 'id': '0217833516502681c4c28e26c266d30c807e3f14d371f952919b3',\n", " 'model': 'deepseek-v4-flash-260425',\n", " 'object': 'chat.completion',\n", " 'service_tier': 'default',\n", " 'system_fingerprint': None,\n", " 'usage': {'completion_tokens': 89,\n", " 'completion_tokens_details': {'accepted_prediction_tokens': None,\n", " 'audio_tokens': None,\n", " 'reasoning_tokens': 0,\n", " 'rejected_prediction_tokens': None},\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0},\n", " 'total_tokens': 101}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "78c1acc6-a7ed-4d93-9c59-a371f17ee703", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 36, "id": "460539aa-b1a6-4562-ae68-2c6bdc1710fa", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:31.973874Z", "iopub.status.busy": "2026-07-06T15:27:31.973753Z", "iopub.status.idle": "2026-07-06T15:27:31.976290Z", "shell.execute_reply": "2026-07-06T15:27:31.975599Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你解答问题、处理信息、进行对话等。我支持阅读链接、上传文件(图像、txt、pdf、ppt、word、excel等),还能联网搜索(需要手动开启)。我知识截止于2025年5月,版本是DeepSeek最新版。有什么我可以帮你的吗?😊\n" ] } ], "source": [ "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "0e9caa83-5d62-4f8c-98da-07bce9ed76ad", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 37, "id": "637b7d02-343c-4193-8c3a-13d7c28ed53a", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:31.977843Z", "iopub.status.busy": "2026-07-06T15:27:31.977732Z", "iopub.status.idle": "2026-07-06T15:27:31.982410Z", "shell.execute_reply": "2026-07-06T15:27:31.981742Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens\n", "输出: 89 tokens\n", "总消耗: 101 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0002 元\n", "预估总成本: ¥0.0002 元\n" ] } ], "source": [ "def print_chat_usage(completion, input_cost=1.0, output_cost=2.0, cache_hit_cost=0.02):\n", " \"\"\"\n", " 参数:\n", " input_cost: 输入价格(元/百万 tokens)\n", " output_cost: 输出价格(元/百万 tokens)\n", " cache_hit_cost: 缓存命中价格(当平台不支持时自动退化到全价模式)\n", "\n", " 按 DeepSeek 聊天模型定价设定默认成本(单位:元):\n", " 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", "\t- 输出: 2元/百万 tokens\n", " 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " \"\"\"\n", " stats = completion.usage\n", "\n", " # 尝试获取字段(兼容其他平台)\n", " hit = getattr(stats, 'prompt_cache_hit_tokens', None) # 无缓存机制的平台没有该字段\n", " has_cache = hit is not None # 注意:命中 0 个时字段仍存在,值为 0\n", " if not has_cache:\n", " hit = 0 # 后续统一按数字处理\n", " miss = getattr(stats, 'prompt_cache_miss_tokens', \n", " stats.prompt_tokens - hit if hasattr(stats, 'prompt_tokens') else 0)\n", "\n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " # 仅在平台提供缓存字段时显示细节\n", " if has_cache:\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " else:\n", " print(f\"输入: {stats.prompt_tokens} tokens\")\n", "\n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", "\n", " # 动态成本计算\n", " input_cost = (hit * cache_hit_cost + miss * input_cost) / 1_000_000\n", " output_cost = stats.completion_tokens * output_cost / 1_000_000\n", " total_cost = input_cost + output_cost\n", "\n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_chat_usage(completion)" ] }, { "cell_type": "markdown", "id": "3f7be81a-745f-468c-8e2b-84db9d9d47af", "metadata": {}, "source": [ "### 思考模式" ] }, { "cell_type": "code", "execution_count": 38, "id": "1b323e6d-31f2-41d3-9606-1bade6780599", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:31.984250Z", "iopub.status.busy": "2026-07-06T15:27:31.984145Z", "iopub.status.idle": "2026-07-06T15:27:33.652954Z", "shell.execute_reply": "2026-07-06T15:27:33.651973Z" }, "scrolled": true }, "outputs": [], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\", # 3:思考模式(V4 默认开启,无需更换模型)\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'},\n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 39, "id": "80c8acac-05ea-46ac-bdf2-cde82ac18516", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:33.655138Z", "iopub.status.busy": "2026-07-06T15:27:33.654964Z", "iopub.status.idle": "2026-07-06T15:27:33.658736Z", "shell.execute_reply": "2026-07-06T15:27:33.658045Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'choices': [{'finish_reason': 'stop',\n", " 'index': 0,\n", " 'logprobs': None,\n", " 'message': {'annotations': None,\n", " 'audio': None,\n", " 'content': '你好!我是DeepSeek,由深度求索公司创造的AI助手。很高兴为你服务!有什么问题可以随时问我。😊',\n", " 'function_call': None,\n", " 'reasoning_content': '我们被问到\"你是谁?\"。这是一个简单的自我介绍问题。作为AI助手,我需要友好地介绍自己。注意,用户是中文用户,所以用中文回答。我是DeepSeek,由深度求索公司创造的AI助手。回答要简洁、友好。',\n", " 'refusal': None,\n", " 'role': 'assistant',\n", " 'tool_calls': None}}],\n", " 'created': 1783351653,\n", " 'id': '0217833516523461c4c28e26c266d30c807e3f14d371f956f0649',\n", " 'model': 'deepseek-v4-flash-260425',\n", " 'object': 'chat.completion',\n", " 'service_tier': 'default',\n", " 'system_fingerprint': None,\n", " 'usage': {'completion_tokens': 83,\n", " 'completion_tokens_details': {'accepted_prediction_tokens': None,\n", " 'audio_tokens': None,\n", " 'reasoning_tokens': 55,\n", " 'rejected_prediction_tokens': None},\n", " 'prompt_tokens': 12,\n", " 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0},\n", " 'total_tokens': 95}}\n" ] } ], "source": [ "from pprint import pprint\n", "\n", "pprint(completion.model_dump())" ] }, { "cell_type": "markdown", "id": "e4fc2343-5945-4d3c-8cb5-05667c2acc06", "metadata": {}, "source": [ "#### 获取模型回复(choices)" ] }, { "cell_type": "code", "execution_count": 40, "id": "8a873452-370d-4e51-ae2c-a42c0536b781", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:33.662368Z", "iopub.status.busy": "2026-07-06T15:27:33.662151Z", "iopub.status.idle": "2026-07-06T15:27:33.665653Z", "shell.execute_reply": "2026-07-06T15:27:33.664982Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "我们被问到\"你是谁?\"。这是一个简单的自我介绍问题。作为AI助手,我需要友好地介绍自己。注意,用户是中文用户,所以用中文回答。我是DeepSeek,由深度求索公司创造的AI助手。回答要简洁、友好。\n", "===== 模型回复 =====\n", "你好!我是DeepSeek,由深度求索公司创造的AI助手。很高兴为你服务!有什么问题可以随时问我。😊\n" ] } ], "source": [ "# 获取推理思考过程(Reasoner特有字段)\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\")\n", "\n", "# 获取模型回复内容(与之前相同)\n", "content = completion.choices[0].message.content\n", "print(f\"===== 模型回复 =====\\n{content}\")" ] }, { "cell_type": "markdown", "id": "08821e68-c3b7-4e28-b83f-3f9961102704", "metadata": {}, "source": [ "#### 获取用量信息(usage)" ] }, { "cell_type": "code", "execution_count": 41, "id": "19d1ff7d-c761-41af-bd52-f0615c048138", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:33.668049Z", "iopub.status.busy": "2026-07-06T15:27:33.667898Z", "iopub.status.idle": "2026-07-06T15:27:33.675079Z", "shell.execute_reply": "2026-07-06T15:27:33.674456Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== TOKEN 消耗明细 =====\n", "输入: 12 tokens\n", "输出: 83 tokens\n", "├─ 推理过程: 55 tokens\n", "└─ 最终回答: 28 tokens\n", "总消耗: 95 tokens\n", "\n", "===== 成本明细 =====\n", "输入成本: ¥0.0000 元\n", "输出成本: ¥0.0002 元\n", "预估总成本: ¥0.0002 元\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/var/folders/cv/p24b2d5j4hjg9ndjzbbwgplh0000gn/T/ipykernel_73850/1154722965.py:37: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.12/migration/\n", " details = getattr(details, 'dict', lambda: {})()\n" ] } ], "source": [ "def print_reasoner_usage(completion, input_cost=1.0, output_cost=2.0, cache_hit_cost=0.02):\n", " \"\"\"\n", " 参数:\n", " input_cost: 输入价格(元/百万 tokens)\n", " output_cost: 输出价格(元/百万 tokens)\n", " cache_hit_cost: 缓存命中价格(当平台不支持时自动退化到全价模式)\n", "\n", " 按 DeepSeek 推理模型定价设定默认成本(单位:元):\n", " 输入: 1元/百万 tokens(缓存命中 0.02元/百万 tokens)\n", " 输出: 2元/百万 tokens\n", " 官方价格文档:https://api-docs.deepseek.com/zh-cn/quick_start/pricing/\n", " \"\"\"\n", " stats = completion.usage\n", " \n", " # 尝试获取字段(兼容其他平台)\n", " hit = getattr(stats, 'prompt_cache_hit_tokens', None) # 无缓存机制的平台没有该字段\n", " has_cache = hit is not None # 注意:命中 0 个时字段仍存在,值为 0\n", " if not has_cache:\n", " hit = 0 # 后续统一按数字处理\n", " miss = getattr(stats, 'prompt_cache_miss_tokens', \n", " stats.prompt_tokens - hit if hasattr(stats, 'prompt_tokens') else 0)\n", " \n", " print(f\"===== TOKEN 消耗明细 =====\")\n", " # 仅在平台提供缓存字段时显示细节\n", " if has_cache:\n", " print(f\"输入: {stats.prompt_tokens} tokens [缓存命中: {hit} | 未命中: {miss}]\")\n", " else:\n", " print(f\"输入: {stats.prompt_tokens} tokens\")\n", " \n", " print(f\"输出: {stats.completion_tokens} tokens\")\n", "\n", " # 尝试获取推理过程详情\n", " details = getattr(stats, 'completion_tokens_details', None)\n", " reasoning = 0\n", " if details:\n", " if not isinstance(details, dict):\n", " details = getattr(details, 'dict', lambda: {})()\n", " # 尝试获取 reasoning_tokens\n", " reasoning = details.get('reasoning_tokens', 0)\n", " \n", " # 仅在存在推理tokens数量字段时处理\n", " if reasoning > 0:\n", " final = stats.completion_tokens - reasoning\n", " print(f\"├─ 推理过程: {reasoning} tokens\")\n", " print(f\"└─ 最终回答: {final} tokens\")\n", " \n", " print(f\"总消耗: {stats.total_tokens} tokens\")\n", " \n", " # 动态成本计算\n", " input_cost_total = (hit * cache_hit_cost + miss * input_cost) / 1_000_000\n", " output_cost_total = stats.completion_tokens * output_cost / 1_000_000\n", " total_cost = input_cost_total + output_cost_total\n", " \n", " print(f\"\\n===== 成本明细 =====\")\n", " print(f\"输入成本: ¥{input_cost_total:.4f} 元\")\n", " print(f\"输出成本: ¥{output_cost_total:.4f} 元\")\n", " print(f\"预估总成本: ¥{total_cost:.4f} 元\")\n", "\n", "print_reasoner_usage(completion)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.14" } }, "nbformat": 4, "nbformat_minor": 5 }