{ "cells": [ { "cell_type": "markdown", "id": "bb4b298d-5e1a-4e98-ab64-934804ad626a", "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", "> 在代码运行过程中可能遇到的问题:\n", "> 1. 为什么等待时间那么长?\n", ">\n", "> 答:因为默认参数 `stream=False`,不启用流式输出。对于推理模型来说,非流式输出下的用户体验极其糟糕,故当前代码文件为最后一次非流式输出的代码演示,之后将默认采用流式输出。\n", "> 2. 504 报错:对应服务当前的负载高,可以稍后尝试或者切换平台。\n", "\n", "从下方选择平台开始,替换 `your-api-key` 后点击 `►` 或使用 `Shift + 回车` 运行代码块。\n", "\n", "**注意**:\n", "\n", "- 当前代码为非流式输出。\n", "\n", "在线链接:[Kaggle](https://www.kaggle.com/code/aidemos/deepseek-api-guide-4) | [Colab](https://colab.research.google.com/drive/12HBOxSD-SsVc0qkEhdYBWTRKjQ80gMPw?usp=sharing)" ] }, { "cell_type": "markdown", "id": "b14b6944-18b4-4b04-be0a-c84f577b4986", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# DeepSeek" ] }, { "cell_type": "markdown", "id": "d9e23572-b60b-4fa6-ba69-0182088afc44", "metadata": {}, "source": [ "## 非思考模式" ] }, { "cell_type": "code", "execution_count": 2, "id": "cd3bb2c1-57d1-4be7-a9e8-84bc2b9004fa", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:38.225046Z", "iopub.status.busy": "2026-07-06T15:27:38.224892Z", "iopub.status.idle": "2026-07-06T15:27:38.831788Z", "shell.execute_reply": "2026-07-06T15:27:38.830954Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "# 临时环境变量配置\n", "os.environ[\"DEEPSEEK_API_KEY\"] = \"your-api-key\"\n", "\n", "client = OpenAI(\n", " api_key=os.getenv(\"DEEPSEEK_API_KEY\"),\n", " base_url=\"https://api.deepseek.com\",\n", ")" ] }, { "cell_type": "markdown", "id": "8811ccbe-cfd1-45e4-be3f-c658e69bd6fa", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 3, "id": "5fa2d7da-cce2-404a-a603-f68ed45c1c47", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:38.834040Z", "iopub.status.busy": "2026-07-06T15:27:38.833891Z", "iopub.status.idle": "2026-07-06T15:27:40.383365Z", "shell.execute_reply": "2026-07-06T15:27:40.382615Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是DeepSeek,由深度求索公司创造的AI助手。我在这里为你提供各种帮助,回答问题、处理信息、协助思考,或者就是和你聊聊天。无论你需要什么,尽管问我,我会尽力帮你!😊\n" ] } ], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 打印模型消息\n", "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "3170b31e-0cb5-4be5-b7f1-a8f2d0576e7f", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 4, "id": "8e22b864-d4c2-4815-a00e-f91c25dfa306", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:40.385683Z", "iopub.status.busy": "2026-07-06T15:27:40.385532Z", "iopub.status.idle": "2026-07-06T15:27:44.704538Z", "shell.execute_reply": "2026-07-06T15:27:44.703668Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AI: 这个问题其实是个常见的“陷阱题”,很容易被人误解。\n", "\n", "**如果单纯比较数值大小:** \n", "9.11 和 9.8,9.11 更大。因为 9.11 = 9 + 0.11,而 9.8 = 9 + 0.8,但注意 0.8 = 0.80,而 0.11 < 0.80,所以实际上 **9.8 > 9.11**。\n", "\n", "所以正确答案是:**9.8 更大**。\n", "\n", "但很多人会误以为 9.11 更大,因为觉得“11 > 8”,其实这是忽略了小数点后的位数不同。比较小数时,要从左到右逐位比较: \n", "- 个位:9 = 9 \n", "- 十分位:1 < 8 \n", "所以 9.8 更大。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 我刚才针对的是 **9.11 和 9.8** 这两个数值进行了比较。\n", "\n", "所以回答是:**9.8 更大**,因为 9.8 的十分位是 8,而 9.11 的十分位是 1,所以 9.8 > 9.11。\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)\n", "\n", "# 将第一轮模型回复加入历史记录\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)" ] }, { "cell_type": "markdown", "id": "c3ee8c47-a782-4e91-875e-a99f7e32d6f2", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 5, "id": "78a21713-5256-4e5a-9c4a-60f2c172ca75", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:44.707741Z", "iopub.status.busy": "2026-07-06T15:27:44.707551Z", "iopub.status.idle": "2026-07-06T15:27:46.008286Z", "shell.execute_reply": "2026-07-06T15:27:46.007611Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " # 获取用户输入\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", " \n", " # 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", " \n", " # 调用 API 获取模型回复\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", " )\n", " content = completion.choices[0].message.content\n", " print(\"AI:\", content)\n", " \n", " # 记录模型回复\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "eefec12c-7140-49bf-9a1c-05b080c7f1d1", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 6, "id": "12de2c9c-58e8-43df-b671-ef0cd6491cd6", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:46.010260Z", "iopub.status.busy": "2026-07-06T15:27:46.010121Z", "iopub.status.idle": "2026-07-06T15:27:47.526071Z", "shell.execute_reply": "2026-07-06T15:27:47.525437Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You: 1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You: 再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You: exit\n" ] } ], "source": [ "class ChatSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " content (str): 模型的回复内容\n", " \"\"\"\n", " self.append_message('user', user_input)\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=self.messages\n", " )\n", " content = completion.choices[0].message.content\n", " self.append_message('assistant', content)\n", " return content\n", "\n", "\n", "# 初始化对话会话,采用默认的系统消息\n", "session = ChatSession(client)\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You: \")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", " reply = session.get_response(user_input)\n", " print(\"AI:\", reply)" ] }, { "cell_type": "markdown", "id": "d0a7d31b-0fb6-4415-8011-d1ded410af78", "metadata": {}, "source": [ "## 思考模式" ] }, { "cell_type": "markdown", "id": "e498e26f-60bf-41bd-9974-601b64bd0961", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 7, "id": "52223508-99a5-455b-afe2-f02f216f1820", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:47.527876Z", "iopub.status.busy": "2026-07-06T15:27:47.527762Z", "iopub.status.idle": "2026-07-06T15:27:50.159000Z", "shell.execute_reply": "2026-07-06T15:27:50.158389Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "嗯,用户问“你是谁”,这是一个非常基础的自我介绍问题。用户可能是第一次接触我,或者想确认我的身份和功能。我需要清晰、简洁地说明我是谁、能做什么,同时保持友好和热情。\n", "\n", "想到了直接说明我是DeepSeek,由深度求索公司创造。然后简要概括我的核心特点:免费、纯文本助手、支持文件处理、长上下文等。最后以开放式的提问结尾,邀请用户提出具体需求。\n", "\n", "用自然的语气组织这些信息,避免过于技术化或冗长,让用户快速了解我的能力。\n", "\n", "===== 模型回复 =====\n", "你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你解答问题、处理信息、进行对话交流等。我支持阅读链接、上传文件(图像、txt、pdf、ppt、word、excel等),还能联网搜索(需要手动开启)。我的上下文容量高达1M,可以一次性处理像《三体》三部曲那样体量的书籍。最棒的是,我完全免费使用!有什么我可以帮你的吗?😊\n", "\n" ] } ], "source": [ "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\n{content}\\n\")" ] }, { "cell_type": "markdown", "id": "d4ac0f2b-d933-433b-856c-5c74d98ea995", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 8, "id": "10b95b32-1e4e-4abc-b93a-b385e2e86fde", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:50.160757Z", "iopub.status.busy": "2026-07-06T15:27:50.160639Z", "iopub.status.idle": "2026-07-06T15:27:53.343223Z", "shell.execute_reply": "2026-07-06T15:27:53.342819Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 第一轮推理过程 =====\n", "我们被问到:\"9.11 和 9.8 哪个更大?\" 这是一个简单的问题,但要注意可能有陷阱。通常,比较小数时,9.11和9.8,9.8更大,因为9.8 = 9.80,而9.11 < 9.80。所以答案是9.8更大。但有时人们会误解为版本号或类似的东西,但这里显然是数字。所以回答:9.8更大。\n", "\n", "===== 模型回复 =====\n", "AI: 9.8 更大,因为 9.8 相当于 9.80,而 9.11 小于 9.80。\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 第二轮推理过程 =====\n", "我们需要理解用户的问题。用户问“刚刚针对哪两个数值进行了比较?”指的是上一轮对话中,我比较了9.11和9.8,并指出9.8更大。所以答案是:9.11和9.8。\n", "\n", "===== 模型回复 =====\n", "AI: 刚刚是针对 **9.11** 和 **9.8** 这两个数值进行了比较。\n", "\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第一轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", "# 只将最终的回复(content)加入对话历史\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第二轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")" ] }, { "cell_type": "markdown", "id": "38e1a19a-f138-4e88-b7ec-348d570c7096", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 9, "id": "12d97e64-1841-4633-b828-f432ab33d3ec", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:53.345238Z", "iopub.status.busy": "2026-07-06T15:27:53.345116Z", "iopub.status.idle": "2026-07-06T15:27:55.228947Z", "shell.execute_reply": "2026-07-06T15:27:55.228144Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们要求回答1+1等于几,只回答数字。所以答案是2。\n", "\n", "===== 模型回复 =====\n", "AI: 2\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被问到:\"再加10呢?只回答数字。\" 之前的提问是\"1+1等于几?\" 回答\"2\"。然后\"再加10呢?\" 意思是2+10=12。只回答数字。所以答案应该是12。\n", "\n", "===== 模型回复 =====\n", "AI: 12\n", "\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", "\n", " # 1. 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", "\n", " # 2. 调用 API\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", " )\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 3. 输出推理思考过程与最终回复\n", " print(f\"===== 推理过程 =====\\n{reasoning_content}\\n\")\n", " print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", " # 4. 只将模型的最终回复写入到历史消息中\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "2d12ec5b-de8c-472b-88af-7f81760c5288", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 10, "id": "fd05574d-eb19-4f4a-bf79-2aaf3d77658a", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:55.231136Z", "iopub.status.busy": "2026-07-06T15:27:55.231004Z", "iopub.status.idle": "2026-07-06T15:27:57.125659Z", "shell.execute_reply": "2026-07-06T15:27:57.124901Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们要求只回答数字,所以直接输出2。\n", "\n", "===== 模型回复 =====\n", "AI: 2\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被问到:\"再加10呢?只回答数字。\" 之前的对话是:用户问\"1+1等于几?只回答数字。\" 我们回答了\"2\"。现在用户说\"再加10呢?\" 意思是基于之前的结果2,再加10,即2+10=12。只回答数字。所以回答12。\n", "\n", "===== 模型回复 =====\n", "AI: 12\n", "\n", "You:exit\n" ] } ], "source": [ "class ReasonerSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取思维链和回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " (reasoning_content, content) (tuple): 模型的推理过程和回复\n", " \"\"\"\n", " # 1. 记录用户输入\n", " self.append_message('user', user_input)\n", "\n", " # 2. 调用 API\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=self.messages\n", " )\n", "\n", " # 3. 获取推理思考过程和最终回复\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 4. 只将模型的最终回复加入到历史消息\n", " self.append_message('assistant', content)\n", "\n", " return reasoning_content, content\n", "\n", "\n", "# 初始化推理会话,采用默认的系统消息\n", "session = ReasonerSession(client)\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", "\n", " reasoning, reply = session.get_response(user_input)\n", " print(f\"===== 推理过程 =====\\n{reasoning}\\n\")\n", " print(f\"===== 模型回复 =====\\nAI: {reply}\\n\")" ] }, { "cell_type": "markdown", "id": "502678c3-6645-49b6-a707-6a29f45c3895", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# 硅基流动" ] }, { "cell_type": "markdown", "id": "ff6d162c-a955-4e61-a60b-3d673c6dd871", "metadata": {}, "source": [ "## 非思考模式" ] }, { "cell_type": "code", "execution_count": 11, "id": "8b444291-851d-40c6-86f0-241d4aec1d4d", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:57.127991Z", "iopub.status.busy": "2026-07-06T15:27:57.127866Z", "iopub.status.idle": "2026-07-06T15:27:57.188367Z", "shell.execute_reply": "2026-07-06T15:27:57.187306Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "# 临时环境变量配置\n", "os.environ[\"SILICONFLOW_API_KEY\"] = \"your-api-key\"\n", "\n", "client = OpenAI(\n", " api_key=os.getenv(\"SILICONFLOW_API_KEY\"),\n", " base_url=\"https://api.siliconflow.cn/v1\",\n", ")" ] }, { "cell_type": "markdown", "id": "ea40b539-89f2-4120-be55-d02eadb6610a", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 12, "id": "7a960861-bd20-461a-85b0-1e873d7bafee", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:27:57.190773Z", "iopub.status.busy": "2026-07-06T15:27:57.190591Z", "iopub.status.idle": "2026-07-06T15:28:00.096788Z", "shell.execute_reply": "2026-07-06T15:28:00.095779Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你解答问题、处理信息、进行对话等。虽然我不支持多模态识别(比如直接识别图片内容),但我可以读取链接,也能处理你上传的文件(图像、txt、pdf、ppt、word、excel等),从中提取文字信息。而且我完全免费,上下文长度可达1M,能一次性处理像《三体》三部曲那样体量的书籍。\n", "\n", "有什么我可以帮你的吗?😊\n" ] } ], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 打印模型消息\n", "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "222db473-49b0-4f5e-bb74-1d53fa67e50c", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 13, "id": "b7dda8b6-da57-45ed-81ea-5b9829e3a56c", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:28:00.099309Z", "iopub.status.busy": "2026-07-06T15:28:00.098986Z", "iopub.status.idle": "2026-07-06T15:28:06.037900Z", "shell.execute_reply": "2026-07-06T15:28:06.037148Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AI: 这个问题其实有点陷阱,需要看具体语境:\n", "\n", "1. **如果是比较小数(数学上)**: \n", " 9.11 和 9.8 比较,**9.8 更大**。 \n", " 因为 9.8 = 9.80,而 9.11 < 9.80。\n", "\n", "2. **如果是比较版本号(比如软件版本)**: \n", " 有些地方会把版本号按“数字部分逐段比较”,这时 9.11 可能被认为比 9.8 大(因为 11 > 8)。但这并不是标准数学比较。\n", "\n", "所以,**通常情况下(数学语境)答案是 9.8 更大**。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 刚刚比较的两个数值是 **9.11** 和 **9.8**。\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)\n", "\n", "# 将第一轮模型回复加入历史记录\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)" ] }, { "cell_type": "markdown", "id": "a62411aa-c9af-4312-9164-59127b57b98f", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 14, "id": "7dcf81f2-506b-4e46-8338-77f2d6b91e6a", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:28:06.039425Z", "iopub.status.busy": "2026-07-06T15:28:06.039307Z", "iopub.status.idle": "2026-07-06T15:29:05.855460Z", "shell.execute_reply": "2026-07-06T15:29:05.853923Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " # 获取用户输入\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", " \n", " # 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", " \n", " # 调用 API 获取模型回复\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", " )\n", " content = completion.choices[0].message.content\n", " print(\"AI:\", content)\n", " \n", " # 记录模型回复\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "df1715d9-bdb0-4af2-b9c4-d3292d76e323", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 15, "id": "e5da4161-6b31-4c5a-b895-40dc05e8b3e1", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:05.858553Z", "iopub.status.busy": "2026-07-06T15:29:05.858378Z", "iopub.status.idle": "2026-07-06T15:29:11.749284Z", "shell.execute_reply": "2026-07-06T15:29:11.748561Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You: 1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You: 再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You: exit\n" ] } ], "source": [ "class ChatSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " content (str): 模型的回复内容\n", " \"\"\"\n", " self.append_message('user', user_input)\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=self.messages\n", " )\n", " content = completion.choices[0].message.content\n", " self.append_message('assistant', content)\n", " return content\n", "\n", "\n", "# 初始化对话会话,采用默认的系统消息\n", "session = ChatSession(client)\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You: \")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", " reply = session.get_response(user_input)\n", " print(\"AI:\", reply)" ] }, { "cell_type": "markdown", "id": "fe72a506-7390-497d-b072-f3a913b1b27f", "metadata": {}, "source": [ "## 思考模式" ] }, { "cell_type": "markdown", "id": "70fd3357-93da-4520-bbfa-6f0c5f31c5ed", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 16, "id": "c48ceb51-dbd9-4804-a141-3f3fc57eea0e", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:11.751416Z", "iopub.status.busy": "2026-07-06T15:29:11.751280Z", "iopub.status.idle": "2026-07-06T15:29:21.125636Z", "shell.execute_reply": "2026-07-06T15:29:21.124677Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "嗯,用户问“你是谁”,这是一个非常基础的自我介绍问题。用户可能是初次接触,想了解我的身份和功能。需要简洁清晰地说明我是AI助手,由深度求索公司创造,并说明我的主要能力和特点,比如支持多语言、长文本处理、文件上传等。最后可以表达友好和愿意提供帮助的态度。\n", "\n", "===== 模型回复 =====\n", "你好!我是DeepSeek,由深度求索公司创造的AI助手。我可以帮你解答问题、提供建议、进行对话,或者处理文本任务。我支持处理长文本(比如一次性读完《三体》三部曲)、上传图像、PDF、Word等文件,还能联网搜索(需要你手动开启)。有什么我可以帮你的吗?😊\n", "\n" ] } ], "source": [ "completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"enabled\"}}, # 硅基流动上偶尔不默认思考,所以这里显式开启\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\n{content}\\n\")" ] }, { "cell_type": "markdown", "id": "d9d7b618-ce47-4f86-82b6-8156a1fd2168", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 17, "id": "dd82894a-739c-481c-835d-6bbefa6c1c77", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:21.128186Z", "iopub.status.busy": "2026-07-06T15:29:21.128049Z", "iopub.status.idle": "2026-07-06T15:29:31.241582Z", "shell.execute_reply": "2026-07-06T15:29:31.240736Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 第一轮推理过程 =====\n", "我们被问到:\"9.11 和 9.8 哪个更大?\" 这是一个简单的数字比较问题。9.11和9.8,比较小数部分:9.11的十分位是1,9.8的十分位是8,所以9.8更大。但要注意,有些人可能会误解为版本号或别的,但通常数学上9.8更大。所以答案:9.8更大。\n", "\n", "===== 模型回复 =====\n", "AI: 9.8 更大。因为比较小数时,先看整数部分相同,再看十分位,9.8 的十分位是 8,而 9.11 的十分位是 1,所以 9.8 > 9.11。\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 第二轮推理过程 =====\n", "我们刚刚比较的是9.11和9.8这两个数值。用户问“刚刚针对哪两个数值进行了比较?”,答案就是9.11和9.8。\n", "\n", "===== 模型回复 =====\n", "AI: 刚刚比较的是 **9.11** 和 **9.8** 这两个数值。\n", "\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"enabled\"}}, # 硅基流动上偶尔不默认思考,所以这里显式开启\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第一轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", "# 只将最终的回复(content)加入对话历史\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"enabled\"}}, # 硅基流动上偶尔不默认思考,所以这里显式开启\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第二轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")" ] }, { "cell_type": "markdown", "id": "6b31a73d-9d50-4db2-9eaf-b1b518d0d106", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 18, "id": "efdb2cba-66b4-4207-99b8-339fdb435bd1", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:31.245129Z", "iopub.status.busy": "2026-07-06T15:29:31.244899Z", "iopub.status.idle": "2026-07-06T15:29:33.868569Z", "shell.execute_reply": "2026-07-06T15:29:33.867674Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们要求回答1+1等于几,只输出数字。答案是2。\n", "\n", "===== 模型回复 =====\n", "AI: 2\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被问到:\"再加10呢?只回答数字。\" 前面的对话是:\"1+1等于几?只回答数字。\" 然后回答\"2\"。现在问\"再加10呢?\" 意思是2加10,结果是12。只回答数字。\n", "\n", "===== 模型回复 =====\n", "AI: 12\n", "\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", "\n", " # 1. 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", "\n", " # 2. 调用 API\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"enabled\"}}, # 硅基流动上偶尔不默认思考,所以这里显式开启\n", " messages=messages\n", " )\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 3. 输出推理思考过程与最终回复\n", " print(f\"===== 推理过程 =====\\n{reasoning_content}\\n\")\n", " print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", " # 4. 只将模型的最终回复写入到历史消息中\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "7c8607c0-7697-4031-80e6-bd062c85cd56", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 19, "id": "a1cbfef1-a108-48d6-80a0-6209e1cd60be", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:33.871026Z", "iopub.status.busy": "2026-07-06T15:29:33.870870Z", "iopub.status.idle": "2026-07-06T15:29:37.834668Z", "shell.execute_reply": "2026-07-06T15:29:37.833813Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被问到:\"1+1等于几?只回答数字。\" 所以答案应该是2。只输出数字。\n", "\n", "===== 模型回复 =====\n", "AI: 2\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被要求只回答数字。上一个问题是1+1等于几,回答2。然后问再加10呢?即2+10=12。只回答数字。\n", "\n", "===== 模型回复 =====\n", "AI: 12\n", "\n", "You:exit\n" ] } ], "source": [ "class ReasonerSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取思维链和回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " (reasoning_content, content) (tuple): 模型的推理过程和回复\n", " \"\"\"\n", " # 1. 记录用户输入\n", " self.append_message('user', user_input)\n", "\n", " # 2. 调用 API\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-ai/DeepSeek-V4-Flash\",\n", " extra_body={\"thinking\": {\"type\": \"enabled\"}}, # 硅基流动上偶尔不默认思考,所以这里显式开启\n", " messages=self.messages\n", " )\n", "\n", " # 3. 获取推理思考过程和最终回复\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 4. 只将模型的最终回复加入到历史消息\n", " self.append_message('assistant', content)\n", "\n", " return reasoning_content, content\n", "\n", "\n", "# 初始化推理会话,采用默认的系统消息\n", "session = ReasonerSession(client)\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", "\n", " reasoning, reply = session.get_response(user_input)\n", " print(f\"===== 推理过程 =====\\n{reasoning}\\n\")\n", " print(f\"===== 模型回复 =====\\nAI: {reply}\\n\")" ] }, { "cell_type": "markdown", "id": "668a9b2c-ec58-40cc-96d1-600a984eb161", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# 阿里云百炼" ] }, { "cell_type": "markdown", "id": "9ba21368-4577-439e-a594-58a76226e6b6", "metadata": {}, "source": [ "## 非思考模式" ] }, { "cell_type": "code", "execution_count": 20, "id": "dbfd8aea-b5a0-4664-9026-f5c8cffa0654", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:37.837745Z", "iopub.status.busy": "2026-07-06T15:29:37.837403Z", "iopub.status.idle": "2026-07-06T15:29:37.914573Z", "shell.execute_reply": "2026-07-06T15:29:37.913369Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "# 临时环境变量配置\n", "os.environ[\"DASHSCOPE_API_KEY\"] = \"your-api-key\"\n", "\n", "client = OpenAI(\n", " api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n", " base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n", ")" ] }, { "cell_type": "markdown", "id": "afb3c8ae-c9bd-4718-b7bd-4df6ca34f673", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 21, "id": "b28a6d91-4c59-4f13-8ca9-99feb95356c6", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:37.918848Z", "iopub.status.busy": "2026-07-06T15:29:37.918612Z", "iopub.status.idle": "2026-07-06T15:29:39.501104Z", "shell.execute_reply": "2026-07-06T15:29:39.500194Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是DeepSeek,由深度求索公司创造的AI助手。我是一个纯文本模型,可以帮你解答问题、提供信息、进行对话交流等。我的知识截止日期是2025年5月,目前是DeepSeek最新版本模型。\n", "\n", "有什么我可以帮你的吗?😊\n" ] } ], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 打印模型消息\n", "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "1790ea0a-2ae6-41e6-bd99-d466cd63e9d5", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 22, "id": "387109f2-f41a-4642-8ef7-75e495c9bafb", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:39.503890Z", "iopub.status.busy": "2026-07-06T15:29:39.503704Z", "iopub.status.idle": "2026-07-06T15:29:43.543556Z", "shell.execute_reply": "2026-07-06T15:29:43.542905Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AI: 这个问题其实有点陷阱,要看是在什么语境下。\n", "\n", "- 如果是**小数**比较,9.11 和 9.8,9.8 更大,因为 9.8 = 9.80,而 9.11 < 9.80。\n", "- 如果是**版本号**(比如软件版本),9.11 通常被认为是比 9.8 更新的版本,所以更大。\n", "- 如果是**数字字符串**按字典序比较,则 \"9.11\" 小于 \"9.8\",因为字符 '1' 小于 '8'。\n", "\n", "不过最常见的数学意义上,**9.8 更大**。如果你问的是别的情况,可以再说明一下。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 刚刚比较的两个数值是 **9.11** 和 **9.8**。\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)\n", "\n", "# 将第一轮模型回复加入历史记录\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)" ] }, { "cell_type": "markdown", "id": "be181f77-afb2-4400-b705-4e3b448d262a", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 23, "id": "77519a99-4203-41ab-a7a8-35510c50fdc4", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:43.545430Z", "iopub.status.busy": "2026-07-06T15:29:43.545327Z", "iopub.status.idle": "2026-07-06T15:29:45.648519Z", "shell.execute_reply": "2026-07-06T15:29:45.647598Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " # 获取用户输入\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", " \n", " # 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", " \n", " # 调用 API 获取模型回复\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", " )\n", " content = completion.choices[0].message.content\n", " print(\"AI:\", content)\n", " \n", " # 记录模型回复\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "7f387a5a-fe7d-472c-91a1-6a06ecc56cae", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 24, "id": "3d5ae085-3a1f-4160-9156-bb13a536bc66", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:45.650825Z", "iopub.status.busy": "2026-07-06T15:29:45.650703Z", "iopub.status.idle": "2026-07-06T15:29:47.908515Z", "shell.execute_reply": "2026-07-06T15:29:47.907486Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You: 1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You: 再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You: exit\n" ] } ], "source": [ "class ChatSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " content (str): 模型的回复内容\n", " \"\"\"\n", " self.append_message('user', user_input)\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=self.messages\n", " )\n", " content = completion.choices[0].message.content\n", " self.append_message('assistant', content)\n", " return content\n", "\n", "\n", "# 初始化对话会话,采用默认的系统消息\n", "session = ChatSession(client)\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You: \")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", " reply = session.get_response(user_input)\n", " print(\"AI:\", reply)" ] }, { "cell_type": "markdown", "id": "f0039960-8b0c-453d-963d-ae4f09a6f903", "metadata": {}, "source": [ "## 思考模式" ] }, { "cell_type": "markdown", "id": "021ca2d2-21f6-45e5-ae8e-f037906201be", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 25, "id": "1fe0cd25-e290-4f23-b99b-e98f391091f5", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:47.910598Z", "iopub.status.busy": "2026-07-06T15:29:47.910437Z", "iopub.status.idle": "2026-07-06T15:29:49.841649Z", "shell.execute_reply": "2026-07-06T15:29:49.840822Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "我们被问到\"你是谁?\",这是一个简单的问题。作为AI助手,我需要明确自己的身份。用户可能想知道我的名称、创建者或功能。通常我会回答:我是DeepSeek,由深度求索公司创造的AI助手。我会用友好的语气回答。\n", "\n", "===== 模型回复 =====\n", "你好!我是DeepSeek,由深度求索公司创造的AI助手。我在这里帮助你解答问题、提供信息,以及协助你完成各种任务。无论是学习、工作还是日常生活中的疑问,都可以向我提问,我会尽力提供准确、有用的回答。有什么我可以帮你的吗?😊\n", "\n" ] } ], "source": [ "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\n{content}\\n\")" ] }, { "cell_type": "markdown", "id": "e89e32e5-2fbc-4172-b519-ff0dd50c5ca2", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 26, "id": "a472056d-100c-41b2-87a3-11b48429a2fb", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:49.844231Z", "iopub.status.busy": "2026-07-06T15:29:49.844067Z", "iopub.status.idle": "2026-07-06T15:29:53.661655Z", "shell.execute_reply": "2026-07-06T15:29:53.660865Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 第一轮推理过程 =====\n", "我们比较两个小数:9.11 和 9.8。直观上,9.8 = 9.80,而9.11 < 9.80,所以9.8更大。但有人可能会误解为9.11更大,因为11>8,但实际上是小数比较,先比较整数部分相同,再比较十分位,9.8的十分位是8,9.11的十分位是1,所以9.8大。因此答案是9.8。\n", "\n", "===== 模型回复 =====\n", "AI: 9.8 更大。因为比较小数时,先看整数部分(都是9),然后看十分位,9.8的十分位是8,而9.11的十分位是1,所以9.8 > 9.11。\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 第二轮推理过程 =====\n", "我们刚刚比较了9.11和9.8。用户问“刚刚针对哪两个数值进行了比较?”,所以回答应该是9.11和9.8。\n", "\n", "===== 模型回复 =====\n", "AI: 我们刚刚比较的是 9.11 和 9.8 这两个数值。\n", "\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第一轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", "# 只将最终的回复(content)加入对话历史\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第二轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")" ] }, { "cell_type": "markdown", "id": "bd05db35-06b8-4671-b632-dc84f3faa471", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 27, "id": "8622d231-dae3-45e8-baae-6d2c78780a76", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:53.665912Z", "iopub.status.busy": "2026-07-06T15:29:53.665593Z", "iopub.status.idle": "2026-07-06T15:29:58.450893Z", "shell.execute_reply": "2026-07-06T15:29:58.448326Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们只需要回答数字,所以答案是2。\n", "\n", "===== 模型回复 =====\n", "AI: 2\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "用户问了1+1等于几,我只回答了数字2。现在用户继续问再加10呢,并且要求只回答数字。这是在前一个结果的基础上加10,也就是2+10=12。按照要求,只输出数字,不输出任何其他内容。\n", "\n", "===== 模型回复 =====\n", "AI: 12\n", "\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", "\n", " # 1. 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", "\n", " # 2. 调用 API\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", " )\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 3. 输出推理思考过程与最终回复\n", " print(f\"===== 推理过程 =====\\n{reasoning_content}\\n\")\n", " print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", " # 4. 只将模型的最终回复写入到历史消息中\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "9c4eca43-71aa-4226-a6c7-eb414aebe0f2", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 28, "id": "866b4c99-7d4d-412c-9d1b-0dd12d7310e9", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:29:58.453894Z", "iopub.status.busy": "2026-07-06T15:29:58.453650Z", "iopub.status.idle": "2026-07-06T15:30:00.390011Z", "shell.execute_reply": "2026-07-06T15:30:00.388659Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们要求回答1+1等于几,只回答数字。所以答案是2。\n", "\n", "===== AI回复 =====\n", "AI: 2\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "用户问“再加10”,在之前回答1+1=2的基础上,加10就是12。只输出数字。\n", "\n", "===== AI回复 =====\n", "AI: 12\n", "\n", "You:exit\n" ] } ], "source": [ "class ReasonerSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取思维链和回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " (reasoning_content, content) (tuple): 模型的推理过程和回复\n", " \"\"\"\n", " # 1. 记录用户输入\n", " self.append_message('user', user_input)\n", "\n", " # 2. 调用 API\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=self.messages\n", " )\n", "\n", " # 3. 获取推理思考过程和最终回复\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 4. 只将模型的最终回复加入到历史消息\n", " self.append_message('assistant', content)\n", "\n", " return reasoning_content, content\n", "\n", "\n", "# 初始化推理会话,采用默认的系统消息\n", "session = ReasonerSession(client)\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", "\n", " reasoning, reply = session.get_response(user_input)\n", " print(f\"===== 推理过程 =====\\n{reasoning}\\n\")\n", " print(f\"===== AI回复 =====\\nAI: {reply}\\n\")" ] }, { "cell_type": "markdown", "id": "c196c658-9054-4aaf-89ec-aa715bd8f1e3", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# 百度智能云" ] }, { "cell_type": "markdown", "id": "c2eadd99-8d5f-4e9b-9763-e7a2fb672d19", "metadata": {}, "source": [ "## 非思考模式" ] }, { "cell_type": "code", "execution_count": 29, "id": "4a28226b-1a13-422d-9c50-cddfd7447bb9", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:00.393490Z", "iopub.status.busy": "2026-07-06T15:30:00.393311Z", "iopub.status.idle": "2026-07-06T15:30:00.467884Z", "shell.execute_reply": "2026-07-06T15:30:00.466562Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "# 临时环境变量配置\n", "os.environ[\"BAIDU_API_KEY\"] = \"your-api-key\"\n", "\n", "client = OpenAI(\n", " api_key=os.getenv(\"BAIDU_API_KEY\"),\n", " base_url=\"https://qianfan.baidubce.com/v2\",\n", ")" ] }, { "cell_type": "markdown", "id": "0b35207b-cb22-445f-9b7e-3b26d09b5f07", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 30, "id": "44ac6e82-7408-41b2-b7a1-28698b536de3", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:00.471959Z", "iopub.status.busy": "2026-07-06T15:30:00.471576Z", "iopub.status.idle": "2026-07-06T15:30:01.618225Z", "shell.execute_reply": "2026-07-06T15:30:01.617335Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是 DeepSeek,一个由深度求索公司开发的 AI 助手。我可以帮你回答问题、提供信息、进行对话,或者协助处理各种任务。有什么我可以帮你的吗?😊\n" ] } ], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 打印模型消息\n", "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "becbede1-d20c-4779-aeba-32a8704a4e62", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 31, "id": "4c0ee0cb-cd8a-4268-9d59-7c0a8f006948", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:01.621247Z", "iopub.status.busy": "2026-07-06T15:30:01.620933Z", "iopub.status.idle": "2026-07-06T15:30:04.108798Z", "shell.execute_reply": "2026-07-06T15:30:04.107750Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AI: 9.11 大于 9.8。比较时先看整数部分(都是9),然后比较小数部分:9.11 的小数部分为 0.11,而 9.8 的小数部分为 0.80,因此 9.11 < 9.8? \n", "实际上,9.8 等于 9.80,0.80 大于 0.11,所以 **9.8 更大**。抱歉之前的错误。正确答案是 9.8 更大。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 刚刚针对 **9.11** 和 **9.8** 这两个数值进行了比较。\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)\n", "\n", "# 将第一轮模型回复加入历史记录\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)" ] }, { "cell_type": "markdown", "id": "69a9ea1b-d3a1-47ea-8663-adf063d14a85", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 32, "id": "2adeea2e-34ca-4d6c-b336-6953a2a792d1", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:04.110453Z", "iopub.status.busy": "2026-07-06T15:30:04.110328Z", "iopub.status.idle": "2026-07-06T15:30:05.569523Z", "shell.execute_reply": "2026-07-06T15:30:05.569005Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " # 获取用户输入\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", " \n", " # 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", " \n", " # 调用 API 获取模型回复\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", " )\n", " content = completion.choices[0].message.content\n", " print(\"AI:\", content)\n", " \n", " # 记录模型回复\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "c443c69b-e9cb-4a73-b7db-8c075806f2e1", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 33, "id": "fbf27e5a-51fb-41f0-ae74-efe01bb46cb5", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:05.571365Z", "iopub.status.busy": "2026-07-06T15:30:05.571233Z", "iopub.status.idle": "2026-07-06T15:30:06.511882Z", "shell.execute_reply": "2026-07-06T15:30:06.511090Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You: 1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You: 再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You: exit\n" ] } ], "source": [ "class ChatSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " content (str): 模型的回复内容\n", " \"\"\"\n", " self.append_message('user', user_input)\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=self.messages\n", " )\n", " content = completion.choices[0].message.content\n", " self.append_message('assistant', content)\n", " return content\n", "\n", "\n", "# 初始化对话会话,采用默认的系统消息\n", "session = ChatSession(client)\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You: \")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", " reply = session.get_response(user_input)\n", " print(\"AI:\", reply)" ] }, { "cell_type": "markdown", "id": "1b9e5536-06f8-4701-bc03-c7a5ec13728a", "metadata": {}, "source": [ "## 思考模式" ] }, { "cell_type": "markdown", "id": "54a64dd4-30cd-4666-ad7c-d0cb012ef154", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 34, "id": "68262aa1-14a4-4013-9461-d2fc2ce7cff2", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:06.513797Z", "iopub.status.busy": "2026-07-06T15:30:06.513649Z", "iopub.status.idle": "2026-07-06T15:30:09.069676Z", "shell.execute_reply": "2026-07-06T15:30:09.068657Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "嗯,用户问“你是谁?”,这是一个非常基础的自我介绍问题。用户可能是初次接触,想确认我的身份和功能。我需要简洁清晰地说明自己的名称、创造者、核心能力和特点。\n", "\n", "想到了直接告诉用户我是DeepSeek,由深度求索公司创造,并列举主要功能如对话、文件处理、联网搜索等,同时说明免费和知识截止日期。这样用户能快速了解我能做什么和不能做什么。另外可以加上友好结尾,邀请用户提问。\n", "\n", "===== 模型回复 =====\n", "你好!我是 DeepSeek,由深度求索公司创造的 AI 助手。我可以帮你回答问题、提供信息、创作内容,或者只是聊聊天。我支持处理文本、阅读链接和上传的文件(如图像、PDF、Word 等),还能进行联网搜索(需要你手动开启)。目前我是完全免费的,知识截止于 2025 年 5 月。有什么我可以帮你的吗?😊\n", "\n" ] } ], "source": [ "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\n{content}\\n\")" ] }, { "cell_type": "markdown", "id": "8d49695d-a3fa-40ea-a95d-ec5a7b5a56c2", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 35, "id": "c88b932a-430e-4e0b-a8e7-798810a149a2", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:09.072236Z", "iopub.status.busy": "2026-07-06T15:30:09.072091Z", "iopub.status.idle": "2026-07-06T15:30:12.029845Z", "shell.execute_reply": "2026-07-06T15:30:12.028314Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 第一轮推理过程 =====\n", "我们比较两个数字9.11和9.8。注意这是十进制数,不是版本号。9.8 = 9.80,而9.11 = 9.11,显然9.8更大,因为十分位8大于1。所以9.8 > 9.11。答案:9.8更大。\n", "\n", "===== 模型回复 =====\n", "AI: 9.8 更大。因为比较小数时,先比较整数部分,两者都是9,然后比较十分位,8大于1,所以9.8 > 9.11。\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 第二轮推理过程 =====\n", "我们刚刚比较的是9.11和9.8。用户问“刚刚针对哪两个数值进行了比较?”,所以回答9.11和9.8即可。\n", "\n", "===== 模型回复 =====\n", "AI: 刚刚比较的是 9.11 和 9.8 这两个数值。\n", "\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第一轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", "# 只将最终的回复(content)加入对话历史\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第二轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")" ] }, { "cell_type": "markdown", "id": "2cf8d1e8-45ef-484a-bb9f-bdc794183482", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 36, "id": "5af4cce2-b5db-4138-989b-53ebceee6902", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:12.033810Z", "iopub.status.busy": "2026-07-06T15:30:12.033440Z", "iopub.status.idle": "2026-07-06T15:30:13.615950Z", "shell.execute_reply": "2026-07-06T15:30:13.614922Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们要求只回答数字,所以答案是2。\n", "\n", "===== 模型回复 =====\n", "AI: 2\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被要求只回答数字。第一问已经回答了2,第二问是“再加10呢”,即2+10=12。所以回答12。\n", "\n", "===== 模型回复 =====\n", "AI: 12\n", "\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", "\n", " # 1. 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", "\n", " # 2. 调用 API\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=messages\n", " )\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 3. 输出推理思考过程与最终回复\n", " print(f\"===== 推理过程 =====\\n{reasoning_content}\\n\")\n", " print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", " # 4. 只将模型的最终回复写入到历史消息中\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "f16b814d-ffbe-4c69-8fad-bd2915cdf2af", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 37, "id": "6c60fc72-f2f7-4b8e-a11c-510868225aac", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:13.618875Z", "iopub.status.busy": "2026-07-06T15:30:13.618561Z", "iopub.status.idle": "2026-07-06T15:30:15.276837Z", "shell.execute_reply": "2026-07-06T15:30:15.275975Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们要求只回答数字,所以输出就是2。\n", "\n", "===== AI回复 =====\n", "AI: 2\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被问到:\"再加10呢?只回答数字。\" 前一个问题:\"1+1等于几?只回答数字。\" 回答是2。然后\"再加10呢?\" 意思是在2的基础上加10,所以是12。只回答数字。\n", "\n", "===== AI回复 =====\n", "AI: 12\n", "\n", "You:exit\n" ] } ], "source": [ "class ReasonerSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取思维链和回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " (reasoning_content, content) (tuple): 模型的推理过程和回复\n", " \"\"\"\n", " # 1. 记录用户输入\n", " self.append_message('user', user_input)\n", "\n", " # 2. 调用 API\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-v4-flash\",\n", " messages=self.messages\n", " )\n", "\n", " # 3. 获取推理思考过程和最终回复\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 4. 只将模型的最终回复加入到历史消息\n", " self.append_message('assistant', content)\n", "\n", " return reasoning_content, content\n", "\n", "\n", "# 初始化推理会话,采用默认的系统消息\n", "session = ReasonerSession(client)\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", "\n", " reasoning, reply = session.get_response(user_input)\n", " print(f\"===== 推理过程 =====\\n{reasoning}\\n\")\n", " print(f\"===== AI回复 =====\\nAI: {reply}\\n\")" ] }, { "cell_type": "markdown", "id": "3e531cf4-a20e-4647-9bc1-0389b6caaab2", "metadata": {}, "source": [ "# 字节火山引擎" ] }, { "cell_type": "markdown", "id": "ffde8cc5-4f58-4ad8-8e02-59ad0b084c66", "metadata": {}, "source": [ "## 非思考模式" ] }, { "cell_type": "code", "execution_count": 38, "id": "4d59241c-2c82-4dd3-9b9d-0c1ea3ebb1b0", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:15.279192Z", "iopub.status.busy": "2026-07-06T15:30:15.278941Z", "iopub.status.idle": "2026-07-06T15:30:15.351346Z", "shell.execute_reply": "2026-07-06T15:30:15.350512Z" } }, "outputs": [], "source": [ "from openai import OpenAI\n", "import os\n", "\n", "# 临时环境变量配置\n", "os.environ[\"ARK_API_KEY\"] = \"your-api-key\"\n", "\n", "client = OpenAI(\n", " api_key=os.getenv(\"ARK_API_KEY\"),\n", " base_url=\"https://ark.cn-beijing.volces.com/api/v3\",\n", ")" ] }, { "cell_type": "markdown", "id": "79b317e8-c526-49c1-bca8-7fa18cadd1d7", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 39, "id": "a1b0169f-23d9-4d18-81f5-687c1031ab4e", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:15.353693Z", "iopub.status.busy": "2026-07-06T15:30:15.353565Z", "iopub.status.idle": "2026-07-06T15:30:17.740264Z", "shell.execute_reply": "2026-07-06T15:30:17.739557Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "你好!我是DeepSeek,由深度求索公司创造的AI助手。😊\n", "\n", "我是一个纯文本模型,可以帮你回答各种问题、进行对话、处理文字信息等。我的知识截止日期是2025年5月,拥有1M的上下文窗口,能够一次性处理像《三体》三部曲那样体量的超长文本。\n", "\n", "我支持文件上传(图像、txt、pdf、ppt、word、excel等),可以从中读取文字信息进行处理。我还支持联网搜索功能(需要你在Web/App端手动点开联网搜索按键),以及阅读链接内容。\n", "\n", "最重要的是,我完全免费使用!你可以在官方应用商店下载App,App端还支持语音输入功能。\n", "\n", "有什么我可以帮你的吗?😊\n" ] } ], "source": [ "# 单轮对话示例\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 打印模型消息\n", "print(completion.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "a75f4439-1aff-4a42-ac40-b4da3af4ead5", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 40, "id": "9c5d8560-2d45-431a-9eff-dc86c49c9fed", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:17.743445Z", "iopub.status.busy": "2026-07-06T15:30:17.743257Z", "iopub.status.idle": "2026-07-06T15:30:21.300065Z", "shell.execute_reply": "2026-07-06T15:30:21.299091Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AI: 这个问题其实是一个常见的小陷阱。从数字大小来看,**9.11 比 9.8 小**,而不是更大。\n", "\n", "解释一下:\n", "- 比较小数时,先比较整数部分:都是 9。\n", "- 然后比较小数部分:9.11 的小数部分是 0.11,9.8 的小数部分是 0.8。\n", "- 0.11 < 0.8,所以 **9.8 更大**。\n", "\n", "很多人会误以为 9.11 更大,是因为把 9.11 看成了“9 点 11”,而 9.8 看成了“9 点 8”,但按十进制小数比较,9.8 = 9.80,确实大于 9.11。\n", "\n", "所以答案是:**9.8 更大**。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 刚刚比较的两个数值是 **9.11** 和 **9.8**。\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)\n", "\n", "# 将第一轮模型回复加入历史记录\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", ")\n", "content = completion.choices[0].message.content\n", "print(\"AI:\", content)" ] }, { "cell_type": "markdown", "id": "03a01d98-2b66-4452-af45-96a69803273b", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 41, "id": "6a330243-c55f-4c3d-9090-50f4279c30c3", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:21.302023Z", "iopub.status.busy": "2026-07-06T15:30:21.301904Z", "iopub.status.idle": "2026-07-06T15:30:22.567706Z", "shell.execute_reply": "2026-07-06T15:30:22.567214Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " # 获取用户输入\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", " \n", " # 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", " \n", " # 调用 API 获取模型回复\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=messages\n", " )\n", " content = completion.choices[0].message.content\n", " print(\"AI:\", content)\n", " \n", " # 记录模型回复\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "20ade4bd-bd3e-4c7a-8ac8-b35394b6fc40", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 42, "id": "d984c929-e834-4fdc-8747-5f444abca036", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:22.569563Z", "iopub.status.busy": "2026-07-06T15:30:22.569449Z", "iopub.status.idle": "2026-07-06T15:30:23.957792Z", "shell.execute_reply": "2026-07-06T15:30:23.956862Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话,输入 'exit' 或 'quit' 结束对话。\n", "You: 1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 2\n", "You: 再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "AI: 12\n", "You: exit\n" ] } ], "source": [ "class ChatSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " content (str): 模型的回复内容\n", " \"\"\"\n", " self.append_message('user', user_input)\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " extra_body={\"thinking\": {\"type\": \"disabled\"}}, # 关闭思考\n", " messages=self.messages\n", " )\n", " content = completion.choices[0].message.content\n", " self.append_message('assistant', content)\n", " return content\n", "\n", "\n", "# 初始化对话会话,采用默认的系统消息\n", "session = ChatSession(client)\n", "\n", "print(\"开始对话,输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You: \")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", " reply = session.get_response(user_input)\n", " print(\"AI:\", reply)" ] }, { "cell_type": "markdown", "id": "92ce4689-2261-499c-8519-d27c3edcf1c5", "metadata": {}, "source": [ "## 思考模式" ] }, { "cell_type": "markdown", "id": "1624fcf7-d91b-41c2-be58-8f9f51043a01", "metadata": {}, "source": [ "### 单轮对话" ] }, { "cell_type": "code", "execution_count": 43, "id": "57e4f515-589a-44ba-b283-a3c920323926", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:23.959706Z", "iopub.status.busy": "2026-07-06T15:30:23.959572Z", "iopub.status.idle": "2026-07-06T15:30:25.495348Z", "shell.execute_reply": "2026-07-06T15:30:25.494469Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 模型推理过程 =====\n", "我们被问到:\"你是谁?\" 这是一个简单的自我介绍问题。作为AI助手,我应该友好地回应,说明自己的身份和功能。\n", "\n", "===== 模型回复 =====\n", "你好!我是 DeepSeek,一个由深度求索公司创造的 AI 助手。我可以帮你解答问题、提供信息、处理文本、分析数据等等。有什么我可以帮你的吗?😊\n", "\n" ] } ], "source": [ "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " messages=[\n", " {'role': 'system', 'content': 'You are a helpful assistant.'}, \n", " {'role': 'user', 'content': '你是谁?'}\n", " ]\n", ")\n", "\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 模型推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\n{content}\\n\")" ] }, { "cell_type": "markdown", "id": "9fa07faa-a1b0-4f11-bcac-937b44e69d59", "metadata": {}, "source": [ "### 两轮对话" ] }, { "cell_type": "code", "execution_count": 44, "id": "be56e2e6-5336-46c0-a48d-033f2afc9812", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:25.497162Z", "iopub.status.busy": "2026-07-06T15:30:25.497030Z", "iopub.status.idle": "2026-07-06T15:30:30.548948Z", "shell.execute_reply": "2026-07-06T15:30:30.547073Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "===== 第一轮推理过程 =====\n", "我们被问到:\"9.11 和 9.8 哪个更大?\" 这是一个简单的问题,但需要注意数字的表示。9.11和9.8,通常比较小数时,9.8 = 9.80,而9.11 < 9.80,所以9.8更大。但有时人们会误解为版本号或类似的东西,但这里显然是十进制数。所以答案是9.8更大。\n", "\n", "===== 模型回复 =====\n", "AI: 9.8 更大,因为 9.8 相当于 9.80,而 9.11 小于 9.80。\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 第二轮推理过程 =====\n", "我们刚刚比较的是9.11和9.8。用户问“刚刚针对哪两个数值进行了比较?”,需要明确指出是9.11和9.8。\n", "\n", "===== 模型回复 =====\n", "AI: 刚刚比较的是 **9.11** 和 **9.8** 这两个数值。\n", "\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "# 第一轮对话\n", "messages.append({'role': 'user', 'content': '9.11 和 9.8 哪个更大?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第一轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", "# 只将最终的回复(content)加入对话历史\n", "messages.append({'role': 'assistant', 'content': content})\n", "\n", "# 第二轮对话\n", "messages.append({'role': 'user', 'content': '刚刚针对哪两个数值进行了比较?'})\n", "completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " messages=messages\n", ")\n", "# 获取推理思考过程和模型回复\n", "reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", "content = completion.choices[0].message.content\n", "\n", "print(f\"===== 第二轮推理过程 =====\\n{reasoning_content}\\n\")\n", "print(f\"===== 模型回复 =====\\nAI: {content}\\n\")" ] }, { "cell_type": "markdown", "id": "0fef03e7-de0a-4c3d-9c49-eaed07d24a08", "metadata": {}, "source": [ "### 多轮对话" ] }, { "cell_type": "code", "execution_count": 45, "id": "6b522d2f-f264-48dd-ae2d-8a7dc918e387", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:30.553337Z", "iopub.status.busy": "2026-07-06T15:30:30.553106Z", "iopub.status.idle": "2026-07-06T15:30:32.479946Z", "shell.execute_reply": "2026-07-06T15:30:32.478701Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们要求只回答数字,所以直接输出2。\n", "\n", "===== 模型回复 =====\n", "AI: 2.0\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被问到:\"再加10呢?只回答数字。\" 前面有1+1等于2,再加10就是12。所以答案应该是12。\n", "\n", "===== 模型回复 =====\n", "AI: 12.0\n", "\n", "You:exit\n" ] } ], "source": [ "# 初始化对话历史,包含系统消息\n", "messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']:\n", " break\n", "\n", " # 1. 记录用户输入\n", " messages.append({'role': 'user', 'content': user_input})\n", "\n", " # 2. 调用 API\n", " completion = client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " messages=messages\n", " )\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 3. 输出推理思考过程与最终回复\n", " print(f\"===== 推理过程 =====\\n{reasoning_content}\\n\")\n", " print(f\"===== 模型回复 =====\\nAI: {content}\\n\")\n", "\n", " # 4. 只将模型的最终回复写入到历史消息中\n", " messages.append({'role': 'assistant', 'content': content})" ] }, { "cell_type": "markdown", "id": "0577a773-f052-409b-bf36-e5733b40e4a2", "metadata": {}, "source": [ "### 封装对话逻辑" ] }, { "cell_type": "code", "execution_count": 46, "id": "f1f23a67-d853-4d84-a8f0-51c83b0d1ceb", "metadata": { "execution": { "iopub.execute_input": "2026-07-06T15:30:32.483978Z", "iopub.status.busy": "2026-07-06T15:30:32.483766Z", "iopub.status.idle": "2026-07-06T15:30:34.996790Z", "shell.execute_reply": "2026-07-06T15:30:34.994770Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\n", "You:1+1等于几?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们要求只回答数字,所以直接输出结果。1+1=2。\n", "\n", "===== AI回复 =====\n", "AI: 2.\n", "\n", "You:再加10呢?只回答数字。\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "===== 推理过程 =====\n", "我们被问到:\"再加10呢?只回答数字。\" 前一个问题是\"1+1等于几?\" 我们回答2。然后\"再加10呢?\" 意思是2+10=12。只回答数字。\n", "\n", "===== AI回复 =====\n", "AI: 12.\n", "\n", "You:exit\n" ] } ], "source": [ "class ReasonerSession:\n", " def __init__(self, client, system_message=\"You are a helpful assistant.\"):\n", " \"\"\"\n", " 参数:\n", " client (openai.OpenAI): OpenAI 客户端实例\n", " system_message (str): 系统消息,用于设定对话背景\n", " \"\"\"\n", " self.client = client\n", " self.messages = [{'role': 'system', 'content': system_message}]\n", "\n", " def append_message(self, role, content):\n", " \"\"\"\n", " 添加一条对话消息\n", " 参数:\n", " role (str): 消息角色,为 'user' 或 'assistant'\n", " content (str): 消息内容\n", " \"\"\"\n", " self.messages.append({'role': role, 'content': content})\n", "\n", " def get_response(self, user_input):\n", " \"\"\"\n", " 添加用户消息,调用 API 获取思维链和回复,并将回复加入历史记录\n", " 参数:\n", " user_input (str): 用户输入的消息\n", " 返回:\n", " (reasoning_content, content) (tuple): 模型的推理过程和回复\n", " \"\"\"\n", " # 1. 记录用户输入\n", " self.append_message('user', user_input)\n", "\n", " # 2. 调用 API\n", " completion = self.client.chat.completions.create(\n", " model=\"deepseek-v4-flash-260425\",\n", " messages=self.messages\n", " )\n", "\n", " # 3. 获取推理思考过程和最终回复\n", " reasoning_content = getattr(completion.choices[0].message, 'reasoning_content', None)\n", " content = completion.choices[0].message.content\n", "\n", " # 4. 只将模型的最终回复加入到历史消息\n", " self.append_message('assistant', content)\n", "\n", " return reasoning_content, content\n", "\n", "\n", "# 初始化推理会话,采用默认的系统消息\n", "session = ReasonerSession(client)\n", "\n", "print(\"开始对话(Reasoner),输入 'exit' 或 'quit' 结束对话。\")\n", "while True:\n", " user_input = input(\"You:\")\n", " if user_input.lower() in ['exit', 'quit']: # 退出条件\n", " break\n", "\n", " reasoning, reply = session.get_response(user_input)\n", " print(f\"===== 推理过程 =====\\n{reasoning}\\n\")\n", " print(f\"===== AI回复 =====\\nAI: {reply}\\n\")" ] } ], "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.12.0" } }, "nbformat": 4, "nbformat_minor": 5 }