Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

native-reasoning-docs.json

19 lines304.6 KB

1{
2 "https://www.alibabacloud.com/help/en/model-studio/deep-thinking.md": "# Deep thinking\n\n> Deep thinking models reason before responding, improving accuracy on complex tasks like logical reasoning and math.\n\n> This article describes how to call the Deep Think model via the OpenAI-compatible Chat Completion interface or the DashScope interface. For Responses API usage, see: [Deep Think](/help/en/model-studio/compatibility-with-openai-responses-api#example-deep-thinking-title).\n\n## Demo <span id=\"h2_demo_deep_thinking\" /> <span id=\"6ef656ea609ps\" />\n\nThe following is a conversation example of the Deep Think model, showing how the model first performs reasoning and then gives an answer.\n\n<table style={{ display: \"table\", tableLayout: \"fixed\", width: \"100%\", overflowWrap: \"anywhere\" }}><colgroup><col style={{ width: \"100%\" }} /></colgroup><tbody><tr><td style={{ verticalAlign: \"top\" }}><p><strong>User Question</strong></p> <p>9.9 and 9.11, which is larger?</p> <p><strong>Thinking Process</strong> (reasoning\\_content field)</p> <p>First, the user's question is: \"9.9 and 9.11, which is larger\", which appears to be comparing two numbers: 9.9 and 9.11.</p> <p>I need to understand the meaning of these numbers. In mathematics, 9.9 is equivalent to 9.90, and 9.11 is 9.11.</p> <p>To compare them, I should treat them as decimals. 9.9 is 9 + 9/10 = 9.9, while 9.11 is 9 + 11/100 = 9.11.</p> <p>Now, compare 9.9 and 9.11: 9.9 is equal to 9.90 (because 9.9 = 9.90), and 9.11 is 9.11. Now, compare 9.90 with 9.11: 9.90 is greater than 9.11, because 90/100 > 11/100.</p> <p>More precisely: 9.9 = 99/10 = 990/100, 9.11 = 911/100, compare 990/100 with 911/100, obviously 990 > 911, so 990/100 > 911/100, therefore 9.9 > 9.11.</p> <p>I can also look directly at the decimal part: the decimal part of 9.9 is 0.9, and the decimal part of 9.11 is 0.11. 0.9 is greater than 0.11, because 0.9 = 0.90 > 0.11.</p> <p>So, 9.9 is greater than 9.11.</p> <p><strong>Model response</strong>(content field)</p> <p>Conclusion: 9.9 is greater than 9.11.</p></td></tr></tbody></table>\n\n## Usage <span id=\"bf233b1632s0l\" /> <span id=\"95782ce75246y\" />\n\nThe Bailian Deep Think Model is divided into two modes:\n\n- <strong>Mixed Thinking Mode</strong>: Thinking can be enabled or disabled per request, and the control parameters vary by model. The following example uses `enable_thinking`, the values are as follows:\n\n - Set to`true`: the model thinks before responding;\n - Set to`false`: the model responds directly;\n\n <Tabs>\n <Tab title=\"OpenAI Compatible\">\n ```python\n # 导入依赖与创建客户端...\n completion = client.chat.completions.create(\n model=\"qwen3.8-max\", # 选择模型\n messages=[{\"role\": \"user\", \"content\": \"你是谁\"}],\n # 由于 enable_thinking 非 OpenAI 标准参数,需要通过 extra_body 传入\n extra_body={\"enable_thinking\":True},\n # 流式输出方式调用\n stream=True,\n # 使流式返回的最后一个数据包包含Token消耗信息\n stream_options={\n \"include_usage\": True\n }\n )\n ```\n </Tab>\n\n <Tab title=\"DashScope\">\n > Qwen3.5 series DashScope API uses a multimodal interface, the following example will throw an error `url error`. For the calling method, please refer to [Enable/Disable Thinking Mode](/help/en/model-studio/vision#bc67a9a2bd2of).\n\n ```python\n # 导入依赖...\n\n response = MultiModalConversation.call(\n # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key = \"sk-xxx\",\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n # 可按需更换为其它深度思考模型\n model=\"qwen3.8-max\",\n messages=messages,\n enable_thinking=True,\n stream=True,\n incremental_output=True\n )\n ```\n </Tab>\n </Tabs>\n- <strong>Thinking-only mode</strong>: The model always thinks before replying and cannot be disabled. Except that you do not need to set the `enable_thinking` parameter, the request format is consistent with the hybrid thinking mode.\n\nThe thinking content is returned through the`reasoning_content`field, and the reply content is returned through the`content`field. Deep Think requires additional reasoning time. The examples in this article use streaming calling by default (recommended, you can view the Thinking Process in real time and avoid long waits). The commercial Deep Think model also supports non-streaming (synchronous) Output. For usage and precautions, see the<strong>FAQ</strong>below; some models (such as qwen3-235b-a22b, qwen3-32b and other open-source versions) only support Stream Output, and non-streaming calling will report an error.\n\n## Supported Models <span id=\"78286fdc35hlw\" /> <span id=\"e77086fb2f2at\" />\n\n<Tabs>\n <Tab title=\"Qwen3.8\">\n <strong>Qwen3.8 Max Series</strong> (Hybrid thinking mode, <strong>thinking mode enabled by default</strong>): qwen3.8-max\n\n <strong>Qwen3.8 Flash series</strong> (Hybrid thinking mode, <strong>thinking mode enabled by default</strong>): qwen3.8-flash\n\n <strong>Qwen3.8 open-source series</strong> (Hybrid thinking mode, <strong>thinking mode enabled by default</strong>): qwen3.8-27b\n\n <strong>Qwen3.8 open-source series</strong> (<strong>Supports thinking mode only</strong>): qwen3.8-2.4t-a95b\n\n <strong>Qwen3.8 Omni series</strong> (Hybrid thinking mode, <strong>thinking mode enabled by default</strong>): qwen3.8-omni-flash. Adjust thinking effort via `reasoning_effort`. For more information, see [Thinking mode configuration](/help/en/model-studio/qwen-omni#bc67a9a2bd2of).\n </Tab>\n\n <Tab title=\"Qwen3.7\">\n <strong>Qwen3.7 Max series</strong> (Hybrid thinking mode, <strong>thinking mode enabled by default</strong>): qwen3.7-max, qwen3.7-max-2026-05-20, qwen3.7-max-2026-06-08\n\n <strong>Qwen3.7 Max series</strong> (<strong>Only thinking mode supported</strong>): qwen3.7-max-preview, qwen3.7-max-2026-05-17\n\n <strong>Qwen3.7 Plus series</strong> (Hybrid thinking mode, <strong>thinking mode enabled by default</strong>): qwen3.7-plus, qwen3.7-plus-2026-05-26\n\n <strong>Qwen3.7 Flash series</strong> (Hybrid thinking mode, <strong>thinking mode enabled by default</strong>): qwen3.7-flash, qwen3.7-flash-2026-07-15\n </Tab>\n\n <Tab title=\"Qwen3.6\">\n <strong>Qwen3.6 Max series</strong> (Hybrid thinking mode, <strong>thinking mode enabled by default</strong>): qwen3.6-max-preview\n\n <strong>Qwen3.6 Plus Series</strong> (Hybrid Thinking Mode, <strong>Thinking mode enabled by default</strong>): qwen3.6-plus, qwen3.6-plus-2026-04-02\n\n <strong>Qwen3.6 Flash Series</strong> (Hybrid Thinking Mode, <strong>Thinking mode enabled by default</strong>): qwen3.6-flash, qwen3.6-flash-2026-04-16\n\n <strong>Qwen3.6 Open Source Edition</strong>: qwen3.6-35b-a3b\n </Tab>\n\n <Tab title=\"Qwen3.5\">\n - <strong>Commercial Edition</strong>\n\n - <strong>Qwen3.5 Plus Series</strong> (Hybrid Thinking Mode, <strong>Thinking mode enabled by default</strong>): qwen3.5-plus, qwen3.5-plus-2026-02-15\n - <strong>Qwen3.5 Flash series</strong> (Hybrid thinking mode, <strong>Thinking mode enabled by default</strong>): qwen3.5-flash, qwen3.5-flash-2026-02-23\n - <strong>Open-source version</strong>\n\n - Hybrid thinking mode, <strong>Thinking mode enabled by default</strong>: qwen3.5-397b-a17b, qwen3.5-122b-a10b, qwen3.5-27b, qwen3.5-35b-a3b\n </Tab>\n\n <Tab title=\"Qwen3\">\n - <strong>Commercial version</strong>\n\n - <strong>Qwen Max series</strong>: qwen3-max, qwen3-max-2026-01-23, qwen3-max-preview (Hybrid thinking mode, thinking mode disabled by default)\n - <strong>Qwen Plus Series</strong> (Hybrid thinking mode, thinking mode not enabled by default): qwen-plus, qwen-plus-latest, qwen-plus-2025-04-28 and later snapshot models\n - <strong>Qwen Flash Series</strong> (Hybrid thinking mode, thinking mode not enabled by default): qwen-flash, qwen-flash-2025-07-28 and later snapshot models\n - <strong>Qwen Turbo Series</strong> (Hybrid thinking mode, thinking mode not enabled by default): qwen-turbo and later snapshot models\n - <strong>Open Source Version</strong>\n\n - Hybrid thinking mode, thinking mode enabled by default: qwen3-235b-a22b, qwen3-32b, qwen3-30b-a3b, qwen3-14b, qwen3-8b\n - Thinking mode only: qwen3-next-80b-a3b-thinking, qwen3-235b-a22b-thinking-2507, qwen3-30b-a3b-thinking-2507\n </Tab>\n\n <Tab title=\"QwQ (based on Qwen2.5)\">\n Thinking mode only: qwq-plus\n </Tab>\n\n <Tab title=\"DeepSeek\">\n - Hybrid thinking mode, thinking mode enabled by default: deepseek-v4.1-flash, deepseek-v4-pro, deepseek-v4-flash\n - Hybrid thinking mode, thinking mode not enabled by default: deepseek-v3.2, deepseek-v3.2-exp, deepseek-v3.1\n - Thinking-only mode: deepseek-r1, deepseek-r1-0528, deepseek-r1 distillation models\n </Tab>\n\n <Tab title=\"GLM\">\n - Thinking-only mode: glm-5.3\n - Hybrid thinking mode, thinking mode enabled by default: glm-5.2, glm-5.2-fast-preview, glm-5.1, glm-5, glm-4.7, glm-4.6\n </Tab>\n\n <Tab title=\"Kimi\">\n - Hybrid thinking mode, thinking mode disabled by default: kimi-k2.6, kimi-k2.5\n - Thinking-only mode: kimi-k2.7-code, kimi-k2-thinking\n </Tab>\n\n <Tab title=\"MiniMax\">\n Thinking-only mode: MiniMax-M2.5\n </Tab>\n</Tabs>\n\n## Quick Start <span id=\"0be77a07d89w8\" /> <span id=\"a0acb1327ftxx\" />\n\nAPI usage prerequisite: Already[Obtain and Configure API Key](/help/en/model-studio/get-api-key)and complete[Configure API Key to environment variables](/help/en/model-studio/get-api-key). If Pass SDK Calling, need[Install OpenAI Or DashScope SDK](/help/en/model-studio/install-sdk)(DashScope Java SDK requires at least 2.19.4 Version).\n\nThe following code uses stream Calling qwen3.8-max Enable thinking mode as an example.\n\n<Tabs>\n <Tab title=\"OpenAI Compatible\">\n <Tabs>\n <Tab title=\"Python\">\n ### Sample Code <span id=\"476b0d8764uct\" /> <span id=\"f10ba272f6uu6\" />\n\n ```python expandable\n from openai import OpenAI\n import os\n\n # 初始化OpenAI客户端\n client = OpenAI(\n # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key\n # 如果没有配置环境变量,请用阿里云百炼API Key替换:api_key=\"sk-xxx\"\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n base_url=\"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1\",\n )\n\n messages = [{\"role\": \"user\", \"content\": \"你是谁\"}]\n\n completion = client.chat.completions.create(\n model=\"qwen3.8-max\", # 您可以按需更换为其它深度思考模型\n messages=messages,\n extra_body={\"enable_thinking\": True},\n stream=True,\n stream_options={\n \"include_usage\": True\n },\n )\n\n reasoning_content = \"\" # 完整思考过程\n answer_content = \"\" # 完整回复\n is_answering = False # 是否进入回复阶段\n print(\"\\n\" + \"=\" * 20 + \"思考过程\" + \"=\" * 20 + \"\\n\")\n\n for chunk in completion:\n if not chunk.choices:\n print(\"\\nUsage:\")\n print(chunk.usage)\n continue\n\n delta = chunk.choices[0].delta\n\n # 只收集思考内容\n if hasattr(delta, \"reasoning_content\") and delta.reasoning_content is not None:\n if not is_answering:\n print(delta.reasoning_content, end=\"\", flush=True)\n reasoning_content += delta.reasoning_content\n\n # 收到content,开始进行回复\n if hasattr(delta, \"content\") and delta.content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"完整回复\" + \"=\" * 20 + \"\\n\")\n is_answering = True\n print(delta.content, end=\"\", flush=True)\n answer_content += delta.content\n ```\n\n ### Response <span id=\"0a46d1b6d1jwu\" /> <span id=\"b3c846e0cfpsc\" />\n\n ```plaintext\n ====================思考过程====================\n\n 好的,用户问“你是谁”,我需要给出一个准确且友好的回答。首先,我要确认自己的身份,即千问,由阿里巴巴集团旗下的通义实验室研发。接下来,应该说明我的主要功能,比如回答问题、创作文字、逻辑推理等。同时,要保持语气亲切,避免过于技术化,让用户感觉轻松。还要注意不要使用复杂术语,确保回答简洁明了。另外,可能需要加入一些互动元素,邀请用户提问,促进进一步交流。最后,检查是否有遗漏的重要信息,比如我的中文名称“千问”和英文名称“Qwen”,以及所属公司和实验室。确保回答全面且符合用户期望。\n ====================完整回复====================\n\n 你好!我是千问,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以回答问题、创作文字、进行逻辑推理、编程等,旨在为用户提供高质量的信息和服务。你可以叫我Qwen,或者直接叫我千问。有什么我可以帮你的吗?\n ```\n </Tab>\n\n <Tab title=\"Node.js\">\n ### Sample Code <span id=\"aa3379a8a8m8l\" /> <span id=\"8f86ee2cee7b8\" />\n\n ```javascript expandable\n import OpenAI from \"openai\";\n import process from 'process';\n\n // 初始化 openai 客户端\n const openai = new OpenAI({\n apiKey: process.env.DASHSCOPE_API_KEY, // 从环境变量读取\n // 以下为新加坡地域base_url,若使用弗吉尼亚地域模型,需要将base_url换成https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1\n // 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'\n });\n\n let reasoningContent = '';\n let answerContent = '';\n let isAnswering = false;\n\n async function main() {\n try {\n const messages = [{ role: 'user', content: '你是谁' }];\n const stream = await openai.chat.completions.create({\n model: 'qwen-plus',\n messages,\n stream: true,\n enable_thinking: true\n });\n console.log('\\n' + '='.repeat(20) + '思考过程' + '='.repeat(20) + '\\n');\n\n for await (const chunk of stream) {\n if (!chunk.choices?.length) {\n console.log('\\nUsage:');\n console.log(chunk.usage);\n continue;\n }\n\n const delta = chunk.choices[0].delta;\n\n // 只收集思考内容\n if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {\n if (!isAnswering) {\n process.stdout.write(delta.reasoning_content);\n }\n reasoningContent += delta.reasoning_content;\n }\n\n // 收到content,开始进行回复\n if (delta.content !== undefined && delta.content) {\n if (!isAnswering) {\n console.log('\\n' + '='.repeat(20) + '完整回复' + '='.repeat(20) + '\\n');\n isAnswering = true;\n }\n process.stdout.write(delta.content);\n answerContent += delta.content;\n }\n }\n } catch (error) {\n console.error('Error:', error);\n }\n }\n\n main();\n ```\n\n ### Response <span id=\"ea1e31951foc2\" /> <span id=\"a2d7f41db5of6\" />\n\n ```plaintext\n ====================思考过程====================\n\n 好的,用户问“你是谁”,我需要回答我的身份。首先,我应该明确说明我是千问,由阿里云开发的超大规模语言模型。接下来,可以提到我的主要功能,比如回答问题、创作文字、逻辑推理等。还要强调我的多语言支持,包括中文和英文,这样用户知道我可以处理不同语言的请求。另外,可能需要解释一下我的应用场景,比如学习、工作和生活中的帮助。不过用户的问题比较直接,可能不需要太详细的信息,保持简洁明了。同时,要确保语气友好,邀请用户进一步提问。检查有没有遗漏的重要信息,比如我的版本或最新更新,但可能用户不需要那么详细。最后,确认回答准确无误,没有错误信息。\n ====================完整回复====================\n\n 我是千问,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字、逻辑推理、编程等多种任务,支持中英文等多种语言。如果你有任何问题或需要帮,欢迎随时告诉我!\n ```\n </Tab>\n\n <Tab title=\"HTTP\">\n ### Sample Code <span id=\"8a6ac5c012uov\" /> <span id=\"9a218b8ab4hbj\" />\n\n <Tabs>\n <Tab title=\"curl\">\n ```bash\n # ======= 重要提示 =======\n # 以下是新加坡base_url,如果使用北京地域的模型,需要将base_url替换为:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions\n # 如果使用弗吉尼亚地域的模型,需要将base_url替换为:https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions\n # === 执行时请删除该注释 ===\n curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"qwen3.8-max\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"你是谁\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"enable_thinking\": true\n }'\n ```\n </Tab>\n </Tabs>\n\n ### Response <span id=\"3434f14720siq\" /> <span id=\"9bf55011438o7\" />\n\n ```json\n data: {\"choices\":[{\"delta\":{\"content\":null,\"role\":\"assistant\",\"reasoning_content\":\"\"},\"index\":0,\"logprobs\":null,\"finish_reason\":null}],\"object\":\"chat.completion.chunk\",\"usage\":null,\"created\":1745485391,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503\"}\n\n .....\n\n data: {\"choices\":[{\"finish_reason\":\"stop\",\"delta\":{\"content\":\"\",\"reasoning_content\":null},\"index\":0,\"logprobs\":null}],\"object\":\"chat.completion.chunk\",\"usage\":null,\"created\":1745485391,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503\"}\n\n data: {\"choices\":[],\"object\":\"chat.completion.chunk\",\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":360,\"total_tokens\":370},\"created\":1745485391,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503\"}\n\n data: [DONE]\n ```\n </Tab>\n </Tabs>\n </Tab>\n\n <Tab title=\"DashScope\">\n > Qwen3.5 series DashScope API uses a multimodal interface, the following example will report an error `url error`. For the calling method please see [Enable/Disable Deep Think mode](/help/en/model-studio/vision#bc67a9a2bd2of).\n\n <Tabs>\n <Tab title=\"Python\">\n ### Sample Code <span id=\"ed8257af27xad\" /> <span id=\"db8175594ayzt\" />\n\n ```python expandable\n import os\n from dashscope import MultiModalConversation\n import dashscope\n\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n dashscope.base_http_api_url = \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1\"\n\n messages = [{\"role\": \"user\", \"content\": [{\"text\": \"你是谁?\"}]}]\n\n completion = MultiModalConversation.call(\n # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key = \"sk-xxx\",\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n model=\"qwen3.8-max\",\n messages=messages,\n enable_thinking=True,\n stream=True,\n incremental_output=True,\n )\n\n # 定义完整思考过程\n reasoning_content = \"\"\n # 定义完整回复\n answer_content = \"\"\n # 判断是否结束思考过程并开始回复\n is_answering = False\n\n print(\"=\" * 20 + \"思考过程\" + \"=\" * 20)\n\n for chunk in completion:\n # 如果思考过程与回复皆为空,则忽略\n content = chunk.output.choices[0].message.content\n reasoning = chunk.output.choices[0].message.reasoning_content\n if not content and reasoning == \"\":\n pass\n else:\n # 如果当前为思考过程\n if reasoning != \"\" and not content:\n print(reasoning, end=\"\", flush=True)\n reasoning_content += reasoning\n # 如果当前为回复\n elif content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"完整回复\" + \"=\" * 20)\n is_answering = True\n print(content[0][\"text\"], end=\"\", flush=True)\n answer_content += content[0][\"text\"]\n\n # 如果您需要打印完整思考过程与完整回复,请将以下代码解除注释后运行\n # print(\"=\" * 20 + \"完整思考过程\" + \"=\" * 20 + \"\\n\")\n # print(f\"{reasoning_content}\")\n # print(\"=\" * 20 + \"完整回复\" + \"=\" * 20 + \"\\n\")\n # print(f\"{answer_content}\")\n ```\n\n ### Response <span id=\"ba3b8246a48qv\" /> <span id=\"27e3023ebfs6k\" />\n\n ```plaintext\n ====================思考过程====================\n 好的,用户问:“你是谁?”我需要回答这个问题。首先,我要明确自己的身份,即千问,由阿里云开发的超大规模语言模型。接下来,要说明我的功能和用途,比如回答问题、创作文字、逻辑推理等。同时,要强调我的目标是成为用户的得力助手,提供帮助和支持。\n\n 在表达时,要保持口语化,避免使用专业术语或复杂句式。可以加入一些亲切的语气词,比如“你好呀~”,让对话更自然。另外,要确保信息准确,不遗漏关键点,比如我的开发者、主要功能和使用场景。\n\n 还要考虑用户可能的后续问题,比如具体的应用例子或技术细节,所以在回答中可以适当埋下伏笔,引导用户进一步提问。例如,提到“无论是日常生活的疑问还是专业领域的问题,我都能尽力提供帮助”,这样既全面又开放。\n\n 最后,检查回答是否流畅,有没有重复或冗余的信息,确保简洁明了。同时,保持友好和专业的平衡,让用户感受到既亲切又可靠。\n ====================完整回复====================\n 你好呀~我是千问,是阿里云开发的一款超大规模语言模型。我能够回答问题、创作文字、进行逻辑推理、编程等等,旨在为用户提供帮助和支持。无论是日常生活的疑问还是专业领域的问题,我都能尽力提供帮助。有什么我可以帮你的吗?\n ```\n </Tab>\n\n <Tab title=\"Java\">\n ### Sample Code <span id=\"4ac031f0676c1\" /> <span id=\"c1f85ae04esps\" />\n\n ```java expandable\n // dashscope SDK的版本 >= 2.19.4\n import java.util.Arrays;\n import java.util.Collections;\n import java.util.List;\n import java.util.Map;\n import org.slf4j.Logger;\n import org.slf4j.LoggerFactory;\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;\n import com.alibaba.dashscope.common.MultiModalMessage;\n import com.alibaba.dashscope.common.Role;\n import com.alibaba.dashscope.exception.ApiException;\n import com.alibaba.dashscope.exception.InputRequiredException;\n import com.alibaba.dashscope.exception.NoApiKeyException;\n import com.alibaba.dashscope.exception.UploadFileException;\n import io.reactivex.Flowable;\n import java.lang.System;\n import com.alibaba.dashscope.utils.Constants;\n\n public class Main {\n static {\n // 以下为新加坡地域base_url,若使用弗吉尼亚地域模型,需要将base_url换成https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1\n // 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n Constants.baseHttpApiUrl=\"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1\";\n }\n private static final Logger logger = LoggerFactory.getLogger(Main.class);\n private static StringBuilder reasoningContent = new StringBuilder();\n private static StringBuilder finalContent = new StringBuilder();\n private static boolean isFirstPrint = true;\n\n private static void handleMultiModalConversationResult(MultiModalConversationResult message) {\n String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();\n List<Map<String, Object>> contentList = (List<Map<String, Object>>) message.getOutput().getChoices().get(0).getMessage().getContent();\n String content = (contentList != null && !contentList.isEmpty()) ? (String) contentList.get(0).get(\"text\") : \"\";\n\n if (!reasoning.isEmpty()) {\n reasoningContent.append(reasoning);\n if (isFirstPrint) {\n System.out.println(\"====================思考过程====================\");\n isFirstPrint = false;\n }\n System.out.print(reasoning);\n }\n\n if (!content.isEmpty()) {\n finalContent.append(content);\n if (!isFirstPrint) {\n System.out.println(\"\\n====================完整回复====================\");\n isFirstPrint = true;\n }\n System.out.print(content);\n }\n }\n private static MultiModalConversationParam buildMultiModalConversationParam(MultiModalMessage userMsg) {\n return MultiModalConversationParam.builder()\n // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key\n // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey(\"sk-xxx\")\n .apiKey(System.getenv(\"DASHSCOPE_API_KEY\"))\n .model(\"qwen3.8-max\")\n .enableThinking(true)\n .incrementalOutput(true)\n .messages(Arrays.asList(userMsg))\n .build();\n }\n public static void streamCallWithMessage(MultiModalConversation conv, MultiModalMessage userMsg)\n throws NoApiKeyException, ApiException, InputRequiredException, UploadFileException {\n MultiModalConversationParam param = buildMultiModalConversationParam(userMsg);\n Flowable<MultiModalConversationResult> result = conv.streamCall(param);\n result.blockingForEach(message -> handleMultiModalConversationResult(message));\n }\n\n public static void main(String[] args) {\n try {\n MultiModalConversation conv = new MultiModalConversation();\n MultiModalMessage userMsg = MultiModalMessage.builder().role(Role.USER.getValue()).content(Arrays.asList(Collections.singletonMap(\"text\", \"你是谁?\"))).build();\n streamCallWithMessage(conv, userMsg);\n // 打印最终结果\n // if (reasoningContent.length() > 0) {\n // System.out.println(\"\\n====================完整回复====================\");\n // System.out.println(finalContent.toString());\n // }\n } catch (ApiException | NoApiKeyException | InputRequiredException | UploadFileException e) {\n logger.error(\"An exception occurred: {}\", e.getMessage());\n }\n System.exit(0);\n }\n }\n ```\n\n ### Response <span id=\"24452535a8371\" /> <span id=\"2d6b7cc6257zq\" />\n\n ```plaintext\n ====================思考过程====================\n 好的,用户问“你是谁?”,我需要根据之前的设定来回答。首先,我的角色是千问,阿里巴巴集团旗下的超大规模语言模型。要保持口语化,简洁易懂。\n\n 用户可能刚接触我,或者想确认我的身份。应该先直接回答我是谁,然后简要说明我的功能和用途,比如回答问题、创作文字、编程等。还要提到支持多语言,这样用户知道我可以处理不同语言的需求。\n\n 另外,根据指导方针,要保持拟人性,所以语气要友好,可能用表情符号增加亲切感。同时,可能需要引导用户进一步提问或使用我的功能,比如问他们需要什么帮助。\n\n 需要注意不要使用复杂术语,避免冗长。检查是否有遗漏的关键点,比如多语言支持和具体能力。确保回答符合所有要求,包括口语化和简洁。\n ====================完整回复====================\n 你好!我是千问,阿里巴巴集团旗下的超大规模语言模型。我能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等,还能表达观点,玩游戏等。我熟练掌握多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。有什么需要我帮忙的吗?\n ```\n </Tab>\n\n <Tab title=\"HTTP\">\n ### Sample Code <span id=\"e93608c894qfe\" /> <span id=\"97869f545fllm\" />\n\n <Tabs>\n <Tab title=\"curl\">\n ```bash\n # ======= 重要提示 =======\n # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key\n # 以下为新加坡地域url,若使用北京地域的模型,需将url替换为:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation\n # 若使用弗吉尼亚地域的模型,需要将base_url替换为:https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation\n # === 执行时请删除该注释 ===\n curl -X POST \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation\" \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"X-DashScope-SSE: enable\" \\\n -d '{\n \"model\": \"qwen3.8-max\",\n \"input\":{\n \"messages\":[\n {\n \"role\": \"user\",\n \"content\": [{\"text\": \"你是谁?\"}]\n }\n ]\n },\n \"parameters\":{\n \"enable_thinking\": true,\n \"incremental_output\": true,\n \"result_format\": \"message\"\n }\n }'\n ```\n </Tab>\n </Tabs>\n\n ### Response <span id=\"1e0bfae0c9vk1\" /> <span id=\"e7290dd8d88yb\" />\n\n ```plaintext expandable\n id:1\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"嗯\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":14,\"input_tokens\":11,\"output_tokens\":3},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:2\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\",\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":15,\"input_tokens\":11,\"output_tokens\":4},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:3\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"用户\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":16,\"input_tokens\":11,\"output_tokens\":5},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:4\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"问\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":17,\"input_tokens\":11,\"output_tokens\":6},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:5\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"“\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":18,\"input_tokens\":11,\"output_tokens\":7},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n ......\n\n id:358\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"帮助\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":373,\"input_tokens\":11,\"output_tokens\":362},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:359\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\",\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":374,\"input_tokens\":11,\"output_tokens\":363},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:360\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"欢迎\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":375,\"input_tokens\":11,\"output_tokens\":364},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:361\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"随时\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":376,\"input_tokens\":11,\"output_tokens\":365},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:362\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"告诉我\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":377,\"input_tokens\":11,\"output_tokens\":366},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:363\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"!\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":378,\"input_tokens\":11,\"output_tokens\":367},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:364\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"stop\"}]},\"usage\":{\"total_tokens\":378,\"input_tokens\":11,\"output_tokens\":367},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n ```\n </Tab>\n </Tabs>\n </Tab>\n</Tabs>\n\n## Core Capabilities <span id=\"f8de8e9a49ucb\" /> <span id=\"ba352d9f05zpz\" />\n\n### Switch Thinking/Non-Thinking Mode <span id=\"5a3fefa9786lt\" /> <span id=\"1dd26768ddaua\" />\n\nEnabling thinking mode can improve response quality, but will increase response latency and Token consumption. When using models with hybrid thinking mode, you can dynamically switch based on problem complexity without changing the model:\n\n- Simple tasks (daily chat, simple Q\\&A): Set`enable_thinking`to`false`to disable thinking;\n- Complex tasks (logical reasoning, Code generation, mathematical solutions): Set`enable_thinking`to`true`Enable thinking.\n\n<Tabs>\n <Tab title=\"OpenAI Compatible\">\n <Tip>\n `enable_thinking`Non-OpenAI standard parameter. If using the OpenAI Python SDK, pass it via `extra_body`. In the Node.js SDK, pass it as a top-level parameter.\n </Tip>\n\n <Tabs>\n <Tab title=\"Python\">\n ### Sample Code <span id=\"0f2b6b7fcalv1\" /> <span id=\"692583ac99vb1\" />\n\n ```python expandable\n from openai import OpenAI\n import os\n\n # 初始化OpenAI客户端\n client = OpenAI(\n # 如果没有配置环境变量,请用阿里云百炼API Key替换:api_key=\"sk-xxx\"\n # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n base_url=\"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1\",\n )\n\n messages = [{\"role\": \"user\", \"content\": \"你是谁\"}]\n completion = client.chat.completions.create(\n model=\"qwen3.8-max\",\n messages=messages,\n # 通过 extra_body 设置 enable_thinking 开启思考过程\n extra_body={\"enable_thinking\": True},\n stream=True,\n stream_options={\n \"include_usage\": True\n },\n )\n\n reasoning_content = \"\" # 完整思考过程\n answer_content = \"\" # 完整回复\n is_answering = False # 是否进入回复阶段\n print(\"\\n\" + \"=\" * 20 + \"思考过程\" + \"=\" * 20 + \"\\n\")\n\n for chunk in completion:\n if not chunk.choices:\n print(\"\\n\" + \"=\" * 20 + \"Token 消耗\" + \"=\" * 20 + \"\\n\")\n print(chunk.usage)\n continue\n\n delta = chunk.choices[0].delta\n\n # 只收集思考内容\n if hasattr(delta, \"reasoning_content\") and delta.reasoning_content is not None:\n if not is_answering:\n print(delta.reasoning_content, end=\"\", flush=True)\n reasoning_content += delta.reasoning_content\n\n # 收到content,开始进行回复\n if hasattr(delta, \"content\") and delta.content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"完整回复\" + \"=\" * 20 + \"\\n\")\n is_answering = True\n print(delta.content, end=\"\", flush=True)\n answer_content += delta.content\n ```\n\n ### Response <span id=\"20bbe18d4apdz\" /> <span id=\"b9d4c2ab551ee\" />\n\n ```plaintext\n ====================思考过程====================\n\n 嗯,用户问“你是谁”,我需要先确定他们想知道什么。可能他们第一次接触我,或者想确认我的身份。我应该先介绍自己是千问,由通义实验室研发。然后要说明我的功能,比如回答问题、创作文字、编程等,这样用户了解我能提供什么帮助。还要提到我支持多种语言,这样国际用户也会知道他们可以用不同语言交流。最后保持友好,邀请他们提问,这样可以促进进一步互动。要注意简洁明了,避免技术术语太多,让用户容易理解。可能用户需要的是快速了解我的能力,所以重点放在功能和用途上。还要检查有没有遗漏的信息,比如是否要提到阿里巴巴集团,或者更多技术细节。不过用户可能只需要基本的信息,不需要太深入。确保回答友好且专业,同时鼓励用户继续提问。\n ====================完整回复====================\n\n 我是千问,由通义实验室研发的超大规模语言模型。我可以帮助你回答问题、创作文字、编程、表达观点等,支持多语言交流。有什么需要我帮忙的吗?\n ====================Token 消耗====================\n\n CompletionUsage(completion_tokens=221, prompt_tokens=10, total_tokens=231, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=172, rejected_prediction_tokens=None), prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0))\n ```\n </Tab>\n\n <Tab title=\"Node.js\">\n ### Sample Code <span id=\"504bfa803c59y\" /> <span id=\"ca1b1412614e6\" />\n\n ```javascript expandable\n import OpenAI from \"openai\";\n import process from 'process';\n\n // 初始化OpenAI客户端\n const openai = new OpenAI({\n // 如果没有配置环境变量,请用阿里云百炼API Key替换:apiKey: \"sk-xxx\"\n apiKey: process.env.DASHSCOPE_API_KEY,\n // 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'\n });\n\n let reasoningContent = ''; // 完整思考过程\n let answerContent = ''; // 完整回复\n let isAnswering = false; // 是否进入回复阶段\n\n async function main() {\n try {\n const messages = [{ role: 'user', content: '你是谁' }];\n\n const stream = await openai.chat.completions.create({\n model: 'qwen-plus',\n messages,\n // Node.js SDK 中,enable_thinking 等非标准参数作为顶层属性传递,无需放在 extra_body 中\n enable_thinking: true,\n stream: true,\n stream_options: {\n include_usage: true\n },\n });\n\n console.log('\\n' + '='.repeat(20) + '思考过程' + '='.repeat(20) + '\\n');\n\n for await (const chunk of stream) {\n if (!chunk.choices?.length) {\n console.log('\\n' + '='.repeat(20) + 'Token 消耗' + '='.repeat(20) + '\\n');\n console.log(chunk.usage);\n continue;\n }\n\n const delta = chunk.choices[0].delta;\n\n // 只收集思考内容\n if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {\n if (!isAnswering) {\n process.stdout.write(delta.reasoning_content);\n }\n reasoningContent += delta.reasoning_content;\n }\n\n // 收到content,开始进行回复\n if (delta.content !== undefined && delta.content) {\n if (!isAnswering) {\n console.log('\\n' + '='.repeat(20) + '完整回复' + '='.repeat(20) + '\\n');\n isAnswering = true;\n }\n process.stdout.write(delta.content);\n answerContent += delta.content;\n }\n }\n } catch (error) {\n console.error('Error:', error);\n }\n }\n\n main();\n ```\n\n ### Response <span id=\"afb225cc29u3t\" /> <span id=\"8333c4b43b3t7\" />\n\n ```plaintext\n ====================思考过程====================\n\n 嗯,用户问“你是谁”,我需要先确定他们想知道什么。可能他们第一次接触我,或者想确认我的身份。我应该先介绍自己的名字和身份,比如千问,英文名Qwen。然后说明我是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。接下来要提到我的功能,比如回答问题、创作文字、编程、表达观点等,这样用户能了解我的用途。还要提到我支持多语言,这样国际用户会觉得有用。最后邀请他们提问,保持友好和开放的态度。注意用简洁易懂的语言,避免技术术语太多。可能用户需要帮助,或者只是好奇,所以回应要亲切,鼓励他们进一步互动。另外,可能需要考虑用户是否有更深层的需求,比如测试我的能力或者寻找特定帮助,但初次回答还是以基本信息和引导为主。保持口语化,不用复杂句子,让信息传达更有效。\n ====================完整回复====================\n\n 你好!我是千问,英文名Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你回答问题、创作文字(比如写故事、写公文、写邮件、写剧本等)、进行逻辑推理、编程,甚至表达观点和玩游戏。我支持多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。\n\n 如果你有任何问题或需要帮助,随时告诉我!\n ====================Token 消耗====================\n\n {\n prompt_tokens: 10,\n completion_tokens: 288,\n total_tokens: 298,\n completion_tokens_details: { reasoning_tokens: 188 },\n prompt_tokens_details: { cached_tokens: 0 }\n }\n ```\n </Tab>\n\n <Tab title=\"HTTP\">\n ### Sample Code <span id=\"9296838816y68\" /> <span id=\"ce41bd5dd8kiz\" />\n\n <Tabs>\n <Tab title=\"curl\">\n ```bash\n # ======= 重要提示 =======\n # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/model-studio/get-api-key\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n # === 执行时请删除该注释 ===\n curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"qwen3.8-max\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"你是谁\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"enable_thinking\": true\n }'\n ```\n </Tab>\n </Tabs>\n </Tab>\n </Tabs>\n </Tab>\n\n <Tab title=\"DashScope\">\n > The DashScope API of the Qwen3.5 series uses a multimodal interface. The following example will throw an error `url error`. For the calling method, see [Enable/Disable Thinking Mode](/help/en/model-studio/vision#bc67a9a2bd2of).\n\n <Tabs>\n <Tab title=\"Python\">\n ### Sample Code <span id=\"fbd4f30ff2lyr\" /> <span id=\"364e0515d2s1x\" />\n\n ```python expandable\n import os\n from dashscope import MultiModalConversation\n import dashscope\n\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n dashscope.base_http_api_url = \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/\"\n\n # 初始化请求参数\n messages = [{\"role\": \"user\", \"content\": [{\"text\": \"你是谁?\"}]}]\n\n completion = MultiModalConversation.call(\n # 如果没有配置环境变量,请用阿里云百炼API Key替换:api_key=\"sk-xxx\"\n # 各地域的API Key不同。获取API Key:请参考 https://www.alibabacloud.com/help/model-studio/regions\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n model=\"qwen3.8-max\",\n messages=messages,\n enable_thinking=True, # 开启思考过程\n stream=True, # 开启流式输出\n incremental_output=True, # 开启增量输出\n )\n\n reasoning_content = \"\" # 完整思考过程\n answer_content = \"\" # 完整回复\n is_answering = False # 是否进入回复阶段\n\n print(\"\\n\" + \"=\" * 20 + \"思考过程\" + \"=\" * 20 + \"\\n\")\n\n for chunk in completion:\n message = chunk.output.choices[0].message\n\n # 只收集思考内容\n if message.reasoning_content:\n if not is_answering:\n print(message.reasoning_content, end=\"\", flush=True)\n reasoning_content += message.reasoning_content\n\n # 收到 content,开始进行回复(content 为列表类型)\n if message.content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"完整回复\" + \"=\" * 20 + \"\\n\")\n is_answering = True\n print(message.content[0][\"text\"], end=\"\", flush=True)\n answer_content += message.content[0][\"text\"]\n\n print(\"\\n\" + \"=\" * 20 + \"Token 消耗\" + \"=\" * 20 + \"\\n\")\n print(chunk.usage)\n # 循环结束后,reasoning_content 和 answer_content 变量中包含了完整的内容\n # 您可以在这里根据需要进行后续处理\n # print(f\"\\n\\n完整思考过程:\\n{reasoning_content}\")\n # print(f\"\\n完整回复:\\n{answer_content}\")\n ```\n\n ### Response <span id=\"c1a078ac98toz\" /> <span id=\"a78a7acc51em0\" />\n\n ```plaintext\n ====================思考过程====================\n\n 嗯,用户问“你是谁?”,我需要先确定他们想知道什么。可能他们第一次接触我,或者想确认我的身份。首先,我应该介绍自己的名字,千问,然后说明我是通义实验室研发的超大规模语言模型。接下来,可能需要解释我的功能,比如回答问题、创作文字、编程等,这样用户能了解我的用途。还要提到我支持多种语言,这样国际用户也能知道他们可以用不同语言交流。最后,保持友好,邀请他们提问,这样能促进进一步的互动。要注意用简洁易懂的语言,避免技术术语太多,让用户容易理解。可能用户有更深层的需求,比如测试我的能力,或者寻找帮助,所以提供具体的例子会更好,比如写故事、写公文、写邮件等。还要确保回答结构清晰,分点说明功能,但可能不需要用项目符号,而是自然过渡。另外,要强调我是AI助手,没有个人意识,所有回答都基于训练数据,这样避免误解。可能需要检查有没有遗漏的重要信息,比如多模态能力,或者最新的更新,但根据之前的回复,可能不需要太深入。总之,回答要全面但简洁,友好且有帮助,让用户感到被理解和支持。\n ====================完整回复====================\n\n 我是千问,阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以帮助你:\n\n 1. **回答问题**:无论是学术问题、常识问题还是专业领域问题,我都可以尝试为你解答。\n 2. **创作文字**:写故事、写公文、写邮件、写剧本等,我都可以帮你完成。\n 3. **逻辑推理**:我可以帮助你进行逻辑推理和解决问题。\n 4. **编程**:我可以理解并生成多种编程语言的代码。\n 5. **多语言支持**:我支持多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。\n\n 如果你有任何问题或需要帮助,随时告诉我!\n ====================Token 消耗====================\n\n {\"input_tokens\": 11, \"output_tokens\": 405, \"total_tokens\": 416, \"output_tokens_details\": {\"reasoning_tokens\": 256}, \"prompt_tokens_details\": {\"cached_tokens\": 0}}\n ```\n </Tab>\n\n <Tab title=\"Java\">\n ### Sample Code <span id=\"d7b4e7164300j\" /> <span id=\"7610302307k76\" />\n\n ```java expandable\n // dashscope SDK的版本 >= 2.19.4\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;\n import com.alibaba.dashscope.common.MultiModalMessage;\n import java.util.Collections;\n import com.alibaba.dashscope.common.Role;\n import com.alibaba.dashscope.exception.ApiException;\n import com.alibaba.dashscope.exception.InputRequiredException;\n import com.alibaba.dashscope.exception.NoApiKeyException;\n import com.alibaba.dashscope.exception.UploadFileException;\n import com.alibaba.dashscope.utils.Constants;\n import io.reactivex.Flowable;\n import java.lang.System;\n import java.util.Arrays;\n import java.util.List;\n import java.util.Map;\n import org.slf4j.Logger;\n import org.slf4j.LoggerFactory;\n\n public class Main {\n private static final Logger logger = LoggerFactory.getLogger(Main.class);\n private static StringBuilder reasoningContent = new StringBuilder();\n private static StringBuilder finalContent = new StringBuilder();\n private static boolean isFirstPrint = true;\n\n private static void handleMultiModalConversationResult(MultiModalConversationResult message) {\n String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();\n List<Map<String, Object>> contentList = (List<Map<String, Object>>) message.getOutput().getChoices().get(0).getMessage().getContent();\n String content = (contentList != null && !contentList.isEmpty()) ? (String) contentList.get(0).get(\"text\") : \"\";\n\n if (!reasoning.isEmpty()) {\n reasoningContent.append(reasoning);\n if (isFirstPrint) {\n System.out.println(\"====================思考过程====================\");\n isFirstPrint = false;\n }\n System.out.print(reasoning);\n }\n\n if (!content.isEmpty()) {\n finalContent.append(content);\n if (!isFirstPrint) {\n System.out.println(\"\\n====================完整回复====================\");\n isFirstPrint = true;\n }\n System.out.print(content);\n }\n }\n private static MultiModalConversationParam buildMultiModalConversationParam(MultiModalMessage userMsg) {\n return MultiModalConversationParam.builder()\n // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey(\"sk-xxx\")\n .apiKey(System.getenv(\"DASHSCOPE_API_KEY\"))\n .model(\"qwen3.8-max\")\n .enableThinking(true)\n .incrementalOutput(true)\n .messages(Arrays.asList(userMsg))\n .build();\n }\n public static void streamCallWithMessage(MultiModalConversation conv, MultiModalMessage userMsg)\n throws NoApiKeyException, ApiException, InputRequiredException, UploadFileException {\n MultiModalConversationParam param = buildMultiModalConversationParam(userMsg);\n Flowable<MultiModalConversationResult> result = conv.streamCall(param);\n result.blockingForEach(message -> handleMultiModalConversationResult(message));\n }\n\n public static void main(String[] args) {\n try {\n // 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n MultiModalConversation conv = new MultiModalConversation(\"http\", \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1\");\n MultiModalMessage userMsg = MultiModalMessage.builder().role(Role.USER.getValue()).content(Arrays.asList(Collections.singletonMap(\"text\", \"你是谁?\"))).build();\n streamCallWithMessage(conv, userMsg);\n // 打印最终结果\n // if (reasoningContent.length() > 0) {\n // System.out.println(\"\\n====================完整回复====================\");\n // System.out.println(finalContent.toString());\n // }\n } catch (ApiException | NoApiKeyException | InputRequiredException | UploadFileException e) {\n logger.error(\"An exception occurred: {}\", e.getMessage());\n }\n System.exit(0);\n }\n }\n ```\n\n ### Response <span id=\"81dc6a7769h34\" /> <span id=\"9b996b3c91hke\" />\n\n ```plaintext\n ====================思考过程====================\n 嗯,用户问“你是谁?”,我需要先确定他们想了解什么。可能他们想知道我的身份,或者是在测试我的反应。首先,我应该明确回答我是千问,阿里巴巴集团旗下的超大规模语言模型。然后,可能需要简要介绍我的功能,比如回答问题、创作文字、编程等,这样用户能了解我的用途。还要提到我支持多种语言,这样国际用户也会知道他们可以用不同语言交流。最后,保持友好,邀请他们提问,这样他们会觉得亲切,愿意继续互动。要注意回答不要太长,但信息要全面。可能用户还有后续问题,比如我的技术细节或者使用场景,但初次回答应该简洁明了。确保没有使用专业术语,让所有用户都能理解。检查有没有遗漏的重要信息,比如多语言支持和具体功能例子。好的,这样应该能覆盖用户的需求了。\n ====================完整回复====================\n 我是千问,阿里巴巴集团旗下的超大规模语言模型。我能够回答问题、创作文字(如写故事、写公文、写邮件、写剧本等)、进行逻辑推理、编程、表达观点、玩游戏等,支持多语言交流,包括但不限于中文、英文、德语、法语、西班牙语等。如果你有任何问题或需要帮助,欢迎随时告诉我!\n ```\n </Tab>\n\n <Tab title=\"HTTP\">\n ### Sample Code <span id=\"adea09a017k6l\" /> <span id=\"44fc443dc6tfg\" />\n\n <Tabs>\n <Tab title=\"curl\">\n ```bash\n # ======= 重要提示 =======\n # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/model-studio/get-api-key\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n # === 执行时请删除该注释 ===\n curl -X POST \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation\" \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"X-DashScope-SSE: enable\" \\\n -d '{\n \"model\": \"qwen3.8-max\",\n \"input\":{\n \"messages\":[\n {\n \"role\": \"user\",\n \"content\": [{\"text\": \"你是谁?\"}]\n }\n ]\n },\n \"parameters\":{\n \"enable_thinking\": true,\n \"incremental_output\": true,\n \"result_format\": \"message\"\n }\n }'\n ```\n </Tab>\n </Tabs>\n\n ### Response <span id=\"f64c0e57dfnap\" /> <span id=\"42dab521f9zhn\" />\n\n ```plaintext expandable\n id:1\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"嗯\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":14,\"input_tokens\":11,\"output_tokens\":3},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:2\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\",\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":15,\"input_tokens\":11,\"output_tokens\":4},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:3\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"用户\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":16,\"input_tokens\":11,\"output_tokens\":5},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:4\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"问\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":17,\"input_tokens\":11,\"output_tokens\":6},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:5\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"“\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":18,\"input_tokens\":11,\"output_tokens\":7},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n ......\n\n id:358\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"帮助\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":373,\"input_tokens\":11,\"output_tokens\":362},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:359\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\",\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":374,\"input_tokens\":11,\"output_tokens\":363},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:360\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"欢迎\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":375,\"input_tokens\":11,\"output_tokens\":364},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:361\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"随时\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":376,\"input_tokens\":11,\"output_tokens\":365},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:362\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"告诉我\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":377,\"input_tokens\":11,\"output_tokens\":366},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:363\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"!\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":378,\"input_tokens\":11,\"output_tokens\":367},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n\n id:364\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"stop\"}]},\"usage\":{\"total_tokens\":378,\"input_tokens\":11,\"output_tokens\":367},\"request_id\":\"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1\"}\n ```\n </Tab>\n </Tabs>\n </Tab>\n</Tabs>\n\nIn addition, <strong>Qwen3 open-source hybrid thinking model and qwen-plus-2025-04-28 model</strong>support dynamically controlling thinking mode through prompts.`enable_thinking`When`true`, add it to the prompt`/no_think`to disable thinking; in Multi-turn, to re-enable, add it to the latest prompt`/think`. The Model always follows the latest`/think` or `/no_think` instruction.\n\n### Limit Thinking Length <span id=\"e7c0002fe4meu\" /> <span id=\"6f0633b9cdts1\" />\n\nDeep Think Model sometimes generates verbose Thinking Process, increasing waiting time and consuming more Token. Through`thinking_budget` Parameter sets the maximum Token number of Thinking Process, and after exceeding the limit, the Model immediately Output Response.\n\n> `thinking_budget` The Default Value is the maximum thought chain length of the Model, please see the Model card of Bailian console.\n\n<Tip>\n `thinking_budget`Parameter for the maximum number of Tokens supported in the Thinking Process. Applicable to Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen3, GLM, and Kimi series models.\n</Tip>\n\n### Experience Deep Think in the console <span id=\"console-deep-thinking-title\" /> <span id=\"console-deep-thinking\" />\n\n1. Log in to the Bailian console of the large model service platform.\n2. In the left navigation pane, select<strong>Experience Center</strong> > <strong>Text</strong>.\n3. The page displays the Qwen3.7-Max model by default. You can also click the model name and select other Qwen3 series models from the drop-down list.\n4. Click at the bottom of the input box<strong>Deep Think</strong>, enable the reasoning mode, and view the model's Thinking Process.\n5. Click the upper-right <strong>Debugging</strong>, and in the opened configuration panel, set the `thinking_budget`Parameter, which controls the maximum number of tokens output by the thought chain. Value range 1\\~32768, default value 4000. To experience more models, you can go to Bailian Model Plaza.\n\n<Tabs>\n <Tab title=\"OpenAI Compatible\">\n <Tabs>\n <Tab title=\"Python\">\n ### Sample Code <span id=\"d91219c7fd412\" /> <span id=\"c292d73f4fd96\" />\n\n ```python expandable\n from openai import OpenAI\n import os\n\n # 初始化OpenAI客户端\n client = OpenAI(\n # 如果没有配置环境变量,请用阿里云百炼API Key替换:api_key=\"sk-xxx\"\n # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n base_url=\"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1\",\n )\n\n messages = [{\"role\": \"user\", \"content\": \"你是谁\"}]\n\n completion = client.chat.completions.create(\n model=\"qwen3.8-max\",\n messages=messages,\n # enable_thinking 参数开启思考过程,thinking_budget 参数设置最大推理过程 Token 数\n extra_body={\n \"enable_thinking\": True,\n \"thinking_budget\": 50\n },\n stream=True,\n stream_options={\n \"include_usage\": True\n },\n )\n\n reasoning_content = \"\" # 完整思考过程\n answer_content = \"\" # 完整回复\n is_answering = False # 是否进入回复阶段\n print(\"\\n\" + \"=\" * 20 + \"思考过程\" + \"=\" * 20 + \"\\n\")\n\n for chunk in completion:\n if not chunk.choices:\n print(\"\\nUsage:\")\n print(chunk.usage)\n continue\n\n delta = chunk.choices[0].delta\n\n # 只收集思考内容\n if hasattr(delta, \"reasoning_content\") and delta.reasoning_content is not None:\n if not is_answering:\n print(delta.reasoning_content, end=\"\", flush=True)\n reasoning_content += delta.reasoning_content\n\n # 收到content,开始进行回复\n if hasattr(delta, \"content\") and delta.content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"完整回复\" + \"=\" * 20 + \"\\n\")\n is_answering = True\n print(delta.content, end=\"\", flush=True)\n answer_content += delta.content\n ```\n\n ### Response <span id=\"82896ddaecw1f\" /> <span id=\"d9bdb90c6bqyd\" />\n\n ```plaintext\n ====================思考过程====================\n\n 好的,用户问“你是谁”,我需要给出一个清晰且友好的回答。首先,应该明确自己的身份,即千问,由阿里巴巴集团旗下的通义实验室研发。接下来,要说明自己的主要功能,比如回答\n ====================完整回复====================\n\n 我是千问,是阿里巴巴集团旗下的通义实验室研发的超大规模语言模型。我能够回答问题、创作文字、逻辑推理、编程等,旨在为用户提供帮助和便利。有什么我可以帮您的吗?\n ```\n </Tab>\n\n <Tab title=\"Node.js\">\n ### Sample Code <span id=\"533f715e1agxl\" /> <span id=\"11e4a87be76kd\" />\n\n ```javascript expandable\n import OpenAI from \"openai\";\n import process from 'process';\n\n // 初始化 openai 客户端\n const openai = new OpenAI({\n apiKey: process.env.DASHSCOPE_API_KEY, // 从环境变量读取\n // 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'\n });\n\n let reasoningContent = '';\n let answerContent = '';\n let isAnswering = false;\n\n async function main() {\n try {\n const messages = [{ role: 'user', content: '你是谁' }];\n const stream = await openai.chat.completions.create({\n model: 'qwen-plus',\n messages,\n stream: true,\n // enable_thinking 参数开启思考过程,thinking_budget 参数设置最大推理过程 Token 数\n enable_thinking: true,\n thinking_budget: 50\n });\n console.log('\\n' + '='.repeat(20) + '思考过程' + '='.repeat(20) + '\\n');\n\n for await (const chunk of stream) {\n if (!chunk.choices?.length) {\n console.log('\\nUsage:');\n console.log(chunk.usage);\n continue;\n }\n\n const delta = chunk.choices[0].delta;\n\n // 只收集思考内容\n if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {\n if (!isAnswering) {\n process.stdout.write(delta.reasoning_content);\n }\n reasoningContent += delta.reasoning_content;\n }\n\n // 收到content,开始进行回复\n if (delta.content !== undefined && delta.content) {\n if (!isAnswering) {\n console.log('\\n' + '='.repeat(20) + '完整回复' + '='.repeat(20) + '\\n');\n isAnswering = true;\n }\n process.stdout.write(delta.content);\n answerContent += delta.content;\n }\n }\n } catch (error) {\n console.error('Error:', error);\n }\n }\n\n main();\n ```\n\n ### Response <span id=\"553ca9df55gpu\" /> <span id=\"0f05cad7adg5q\" />\n\n ```plaintext\n ====================思考过程====================\n\n 好的,用户问“你是谁”,我需要给出一个清晰准确的回答。首先,我应该介绍自己的身份,即千问,由阿里巴巴集团旗下的通义实验室研发。接下来,要说明我的主要功能,比如回答问题\n ====================完整回复====================\n\n 我是千问,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字、逻辑推理、编程等多种任务。如果你有任何问题或需要帮助,欢迎随时告诉我!\n ```\n </Tab>\n\n <Tab title=\"HTTP\">\n ### Sample Code <span id=\"091b3616609k8\" /> <span id=\"9ef5800a09shl\" />\n\n <Tabs>\n <Tab title=\"curl\">\n ```bash\n # ======= 重要提示 =======\n # 以下是新加坡base_url,如果使用北京地域的模型,需要将base_url替换为:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions\n # 如果使用弗吉尼亚地域的模型,需要将base_url替换为:https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions\n # === 执行时请删除该注释 ===\n curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"qwen3.8-max\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"你是谁\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"enable_thinking\": true,\n \"thinking_budget\": 50\n }'\n ```\n </Tab>\n </Tabs>\n\n ### Response <span id=\"ac4b041b4bstj\" /> <span id=\"23dd6ef0d3ck0\" />\n\n ```json\n data: {\"choices\":[{\"delta\":{\"content\":null,\"role\":\"assistant\",\"reasoning_content\":\"\"},\"index\":0,\"logprobs\":null,\"finish_reason\":null}],\"object\":\"chat.completion.chunk\",\"usage\":null,\"created\":1745485391,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503\"}\n\n .....\n\n data: {\"choices\":[{\"finish_reason\":\"stop\",\"delta\":{\"content\":\"\",\"reasoning_content\":null},\"index\":0,\"logprobs\":null}],\"object\":\"chat.completion.chunk\",\"usage\":null,\"created\":1745485391,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503\"}\n\n data: {\"choices\":[],\"object\":\"chat.completion.chunk\",\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":360,\"total_tokens\":370},\"created\":1745485391,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503\"}\n\n data: [DONE]\n ```\n </Tab>\n </Tabs>\n </Tab>\n\n <Tab title=\"DashScope\">\n > Qwen3.5 series DashScope API uses a multimodal interface, and the following example will throw an error `url error`. For the calling method, see [Enable/disable thinking mode](/help/en/model-studio/vision#bc67a9a2bd2of).\n\n <Tabs>\n <Tab title=\"Python\">\n ### Sample Code <span id=\"b35afc0045xk2\" /> <span id=\"4acc8dcf77ua9\" />\n\n ```python expandable\n import os\n from dashscope import MultiModalConversation\n import dashscope\n\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n dashscope.base_http_api_url = \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/\"\n\n messages = [{\"role\": \"user\", \"content\": [{\"text\": \"你是谁?\"}]}]\n\n completion = MultiModalConversation.call(\n # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key = \"sk-xxx\",\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n model=\"qwen3.8-max\",\n messages=messages,\n enable_thinking=True,\n # 设置最大推理过程 Token 数\n thinking_budget=50,\n stream=True,\n incremental_output=True,\n )\n\n # 定义完整思考过程\n reasoning_content = \"\"\n # 定义完整回复\n answer_content = \"\"\n # 判断是否结束思考过程并开始回复\n is_answering = False\n\n print(\"=\" * 20 + \"思考过程\" + \"=\" * 20)\n\n for chunk in completion:\n # 如果思考过程与回复皆为空,则忽略\n content = chunk.output.choices[0].message.content\n reasoning = chunk.output.choices[0].message.reasoning_content\n if not content and reasoning == \"\":\n pass\n else:\n # 如果当前为思考过程\n if reasoning != \"\" and not content:\n print(reasoning, end=\"\", flush=True)\n reasoning_content += reasoning\n # 如果当前为回复\n elif content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"完整回复\" + \"=\" * 20)\n is_answering = True\n print(content[0][\"text\"], end=\"\", flush=True)\n answer_content += content[0][\"text\"]\n\n # 如果您需要打印完整思考过程与完整回复,请将以下代码解除注释后运行\n # print(\"=\" * 20 + \"完整思考过程\" + \"=\" * 20 + \"\\n\")\n # print(f\"{reasoning_content}\")\n # print(\"=\" * 20 + \"完整回复\" + \"=\" * 20 + \"\\n\")\n # print(f\"{answer_content}\")\n ```\n\n ### Response <span id=\"421d770d9d4v5\" /> <span id=\"63f2e865fa6m7\" />\n\n ```plaintext\n ====================思考过程====================\n 好的,用户问“你是谁?”,我需要给出一个清晰且友好的回答。首先,我要介绍自己的身份,也就是千问,由阿里巴巴集团旗下的通义实验室研发。接下来,应该说明我的主要功能,比如\n ====================完整回复====================\n 我是千问,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字、逻辑推理、编程等,旨在为用户提供全面、准确和有用的信息与帮助。有什么我可以帮您的吗?\n ```\n </Tab>\n\n <Tab title=\"Java\">\n ### Sample Code <span id=\"7452b19974gb5\" /> <span id=\"b1a1a15624mys\" />\n\n ```java expandable\n // dashscope SDK的版本 >= 2.19.4\n import java.util.Arrays;\n import java.util.Collections;\n import java.util.List;\n import java.util.Map;\n import org.slf4j.Logger;\n import org.slf4j.LoggerFactory;\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;\n import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;\n import com.alibaba.dashscope.common.MultiModalMessage;\n import com.alibaba.dashscope.common.Role;\n import com.alibaba.dashscope.exception.ApiException;\n import com.alibaba.dashscope.exception.InputRequiredException;\n import com.alibaba.dashscope.exception.NoApiKeyException;\n import com.alibaba.dashscope.exception.UploadFileException;\n import io.reactivex.Flowable;\n import java.lang.System;\n import com.alibaba.dashscope.utils.Constants;\n\n public class Main {\n static {\n // 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n Constants.baseHttpApiUrl=\"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1\";\n }\n private static final Logger logger = LoggerFactory.getLogger(Main.class);\n private static StringBuilder reasoningContent = new StringBuilder();\n private static StringBuilder finalContent = new StringBuilder();\n private static boolean isFirstPrint = true;\n\n private static void handleMultiModalConversationResult(MultiModalConversationResult message) {\n String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();\n List<Map<String, Object>> contentList = (List<Map<String, Object>>) message.getOutput().getChoices().get(0).getMessage().getContent();\n String content = (contentList != null && !contentList.isEmpty()) ? (String) contentList.get(0).get(\"text\") : \"\";\n\n if (!reasoning.isEmpty()) {\n reasoningContent.append(reasoning);\n if (isFirstPrint) {\n System.out.println(\"====================思考过程====================\");\n isFirstPrint = false;\n }\n System.out.print(reasoning);\n }\n\n if (!content.isEmpty()) {\n finalContent.append(content);\n if (!isFirstPrint) {\n System.out.println(\"\\n====================完整回复====================\");\n isFirstPrint = true;\n }\n System.out.print(content);\n }\n }\n private static MultiModalConversationParam buildMultiModalConversationParam(MultiModalMessage userMsg) {\n return MultiModalConversationParam.builder()\n // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey(\"sk-xxx\")\n .apiKey(System.getenv(\"DASHSCOPE_API_KEY\"))\n .model(\"qwen3.8-max\")\n .enableThinking(true)\n .thinkingBudget(50)\n .incrementalOutput(true)\n .messages(Arrays.asList(userMsg))\n .build();\n }\n public static void streamCallWithMessage(MultiModalConversation conv, MultiModalMessage userMsg)\n throws NoApiKeyException, ApiException, InputRequiredException, UploadFileException {\n MultiModalConversationParam param = buildMultiModalConversationParam(userMsg);\n Flowable<MultiModalConversationResult> result = conv.streamCall(param);\n result.blockingForEach(message -> handleMultiModalConversationResult(message));\n }\n\n public static void main(String[] args) {\n try {\n MultiModalConversation conv = new MultiModalConversation();\n MultiModalMessage userMsg = MultiModalMessage.builder().role(Role.USER.getValue()).content(Arrays.asList(Collections.singletonMap(\"text\", \"你是谁?\"))).build();\n streamCallWithMessage(conv, userMsg);\n // 打印最终结果\n // if (reasoningContent.length() > 0) {\n // System.out.println(\"\\n====================完整回复====================\");\n // System.out.println(finalContent.toString());\n // }\n } catch (ApiException | NoApiKeyException | InputRequiredException | UploadFileException e) {\n logger.error(\"An exception occurred: {}\", e.getMessage());\n }\n System.exit(0);\n }\n }\n ```\n\n ### Response <span id=\"33a1b902dcq4t\" /> <span id=\"b09ee55dbd8q2\" />\n\n ```plaintext\n ====================思考过程====================\n 好的,用户问“你是谁?”,我需要给出一个清晰且友好的回答。首先,我要介绍自己的身份,也就是千问,由阿里巴巴集团旗下的通义实验室研发。接下来,应该说明我的主要功能,比如\n ====================完整回复====================\n 我是千问,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字、逻辑推理、编程等,旨在为用户提供全面、准确和有用的信息与帮助。有什么我可以帮您的吗?\n ```\n </Tab>\n\n <Tab title=\"HTTP\">\n ### Sample Code <span id=\"6fdf5d6aa9ar1\" /> <span id=\"67b3ce0fe362f\" />\n\n <Tabs>\n <Tab title=\"curl\">\n ```bash\n # ======= 重要提示 =======\n # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n # === 执行时请删除该注释 ===\n curl -X POST \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation\" \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"X-DashScope-SSE: enable\" \\\n -d '{\n \"model\": \"qwen3.8-max\",\n \"input\":{\n \"messages\":[\n {\n \"role\": \"user\",\n \"content\": [{\"text\": \"你是谁?\"}]\n }\n ]\n },\n \"parameters\":{\n \"enable_thinking\": true,\n \"thinking_budget\": 50,\n \"incremental_output\": true,\n \"result_format\": \"message\"\n }\n }'\n ```\n </Tab>\n </Tabs>\n\n ### Response <span id=\"094051445f99h\" /> <span id=\"fe1ad9d096kcj\" />\n\n ```plaintext\n id:1\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"好的\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":14,\"output_tokens\":3,\"input_tokens\":11,\"output_tokens_details\":{\"reasoning_tokens\":1}},\"request_id\":\"2ce91085-3602-9c32-9c8b-fe3d583a2c38\"}\n\n id:2\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\",\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":15,\"output_tokens\":4,\"input_tokens\":11,\"output_tokens_details\":{\"reasoning_tokens\":2}},\"request_id\":\"2ce91085-3602-9c32-9c8b-fe3d583a2c38\"}\n\n ......\n\n id:133\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"!\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":149,\"output_tokens\":138,\"input_tokens\":11,\"output_tokens_details\":{\"reasoning_tokens\":50}},\"request_id\":\"2ce91085-3602-9c32-9c8b-fe3d583a2c38\"}\n\n id:134\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"stop\"}]},\"usage\":{\"total_tokens\":149,\"output_tokens\":138,\"input_tokens\":11,\"output_tokens_details\":{\"reasoning_tokens\":50}},\"request_id\":\"2ce91085-3602-9c32-9c8b-fe3d583a2c38\"}\n ```\n </Tab>\n </Tabs>\n </Tab>\n</Tabs>\n\n### Pass Thinking Process <span id=\"jln7docdq5et5\" /> <span id=\"28uj4lsfdd393\" />\n\nIn Multi-turn, `preserve_thinking` controls whether the Model reads historical assistant message `reasoning_content`. When set to `true`, these thinking contents will be appended to the next-round input. The client needs to provide historical assistant messages and their `messages` in the request's `reasoning_content`. The Default Value of each model is based on [Chat Completions Parameter Description](/help/en/model-studio/qwen-api-via-openai-chat-completions).\n\n<Tip>\n `preserve_thinking`This Parameter only supports qwen3.8-max series, qwen3.8-flash, qwen3.8-omni-flash (enabled by default), qwen3.7-max, qwen3.7-max-2026-05-20, qwen3.7-max-2026-06-08, qwen3.7-max-preview, qwen3.7-max-2026-05-17, qwen3.7-plus, qwen3.7-plus-2026-05-26, qwen3.6-max-preview, qwen3.6-plus, qwen3.6-plus-2026-04-02, qwen3.7-flash, qwen3.7-flash-2026-07-15, kimi-k2.7-code (Alibaba Cloud Bailian deployment), kimi-k2.6 (Alibaba Cloud Bailian deployment), kimi/kimi-k3 (Moonshot deployment), kimi/kimi-k2.7-code-highspeed (Moonshot deployment), kimi/kimi-k2.7-code (Moonshot deployment), kimi/kimi-k2.6 (Moonshot deployment).\n</Tip>\n\n> For the above Qwen3.8 Max, Qwen3.7, Qwen3.6 and Kimi models that support this Parameter, if the historical messages do not contain `reasoning_content`, enabling this Parameter will not cause an error.\n\n> After Enable, in the historical conversation `reasoning_content` will be counted toward input Token count and billing.\n\n<Tabs>\n <Tab title=\"OpenAI Compatible\">\n <Note>\n `preserve_thinking`Non OpenAI standard Parameter, Use Python SDK needs to Pass `extra_body`in.\n </Note>\n\n <Tabs>\n <Tab title=\"Python\">\n ### Sample Code <span id=\"6q1m6d42gm7zm\" /> <span id=\"pc1pyo6zrw6u1\" />\n\n ```python expandable\n from openai import OpenAI\n import os\n\n client = OpenAI(\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n base_url=\"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1\",\n )\n\n # 第一轮对话\n messages = [\n {\"role\": \"user\", \"content\": \"我需要为一个日均千万消息的电商系统选择消息队列,请推荐\"}\n ]\n\n first_reasoning = \"\"\n first_content = \"\"\n is_answering = False\n\n completion = client.chat.completions.create(\n model=\"qwen3.8-max\",\n messages=messages,\n extra_body={\"enable_thinking\": True},\n stream=True,\n stream_options={\"include_usage\": True},\n )\n\n print(\"=\" * 20 + \"第一轮思考过程\" + \"=\" * 20)\n\n for chunk in completion:\n if not chunk.choices:\n continue\n delta = chunk.choices[0].delta\n if hasattr(delta, \"reasoning_content\") and delta.reasoning_content is not None:\n first_reasoning += delta.reasoning_content\n if not is_answering:\n print(delta.reasoning_content, end=\"\", flush=True)\n if hasattr(delta, \"content\") and delta.content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"第一轮回复\" + \"=\" * 20)\n is_answering = True\n print(delta.content, end=\"\", flush=True)\n first_content += delta.content\n\n # 第二轮对话:传递思考过程,追问模型为什么排除了Kafka\n messages = [\n {\"role\": \"user\", \"content\": \"我需要为一个日均千万消息的电商系统选择消息队列,请推荐\"},\n {\n \"role\": \"assistant\",\n \"content\": first_content,\n \"reasoning_content\": first_reasoning,\n },\n {\"role\": \"user\", \"content\": \"你在对比时为什么排除了Kafka?\"},\n ]\n\n reasoning_content = \"\"\n answer_content = \"\"\n is_answering = False\n\n # preserve_thinking 通过 extra_body 传入\n completion = client.chat.completions.create(\n model=\"qwen3.8-max\",\n messages=messages,\n extra_body={\n \"enable_thinking\": True,\n \"preserve_thinking\": True,\n },\n stream=True,\n stream_options={\"include_usage\": True},\n )\n\n print(\"\\n\" + \"=\" * 20 + \"第二轮思考过程\" + \"=\" * 20)\n\n for chunk in completion:\n if not chunk.choices:\n continue\n delta = chunk.choices[0].delta\n if hasattr(delta, \"reasoning_content\") and delta.reasoning_content is not None:\n if not is_answering:\n print(delta.reasoning_content, end=\"\", flush=True)\n reasoning_content += delta.reasoning_content\n if hasattr(delta, \"content\") and delta.content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"第二轮回复\" + \"=\" * 20)\n is_answering = True\n print(delta.content, end=\"\", flush=True)\n answer_content += delta.content\n ```\n\n ### Response <span id=\"zj18n55n2hahz\" /> <span id=\"5fankjytluxxv\" />\n\n ```plaintext\n ====================第一轮思考过程====================\n 用户需要为日均千万消息的电商系统选择消息队列。让我从吞吐量、可靠性、延迟消息、事务支持等维度对比主流方案...\n\n RocketMQ:阿里电商场景验证,原生支持事务消息和延迟消息,分区级严格有序...\n Kafka:极高吞吐量,但无原生事务消息和延迟消息支持,需自研补偿机制...\n RabbitMQ:延迟低,但集群扩展能力有限,峰值万级TPS...\n ====================第一轮回复====================\n 综合电商场景的核心需求(事务消息、延迟消息、顺序性、峰值应对),推荐 Apache RocketMQ。如果团队已有 Kafka 生态或需强实时分析能力,Kafka 也是可行方案。\n ====================第二轮思考过程====================\n 用户在追问为什么排除了Kafka。回顾我的历史思考过程,我并没有排除Kafka,而是给了它4星评分。让我参考之前的详细对比分析来解释...\n\n 在上一轮思考中,我对比了RocketMQ和Kafka在事务消息、延迟消息、顺序性方面的差异。Kafka的劣势主要在于需要额外架构设计来补齐电商特有语义...\n ====================第二轮回复====================\n 我并没有排除Kafka。Kafka在吞吐量和生态方面表现优秀,之所以RocketMQ评分略高,是因为电商核心链路的\"开箱即用\"特性匹配度:RocketMQ原生支持事务消息和延迟消息,而Kafka需要通过Outbox Pattern等架构模式自行实现。如果团队已有Kafka生态,它完全能胜任千万级消息场景。\n ```\n </Tab>\n\n <Tab title=\"Node.js\">\n ### Sample Code <span id=\"myoz9dl6pyu63\" /> <span id=\"y6t4b0fydozi4\" />\n\n ```javascript expandable\n import OpenAI from \"openai\";\n import process from 'process';\n\n const openai = new OpenAI({\n apiKey: process.env.DASHSCOPE_API_KEY,\n // 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'\n });\n\n async function main() {\n // 第一轮对话\n let firstReasoning = '';\n let firstContent = '';\n let isAnswering = false;\n\n const stream1 = await openai.chat.completions.create({\n model: 'qwen3.7-plus',\n messages: [{ role: 'user', content: '我需要为一个日均千万消息的电商系统选择消息队列,请推荐' }],\n stream: true,\n enable_thinking: true\n });\n\n console.log('='.repeat(20) + '第一轮思考过程' + '='.repeat(20));\n\n for await (const chunk of stream1) {\n if (!chunk.choices?.length) continue;\n const delta = chunk.choices[0].delta;\n if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {\n firstReasoning += delta.reasoning_content;\n if (!isAnswering) process.stdout.write(delta.reasoning_content);\n }\n if (delta.content !== undefined && delta.content) {\n if (!isAnswering) {\n console.log('\\n' + '='.repeat(20) + '第一轮回复' + '='.repeat(20));\n isAnswering = true;\n }\n process.stdout.write(delta.content);\n firstContent += delta.content;\n }\n }\n\n // 第二轮对话:传递思考过程\n let reasoningContent = '';\n let answerContent = '';\n isAnswering = false;\n\n const stream2 = await openai.chat.completions.create({\n model: 'qwen3.7-plus',\n messages: [\n { role: 'user', content: '我需要为一个日均千万消息的电商系统选择消息队列,请推荐' },\n {\n role: 'assistant',\n content: firstContent,\n reasoning_content: firstReasoning\n },\n { role: 'user', content: '你在对比时为什么排除了Kafka?' }\n ],\n stream: true,\n enable_thinking: true,\n // preserve_thinking 作为顶层参数传入\n preserve_thinking: true\n });\n\n console.log('\\n' + '='.repeat(20) + '第二轮思考过程' + '='.repeat(20));\n\n for await (const chunk of stream2) {\n if (!chunk.choices?.length) continue;\n const delta = chunk.choices[0].delta;\n if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {\n if (!isAnswering) process.stdout.write(delta.reasoning_content);\n reasoningContent += delta.reasoning_content;\n }\n if (delta.content !== undefined && delta.content) {\n if (!isAnswering) {\n console.log('\\n' + '='.repeat(20) + '第二轮回复' + '='.repeat(20));\n isAnswering = true;\n }\n process.stdout.write(delta.content);\n answerContent += delta.content;\n }\n }\n }\n\n main();\n ```\n\n ### Response <span id=\"83wsvftv26m9f\" /> <span id=\"l8asq6s3pzhq7\" />\n\n ```plaintext\n ====================第一轮思考过程====================\n 用户需要为日均千万消息的电商系统选择消息队列。让我从吞吐量、可靠性、延迟消息、事务支持等维度对比主流方案...\n ====================第一轮回复====================\n 综合电商场景的核心需求,推荐 Apache RocketMQ。如果团队已有 Kafka 生态,Kafka 也是可行方案。\n ====================第二轮思考过程====================\n 用户追问为什么排除了Kafka。参考我之前的思考过程,我并没有排除Kafka...\n ====================第二轮回复====================\n 我并没有排除Kafka。Kafka在吞吐量和生态方面表现优秀,之所以RocketMQ评分略高,是因为电商核心链路的\"开箱即用\"特性匹配度。\n ```\n </Tab>\n\n <Tab title=\"HTTP\">\n ### Sample Code <span id=\"ayokqnr2jhn7d\" /> <span id=\"5b7im7bv9cfdp\" />\n\n <Tabs>\n <Tab title=\"curl\">\n ```bash expandable\n # 各地域base_url不同,请根据实际地域修改\n curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"qwen3.8-max\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"我需要为一个日均千万消息的电商系统选择消息队列,请推荐\"\n },\n {\n \"role\": \"assistant\",\n \"content\": \"综合电商场景的核心需求,推荐 Apache RocketMQ。\",\n \"reasoning_content\": \"用户需要为日均千万消息的电商系统选择消息队列。RocketMQ原生支持事务消息和延迟消息,更适合电商场景。Kafka吞吐量极高但需自研补偿机制。\"\n },\n {\n \"role\": \"user\",\n \"content\": \"你在对比时为什么排除了Kafka?\"\n }\n ],\n \"stream\": true,\n \"stream_options\": {\n \"include_usage\": true\n },\n \"enable_thinking\": true,\n \"preserve_thinking\": true\n }'\n ```\n </Tab>\n </Tabs>\n\n ### Response <span id=\"9llmpvme58had\" /> <span id=\"qia67c28e7n64\" />\n\n ```json\n data: {\"choices\":[{\"delta\":{\"content\":null,\"role\":\"assistant\",\"reasoning_content\":\"\"},\"index\":0,\"logprobs\":null,\"finish_reason\":null}],\"object\":\"chat.completion.chunk\",\"usage\":null,\"created\":1743523200,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-example-001\"}\n\n .....\n\n data: {\"choices\":[{\"finish_reason\":\"stop\",\"delta\":{\"content\":\"\",\"reasoning_content\":null},\"index\":0,\"logprobs\":null}],\"object\":\"chat.completion.chunk\",\"usage\":null,\"created\":1743523200,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-example-001\"}\n\n data: {\"choices\":[],\"object\":\"chat.completion.chunk\",\"usage\":{\"prompt_tokens\":3463,\"completion_tokens\":2387,\"total_tokens\":5850},\"created\":1743523200,\"system_fingerprint\":null,\"model\":\"qwen3.8-max\",\"id\":\"chatcmpl-example-001\"}\n\n data: [DONE]\n ```\n </Tab>\n </Tabs>\n </Tab>\n\n <Tab title=\"DashScope\">\n <Note>\n Java SDK does not currently support `preserve_thinking` parameter. When Calling via HTTP, please put `preserve_thinking`into `parameters` object.\n </Note>\n\n <Tabs>\n <Tab title=\"Python\">\n ### Sample Code <span id=\"2hybb7qx5x673\" /> <span id=\"ppjcnqd8fhfvw\" />\n\n ```python expandable\n import os\n from dashscope import MultiModalConversation\n import dashscope\n\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n dashscope.base_http_api_url = \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/\"\n\n # 第一轮对话\n messages = [\n {\"role\": \"user\", \"content\": [{\"text\": \"我需要为一个日均千万消息的电商系统选择消息队列,请推荐\"}]}\n ]\n\n first_reasoning = \"\"\n first_content = \"\"\n is_answering = False\n\n completion = MultiModalConversation.call(\n # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key=\"sk-xxx\"\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n model=\"qwen3.8-max\",\n messages=messages,\n enable_thinking=True,\n stream=True,\n incremental_output=True,\n )\n\n print(\"=\" * 20 + \"第一轮思考过程\" + \"=\" * 20)\n\n for chunk in completion:\n content = chunk.output.choices[0].message.content\n reasoning = chunk.output.choices[0].message.reasoning_content\n if not content and reasoning == \"\":\n pass\n else:\n if reasoning != \"\" and not content:\n print(reasoning, end=\"\", flush=True)\n first_reasoning += reasoning\n elif content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"第一轮回复\" + \"=\" * 20)\n is_answering = True\n print(content[0][\"text\"], end=\"\", flush=True)\n first_content += content[0][\"text\"]\n\n # 第二轮对话:传递思考过程\n messages = [\n {\"role\": \"user\", \"content\": [{\"text\": \"我需要为一个日均千万消息的电商系统选择消息队列,请推荐\"}]},\n {\n \"role\": \"assistant\",\n \"content\": [{\"text\": first_content}],\n \"reasoning_content\": first_reasoning,\n },\n {\"role\": \"user\", \"content\": [{\"text\": \"你在对比时为什么排除了Kafka?\"}]},\n ]\n\n reasoning_content = \"\"\n answer_content = \"\"\n is_answering = False\n\n completion = MultiModalConversation.call(\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n model=\"qwen3.8-max\",\n messages=messages,\n enable_thinking=True,\n # 传递思考过程\n preserve_thinking=True,\n stream=True,\n incremental_output=True,\n )\n\n print(\"\\n\" + \"=\" * 20 + \"第二轮思考过程\" + \"=\" * 20)\n\n for chunk in completion:\n content = chunk.output.choices[0].message.content\n reasoning = chunk.output.choices[0].message.reasoning_content\n if not content and reasoning == \"\":\n pass\n else:\n if reasoning != \"\" and not content:\n print(reasoning, end=\"\", flush=True)\n reasoning_content += reasoning\n elif content:\n if not is_answering:\n print(\"\\n\" + \"=\" * 20 + \"第二轮回复\" + \"=\" * 20)\n is_answering = True\n print(content[0][\"text\"], end=\"\", flush=True)\n answer_content += content[0][\"text\"]\n ```\n\n ### Response <span id=\"1wpk5lk2sxtce\" /> <span id=\"6j5c82apvuje6\" />\n\n ```plaintext\n ====================第一轮思考过程====================\n 用户需要为日均千万消息的电商系统选择消息队列。让我从吞吐量、可靠性、延迟消息、事务支持等维度对比主流方案...\n ====================第一轮回复====================\n 综合电商场景的核心需求,推荐 Apache RocketMQ。如果团队已有 Kafka 生态,Kafka 也是可行方案。\n ====================第二轮思考过程====================\n 用户追问为什么排除了Kafka。参考我之前的思考过程,我并没有排除Kafka...\n ====================第二轮回复====================\n 我并没有排除Kafka。Kafka在吞吐量和生态方面表现优秀,之所以RocketMQ评分略高,是因为电商核心链路的\"开箱即用\"特性匹配度。\n ```\n </Tab>\n\n <Tab title=\"HTTP\">\n ### Sample Code <span id=\"km28zc40ouxpi\" /> <span id=\"zntuutojgvxal\" />\n\n <Tabs>\n <Tab title=\"curl\">\n ```bash expandable\n # 各地域base_url不同,请根据实际地域修改\n curl -X POST \"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation\" \\\n -H \"Authorization: Bearer $DASHSCOPE_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -H \"X-DashScope-SSE: enable\" \\\n -d '{\n \"model\": \"qwen3.8-max\",\n \"input\":{\n \"messages\":[\n {\n \"role\": \"user\",\n \"content\": [{\"text\": \"我需要为一个日均千万消息的电商系统选择消息队列,请推荐\"}]\n },\n {\n \"role\": \"assistant\",\n \"content\": [{\"text\": \"综合电商场景的核心需求,推荐 Apache RocketMQ。\"}],\n \"reasoning_content\": \"用户需要为日均千万消息的电商系统选择消息队列。RocketMQ原生支持事务消息和延迟消息,更适合电商场景。Kafka吞吐量极高但需自研补偿机制。\"\n },\n {\n \"role\": \"user\",\n \"content\": [{\"text\": \"你在对比时为什么排除了Kafka?\"}]\n }\n ]\n },\n \"parameters\":{\n \"enable_thinking\": true,\n \"preserve_thinking\": true,\n \"incremental_output\": true,\n \"result_format\": \"message\"\n }\n }'\n ```\n </Tab>\n </Tabs>\n\n ### Response <span id=\"rq5sek85kfs70\" /> <span id=\"rq5sek85kfs69\" />\n\n ```plaintext\n id:1\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"用户\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":3466,\"output_tokens\":3,\"input_tokens\":3463,\"output_tokens_details\":{\"reasoning_tokens\":1}},\"request_id\":\"example-request-001\"}\n\n id:2\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"追问\",\"role\":\"assistant\"},\"finish_reason\":\"null\"}]},\"usage\":{\"total_tokens\":3467,\"output_tokens\":4,\"input_tokens\":3463,\"output_tokens_details\":{\"reasoning_tokens\":2}},\"request_id\":\"example-request-001\"}\n\n ......\n\n id:200\n event:result\n :HTTP_STATUS/200\n data:{\"output\":{\"choices\":[{\"message\":{\"content\":\"\",\"reasoning_content\":\"\",\"role\":\"assistant\"},\"finish_reason\":\"stop\"}]},\"usage\":{\"total_tokens\":5850,\"output_tokens\":2387,\"input_tokens\":3463,\"output_tokens_details\":{\"reasoning_tokens\":1347}},\"request_id\":\"example-request-001\"}\n ```\n </Tab>\n </Tabs>\n </Tab>\n</Tabs>\n\n### Other Features <span id=\"8fa1d9d3a7jxk\" /> <span id=\"0d96871320nty\" />\n\n- [Multi-turn](/help/en/model-studio/multi-round-conversation#9c315c95a8omt)\n- [Built-in Tools](/help/en/model-studio/qwen-function-calling#fbf3d739f2q9f)\n- [Web Search](/help/en/model-studio/web-search)\n\n## Billing Details <span id=\"e1b6949c321lc\" /> <span id=\"a1b69a01e567m\" />\n\n- Thinking content is billed by Output Token.\n- Some hybrid thinking models have different prices in thinking and non-thinking modes.\n\n > If the model does not Output Thinking Process in thinking mode, it is billed at the non-thinking mode price.\n\n## FAQ <span id=\"b654fdb6bblx9\" /> <span id=\"fe61e978c9pc3\" />\n\n<Accordion title=\"Q: How to disable thinking mode?\">\n Whether the thinking mode can be disabled depends on the model used:\n\n - Hybrid thinking mode models (such as qwen3.6-plus, deepseek-v4-pro): `enable_thinking` set to `false` to disable;\n - Thinking-only mode models (such as qwen3-235b-a22b-thinking-2507, deepseek-r1): cannot be disabled.\n</Accordion>\n\n<Accordion title=\"Q: How to troubleshoot slow qwen3.7-plus responses?\">\n qwen3.7-plus is a hybrid thinking mode model and enables thinking mode by default. The Thinking Process generates a large number of reasoning Tokens (measured to account for over 60% of the total Output Tokens), so the total time of a single Calling is significantly longer than that of the non-thinking mode. The Token generation speed itself is not abnormal (measured at approximately 52-54 Tokens/s), and the difference in total time mainly comes from the number of Tokens generated by the Thinking Process, rather than the Model or network slowing down.\n\n Troubleshooting steps:\n\n 1. Confirm whether thinking mode is Enable. qwen3.7-plus is Enable by default, which can be determined by whether the `reasoning_content` Field is returned in the response.\n 2. Check the `completion_tokens` and `reasoning_tokens` in the response usage. If `reasoning_tokens` is relatively high, the total time consumption is an expected behavior of the Thinking mode.\n 3. If no Thinking Process is needed, set `enable_thinking` to `false` to disable the Thinking mode. Once disabled, the Output Token is significantly reduced, and the actual total time can be reduced by 60%-75%.\n 4. If you need to retain the Thinking capability, you can switch to<strong>Stream</strong> to obtain the first Token more quickly and view the Thinking Process in real time, avoiding long waits for the complete response.\n\n > The usage statistics display the overall time consumption of a single Calling (including the generation time of the Thinking Token), rather than the generation latency of a single Token.\n</Accordion>\n\n<Accordion title=\"Q: How to call deep thinking models in non-streaming (synchronous) mode?\">\n The examples in this article use Stream by default (Recommend, you can view the Thinking Process in real time and avoid long waits). The commercial version Deep Think Model (such as qwen-plus, qwen3-max, qwen-flash, etc.) also supports non-stream (synchronous) Output, returning the complete Thinking Process and response at once.\n\n > When changing the streaming example to non-streaming, please modify<strong>Result parsing code</strong>: non-streaming Calling returns a complete Response object (`completion`), <strong>cannot</strong> iterate through `for chunk in completion` as in the streaming Sample Code (otherwise an error `'tuple' object has no attribute 'choices'` will be raised), and should directly read `completion.choices[0].message.reasoning_content`(Thinking Process) and `completion.choices[0].message.content`(reply content). In addition, `stream=False` cannot set the `stream_options` Parameter.\n\n The following uses the OpenAI-compatible interface with non-streaming Calling of qwen3.8-max with thinking mode enabled as an example:\n\n ```python\n from openai import OpenAI\n import os\n\n client = OpenAI(\n # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key\n # 如果没有配置环境变量,请用阿里云百炼API Key替换:api_key=\"sk-xxx\"\n api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n # 以下为新加坡地域配置,调用时请将{WorkspaceId}替换为真实的业务空间ID,各地域的配置不同。\n base_url=\"https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1\",\n )\n\n completion = client.chat.completions.create(\n model=\"qwen3.8-max\", # 请替换为支持非流式输出的深度思考模型\n messages=[{\"role\": \"user\", \"content\": \"你是谁\"}],\n extra_body={\"enable_thinking\": True},\n stream=False, # 非流式(同步)输出;stream=False 时不能设置 stream_options\n )\n\n # 非流式返回完整响应对象,直接读取 message,无需(也不能)迭代\n message = completion.choices[0].message\n print(\"=\" * 20 + \"思考过程\" + \"=\" * 20 + \"\\n\")\n print(getattr(message, \"reasoning_content\", \"\") or \"\")\n print(\"\\n\" + \"=\" * 20 + \"完整回复\" + \"=\" * 20 + \"\\n\")\n print(message.content)\n ```\n\n > Some models (such as qwen3-235b-a22b, qwen3-32b and other open-source versions) only support Stream output, and non-streaming Calling will result in an error `parameter.enable_thinking only support stream call`. For such models, please Use streaming Calling.\n</Accordion>\n\n<Accordion title=\"Q: How to purchase Tokens after the free quota is exhausted?\">\n Go to [Fees and Costs](https://usercenter2-intl.console.alibabacloud.com/billing/#/account/overview)center to top up, keeping your account balance sufficient to call models normally.\n\n > After exceeding the Free Quota, billing is automatic at minute-level intervals. For consumption details, please go to **;[Bill Details](https://usercenter2-intl.console.alibabacloud.com/finance/expense-report/expense-detail)** to view.\n</Accordion>\n\n<Accordion title=\"Q: Can I upload images or documents for questioning?\">\n The models involved in this article only support text input. Qwen3-VL and QVQ models support image Deep Think.\n</Accordion>\n\n<Accordion title=\"Q: How to view Token consumption and call count?\">\n After Model Calling occurs<strong>minute-level</strong>can be viewed in the monitoring chart. Log in to the Monitoring page ([Singapore](https://modelstudio.console.alibabacloud.com/model/telemetry) or [Beijing](https://modelstudio.console.alibabacloud.com/model/telemetry)), select from the left navigation bar<strong>Operations Management</strong> > <strong>Monitoring</strong>to enter the monitoring overview page, set query conditions (for example, select time range, workspace, etc.), then in the<strong>Models</strong>area, find the target model and click<strong>View Details</strong>to view the call statistics of the model. For more information, see [Monitoring](/help/en/model-studio/model-telemetry) docs.\n\n > Monitoring data is updated at minute level and is for reference only; it is not used as a billing basis.\n</Accordion>\n\n<Accordion title=\"Q: What to do if a long prompt fails to generate or times out?\">\n When Calling the model with long prompts, generation failure or response timeout usually occurs because the thinking mode is enabled (`enable_thinking` is `true`). The thinking mode will increase processing time, and in long prompt scenarios may cause response truncation or request timeout.\n\n Solution:\n\n - Disable thinking mode: Set `enable_thinking` to `false`, reducing processing time from about 50 s to about 30 s.\n - Enable Stream: Set `stream` set to `true` to avoid the timeout limit of non-streaming calls.\n - Increase the timeout: If you need to keep thinking mode, set the client timeout to 180 seconds or above.\n</Accordion>\n\n<Accordion title=\"Q: What to do if a third-party client disconnects after outputting a thinking tag when calling a deep thinking model?\">\n This is a client-side issue, not the model limiting the Thinking Process output. The Bailian platform uses `enable_thinking` parameter to control the thinking mode toggle, and the model returns `reasoning_content` Field contains the complete Thinking Process content, and the model will normally return the thinking content. Disconnections are usually caused by client network fluctuations or client version compatibility issues.\n\n Troubleshooting steps:\n\n - Check the stability of the client network connection.\n - Upgrade the client to the latest version.\n - View the client logs to confirm the association between the disconnection time point and the thinking tag Output.\n\n You can also Calling the model directly via the DashScope API to verify whether the thinking function is working properly.\n</Accordion>\n\n## API Reference <span id=\"8202e9793agxx\" /> <span id=\"c5a5c2752d4m5\" />\n\nFor the input and Output parameters of the Deep Think model, please see[Text Generation](/help/en/model-studio/qwen-api-reference).\n\n## Error Code <span id=\"2048aa1f92x46\" />\n\nIf an execution error occurs, see [Error Code](/help/en/model-studio/error-code) to troubleshoot and resolve.",
3 "https://docs.together.ai/docs/deepseek-v4-quickstart.md": "> ## Documentation Index\n> Fetch the complete documentation index at: https://docs.together.ai/llms.txt\n> Use this file to discover all available pages before exploring further.\n\n# DeepSeek V4 Pro quickstart\n\n> Call DeepSeek V4 Pro on Together for hybrid reasoning, long-context, and tool-using workloads.\n\nDeepSeek V4 Pro is DeepSeek's frontier 1.6T-parameter Mixture-of-Experts model (49B active per token), with a hybrid attention architecture built for long-context, low-cost reasoning. On Together AI, it runs in NVFP4 with a 1M-token context window and supports streaming, function calling, structured outputs, and adjustable reasoning effort.\n\nThe model ID is `deepseek-ai/DeepSeek-V4-Pro-0813`. Pricing is \\$1.32 per 1M input tokens, \\$3.96 per 1M output tokens, and \\$0.13 per 1M cached input tokens.\n\n## Quickstart\n\nReasoning is on by default, so most calls work with no extra configuration. Stream the response, since reasoning output can be long.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n stream = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Prove that the square root of 2 is irrational.\",\n }\n ],\n stream=True,\n )\n\n for chunk in stream:\n if not chunk.choices:\n continue\n delta = chunk.choices[0].delta\n\n if hasattr(delta, \"reasoning\") and delta.reasoning:\n print(delta.reasoning, end=\"\", flush=True)\n if hasattr(delta, \"content\") and delta.content:\n print(delta.content, end=\"\", flush=True)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const stream = await together.chat.completions.stream({\n model: \"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages: [\n { role: \"user\", content: \"Prove that the square root of 2 is irrational.\" },\n ],\n });\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta;\n if (delta?.reasoning) process.stdout.write(delta.reasoning);\n if (delta?.content) process.stdout.write(delta.content);\n }\n ```\n\n ```bash cURL theme={null}\n curl -X POST \"https://api.together.ai/v1/chat/completions\" \\\n -H \"Authorization: Bearer $TOGETHER_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"deepseek-ai/DeepSeek-V4-Pro-0813\",\n \"messages\": [\n {\"role\": \"user\", \"content\": \"Prove that the square root of 2 is irrational.\"}\n ],\n \"stream\": true\n }'\n ```\n</CodeGroup>\n\nThe response separates the chain of thought from the final answer: reasoning tokens arrive in the `reasoning` field on each delta, and the answer arrives in `content`.\n\n## Reasoning effort\n\nDeepSeek V4 Pro accepts two effort levels through the `reasoning_effort` parameter:\n\n* `\"high\"`: The default thinking depth. Use for most complex problems.\n* `\"max\"`: Maximum reasoning effort. Use for the hardest math, planning, and multi-step coding agents. Set the context window to at least 384K tokens for Think Max mode, and set `max_tokens` generously, since `\"max\"` mode can produce very long chains of thought.\n\nTogether normalizes other values automatically: `\"low\"` and `\"medium\"` map to `\"high\"`, and `\"xhigh\"` maps to `\"max\"`.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n stream = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Find all integer solutions to x^3 + y^3 = z^3 + 1 with |x|,|y|,|z| <= 100.\",\n }\n ],\n reasoning_effort=\"max\",\n temperature=1.0,\n top_p=1.0,\n max_tokens=384000,\n stream=True,\n )\n\n for chunk in stream:\n if not chunk.choices:\n continue\n delta = chunk.choices[0].delta\n\n if hasattr(delta, \"reasoning\") and delta.reasoning:\n print(delta.reasoning, end=\"\", flush=True)\n if hasattr(delta, \"content\") and delta.content:\n print(delta.content, end=\"\", flush=True)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const stream = await together.chat.completions.stream({\n model: \"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages: [\n {\n role: \"user\",\n content:\n \"Find all integer solutions to x^3 + y^3 = z^3 + 1 with |x|,|y|,|z| <= 100.\",\n },\n ],\n reasoning_effort: \"max\",\n temperature: 1.0,\n top_p: 1.0,\n max_tokens: 384000,\n });\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta;\n if (delta?.reasoning) process.stdout.write(delta.reasoning);\n if (delta?.content) process.stdout.write(delta.content);\n }\n ```\n</CodeGroup>\n\nFor broader guidance on reasoning controls and prompting, see [Reasoning](/docs/inference/chat/reasoning).\n\n## Long-context use\n\nDeepSeek V4 Pro accepts up to 1M input tokens on Together. The model's hybrid attention combines Compressed Sparse Attention (CSA) with Heavily Compressed Attention (HCA), which keeps the key-value (KV) cache and per-token FLOPs roughly an order of magnitude smaller than DeepSeek V3.2 at long contexts.\n\nUse the full context window with care. The model's ability to retrieve information is not uniform across the window, so refer to the needle-in-a-haystack results from [DeepSeek's paper](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/blob/main/DeepSeek_V4.pdf) below.\n\nFor critical tasks, treat the first 256K of context as more reliable than the next 256K, and so on.\n\n<img src=\"https://mintcdn.com/togetherai-52386018/clRQwip6lGxMeevX/images/niah_deepseekv4.png?fit=max&auto=format&n=clRQwip6lGxMeevX&q=85&s=d6e813c91e3234d0fac839c32f103cfe\" alt=\"DeepSeek V4 Pro context length visualization\" style={{ display: \"block\", margin: \"24px auto\", maxWidth: 600 }} width=\"964\" height=\"462\" data-path=\"images/niah_deepseekv4.png\" />\n\nA few tips for long inputs:\n\n* Put your instructions at the top of the prompt and your question at the bottom.\n* Set `max_tokens` explicitly. Long contexts plus `reasoning_effort=\"max\"` can produce very long completions.\n\n## Recommended sampling parameters\n\nDeepSeek recommends `temperature=1.0` and `top_p=1.0` for V4 Pro. Lower temperatures can collapse the reasoning trace and degrade answer quality, so prefer to control output length with `max_tokens` rather than turning down temperature.\n\n## Reducing reasoning overhead\n\nV4 Pro is a thinking-by-default hybrid model on Together. For turns where reasoning overhead is not needed, disable reasoning with `reasoning={\"enabled\": False}`:\n\n```python theme={null}\nresponse = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Translate 'good morning' into French.\",\n }\n ],\n reasoning={\"enabled\": False},\n max_tokens=512,\n)\n\nprint(response.choices[0].message.content)\n```\n\nWhen you keep reasoning enabled, use `reasoning_effort=\"high\"` (the default) and add a short instruction asking the model to keep its thinking concise.\n\n## Multi-turn conversations\n\nIn each turn of the conversation, the model outputs both a chain-of-thought (`reasoning_content`) and a final answer (`content`). The API itself is stateless, so to continue a conversation, you must resend the prior `messages` for every request.\n\nIf the assistant's response included tool calls, pass both the previous answer and the CoT (`reasoning_content`) back in your next request to maintain the model's reasoning context. However, if there was **no tool call**, the prior CoT (`reasoning_content`) from previous turns is **not** included in the next turn's context. Only the usual conversation history carries forward. The diagram for multi-turn reasoning context illustrates this behavior:\n\n<img src=\"https://mintcdn.com/togetherai-52386018/MqzdCJm37PZ2ceQI/images/deepseek_r1_multiround_example_en.jpeg?fit=max&auto=format&n=MqzdCJm37PZ2ceQI&q=85&s=abd629a7821d0cd9924997a9d20bab76\" alt=\"DeepSeek V4 Pro multi-turn conversation timeline example\" style={{ display: \"block\", margin: \"24px auto\", maxWidth: 600 }} width=\"1923\" height=\"980\" data-path=\"images/deepseek_r1_multiround_example_en.jpeg\" />\n\nCode example:\n\n```python theme={null}\nfrom together import Together\n\nclient = Together()\n\nmessages = [\n {\n \"role\": \"user\",\n \"content\": \"What is the highest mountain in the United States?\",\n }\n]\n\nresponse = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=messages,\n reasoning_effort=\"high\",\n)\n\nassistant_message = response.choices[0].message\n\nmessages.append(\n {\n \"role\": \"assistant\",\n \"content\": assistant_message.content,\n }\n)\nmessages.append({\"role\": \"user\", \"content\": \"How tall is it?\"})\n\nresponse = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=messages,\n reasoning_effort=\"high\",\n)\n\nprint(response.choices[0].message.content)\n```\n\n## Function calling and interleaved reasoning\n\nDeepSeek V4 Pro supports tool calling. Define tools in the standard OpenAI-compatible schema and pass them via `tools`.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n tools = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Get the current weather for a city.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"City name.\",\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\"celsius\", \"fahrenheit\"],\n },\n },\n \"required\": [\"location\"],\n },\n },\n }\n ]\n\n response = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\"role\": \"user\", \"content\": \"What's the weather in Paris and Tokyo?\"}\n ],\n tools=tools,\n )\n\n print(response.choices[0].message.tool_calls)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const tools = [\n {\n type: \"function\" as const,\n function: {\n name: \"get_weather\",\n description: \"Get the current weather for a city.\",\n parameters: {\n type: \"object\",\n properties: {\n location: { type: \"string\", description: \"City name.\" },\n unit: { type: \"string\", enum: [\"celsius\", \"fahrenheit\"] },\n },\n required: [\"location\"],\n },\n },\n },\n ];\n\n const response = await together.chat.completions.create({\n model: \"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages: [{ role: \"user\", content: \"What's the weather in Paris and Tokyo?\" }],\n tools,\n });\n\n console.log(response.choices[0].message.tool_calls);\n ```\n</CodeGroup>\n\nFor multi-turn function calling, pass the assistant message's reasoning trace back in every later request. This preserves the model's reasoning across tool calls and user turns. Include the assistant message's `content`, `reasoning_content`, and `tool_calls`, then append each tool result with the matching `tool_call_id`, as illustrated in the multi-turn function-calling diagram.\n\n<img src=\"https://mintcdn.com/togetherai-52386018/clRQwip6lGxMeevX/images/thinking_with_tools_en.jpg?fit=max&auto=format&n=clRQwip6lGxMeevX&q=85&s=4969aea7932afaf9433f6e2df94109e4\" alt=\"Multi-turn function calling timeline example\" style={{ display: \"block\", margin: \"16px auto\", maxWidth: 600 }} width=\"3418\" height=\"2276\" data-path=\"images/thinking_with_tools_en.jpg\" />\n\nCode example:\n\n```python theme={null}\nimport os\nimport json\nfrom together import Together\nfrom datetime import datetime\n\ntools = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_date\",\n \"description\": \"Get the current date\",\n \"parameters\": {\"type\": \"object\", \"properties\": {}},\n },\n },\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Get weather of a location, the user should supply the location and date.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city name\",\n },\n \"date\": {\n \"type\": \"string\",\n \"description\": \"The date in format YYYY-mm-dd\",\n },\n },\n \"required\": [\"location\", \"date\"],\n },\n },\n },\n]\n\n\ndef get_date_mock():\n return datetime.now().strftime(\"%Y-%m-%d\")\n\n\ndef get_weather_mock(location, date):\n return \"Sunny 68~82°F\"\n\n\nTOOL_CALL_MAP = {\n \"get_date\": get_date_mock,\n \"get_weather\": get_weather_mock,\n}\n\n\ndef run_turn(client, turn, messages):\n sub_turn = 1\n while True:\n response = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=messages,\n tools=tools,\n reasoning_effort=\"high\",\n )\n\n choice = response.choices[0].message\n\n reasoning = getattr(choice, \"reasoning\", None) or getattr(\n choice, \"reasoning_content\", None\n )\n content = choice.content\n tool_calls = choice.tool_calls\n\n print(f\"Turn {turn}.{sub_turn}\")\n print(f\" reasoning = {reasoning}\")\n print(f\" content = {content}\")\n print(f\" tool_calls= {tool_calls}\")\n\n assistant_msg = {\n \"role\": \"assistant\",\n \"content\": content or \"\",\n }\n if reasoning:\n assistant_msg[\"reasoning_content\"] = reasoning\n if tool_calls:\n assistant_msg[\"tool_calls\"] = [\n {\n \"id\": tc.id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tc.function.name,\n \"arguments\": tc.function.arguments,\n },\n }\n for tc in tool_calls\n ]\n messages.append(assistant_msg)\n\n if not tool_calls:\n break\n\n for tool in tool_calls:\n tool_function = TOOL_CALL_MAP[tool.function.name]\n tool_result = tool_function(**json.loads(tool.function.arguments))\n print(f\" tool result for {tool.function.name}: {tool_result}\")\n messages.append(\n {\n \"role\": \"tool\",\n \"tool_call_id\": tool.id,\n \"content\": tool_result,\n }\n )\n\n sub_turn += 1\n print()\n\n\nclient = Together()\n\nmessages = [\n {\"role\": \"user\", \"content\": \"How's the weather in San Francisco tomorrow?\"}\n]\nrun_turn(client, 1, messages)\n\nmessages.append(\n {\"role\": \"user\", \"content\": \"How's the weather in New York tomorrow?\"}\n)\nrun_turn(client, 2, messages)\n```\n\n```text theme={null}\nTurn 1.1\n\n reasoning = The user wants to know the weather in San Francisco tomorrow. I need to get the current date first, and then use that to determine tomorrow's date. Then I'll call the weather function.\n\nLet me start by getting the current date.\n\n content = \n\n tool_calls= [ToolChoice(id='call_02dbb9ade77b4e8890526e02', function=Function(arguments='{}', name='get_date'), index=0.0, type='function')]\n\n tool result for get_date: 2026-04-29\n\nTurn 1.2\n\n reasoning = Today is 2026-04-29, so tomorrow is 2026-04-30. Now let me get the weather for San Francisco on that date.\n\n content = \n\n tool_calls= [ToolChoice(id='call_af2f753610ab4281a4ebe8ed', function=Function(arguments='{\"location\": \"San Francisco\", \"date\": \"2026-04-30\"}', name='get_weather'), index=1.0, type='function')]\n\n tool result for get_weather: Sunny 68~82°F\n\nTurn 1.3\n\n reasoning = I have the weather information for San Francisco tomorrow. Let me summarize it for the user.\n\n content = Tomorrow (April 30, 2026) in San Francisco is looking **sunny** with a temperature range of **68°F to 82°F** (about 20°C to 28°C). Should be a beautiful day — perfect for getting outside! ☀️\n\n tool_calls= []\n\nTurn 2.1\n\n reasoning = The user wants the weather in New York tomorrow. I already know today is 2026-04-29, so tomorrow is 2026-04-30. Let me call the weather function directly.\n\n content = \n\n tool_calls= [ToolChoice(id='call_4c5c442c8f884f8bb09a2ad2', function=Function(arguments='{\"location\": \"New York\", \"date\": \"2026-04-30\"}', name='get_weather'), index=1.0, type='function')]\n\n tool result for get_weather: Sunny 68~82°F\n\nTurn 2.2\n\n reasoning = The weather for New York tomorrow is the same as San Francisco in this case? That's what the tool returned. Let me present this to the user.\n\n content = Tomorrow (April 30, 2026) in New York is also looking **sunny** with a high of **82°F** and a low of **68°F**. Looks like both coasts are getting great weather tomorrow! 🌞\n\n tool_calls= []\n```\n\n\nThis documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.",
4 "https://docs.together.ai/docs/glm-5.3-quickstart.md": "> ## Documentation Index\n> Fetch the complete documentation index at: https://docs.together.ai/llms.txt\n> Use this file to discover all available pages before exploring further.\n\n# GLM-5.3 quickstart\n\n> Call GLM-5.3 and GLM-5.3 Flash on Together for long-horizon coding and agentic work.\n\nGLM-5.3 is Z.ai's flagship mixture-of-experts (MoE) model, built for long-horizon coding and agentic work. It holds project-scale context across many steps and completes multi-stage tasks end to end. Thinking is on by default, so responses carry both a reasoning trace and a final answer.\n\nTwo variants are available on serverless inference, both with a 1M-token context window, streaming, function calling, and structured outputs:\n\n| Model | Model ID | Input / 1M tokens | Cached input / 1M tokens | Output / 1M tokens |\n| - | - | - | - | - |\n| GLM-5.3 | `zai-org/GLM-5.3` | \\$1.40 | \\$0.26 | \\$4.40 |\n| GLM-5.3 Flash | `zai-org/GLM-5.3-Flash` | \\$0.15 | \\$0.03 | \\$0.50 |\n\nGLM-5.3 is Together's [recommended pick](/docs/inference/recommended-models) for coding agents. GLM-5.3 Flash is the recommended pick for function calling and other high-volume calls. The examples below use `zai-org/GLM-5.3`. Swap in `zai-org/GLM-5.3-Flash` when cost and latency matter more than maximum depth.\n\n## Call GLM-5.3\n\nThe reasoning trace arrives on `reasoning_content` and the final answer arrives on `content`. Stream the response and handle both channels, and skip chunks where `choices` is empty, since Together emits a final usage-only chunk.\n\nGLM-5.3 emits the trace under `reasoning_content`, while some other Together models use the newer `reasoning` alias. Reading both keys makes one handler work across models.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n stream = client.chat.completions.create(\n model=\"zai-org/GLM-5.3\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"What are some fun things to do in New York?\",\n }\n ],\n temperature=1.0,\n top_p=0.95,\n max_tokens=8192,\n stream=True,\n )\n\n for chunk in stream:\n if not chunk.choices:\n continue\n delta = chunk.choices[0].delta\n thinking = getattr(delta, \"reasoning_content\", None) or getattr(\n delta, \"reasoning\", None\n )\n # Stream reasoning and content tokens as they arrive\n print(thinking or delta.content or \"\", end=\"\", flush=True)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n import type { ChatCompletionChunk } from \"together-ai/resources/chat/completions\";\n\n const together = new Together();\n\n // GLM-5.3 emits the trace on reasoning_content; other models use reasoning\n type ReasoningDelta = ChatCompletionChunk.Choice.Delta & {\n reasoning_content?: string;\n reasoning?: string;\n };\n\n const stream = await together.chat.completions.create({\n model: \"zai-org/GLM-5.3\",\n messages: [\n {\n role: \"user\",\n content: \"What are some fun things to do in New York?\",\n },\n ],\n temperature: 1.0,\n top_p: 0.95,\n max_tokens: 8192,\n stream: true,\n });\n\n for await (const chunk of stream) {\n if (!chunk.choices?.length) continue;\n const delta = chunk.choices[0]?.delta as ReasoningDelta;\n const thinking = delta?.reasoning_content || delta?.reasoning;\n // Stream reasoning and content tokens as they arrive\n process.stdout.write(thinking || delta?.content || \"\");\n }\n ```\n\n ```bash cURL theme={null}\n curl -X POST \"https://api.together.ai/v1/chat/completions\" \\\n -H \"Authorization: Bearer $TOGETHER_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"zai-org/GLM-5.3\",\n \"messages\": [\n {\"role\": \"user\", \"content\": \"What are some fun things to do in New York?\"}\n ],\n \"temperature\": 1.0,\n \"top_p\": 0.95,\n \"max_tokens\": 8192,\n \"stream\": true\n }'\n ```\n</CodeGroup>\n\n## Set the reasoning effort\n\n`reasoning_effort` accepts `\"low\"`, `\"medium\"`, `\"high\"`, and `\"max\"`. Use `\"low\"` for short, high-volume calls and `\"max\"` for the hardest planning, architecture, and multi-step agentic problems. At `\"max\"`, set `max_tokens` generously, since the trace and the answer share the same completion budget.\n\nThinking cannot be disabled entirely on GLM-5.3. `reasoning_effort=\"low\"` cuts the trace to a few tokens, which is the closest equivalent for trivial turns. The levels are coarse dials rather than a strictly monotonic scale, so measure token counts on your own prompts before you tune. Invalid effort strings are accepted silently instead of returning an error, so validate the value in your own code.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n completion = client.chat.completions.create(\n model=\"zai-org/GLM-5.3\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Design a three-tier architecture for a ticketing system.\",\n }\n ],\n reasoning_effort=\"max\",\n max_tokens=65536,\n )\n\n print(completion.choices[0].message.content)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const completion = await together.chat.completions.create({\n model: \"zai-org/GLM-5.3\",\n messages: [\n {\n role: \"user\",\n content: \"Design a three-tier architecture for a ticketing system.\",\n },\n ],\n reasoning_effort: \"max\",\n max_tokens: 65536,\n });\n\n console.log(completion.choices[0].message.content);\n ```\n</CodeGroup>\n\nFor broader guidance on reasoning controls and prompting, see [Reasoning](/docs/inference/chat/reasoning).\n\n## Preserve thinking across turns\n\nFor coding agents and other agent workflows, enable preserved thinking so the model retains its reasoning from previous turns. Set `\"clear_thinking\": false` in `chat_template_kwargs` to keep reasoning content in context across turns, which improves reasoning continuity and cache hit rates.\n\n```python Python theme={null}\nfrom together import Together\n\nclient = Together()\n\nresponse = client.chat.completions.create(\n model=\"zai-org/GLM-5.3\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Refactor this module without changing its public API.\",\n }\n ],\n chat_template_kwargs={\n \"clear_thinking\": False, # Preserved thinking\n },\n)\n\nprint(response.choices[0].message.content)\n```\n\n<Info>\n When using preserved thinking, return the model's `reasoning_content` blocks exactly as generated. Reordering or editing them degrades performance and hurts cache hit rates.\n</Info>\n\n## Call tools\n\nGLM-5.3 supports tool calling with reasoning interleaved between each step. Define tools in the standard OpenAI-compatible schema and pass them via `tools`.\n\nTo stream tool calls, set `stream=True`. The model emits tool call parameters incrementally, so concatenate the `arguments` fragments from each delta to rebuild the full call. Together does not use a separate `tool_stream` parameter.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n tools = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Get current weather conditions for a city.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"City name, e.g. Beijing, Shanghai.\",\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\"celsius\", \"fahrenheit\"],\n },\n },\n \"required\": [\"location\"],\n },\n },\n }\n ]\n\n stream = client.chat.completions.create(\n model=\"zai-org/GLM-5.3\",\n messages=[{\"role\": \"user\", \"content\": \"What's the weather in Beijing?\"}],\n tools=tools,\n stream=True,\n )\n\n final_tool_calls = {}\n\n for chunk in stream:\n if not chunk.choices:\n continue\n delta = chunk.choices[0].delta\n\n # Reassemble streamed tool calls by index\n if delta.tool_calls:\n for tool_call in delta.tool_calls:\n idx = tool_call.index\n if idx not in final_tool_calls:\n final_tool_calls[idx] = tool_call\n else:\n final_tool_calls[\n idx\n ].function.arguments += tool_call.function.arguments\n\n for idx, tool_call in final_tool_calls.items():\n print(f\"{tool_call.function.name}: {tool_call.function.arguments}\")\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const tools = [\n {\n type: \"function\" as const,\n function: {\n name: \"get_weather\",\n description: \"Get current weather conditions for a city.\",\n parameters: {\n type: \"object\",\n properties: {\n location: {\n type: \"string\",\n description: \"City name, e.g. Beijing, Shanghai.\",\n },\n unit: { type: \"string\", enum: [\"celsius\", \"fahrenheit\"] },\n },\n required: [\"location\"],\n },\n },\n },\n ];\n\n const stream = await together.chat.completions.create({\n model: \"zai-org/GLM-5.3\",\n messages: [{ role: \"user\", content: \"What's the weather in Beijing?\" }],\n tools,\n stream: true,\n });\n\n const finalToolCalls: Record<number, { name: string; arguments: string }> = {};\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta;\n if (!delta?.tool_calls) continue;\n\n for (const toolCall of delta.tool_calls) {\n const idx = toolCall.index;\n if (!(idx in finalToolCalls)) {\n finalToolCalls[idx] = {\n name: toolCall.function?.name ?? \"\",\n arguments: toolCall.function?.arguments ?? \"\",\n };\n } else {\n finalToolCalls[idx].arguments += toolCall.function?.arguments ?? \"\";\n }\n }\n }\n\n for (const idx in finalToolCalls) {\n const call = finalToolCalls[idx];\n console.log(`${call.name}: ${call.arguments}`);\n }\n ```\n</CodeGroup>\n\nFor the full tool-calling loop, including how to return tool results to the model, see [Function calling](/docs/inference/function-calling/overview).\n\n## Constrain the output to a schema\n\nGLM-5.3 supports structured outputs. Pass a JSON schema through `response_format` to constrain the response to a fixed shape. Parse `content` only, never `reasoning_content`.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n response = client.chat.completions.create(\n model=\"zai-org/GLM-5.3\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Extract the person: John is 30 years old.\",\n }\n ],\n response_format={\n \"type\": \"json_schema\",\n \"json_schema\": {\n \"name\": \"person\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"age\": {\"type\": \"integer\"},\n },\n \"required\": [\"name\", \"age\"],\n },\n },\n },\n )\n\n print(response.choices[0].message.content)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const response = await together.chat.completions.create({\n model: \"zai-org/GLM-5.3\",\n messages: [\n { role: \"user\", content: \"Extract the person: John is 30 years old.\" },\n ],\n response_format: {\n type: \"json_schema\",\n json_schema: {\n name: \"person\",\n schema: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n age: { type: \"integer\" },\n },\n required: [\"name\", \"age\"],\n },\n },\n },\n });\n\n console.log(response.choices[0].message.content);\n ```\n</CodeGroup>\n\nFor schema design guidance, see [Structured outputs](/docs/inference/chat/structured-outputs).\n\n## Usage tips\n\n| Tip | Rationale |\n| - | - |\n| **Read both `reasoning_content` and `reasoning`** | GLM-5.3 emits the trace on `reasoning_content`. Other Together models use the `reasoning` alias. One handler then covers both. |\n| **Parse `content` only** | Never run JSON parsing over the thinking trace. |\n| **Temperature = 1.0, top\\_p = 0.95** | Recommended defaults. Adjust only one of the two, not both at once. |\n| **Match `reasoning_effort` to the task** | Use `\"low\"` for trivial turns and `\"max\"` with generous `max_tokens` for hard planning and architecture work. |\n| **Use GLM-5.3 Flash for high-volume calls** | Same 1M context and tool support at a fraction of the price, for function calling and latency-sensitive work. |\n| **Use preserved thinking for agents** | Set `\"clear_thinking\": false` in `chat_template_kwargs` so coding agents keep reasoning continuity across turns. |\n| **Think in goals, not steps** | GLM-5.3 is agentic. Give high-level objectives and let it orchestrate sub-tasks and tool calls. |\n| **State constraints explicitly** | For engineering tasks, spell out hard constraints (no new dependencies, no API changes, run the tests) so the model holds the line. |\n\n## Next steps\n\n<CardGroup cols={2}>\n <Card title=\"Reasoning\" icon=\"brain\" href=\"/docs/inference/chat/reasoning\">\n Control reasoning depth and handle reasoning output across models.\n </Card>\n\n <Card title=\"Function calling\" icon=\"tool\" href=\"/docs/inference/function-calling/overview\">\n Build tool-calling loops against any function-calling model.\n </Card>\n\n <Card title=\"Recommended models\" icon=\"star\" href=\"/docs/inference/recommended-models\">\n See Together's current picks for every use case.\n </Card>\n\n <Card title=\"Serverless models\" icon=\"stack-2\" href=\"/docs/serverless/models\">\n Browse every model, context length, and price on serverless inference.\n </Card>\n</CardGroup>\n\n\nThis documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.",
5 "https://docs.together.ai/docs/inference/chat/reasoning.md": "> ## Documentation Index\n> Fetch the complete documentation index at: https://docs.together.ai/llms.txt\n> Use this file to discover all available pages before exploring further.\n\n# Reasoning\n\n> Use reasoning models that think step-by-step before answering.\n\nReasoning models are trained to think step-by-step before responding with an answer. Given an input prompt, they first produce a chain of thought, visible as tokens in a dedicated output field (`reasoning` or `reasoning_content`, depending on the model), and then output a final answer in the `content` field.\n\n## Supported models\n\nReasoning models fall into a few behavioral types:\n\n* **Reasoning only:** Always produces reasoning tokens. Cannot be toggled off.\n* **Hybrid:** Supports both reasoning and non-reasoning modes via `reasoning={\"enabled\": True/False}`.\n* **Adjustable effort:** Supports the `reasoning_effort` parameter to control reasoning depth (`\"low\"`, `\"medium\"`, or `\"high\"`).\n\nThe following models support reasoning on [serverless inference](/docs/serverless/models):\n\n| Model | API string | Type | Context length |\n| :- | :- | :- | :- |\n| MiniMax M3 | `MiniMaxAI/MiniMax-M3` | Hybrid (on by default) | 512K |\n| DeepSeek V4 Pro 0813 | `deepseek-ai/DeepSeek-V4-Pro-0813` | Hybrid (on by default) | 1M |\n| GLM-5.2 | `zai-org/GLM-5.2` | Hybrid (on by default) | 512K |\n| Kimi K3 | `moonshotai/Kimi-K3` | Hybrid (on by default) | 1M |\n| Qwen3.6 Plus | `Qwen/Qwen3.6-Plus` | Hybrid (on by default) | 1M |\n| Qwen3.5 9B | `Qwen/Qwen3.5-9B` | Hybrid (on by default) | 262K |\n| GPT-OSS 120B | `openai/gpt-oss-120b` | Adjustable effort | 128K |\n\nAdditional reasoning models, including Kimi K2.6, GLM-5, Cogito v2.1 671B, DeepSeek-R1 and its distillations, Qwen QwQ-32B, and DeepSeek V3.1 (hybrid), are available for [dedicated model inference](/docs/dedicated-endpoints/models).\n\n## Quickstart\n\nReasoning models return the chain of thought in a separate field alongside `content` in the response. The field name varies by model (see [Handle reasoning tokens](#handle-reasoning-tokens)). Reasoning models produce longer outputs, so you should stream the response:\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n stream = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Which number is bigger, 9.11 or 9.9?\",\n }\n ],\n stream=True,\n )\n\n for chunk in stream:\n if chunk.choices:\n delta = chunk.choices[0].delta\n\n # Show reasoning tokens if present\n if hasattr(delta, \"reasoning\") and delta.reasoning:\n print(delta.reasoning, end=\"\", flush=True)\n\n # Show content tokens if present\n if hasattr(delta, \"content\") and delta.content:\n print(delta.content, end=\"\", flush=True)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n import type { ChatCompletionChunk } from \"together-ai/resources/chat/completions\";\n\n const together = new Together();\n\n const stream = await together.chat.completions.stream({\n model: \"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages: [\n { role: \"user\", content: \"Which number is bigger, 9.11 or 9.9?\" },\n ],\n } as any);\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta as ChatCompletionChunk.Choice.Delta & {\n reasoning?: string;\n };\n\n // Show reasoning tokens if present\n if (delta?.reasoning) process.stdout.write(delta.reasoning);\n\n // Show content tokens if present\n if (delta?.content) process.stdout.write(delta.content);\n }\n ```\n\n ```bash cURL theme={null}\n curl -X POST \"https://api.together.ai/v1/chat/completions\" \\\n -H \"Authorization: Bearer $TOGETHER_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"deepseek-ai/DeepSeek-V4-Pro-0813\",\n \"messages\": [\n {\"role\": \"user\", \"content\": \"Which number is bigger, 9.11 or 9.9?\"}\n ],\n \"stream\": true\n }'\n ```\n</CodeGroup>\n\nThe response contains both the model's reasoning process and the final answer:\n\n```json theme={null}\n{\n \"choices\": [\n {\n \"message\": {\n \"role\": \"assistant\",\n \"content\": \"9.9 is bigger than 9.11.\",\n \"reasoning\": \"Let me compare 9.11 and 9.9. Both have 9 as the integer part, so I need to compare the decimal parts: 0.11 vs 0.9. Since 0.9 = 0.90, and 0.90 > 0.11, we know 9.9 > 9.11.\"\n }\n }\n ]\n}\n```\n\n<Info>\n DeepSeek-R1 uses a different format. It outputs reasoning inside `<think>` tags within the `content` field rather than a separate `reasoning` field. See [Handle reasoning tokens](#handle-reasoning-tokens) for details.\n</Info>\n\n## Enable and disable reasoning\n\nHybrid models let you toggle reasoning on or off using the `reasoning` parameter. This is useful when you want reasoning for complex queries but want faster, cheaper responses for simple ones.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n # Enable reasoning\n response = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Prove that the square root of 2 is irrational.\",\n }\n ],\n reasoning={\"enabled\": True},\n stream=True,\n )\n\n for chunk in response:\n if not chunk.choices:\n continue\n delta = chunk.choices[0].delta\n\n if hasattr(delta, \"reasoning\") and delta.reasoning:\n print(delta.reasoning, end=\"\", flush=True)\n\n if hasattr(delta, \"content\") and delta.content:\n print(delta.content, end=\"\", flush=True)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const stream = await together.chat.completions.stream({\n model: \"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages: [\n { role: \"user\", content: \"Prove that the square root of 2 is irrational.\" },\n ],\n reasoning: { enabled: true },\n });\n\n for await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta;\n\n if (delta?.reasoning) process.stdout.write(delta.reasoning);\n if (delta?.content) process.stdout.write(delta.content);\n }\n ```\n\n ```bash cURL theme={null}\n curl -X POST \"https://api.together.ai/v1/chat/completions\" \\\n -H \"Authorization: Bearer $TOGETHER_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"deepseek-ai/DeepSeek-V4-Pro-0813\",\n \"messages\": [\n {\"role\": \"user\", \"content\": \"Prove that the square root of 2 is irrational.\"}\n ],\n \"reasoning\": {\"enabled\": true},\n \"stream\": true\n }'\n ```\n</CodeGroup>\n\nAlternatively, you can enable or disable reasoning using `chat_template_kwargs`:\n\n```python theme={null}\nresponse = client.chat.completions.create(\n model=\"Qwen/Qwen3.5-9B\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Prove that the square root of 2 is irrational.\",\n }\n ],\n chat_template_kwargs={\n \"thinking\": True,\n # or use \"enable_thinking\": True\n },\n stream=True,\n)\n```\n\n<Warning>\n GLM-5.2 has thinking enabled by default. Pass `reasoning={\"enabled\": False}` to disable it for simple tasks where reasoning overhead isn't needed.\n</Warning>\n\nFor the list of hybrid models, see [Supported models](#supported-models).\n\n<Info>\n For DeepSeek V3.1, function calling only works in non-reasoning mode (`reasoning={\"enabled\": False}`).\n</Info>\n\n## Reasoning effort\n\nGPT-OSS models support a `reasoning_effort` parameter that controls how much computation the model spends on reasoning. This lets you balance accuracy against cost and latency.\n\n* **`\"low\"`**: Faster responses for simpler tasks with reduced reasoning depth.\n* **`\"medium\"`**: Balanced performance for most use cases (recommended default).\n* **`\"high\"`**: Maximum reasoning for complex problems. Set `max_tokens` to \\~30,000 with this setting.\n\nDeepSeek V4 Pro 0813 accepts only `\"high\"` and `\"max\"` for `reasoning_effort`. Other values are mapped automatically:\n\n* `\"low\"` and `\"medium\"` map to `\"high\"`.\n* `\"high\"` and `\"xhigh\"` map to `\"max\"`.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n stream = client.chat.completions.create(\n model=\"openai/gpt-oss-120b\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Solve: If all roses are flowers and some flowers are red, can we conclude that some roses are red?\",\n }\n ],\n temperature=1.0,\n top_p=1.0,\n reasoning_effort=\"medium\",\n stream=True,\n )\n\n for chunk in stream:\n if chunk.choices:\n print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const stream = await together.chat.completions.create({\n model: \"openai/gpt-oss-120b\",\n messages: [\n {\n role: \"user\",\n content:\n \"Solve: If all roses are flowers and some flowers are red, can we conclude that some roses are red?\",\n },\n ],\n temperature: 1.0,\n top_p: 1.0,\n reasoning_effort: \"medium\",\n stream: true,\n });\n\n for await (const chunk of stream) {\n process.stdout.write(chunk.choices[0]?.delta?.content || \"\");\n }\n ```\n\n ```bash cURL theme={null}\n curl -X POST \"https://api.together.ai/v1/chat/completions\" \\\n -H \"Authorization: Bearer $TOGETHER_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"openai/gpt-oss-120b\",\n \"messages\": [\n {\"role\": \"user\", \"content\": \"Solve: If all roses are flowers and some flowers are red, can we conclude that some roses are red?\"}\n ],\n \"temperature\": 1.0,\n \"top_p\": 1.0,\n \"reasoning_effort\": \"medium\",\n \"stream\": true\n }'\n ```\n</CodeGroup>\n\n### Controlling reasoning depth via prompting\n\nFor models that don't support a `reasoning_effort` parameter, you can influence how much the model thinks by including instructions in your prompt. This is a simple way to reduce token usage and latency when the problem doesn't warrant deep reasoning.\n\nAsk the model to keep its thinking concise:\n\n```python theme={null}\nresponse = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Please be succinct in your thinking.\\n\\nWhat is the derivative of x^3 + 2x?\",\n }\n ],\n stream=True,\n)\n```\n\nYou can also suggest an approximate budget for the reasoning process:\n\n```python theme={null}\nresponse = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Please use around 1000 words to think, but do not literally count each one.\\n\\nExplain why quicksort has O(n log n) average-case complexity.\",\n }\n ],\n stream=True,\n)\n```\n\n<Info>\n This technique works across all reasoning models. The model won't hit an exact word count, but it reliably produces shorter or longer reasoning chains in response to the guidance. Combine it with `max_tokens` for a hard ceiling on total output.\n</Info>\n\n## Thinking modes\n\nMany of our models support advanced thinking modes that control how reasoning integrates with tool calling and multi-turn conversations.\n\n### Interleaved thinking\n\nThe default mode. The model reasons between tool calls and after receiving tool results, enabling complex step-by-step reasoning where it interprets each tool output before deciding what to do next.\n\n```python theme={null}\nfrom together import Together\n\nclient = Together()\n\ntools = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Get the current weather for a location.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\"type\": \"string\", \"description\": \"City name\"}\n },\n \"required\": [\"location\"],\n },\n },\n }\n]\n\nresponse = client.chat.completions.create(\n model=\"zai-org/GLM-5.2\",\n messages=[\n {\"role\": \"user\", \"content\": \"What's the weather in Paris and Tokyo?\"}\n ],\n tools=tools,\n)\n\nprint(\n json.dumps(\n response.choices[0].message.model_dump()[\"tool_calls\"],\n indent=2,\n )\n)\n```\n\nIn this mode, the model will reason about which tool to call first, interpret the result, then reason again before making the next call.\n\n### Preserved thinking\n\nThe model retains reasoning content from previous assistant turns in the conversation context, improving reasoning continuity and cache hit rates. This is ideal for coding agents and multi-turn agent workflows.\n\nEnable preserved thinking by setting `clear_thinking` to `false`:\n\n```python theme={null}\nresponse = client.chat.completions.create(\n model=\"zai-org/GLM-5.2\",\n messages=messages,\n tools=tools,\n stream=True,\n chat_template_kwargs={\n \"clear_thinking\": False, # Preserved Thinking\n },\n)\n```\n\nWhen using preserved thinking, include the unmodified `reasoning_content` from previous turns back in the conversation:\n\n```python theme={null}\nmessages.append(\n {\n \"role\": \"assistant\",\n \"content\": content,\n \"reasoning_content\": reasoning_content, # Return reasoning content faithfully\n \"tool_calls\": tool_calls,\n }\n)\n```\n\n<Warning>\n When using preserved thinking, all consecutive `reasoning_content` blocks must exactly match the original sequence generated by the model. Don't reorder or edit these blocks. Otherwise, performance may degrade and cache hit rates will drop.\n</Warning>\n\n### Turn-level thinking\n\nControl reasoning on a per-turn basis within the same session. Enable thinking for hard turns (planning, debugging) and disable it for simple ones (facts, rewording) to save cost.\n\nFor a complete streamed tool-calling example, see the [GLM-5.3 quickstart](/docs/glm-5.3-quickstart#call-tools).\n\n## Handle reasoning tokens\n\nThere are two patterns for accessing reasoning tokens, depending on the model.\n\n### Separate reasoning field\n\nSome models (DeepSeek V4 Pro 0813, GPT-OSS) return reasoning in a dedicated `reasoning` field on the response message or streaming delta. Others (Kimi K3, GLM-5.2, MiniMax M3) use a `reasoning_content` field the same way:\n\n```python theme={null}\nfrom together import Together\n\nclient = Together()\n\nresponse = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Say test 10 times\",\n }\n ],\n)\n\nprint(\"Reasoning:\", response.choices[0].message.reasoning)\nprint(\"Answer:\", response.choices[0].message.content)\n```\n\n<Note>\n Use the same field for input and output. The model returns its chain of thought in `reasoning` or `reasoning_content` (also on the streaming `delta`), and you pass it back under the same key when you send a prior assistant turn to the API for [preserved thinking](#preserved-thinking) or multi-turn tool calling.\n</Note>\n\n### `<think>` tags in content\n\nDeepSeek-R1 embeds reasoning directly in the `content` field using `<think>` tags:\n\n```plain theme={null}\n<think>\nLet me compare 9.11 and 9.9 by looking at their decimal parts...\n0.11 vs 0.9 , since 0.9 is larger, 9.9 > 9.11.\n</think>\n\n**Answer:** 9.9 is bigger.\n```\n\nTo extract the reasoning and answer separately:\n\n```python theme={null}\nimport re\n\ncontent = response.choices[0].message.content\n\nthink_match = re.search(r\"<think>(.*?)</think>\", content, re.DOTALL)\n\nreasoning = think_match.group(1).strip() if think_match else \"\"\n\nanswer = re.sub(r\"<think>.*?</think>\", \"\", content, flags=re.DOTALL).strip()\n```\n\n## Structured outputs with reasoning models\n\nReasoning models can return JSON that conforms to a schema, the same way non-reasoning models do. The model still produces its chain of thought in the `reasoning` field, then writes the structured answer to `content`.\n\nExample: have DeepSeek V4 Pro 0813 solve a math problem and return the steps as typed JSON.\n\n```python Python theme={null}\nimport json\nfrom together import Together\nfrom pydantic import BaseModel\n\nclient = Together()\n\n\nclass Step(BaseModel):\n explanation: str\n output: str\n\n\nclass MathReasoning(BaseModel):\n steps: list[Step]\n final_answer: str\n\n\ncompletion = client.chat.completions.create(\n model=\"deepseek-ai/DeepSeek-V4-Pro-0813\",\n messages=[\n {\n \"role\": \"system\",\n \"content\": \"You are a helpful math tutor. Guide the user through the solution step by step.\",\n },\n {\"role\": \"user\", \"content\": \"how can I solve 8x + 7 = -23\"},\n ],\n response_format={\n \"type\": \"json_schema\",\n \"json_schema\": {\n \"name\": \"math_reasoning\",\n \"schema\": MathReasoning.model_json_schema(),\n },\n },\n)\n\nmath_reasoning = json.loads(completion.choices[0].message.content)\nprint(json.dumps(math_reasoning, indent=2))\n```\n\nExample output:\n\n```json JSON theme={null}\n{\n \"steps\": [\n {\n \"explanation\": \"To solve 8x + 7 = -23, I need to isolate x.\",\n \"output\": \"\"\n },\n {\n \"explanation\": \"Subtract 7 from both sides.\",\n \"output\": \"8x = -30\"\n },\n {\n \"explanation\": \"Divide both sides by 8.\",\n \"output\": \"x = -30/8 = -15/4\"\n }\n ],\n \"final_answer\": \"x = -15/4\"\n}\n```\n\nFor the full structured-outputs reference, see [Structured outputs](/docs/inference/chat/structured-outputs).\n\n## Prompting best practices\n\nPrompt reasoning models differently than standard models:\n\n| Tip | Details |\n| - | - |\n| **Use the right temperature** | DeepSeek-R1: 0.6. DeepSeek V4 Pro 0813 / GLM-5.2 / Kimi K3 / GPT-OSS: 1.0. |\n| **System prompts vary by model** | DeepSeek-R1: omit system prompts entirely. Kimi models: use `\"You are Kimi, an AI assistant created by Moonshot AI.\"` GPT-OSS: use the `developer` role message. |\n| **Don't add chain-of-thought instructions** | These models already reason step-by-step. Telling them to \"think step by step\" is unnecessary and can hurt performance. |\n| **Avoid few-shot examples** | Few-shot prompting can degrade performance. Describe the task and desired output format instead. |\n| **Think in goals, not steps** | Provide high-level objectives (e.g., \"Analyze this data and identify trends\") and let the model determine the methodology. Over-prompting limits reasoning ability. |\n| **Structure your prompt** | Use XML tags, markdown formatting, or labeled sections to separate different parts of your prompt. |\n| **Set generous `max_tokens`** | Reasoning tokens can number in the tens of thousands for complex problems. Ensure your `max_tokens` accommodates both reasoning and content. |\n\n## When not to use reasoning\n\nNon-reasoning models are a better fit when:\n\n* **Latency is critical**: Real-time voice agents, instant-response chatbots, or other applications that need fast responses.\n* **Tasks are straightforward**: Simple classification, basic text generation, factual lookups, or quick summaries don't benefit from extended reasoning.\n* **Cost is the priority**: High-volume pipelines processing many simple queries. Reasoning tokens significantly increase per-query costs.\n\nFor these use cases, consider faster non-reasoning models like [Llama 3.3 70B](/docs/serverless/models) or [Qwen3.5 9B](/docs/serverless/models).\n\n## Manage costs and latency\n\nReasoning tokens can vary from a few hundred for simple problems to tens of thousands for complex challenges. Strategies to keep costs and latency in check:\n\n* **Count reasoning tokens**: Reasoning output is billed as completion tokens and reported under `usage.completion_tokens_details.reasoning_tokens`. See [OpenAI compatibility](/docs/inference/openai-compatibility#response-shape-differences) for the full usage-object shape, which varies by model.\n* **Use `max_tokens`**: Set a token limit to cap total output. This reduces costs but may truncate reasoning on complex problems. Find the right balance for your use case.\n* **Toggle reasoning on hybrid models**: Use `reasoning={\"enabled\": False}` for simple queries and only enable it when the task benefits from deeper analysis.\n* **Use reasoning effort levels**: On GPT-OSS, use `reasoning_effort=\"low\"` for routine tasks and `\"high\"` for critical decisions.\n* **Use turn-level thinking**: On GLM-5.2, disable thinking for simple turns and enable it only for complex ones within the same session.\n* **Prompt for shorter reasoning**: Include instructions like \"Be succinct in your thinking\" to reduce reasoning token usage on simpler problems. See [Controlling reasoning depth via prompting](#controlling-reasoning-depth-via-prompting).\n* **Stream responses**: Since reasoning models produce longer outputs, streaming with `stream=True` provides a better user experience by showing partial results as they arrive.\n\n\nThis documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.",
6 "https://docs.mistral.ai/studio/conversations/reasoning.md": "---\nid: reasoning\ntitle: Reasoning\nsidebar_position: 4\n---\n\n# Reasoning\n\n**Reasoning** is the next step of CoT (Chain of Thought), naturally used to describe the **logical steps generated by the model** before reaching a conclusion. Reasoning strengthens this characteristic by going through **training steps that encourage the model to generate chains of thought freely before producing the final answer**. This allows models to **explore the problem more profoundly and ultimately reach a better solution** to the best of their ability by using extra compute time to generate more tokens and improve the answer—also described as **Test Time Computation**.\n\n<Image\n url={['/img/_reasoning_graph.png', '/img/_reasoning_graph-dark.png']}\n alt=\"Reasoning LLM AI\"\n width=\"700px\"\n centered\n/>\n\nThey excel at complex use cases like math and coding tasks, but can be used in a wide range of scenarios to solve diverse problems. The output of reasoning models includes a reasoning chunk with the model's thinking traces, followed by the final answer.\n\n:::note\nLooking for native reasoning models (`magistral-small-latest`, `magistral-medium-latest`)? These have been deprecated. See [Native reasoning (deprecated)](/resources/deprecated/native-reasoning).\n:::\n\n:::tip\nBefore continuing, we recommend reading the [Chat Completions](/studio/conversations/chat-completion) documentation to learn more about the chat completions API and how to use it before proceeding.\n:::\n\n<SectionTab as=\"h1\" sectionId=\"before-you-start\">\n Before you start\n</SectionTab>\n\n### Model\n\n- `mistral-small-latest`: Supports adjustable reasoning via the `reasoning_effort` parameter. No extra configuration required — just add the parameter to any chat completion request.\n- `mistral-medium-3-5`: Supports adjustable reasoning via the `reasoning_effort` parameter. For agentic and code use cases, `reasoning_effort=\"high\"` is recommended.\n- `mistral-large-4-0`: Supports adjustable reasoning via the `reasoning_effort` parameter. No extra configuration required — just add the parameter to any chat completion request.\n- `zai-glm-5-3`: Supports adjustable reasoning via the `reasoning_effort` parameter. Supported values are `low`, `high`, and `max` (see note below).\n\nThe `reasoning_effort` parameter controls how reasoning is surfaced in the output:\n\n- `reasoning_effort = \"high\"`: The response includes a full thinking chunk before the final answer, at the cost of increased token usage.\n- `reasoning_effort = \"none\"`: The model thinks minimally and the thinking chunk is omitted from the response.\n\n:::note\n`zai-glm-5-3` supports `low`, `high`, and `max` — not `none`. Unlike Mistral models, `message.content` is always returned as a list of chunks (thinking + text) regardless of the `reasoning_effort` value; there is no plain-string mode. The response shape follows the same chunk-list pattern described in [Handling thinking chunks](#handling-thinking-chunks).\n:::\n\n:::note\n`reasoning_effort` is also available on the [Agents](/api/endpoint/beta/agents) and [Conversations](/api/endpoint/beta/conversations) endpoints via the API, inside the `completion_args` field.\n:::\n\n<SectionTab as=\"h1\" sectionId=\"usage\">\n Usage\n</SectionTab>\n\n<SectionTab\n as=\"h2\"\n variant=\"secondary\"\n sectionId=\"reasoning-with-chat-completions\"\n>\n Reasoning with chat completions\n</SectionTab>\n\nHere is an example via our [chat completions](https://docs.mistral.ai/api/#tag/chat) endpoint:\n\n<Tabs groupId=\"code\">\n <TabItem value=\"python\" label=\"python\" default>\n <Tabs groupId=\"sdk-version\">\n <TabItem value=\"v1\" label=\"V1\">\n\n```python\n# Not available in the V1 SDK (mistralai 1.x).\n# This feature requires the V2 SDK: pip install \"mistralai>=2\", then use the V2 tab.\n# Migration guide: https://docs.mistral.ai/resources/migration-guides\n```\n\n </TabItem>\n <TabItem value=\"v2\" label=\"V2\" default>\n\n```python\nimport os\nfrom mistralai.client import Mistral\n\napi_key = os.environ[\"MISTRAL_API_KEY\"]\nmodel = \"mistral-small-latest\"\n\nclient = Mistral(api_key=api_key)\n\nchat_response = client.chat.complete(\n model = model,\n messages = [\n {\n \"role\": \"user\",\n \"content\": \"John is one of 4 children. The first sister is 4 years old. Next year, the second sister will be twice as old as the first sister. The third sister is two years older than the second sister. The third sister is half the age of her older brother. How old is John?\",\n },\n ],\n reasoning_effort=\"high\"\n)\n```\n\n </TabItem>\n </Tabs>\n </TabItem>\n <TabItem value=\"typescript\" label=\"typescript\">\n\n```typescript\n\ndotenv.config();\n\nconst apiKey = process.env.MISTRAL_API_KEY;\n\nconst client = new Mistral({ apiKey: apiKey });\n\nasync function main() {\n const chatResponse = await client.chat.complete({\n model: 'mistral-small-latest',\n messages: [\n {\n role: 'user',\n content:\n 'John is one of 4 children. The first sister is 4 years old. Next year, the second sister will be twice as old as the first sister. The third sister is two years older than the second sister. The third sister is half the age of her older brother. How old is John?',\n },\n ],\n reasoning_effort: \"high\"\n });\n}\n\nmain();\n```\n\n </TabItem>\n <TabItem value=\"curl\" label=\"curl\">\n\n```bash\ncurl --location \"https://api.mistral.ai/v1/chat/completions\" \\\n --header 'Content-Type: application/json' \\\n --header 'Accept: application/json' \\\n --header \"Authorization: Bearer $MISTRAL_API_KEY\" \\\n --data '{\n \"model\": \"mistral-small-latest\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"John is one of 4 children. The first sister is 4 years old. Next year, the second sister will be twice as old as the first sister. The third sister is two years older than the second sister. The third sister is half the age of her older brother. How old is John?\"\n }\n ],\n \"reasoning_effort\": \"high\"\n }'\n```\n\n </TabItem>\n <TabItem value=\"output\" label=\"output\">\n```json\n{\n \"id\":\"0d93cd053f4c4b3ca627ccd07cf2f18c\",\n \"created\":1773842038,\n \"model\":\"mistral-small-latest\",\n \"usage\":\n {\n \"prompt_tokens\":77,\n \"total_tokens\":1191,\n \"completion_tokens\":1114,\n \"prompt_tokens_details\":\n {\n \"cached_tokens\":0\n }\n },\n \"object\":\"chat.completion\",\n \"choices\":\n [\n {\n \"index\":0,\n \"finish_reason\":\"stop\",\n \"message\":\n {\n \"role\":\"assistant\",\n \"tool_calls\":null,\n \"content\":\n [\n {\"type\":\"thinking\",\n \"thinking\":\n [\n {\n \"type\":\"text\",\n \"text\":\"Okay, let's try to figure out John's age. So, John is one of 4 children. There are three sisters and one brother (John). Wait, the problem says \\\"the first sister,\\\" \\\"the second sister,\\\" \\\"the third sister,\\\" so that means there are three sisters and John is the brother. So total four children: three sisters and John.\\n\\nFirst, the first sister is 4 years old. Let's note that down. Let's call the sisters S1, S2, S3, and John is J.\\n\\nGiven:\\n- S1 = 4 years old (current age)\\n- Next year, the second sister (S2) will be twice as old as the first sister (S1). Wait, \\\"next year\\\" meaning one year from now. So next year, S1 will be 5, and S2 will be twice that, so 10? Wait, but let's check.\\n\\nWait, the problem says: \\\"Next year, the second sister will be twice as old as the first sister.\\\" So next year, S2's age = 2 * S1's age next year.\\n\\nS1 is currently 4, so next year S1 will be 5. Therefore, next year S2 will be 2*5=10. Therefore, S2's current age is 10 - 1 = 9 years old.\\n\\nWait, let's confirm that. If S2 is currently X years old, then next year S2 will be X+1. At that time, S1 will be 4+1=5. So X+1 = 2*5 => X+1=10 => X=9. So S2 is currently 9.\\n\\nNext, \\\"The third sister is two years older than the second sister.\\\" So S3 = S2 + 2. Since S2 is 9, S3 is 11.\\n\\nThen, \\\"The third sister is half the age of her older brother.\\\" The older brother is John, since John is a brother (assuming he's older than the sisters; but wait, could John be younger? Wait, the problem says \\\"her older brother,\\\" so the brother is older than the third sister. So John is older than S3.\\n\\nSo S3 = (1/2) * J => J = 2 * S3.\\n\\nSince S3 is 11, then J = 22.\\n\\nWait, let's check all steps again.\\n\\nCurrent ages:\\n\\nS1 = 4\\n\\nNext year, S1 will be 5. At that time, S2 will be twice S1's age next year, so 10. Therefore, S2's current age is 10 - 1 = 9.\\n\\nS3 = S2 + 2 = 9 + 2 = 11.\\n\\nS3 is half the age of her older brother (John), so John's age is 2 * 11 = 22.\\n\\nSo John is 22 years old.\\n\\nWait, but let's make sure there's no mistake here. Let's verify each statement with these ages.\\n\\nFirst sister is 4: correct.\\n\\nNext year, first sister will be 5. Second sister next year will be 9 + 1 = 10, which is twice 5: correct.\\n\\nThird sister is two years older than second sister: 9 + 2 = 11, correct.\\n\\nThird sister (11) is half the age of her older brother: so brother is 22, which is older than 11: correct.\\n\\nSo all conditions are satisfied. Therefore, John is 22.\"}]},{\"type\":\"text\",\"text\":\"Let's denote the ages of the sisters as follows:\\n- \\\\( S_1 \\\\): age of the first sister\\n- \\\\( S_2 \\\\): age of the second sister\\n- \\\\( S_3 \\\\): age of the third sister\\n- \\\\( J \\\\): age of John\\n\\nFrom the problem statement, we have the following information:\\n1. The first sister is currently 4 years old: \\\\( S_1 = 4 \\\\).\\n2. Next year, the second sister will be twice as old as the first sister: \\\\( S_2 + 1 = 2 \\\\times (S_1 + 1) \\\\).\\n3. The third sister is two years older than the second sister: \\\\( S_3 = S_2 + 2 \\\\).\\n4. The third sister is half the age of her older brother: \\\\( S_3 = \\\\frac{1}{2}J \\\\).\\n\\nFirst, we calculate the age of the second sister:\\n\\\\[ S_2 + 1 = 2 \\\\times (4 + 1) \\\\]\\n\\\\[ S_2 + 1 = 2 \\\\times 5 \\\\]\\n\\\\[ S_2 + 1 = 10 \\\\]\\n\\\\[ S_2 = 9 \\\\]\\n\\nNext, we calculate the age of the third sister:\\n\\\\[ S_3 = S_2 + 2 \\\\]\\n\\\\[ S_3 = 9 + 2 \\\\]\\n\\\\[ S_3 = 11 \\\\]\\n\\nFinally, we calculate John's age:\\n\\\\[ S_3 = \\\\frac{1}{2}J \\\\]\\n\\\\[ 11 = \\\\frac{1}{2}J \\\\]\\n\\\\[ J = 22 \\\\]\\n\\nTherefore, John is \\\\(\\\\boxed{22}\\\\) years old.\"\n }\n ]\n }\n }\n ]\n}\n```\n </TabItem>\n</Tabs>\n\n<SectionTab as=\"h1\" sectionId=\"handling-thinking-chunks\">\n Handling thinking chunks\n</SectionTab>\n\nWhen `reasoning_effort` is set to `\"high\"`, the response `message.content` is a **list of chunks** instead of a plain string. Two chunk types appear:\n\n- **`ThinkChunk`** (`type: \"thinking\"`): contains the model's reasoning trace. The `thinking` field is itself a list of `TextChunk` objects.\n- **`TextChunk`** (`type: \"text\"`): contains the final answer.\n\nWhen `reasoning_effort` is `\"none\"`, `message.content` is a plain `str` with no thinking trace.\n\n<SectionTab\n as=\"h2\"\n variant=\"secondary\"\n sectionId=\"parsing-response\"\n>\n Parsing the response\n</SectionTab>\n\n<Tabs groupId=\"code\">\n <TabItem value=\"python\" label=\"python\" default>\n\n```python\nfrom mistralai.client.models import TextChunk, ThinkChunk\n\n# Assuming chat_response from the example above\ncontent = chat_response.choices[0].message.content\n\n# reasoning_effort=\"none\" returns a plain string\nif isinstance(content, str):\n print(content)\nelse:\n for chunk in content:\n if isinstance(chunk, ThinkChunk):\n print(\"--- thinking ---\")\n for inner in chunk.thinking:\n if isinstance(inner, TextChunk):\n print(inner.text)\n print(\"--- /thinking ---\")\n elif isinstance(chunk, TextChunk):\n print(chunk.text)\n```\n\n </TabItem>\n <TabItem value=\"typescript\" label=\"typescript\">\n\n```typescript\n// Assuming chatResponse from the example above\nconst content = chatResponse.choices[0].message.content;\n\nif (typeof content === 'string') {\n console.log(content);\n} else {\n for (const chunk of content) {\n if (chunk.type === 'thinking') {\n console.log('--- thinking ---');\n for (const inner of chunk.thinking) {\n if (inner.type === 'text') {\n console.log(inner.text);\n }\n }\n console.log('--- /thinking ---');\n } else if (chunk.type === 'text') {\n console.log(chunk.text);\n }\n }\n}\n```\n\n </TabItem>\n</Tabs>\n\n<SectionTab\n as=\"h2\"\n variant=\"secondary\"\n sectionId=\"streaming\"\n>\n Streaming\n</SectionTab>\n\nWhen streaming, `delta.content` changes shape during the response:\n\n1. **Thinking phase**: `delta.content` is a list containing a `ThinkChunk`\n2. **Transition**: a single list containing both a closing `ThinkChunk` and the first `TextChunk`\n3. **Answer phase**: `delta.content` is a plain string\n\n<Tabs groupId=\"code\">\n <TabItem value=\"python\" label=\"python\" default>\n\n```python\nimport os\nfrom mistralai.client import Mistral\nfrom mistralai.client.models import TextChunk, ThinkChunk\n\nclient = Mistral(api_key=os.environ[\"MISTRAL_API_KEY\"])\n\nin_thinking = False\n\nfor event in client.chat.stream(\n model=\"mistral-medium-3-5\",\n messages=[{\"role\": \"user\", \"content\": \"What is 17 * 23?\"}],\n reasoning_effort=\"high\",\n):\n delta = event.data.choices[0].delta.content\n if not delta:\n continue\n\n # After thinking ends, delta is a plain string\n if isinstance(delta, str):\n if in_thinking:\n print(\"\\n--- /thinking ---\")\n in_thinking = False\n print(delta, end=\"\", flush=True)\n continue\n\n # During thinking, delta is a list of chunks\n for chunk in delta:\n if isinstance(chunk, ThinkChunk):\n if not in_thinking:\n print(\"--- thinking ---\")\n in_thinking = True\n for inner in chunk.thinking:\n if isinstance(inner, TextChunk):\n print(inner.text, end=\"\", flush=True)\n elif isinstance(chunk, TextChunk):\n if in_thinking:\n print(\"\\n--- /thinking ---\")\n in_thinking = False\n print(chunk.text, end=\"\", flush=True)\n```\n\n </TabItem>\n <TabItem value=\"typescript\" label=\"typescript\">\n\n```typescript\n\nconst client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });\n\nlet inThinking = false;\n\nconst stream = client.chat.stream({\n model: 'mistral-medium-3-5',\n messages: [{ role: 'user', content: 'What is 17 * 23?' }],\n reasoningEffort: 'high',\n});\n\nfor await (const event of stream) {\n const delta = event.data.choices[0].delta.content;\n if (!delta) continue;\n\n if (typeof delta === 'string') {\n if (inThinking) {\n process.stdout.write('\\n--- /thinking ---\\n');\n inThinking = false;\n }\n process.stdout.write(delta);\n continue;\n }\n\n for (const chunk of delta) {\n if (chunk.type === 'thinking') {\n if (!inThinking) {\n process.stdout.write('--- thinking ---\\n');\n inThinking = true;\n }\n for (const inner of chunk.thinking) {\n if (inner.type === 'text') {\n process.stdout.write(inner.text);\n }\n }\n } else if (chunk.type === 'text') {\n if (inThinking) {\n process.stdout.write('\\n--- /thinking ---\\n');\n inThinking = false;\n }\n process.stdout.write(chunk.text);\n }\n }\n}\n```\n\n </TabItem>\n</Tabs>\n\n<SectionTab\n as=\"h2\"\n variant=\"secondary\"\n sectionId=\"multi-turn\"\n>\n Multi-turn conversations\n</SectionTab>\n\nWhen building multi-turn conversations with reasoning, **always replay the full assistant message (including `ThinkChunk`) back into the message history**. Dropping the reasoning trace across turns degrades model performance.\n\n<Tabs groupId=\"code\">\n <TabItem value=\"python\" label=\"python\" default>\n\n```python\nfrom mistralai.client import Mistral\nfrom mistralai.client.models import TextChunk, ThinkChunk, UserMessage\n\nclient = Mistral(api_key=\"your-api-key\", timeout_ms=300_000)\n\nmessages = []\n\nfor user_text in [\"What is 17 * 23?\", \"Now multiply that by 3.\"]:\n messages.append(UserMessage(content=user_text))\n\n response = client.chat.complete(\n model=\"mistral-medium-3-5\",\n messages=messages,\n reasoning_effort=\"high\",\n )\n\n assistant_message = response.choices[0].message\n\n # Print only the final answer (for display purposes)\n content = assistant_message.content\n if isinstance(content, str):\n print(content)\n else:\n answer = \"\".join(\n c.text for c in (content or []) if isinstance(c, TextChunk)\n )\n print(answer)\n\n # IMPORTANT: append the full assistant message to history.\n # This preserves ThinkChunk so the model can see its own\n # reasoning trace in subsequent turns.\n # Do NOT rebuild the message with only the answer text.\n messages.append(assistant_message)\n```\n\n </TabItem>\n <TabItem value=\"output\" label=\"output\">\n\n```\n--- Turn 1: \"What is 17 * 23?\" ---\nUsage: prompt=25, completion=187\n\nThinkChunk:\n Let me think about this multiplication problem. I know that\n 17 times 20 is 340, and 17 times 3 is 51. So, if I add those\n together, 340 + 51 = 391. So, 17 * 23 should be 391.\n\nTextChunk:\n 17 * 23 = 391.\n\n--- Turn 2: \"Now multiply that by 3.\" ---\nUsage: prompt=221, completion=143\n\nThinkChunk:\n The user wants me to multiply the previous result, which was\n 391, by 3.\n 391 * 3:\n - 300 * 3 = 900\n - 90 * 3 = 270\n - 1 * 3 = 3\n 900 + 270 + 3 = 1173\n\nTextChunk:\n 391 * 3 = 1173.\n```\n\nNotice how the prompt token count grows between turns:\n- **Turn 1**: `prompt=25` — just the user message\n- **Turn 2**: `prompt=221` — the original user message (25) + the full assistant reply from turn 1 including its ThinkChunk (187) + the new user message (9) = 221\n\nThe 187 completion tokens from turn 1 are replayed as prompt tokens in turn 2 because we appended the full `assistant_message` (ThinkChunk + TextChunk) to the history. This is what allows the model to correctly reference \"the previous result\" without ambiguity.\n\n </TabItem>\n</Tabs>\n\n:::warning\nDo not strip `ThinkChunk` from assistant messages before replaying them. The model relies on the reasoning trace to maintain coherence across turns. Stripping them increases token efficiency but significantly degrades output quality.\n:::",
7 "https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash.md.txt": "<br />\n\nGemini 3.8 Flash is our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows---all with the speed and cost efficiency of Flash.\n[Try in Google AI Studio](https://aistudio.google.com/prompts/new_chat?model=gemini-3.8-flash)\n\n## Documentation\n\nVisit the\n[Latest model](https://ai.google.dev/gemini-api/docs/latest-model)\npage for full coverage of features and capabilities.\n\n## gemini-3.8-flash\n\n| Property | Description |\n|---|---|\n| Model code | `gemini-3.8-flash` |\n| Supported data types | **Inputs** Text, Image, Video, Audio, and PDF **Output** Text |\n| Token limits^[\\[\\*\\]](https://ai.google.dev/gemini-api/docs/tokens)^ | **Input token limit** 1,048,576 **Output token limit** 65,536 |\n| Capabilities | **[Audio generation](https://ai.google.dev/gemini-api/docs/speech-generation)** Not supported **[Caching](https://ai.google.dev/gemini-api/docs/caching)** Supported **[Code execution](https://ai.google.dev/gemini-api/docs/code-execution)** Supported **[Computer use](https://ai.google.dev/gemini-api/docs/computer-use)** Supported (Preview) **[File search](https://ai.google.dev/gemini-api/docs/file-search)** Supported **[Function calling](https://ai.google.dev/gemini-api/docs/function-calling)** Supported **[Grounding with Google Maps](https://ai.google.dev/gemini-api/docs/maps-grounding)** Supported **[Image generation](https://ai.google.dev/gemini-api/docs/image-generation)** Not supported **[Live API](https://ai.google.dev/gemini-api/docs/live-api)** Not supported **[Search grounding](https://ai.google.dev/gemini-api/docs/google-search)** Supported **[Structured outputs](https://ai.google.dev/gemini-api/docs/structured-output)** Supported **[Thinking](https://ai.google.dev/gemini-api/docs/thinking)** Supported (low, medium, high) Note: `minimal` is not supported and returns an error. **[URL context](https://ai.google.dev/gemini-api/docs/url-context)** Supported |\n| Consumption options | **[Batch API](https://ai.google.dev/gemini-api/docs/batch-api)** Supported **[Flex inference](https://ai.google.dev/gemini-api/docs/flex-inference)** Supported **[Priority inference](https://ai.google.dev/gemini-api/docs/priority-inference)** Supported |\n| Versions | Read the [model version patterns](https://ai.google.dev/gemini-api/docs/models/gemini#model-versions) for more details. - Stable: `gemini-3.8-flash` |\n| Latest update | September 2026 |\n| Model card | [Model card](https://deepmind.google/models/model-cards/gemini-3-8-flash/) |",
8 "https://ai.google.dev/gemini-api/docs/models.md.txt": "This guide introduces all the models available through the Gemini API.\n\n*** ** * ** ***\n\n## Gemini 3\n\n### Stable\n\n[### Gemini 3.8 Flash\nOur most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows.\nNew Stable](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash) [### Gemini 3.8 Live\nDefault Live API model for most low-latency voice agent experiences without reasoning delays.\nNew Stable](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-live) [### Gemini 3.8 Live Extended Thinking\nHigh-reasoning Live API model for voice interactions, recommended when higher background reasoning is required.\nNew Stable](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-live-extended-thinking) [### Gemini 3.8 Flash TTS\nFlagship creative text-to-speech model for studio-grade voice fidelity, expressive acting, Voice design, and Voice replication.\nNew Stable](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash-tts) [### Gemini 3.8 Flash-Lite TTS\nFast, cost-efficient text-to-speech model for high-volume production, real-time voice agent cascades, and Voice replication.\nNew Stable](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash-lite-tts) [### Gemini 3.7 Flash\nOur previous-generation Flash model for complex coding, agentic workflows, and reliable multi-step execution.\nStable](https://ai.google.dev/gemini-api/docs/models/gemini-3.7-flash) [### Gemini 3.6 Flash\nOur previous-generation Flash model, balancing speed and multimodal capabilities across general agentic and everyday tasks.\nStable](https://ai.google.dev/gemini-api/docs/models/gemini-3.6-flash) [### Gemini 3.5 Flash\nOur legacy Flash model, providing baseline speed and foundational performance for routine, high-throughput workloads.\nStable](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-flash) [### Gemini 3.5 Flash-Lite\nOur fastest, most cost-effective 3.5 model for high-throughput execution.\nStable](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-flash-lite) [### Gemini 3.1 Flash-Lite\nFrontier-class performance rivaling larger models at a fraction of the cost.\nStable](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite) [### Nano Banana 2.1\nHigh-efficiency image generation and editing model with improved visual quality, typography, and multi-turn consistency.\nNew Stable](https://ai.google.dev/gemini-api/docs/models/gemini-nano-banana-2.1) [### Nano Banana 2\nPowerful, high-efficiency image generation and editing, optimized for speed and high-volume use cases.\nStable](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-image) [### Nano Banana 2 Lite\nUltra-low latency and cost-effective image generation and editing, designed for high-volume interactive use cases.\nStable](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite-image) [### Nano Banana Pro\nState-of-the-art image generation and editing models for highly contextual native image creation.\nStable](https://ai.google.dev/gemini-api/docs/models/gemini-3-pro-image) [### Gemini 3.5 Transcribe\nLow-latency speech-to-text model with utterance-based language detection, speaker diarization, and word timestamps.\nNew Stable](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-transcribe)\n\n### Preview\n\n[### Gemini 3.1 Pro\nAdvanced intelligence, complex problem-solving skills, and powerful agentic and vibe coding capabilities.\nPreview](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-pro-preview) [### Gemini 3 Flash\nFrontier-class performance rivaling larger models at a fraction of the cost.\nPreview](https://ai.google.dev/gemini-api/docs/models/gemini-3-flash-preview) [### Gemini 3.5 Live Translate\nLow-latency, real-time speech to speech translation model that supports 70+ languages.\nNew](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-live-translate-preview) [### Gemini 3.1 Flash Live\nLegacy Live API preview model. We recommend updating to Gemini 3.8 Live.\nNew](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-live-preview) [### Gemini 3.1 Flash TTS\nLegacy TTS preview model. We recommend updating to Gemini 3.8 Flash TTS or Gemini 3.8 Flash-Lite TTS.\nPreview](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-tts-preview) [### Gemini Omni Flash\nFast video generation, editing, keyframe interpolation, and extension with native audio.\nNew](https://ai.google.dev/gemini-api/docs/models/gemini-omni-flash)\n\n### All Gemini 3 models\n\n| Model | Endpoint |\n|---|---|\n| [Gemini 3.8 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash) | ``` gemini-3.8-flash ``` |\n| [Gemini 3.8 Live](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-live) | ``` gemini-3.8-live ``` |\n| [Gemini 3.8 Live Extended Thinking](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-live-extended-thinking) | ``` gemini-3.8-live-extended-thinking ``` |\n| [Gemini 3.8 Flash TTS](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash-tts) | ``` gemini-3.8-flash-tts ``` |\n| [Gemini 3.8 Flash-Lite TTS](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash-lite-tts) | ``` gemini-3.8-flash-lite-tts ``` |\n| [Gemini 3.7 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3.7-flash) | ``` gemini-3.7-flash ``` |\n| [Gemini 3.6 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3.6-flash) | ``` gemini-3.6-flash ``` |\n| [Gemini 3.5 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-flash) | ``` gemini-3.5-flash ``` |\n| [Gemini 3.5 Flash-Lite](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-flash-lite) | ``` gemini-3.5-flash-lite ``` |\n| [Gemini 3.1 Flash-Lite](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite) | ``` gemini-3.1-flash-lite ``` |\n| [Nano Banana 2.1](https://ai.google.dev/gemini-api/docs/models/gemini-nano-banana-2.1) | ``` gemini-nano-banana-2.1 ``` |\n| [Nano Banana 2](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-image) | ``` gemini-3.1-flash-image ``` |\n| [Nano Banana 2 Lite](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite-image) | ``` gemini-3.1-flash-lite-image ``` |\n| [Nano Banana Pro](https://ai.google.dev/gemini-api/docs/models/gemini-3-pro-image) | ``` gemini-3-pro-image ``` |\n| [Gemini 3.1 Pro](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-pro-preview) | ``` gemini-3.1-pro-preview ``` |\n| [Gemini 3 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3-flash-preview) | ``` gemini-3-flash-preview ``` |\n| [Gemini 3.5 Live Translate](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-live-translate-preview) | ``` gemini-3.5-live-translate-preview ``` |\n| [Gemini 3.1 Flash Live](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-live-preview) | ``` gemini-3.1-flash-live-preview ``` |\n| [Gemini 3.1 Flash TTS](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-tts-preview) | ``` gemini-3.1-flash-tts-preview ``` |\n| [Gemini Omni Flash](https://ai.google.dev/gemini-api/docs/models/gemini-omni-flash) | ``` gemini-omni-1.1-flash ``` |\n| [Gemini 3.5 Transcribe](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-transcribe) | ``` gemini-3.5-transcribe gemini-3.5-transcribe-live ``` |\n\n## Gemini 2.5 Flash\n\n> [!NOTE]\n> **Note:** To ensure reliable performance for everyone, we are limiting access to the 2.5 models to users who have actively used them in the past. These models are not deprecated and will continue to be served until further notice through the API. For any new projects, use our latest models: 3.5 Flash-Lite or 3.8 Flash. This helps us maintain sufficient capacity for both ongoing legacy workflows and new applications.\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Gemini 2.5 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash) | Our best price-performance model for low-latency, high-volume tasks that require reasoning. | ``` gemini-2.5-flash ``` |\n| [Nano Banana](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-image) | State-of-the-art native image generation and editing designed for fast, creative workflows. | ``` gemini-2.5-flash-image ``` |\n| [Gemini 2.5 Flash Live](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-native-audio-preview-12-2025) | Optimized for real-time conversational agents with sub-second native audio streaming. | ``` gemini-2.5-flash-native-audio-preview-12-2025 ``` |\n| [Gemini 2.5 Flash TTS](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-preview-tts) | Controllable text-to-speech audio generation with fine control over style and pacing. | ``` gemini-2.5-flash-preview-tts ``` |\n\n## Gemini 2.5 Flash-Lite\n\n> [!NOTE]\n> **Note:** To ensure reliable performance for everyone, we are limiting access to the 2.5 models to users who have actively used them in the past. These models are not deprecated and will continue to be served until further notice through the API. For any new projects, use our latest models: 3.5 Flash-Lite or 3.8 Flash. This helps us maintain sufficient capacity for both ongoing legacy workflows and new applications.\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Gemini 2.5 Flash-Lite](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-lite) | The fastest and most budget-friendly multimodal model in the 2.5 family. | ``` gemini-2.5-flash-lite ``` |\n\n## Gemini 2.5 Pro\n\n> [!NOTE]\n> **Note:** To ensure reliable performance for everyone, we are limiting access to the 2.5 models to users who have actively used them in the past. These models are not deprecated and will continue to be served until further notice through the API. For any new projects, use our latest models: 3.5 Flash-Lite or 3.8 Flash. This helps us maintain sufficient capacity for both ongoing legacy workflows and new applications.\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Gemini 2.5 Pro](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-pro) | Our most advanced model for complex tasks, featuring deep reasoning and coding capabilities in the 2.5 family. | ``` gemini-2.5-pro ``` |\n| [Gemini 2.5 Pro TTS](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-pro-preview-tts) | High-fidelity speech synthesis optimized for quality in structured workflows like podcasts and audiobooks. | ``` gemini-2.5-pro-preview-tts ``` |\n\n## Audio models\n\n*This section contains all audio models, including ones that may already be listed in other sections*\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Gemini 3.8 Live](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-live) | The default option for most low-latency voice agent experiences and real-time dialogue without reasoning delays. | ``` gemini-3.8-live ``` |\n| [Gemini 3.8 Live Extended Thinking](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-live-extended-thinking) | Our high-reasoning audio-to-audio model, recommended when higher background reasoning is required during live interactions. | ``` gemini-3.8-live-extended-thinking ``` |\n| [Gemini 3.8 Flash TTS](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash-tts) | Flagship creative text-to-speech model for studio-grade voice fidelity, expressive acting, and regional dialects across 130 languages. | ``` gemini-3.8-flash-tts ``` |\n| [Gemini 3.8 Flash-Lite TTS](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash-lite-tts) | Fast, cost-efficient text-to-speech model built for high-throughput production workloads across 101 languages. | ``` gemini-3.8-flash-lite-tts ``` |\n| [Gemini 3.1 Flash Live](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-live-preview) | Legacy audio-to-audio preview model. We recommend updating to Gemini 3.8 Live. | ``` gemini-3.1-flash-live-preview ``` |\n| [Gemini 3.1 Flash TTS](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-tts-preview) | Legacy text-to-speech preview model. We recommend updating to Gemini 3.8 Flash TTS or Gemini 3.8 Flash-Lite TTS. | ``` gemini-3.1-flash-tts-preview ``` |\n| [Gemini 3.5 Transcribe](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-transcribe) | Low-latency speech-to-text model with utterance-based language detection, speaker diarization, word-level timestamps, and custom vocabulary biasing. | ``` gemini-3.5-transcribe gemini-3.5-transcribe-live ``` |\n| [Gemini 2.5 Flash Live](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-native-audio-preview-12-2025) | Our flagship Live API model for low-latency, bidirectional voice and video agents with native audio reasoning. | ``` gemini-2.5-flash-native-audio-preview-12-2025 ``` |\n| [Gemini 2.5 Flash TTS](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-preview-tts) | Fast and controllable text-to-speech for low-latency, cost-efficient applications and real-time assistants. | ``` gemini-2.5-flash-preview-tts ``` |\n| [Gemini 2.5 Pro TTS](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-pro-preview-tts) | High-fidelity speech synthesis optimized for quality in structured workflows like podcasts and audiobooks. | ``` gemini-2.5-pro-preview-tts ``` |\n\n## Generative media models\n\n*This section contains all generative media models, including ones that may already be listed in other sections*\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Nano Banana 2.1](https://ai.google.dev/gemini-api/docs/models/gemini-nano-banana-2.1) | High-efficiency image generation and editing model with improved visual quality, typography, and multi-turn consistency. | ``` gemini-nano-banana-2.1 ``` |\n| [Nano Banana 2](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-image) | High-efficiency production-scale visual creation, combining the intelligence of the Gemini 3 series with lightning-fast generation speeds. | ``` gemini-3.1-flash-image ``` |\n| [Nano Banana 2 Lite](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite-image) | Designed as the efficiency specialist of the image generation family, offering ultra-low latency and cost-effective image generation and editing. | ``` gemini-3.1-flash-lite-image ``` |\n| [Veo 3.1](https://ai.google.dev/gemini-api/docs/models/veo-3.1-generate-preview) | State-of-the-art cinematic video generation with advanced creative controls and natively synchronized audio. | ``` veo-3.1-generate-preview ``` |\n| [Nano Banana Pro](https://ai.google.dev/gemini-api/docs/models/gemini-3-pro-image) | A professional design engine with a reasoning core for studio-quality 4K visuals, complex layouts, and precise text rendering. | ``` gemini-3-pro-image ``` |\n| [Veo 3.1 Lite](https://ai.google.dev/gemini-api/docs/models/veo-3.1-lite-generate-preview) | High-efficiency, low-cost, developer-first video generation, editing, and cinematic control from the Veo 3.1 family. | ``` veo-3.1-lite-generate-preview ``` |\n| [Gemini Omni Flash](https://ai.google.dev/gemini-api/docs/models/gemini-omni-flash) | Fast video generation, editing, keyframe interpolation, and extension with native audio. | ``` gemini-omni-1.1-flash ``` |\n| [Nano Banana](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-image) | State-of-the-art native image generation and editing designed for fast, creative workflows. | ``` gemini-2.5-flash-image ``` |\n| Imagen 4 (Shut down) | Text-to-image model featuring fast and ultra-fast generation (shut down). | ``` imagen-4.0-generate ``` |\n\n## Music generation models\n\n*This section contains all music generation models, including ones that may already be listed in other sections*\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Lyria 3.5](https://ai.google.dev/gemini-api/docs/models/lyria-3.5) | Our flagship music generation model, optimized for full-length songs with complex structural coherence. | ``` lyria-3.5 ``` |\n| [Lyria 3 Clip](https://ai.google.dev/gemini-api/docs/models/lyria-3-clip-preview) | Optimized for generating short musical clips, loops, and previews up to 30 seconds. | ``` lyria-3-clip-preview ``` |\n| [Lyria 3 Pro](https://ai.google.dev/gemini-api/docs/models/lyria-3-pro-preview) | Previous generation music generation model for full-length songs. | ``` lyria-3-pro-preview ``` |\n| [Lyria RealTime](https://ai.google.dev/gemini-api/docs/models/lyria-realtime-exp) | High-fidelity music generation model providing granular creative control and real-time streaming capabilities. | ``` lyria-realtime-exp ``` |\n\n## Tool and agent models\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Gemini Deep Research](https://ai.google.dev/gemini-api/docs/models/deep-research-preview-04-2026) | An agentic model that autonomously plans and executes multi-step research across hundreds of sources to produce cited, interactive reports. | ``` deep-research-preview-04-2026 ``` |\n| [Gemini Deep Research Max](https://ai.google.dev/gemini-api/docs/models/deep-research-max-preview-04-2026) | Maximum comprehensiveness for automated context gathering and synthesis across hundreds of sources. | ``` deep-research-max-preview-04-2026 ``` |\n| [Antigravity Agent](https://ai.google.dev/gemini-api/docs/models/antigravity-preview-09-2026) | A general-purpose managed agent that autonomously plans, reasons, runs code, manages files, and browses the web inside a secure, isolated Linux sandbox. | ``` antigravity-preview-09-2026 ``` |\n\n## Specialized task models\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Gemini Embedding 2](https://ai.google.dev/gemini-api/docs/models/gemini-embedding-2) | Our first multimodal embedding model, mapping text, images, video, audio, and PDFs into a unified embedding space for advanced semantic search and RAG systems. | ``` gemini-embedding-2-preview ``` |\n| [Gemini Embedding](https://ai.google.dev/gemini-api/docs/models/gemini-embedding-001) | High-dimensional vector representations for advanced semantic search, text classification, and RAG systems. | ``` gemini-embedding-001 ``` |\n| [Gemini Robotics ER 2](https://ai.google.dev/gemini-api/docs/robotics-overview) | Embodied reasoning model delivering advanced video understanding, spatial reasoning, multi-step tool orchestration, and multi-robot collaboration for robotics tasks. | ``` gemini-robotics-er-2-preview ``` |\n| [Gemini Robotics ER 1.6](https://ai.google.dev/gemini-api/docs/models/gemini-robotics-er-1.6-preview) | Advanced embodied reasoning model that understands physical spaces and plans multi-step tasks for robotic agents with new capabilities like instrument reading, improved spatial and physical reasoning. | ``` gemini-robotics-er-1.6-preview ``` |\n\n## Previous models\n\n> [!WARNING]\n> These models are [deprecated](https://ai.google.dev/gemini-api/docs/deprecations) and will be shut down soon; migrate to newer models to prevent service interruptions.\n\n| Model | Description | Endpoint |\n|---|---|---|\n| [Computer Use](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-computer-use-preview-10-2025) (Shut down) | A specialized model that can \"see\" a digital screen and perform UI actions like clicking, typing, and navigating to automate complex browser tasks. | ``` gemini-2.5-computer-use-preview-10-2025 ``` |\n| [Gemini 2.0 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-2.0-flash) (Shut down) | Our second generation workhorse model, with next-gen features and improved capabilities, including superior speed, native tool use, and a 1M token context window. | ``` gemini-2.0-flash ``` |\n| [Gemini 2.0 Flash-Lite](https://ai.google.dev/gemini-api/docs/models/gemini-2.0-flash-lite) (Shut down) | Our fastest second generation model, optimized for cost efficiency and low latency. | ``` gemini-2.0-flash-lite ``` |\n| [Gemini 3.1 Flash-Lite Preview](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite-preview) (Shut down) | Our most cost-efficient multimodal model, offering the fastest performance for high-frequency, lightweight tasks. | ``` gemini-3.1-flash-lite-preview ``` |\n| [Gemini 3 Pro Preview](https://ai.google.dev/gemini-api/docs/models/gemini-3-pro-preview) (Shut down) | Our state-of-the-art reasoning model, with advanced multimodal understanding. | ``` gemini-3-pro-preview ``` |\n\n## Model version name patterns\n\nGemini models are available in either *stable* , *preview* , *latest* , or\n*experimental* versions.\n\n> [!NOTE]\n> **Note:** The following list refers to the model string naming convention as of September, 2025. Models released prior to that may have different naming conventions. Refer to the exact model string if you are using an older model.\n\n### Stable\n\nPoints to a specific stable model. Stable models usually don't change. Most\nproduction apps should use a specific stable model.\n\nFor example: `gemini-3.6-flash`.\n\n### Preview\n\nPoints to a preview model which may be used for production. Preview models will\ntypically have billing enabled, might come with more restrictive rate limits and\nwill be deprecated with at least 2 weeks notice.\n\nFor example: `gemini-2.5-flash-preview-09-2025`.\n\n### Latest\n\nPoints to the latest release for a specific model variation. This can be a\nstable, preview or experimental release. This alias will get hot-swapped with\nevery new release of a specific model variation. For breaking changes, a\n**2-week notice** will be provided through email before the version behind\nlatest is changed.\n\nFor example: `gemini-flash-latest`.\n\n### Experimental\n\nPoints to an experimental model which will typically be not be suitable for\nproduction use and come with more restrictive rate limits. We release\nexperimental models to gather feedback and get our latest updates into the hands\nof developers quickly.\n\nExperimental models are not stable and availability of model endpoints is\nsubject to change.\n\n## Model deprecations\n\nFor information about model deprecations, visit the [Gemini deprecations](https://ai.google.dev/gemini-api/docs/deprecations) page.",
9 "https://ai.google.dev/gemini-api/docs/generate-content/thinking.md.txt": "The [Gemini 3 and 2.5 series models](https://ai.google.dev/gemini-api/docs/models) use an internal\n\"thinking process\" that significantly improves their reasoning and multi-step\nplanning abilities, making them highly effective for complex tasks such as\ncoding, advanced mathematics, and data analysis.\n\nThis guide shows you how to work with Gemini's thinking capabilities using the\nGemini API.\n\n## Generating content with thinking\n\nInitiating a request with a thinking model is similar to any other content\ngeneration request. The key difference lies in specifying one of the\n[models with thinking support](https://ai.google.dev/gemini-api/docs/generate-content/thinking#supported-models) in the `model` field, as\ndemonstrated in the following [text generation](https://ai.google.dev/gemini-api/docs/text-generation#text-input) example:\n\n### Python\n\n from google import genai\n\n client = genai.Client()\n prompt = \"Explain the concept of Occam's Razor and provide a simple, everyday example.\"\n response = client.models.generate_content(\n model=\"gemini-3.8-flash\",\n contents=prompt\n )\n\n print(response.text)\n\n### JavaScript\n\n import { GoogleGenAI } from \"@google/genai\";\n\n const ai = new GoogleGenAI({});\n\n async function main() {\n const prompt = \"Explain the concept of Occam's Razor and provide a simple, everyday example.\";\n\n const response = await ai.models.generateContent({\n model: \"gemini-3.8-flash\",\n contents: prompt,\n });\n\n console.log(response.text);\n }\n\n main();\n\n### Go\n\n package main\n\n import (\n \"context\"\n \"fmt\"\n \"log\"\n \"os\"\n \"google.golang.org/genai\"\n )\n\n func main() {\n ctx := context.Background()\n client, err := genai.NewClient(ctx, nil)\n if err != nil {\n log.Fatal(err)\n }\n\n prompt := \"Explain the concept of Occam's Razor and provide a simple, everyday example.\"\n model := \"gemini-3.8-flash\"\n\n resp, _ := client.Models.GenerateContent(ctx, model, genai.Text(prompt), nil)\n\n fmt.Println(resp.Text())\n }\n\n### REST\n\n curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\\n -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n -H 'Content-Type: application/json' \\\n -X POST \\\n -d '{\n \"contents\": [\n {\n \"parts\": [\n {\n \"text\": \"Explain the concept of Occam'\\''s Razor and provide a simple, everyday example.\"\n }\n ]\n }\n ]\n }'\n ```\n\n## Thought summaries\n\nThought summaries are summarized versions of the model's raw thoughts and offer\ninsights into the model's internal reasoning process. Note that\nthinking levels and budgets apply to the model's raw thoughts and not to thought\nsummaries.\n\nYou can enable thought summaries by setting `includeThoughts` to `true` in your\nrequest configuration. You can then access the summary by iterating through the\n`response` parameter's `parts`, and checking the `thought` boolean.\n\nHere's an example demonstrating how to enable and retrieve thought summaries\nwithout streaming, which returns a single, final thought summary with the\nresponse:\n\n### Python\n\n from google import genai\n from google.genai import types\n\n client = genai.Client()\n prompt = \"What is the sum of the first 50 prime numbers?\"\n response = client.models.generate_content(\n model=\"gemini-3.8-flash\",\n contents=prompt,\n config=types.GenerateContentConfig(\n thinking_config=types.ThinkingConfig(\n include_thoughts=True\n )\n )\n )\n\n for part in response.candidates[0].content.parts:\n if not part.text:\n continue\n if part.thought:\n print(\"Thought summary:\")\n print(part.text)\n print()\n else:\n print(\"Answer:\")\n print(part.text)\n print()\n\n### JavaScript\n\n import { GoogleGenAI } from \"@google/genai\";\n\n const ai = new GoogleGenAI({});\n\n async function main() {\n const response = await ai.models.generateContent({\n model: \"gemini-3.8-flash\",\n contents: \"What is the sum of the first 50 prime numbers?\",\n config: {\n thinkingConfig: {\n includeThoughts: true,\n },\n },\n });\n\n for (const part of response.candidates[0].content.parts) {\n if (!part.text) {\n continue;\n }\n else if (part.thought) {\n console.log(\"Thoughts summary:\");\n console.log(part.text);\n }\n else {\n console.log(\"Answer:\");\n console.log(part.text);\n }\n }\n }\n\n main();\n\n### Go\n\n package main\n\n import (\n \"context\"\n \"fmt\"\n \"google.golang.org/genai\"\n \"os\"\n )\n\n func main() {\n ctx := context.Background()\n client, err := genai.NewClient(ctx, nil)\n if err != nil {\n log.Fatal(err)\n }\n\n contents := genai.Text(\"What is the sum of the first 50 prime numbers?\")\n model := \"gemini-3.8-flash\"\n resp, _ := client.Models.GenerateContent(ctx, model, contents, &genai.GenerateContentConfig{\n ThinkingConfig: &genai.ThinkingConfig{\n IncludeThoughts: true,\n },\n })\n\n for _, part := range resp.Candidates[0].Content.Parts {\n if part.Text != \"\" {\n if part.Thought {\n fmt.Println(\"Thoughts Summary:\")\n fmt.Println(part.Text)\n } else {\n fmt.Println(\"Answer:\")\n fmt.Println(part.Text)\n }\n }\n }\n }\n\nAnd here is an example using thinking with streaming, which returns rolling,\nincremental summaries during generation:\n\n### Python\n\n from google import genai\n from google.genai import types\n\n client = genai.Client()\n\n prompt = \"\"\"\n Alice, Bob, and Carol each live in a different house on the same street: red, green, and blue.\n The person who lives in the red house owns a cat.\n Bob does not live in the green house.\n Carol owns a dog.\n The green house is to the left of the red house.\n Alice does not own a cat.\n Who lives in each house, and what pet do they own?\n \"\"\"\n\n thoughts = \"\"\n answer = \"\"\n\n for chunk in client.models.generate_content_stream(\n model=\"gemini-3.8-flash\",\n contents=prompt,\n config=types.GenerateContentConfig(\n thinking_config=types.ThinkingConfig(\n include_thoughts=True\n )\n )\n ):\n for part in chunk.candidates[0].content.parts:\n if not part.text:\n continue\n elif part.thought:\n if not thoughts:\n print(\"Thoughts summary:\")\n print(part.text)\n thoughts += part.text\n else:\n if not answer:\n print(\"Answer:\")\n print(part.text)\n answer += part.text\n\n### JavaScript\n\n import { GoogleGenAI } from \"@google/genai\";\n\n const ai = new GoogleGenAI({});\n\n const prompt = `Alice, Bob, and Carol each live in a different house on the same\n street: red, green, and blue. The person who lives in the red house owns a cat.\n Bob does not live in the green house. Carol owns a dog. The green house is to\n the left of the red house. Alice does not own a cat. Who lives in each house,\n and what pet do they own?`;\n\n let thoughts = \"\";\n let answer = \"\";\n\n async function main() {\n const response = await ai.models.generateContentStream({\n model: \"gemini-3.8-flash\",\n contents: prompt,\n config: {\n thinkingConfig: {\n includeThoughts: true,\n },\n },\n });\n\n for await (const chunk of response) {\n for (const part of chunk.candidates[0].content.parts) {\n if (!part.text) {\n continue;\n } else if (part.thought) {\n if (!thoughts) {\n console.log(\"Thoughts summary:\");\n }\n console.log(part.text);\n thoughts = thoughts + part.text;\n } else {\n if (!answer) {\n console.log(\"Answer:\");\n }\n console.log(part.text);\n answer = answer + part.text;\n }\n }\n }\n }\n\n await main();\n\n### Go\n\n package main\n\n import (\n \"context\"\n \"fmt\"\n \"log\"\n \"os\"\n \"google.golang.org/genai\"\n )\n\n const prompt = `\n Alice, Bob, and Carol each live in a different house on the same street: red, green, and blue.\n The person who lives in the red house owns a cat.\n Bob does not live in the green house.\n Carol owns a dog.\n The green house is to the left of the red house.\n Alice does not own a cat.\n Who lives in each house, and what pet do they own?\n `\n\n func main() {\n ctx := context.Background()\n client, err := genai.NewClient(ctx, nil)\n if err != nil {\n log.Fatal(err)\n }\n\n contents := genai.Text(prompt)\n model := \"gemini-3.8-flash\"\n\n resp := client.Models.GenerateContentStream(ctx, model, contents, &genai.GenerateContentConfig{\n ThinkingConfig: &genai.ThinkingConfig{\n IncludeThoughts: true,\n },\n })\n\n for chunk := range resp {\n for _, part := range chunk.Candidates[0].Content.Parts {\n if len(part.Text) == 0 {\n continue\n }\n\n if part.Thought {\n fmt.Printf(\"Thought: %s\\n\", part.Text)\n } else {\n fmt.Printf(\"Answer: %s\\n\", part.Text)\n }\n }\n }\n }\n\n## Controlling thinking\n\nGemini models engage in dynamic thinking by default, automatically adjusting the\namount of reasoning effort based on the complexity of the user's request.\nHowever, if you have specific latency constraints or require the model to engage\nin deeper reasoning than usual, you can optionally use parameters to control\nthinking behavior.\n\n### Thinking levels (Gemini 3)\n\nThe `thinkingLevel` parameter, recommended for Gemini 3 models and onwards,\nlets you control reasoning behavior.\n\nThe following table details the `thinkingLevel` settings for each model type:\n\n| Thinking Level | Gemini 3.8 \\& 3.7 Flash | Gemini 3.6 \\& 3.5 Flash | Gemini 3.1 Pro | Gemini 3.5 \\& 3.1 Flash-Lite | Gemini 3.1 Flash-Lite Image | Gemini 3 Flash | Gemini Robotics ER 2 | Description |\n|---|---|---|---|---|---|---|---|---|\n| **`minimal`** | Not supported (error) | Supported | Not supported | Supported (Default) | Supported (Default) | Supported | Supported | Matches the \"no thinking\" setting for most queries. Note, `minimal` does not guarantee that thinking is off, the model may reason very minimally for complex tasks. |\n| **`low`** | Supported | Supported | Supported | Supported | Not Supported | Supported | Supported | Minimizes latency and cost. |\n| **`medium`** | Supported (Default) | Supported (Default) | Supported | Supported | Not supported | Supported | Supported | Balanced thinking for most tasks. |\n| **`high`** | Supported (Dynamic) | Supported (Dynamic) | Supported (Default, Dynamic) | Supported (Dynamic) | Supported (Dynamic) | Supported (Default, Dynamic) | Supported (Default, Dynamic) | Maximizes reasoning depth. The model may take significantly longer to reach a first (non thinking) output token, but the output will be more carefully reasoned. |\n\nThe following example shows how to set the thinking level.\n\n### Python\n\n from google import genai\n from google.genai import types\n\n client = genai.Client()\n\n response = client.models.generate_content(\n model=\"gemini-3.8-flash\",\n contents=\"Provide a list of 3 famous physicists and their key contributions\",\n config=types.GenerateContentConfig(\n thinking_config=types.ThinkingConfig(thinking_level=\"low\")\n ),\n )\n\n print(response.text)\n\n### JavaScript\n\n import { GoogleGenAI, ThinkingLevel } from \"@google/genai\";\n\n const ai = new GoogleGenAI({});\n\n async function main() {\n const response = await ai.models.generateContent({\n model: \"gemini-3.8-flash\",\n contents: \"Provide a list of 3 famous physicists and their key contributions\",\n config: {\n thinkingConfig: {\n thinkingLevel: ThinkingLevel.LOW,\n },\n },\n });\n\n console.log(response.text);\n }\n\n main();\n\n### Go\n\n package main\n\n import (\n \"context\"\n \"fmt\"\n \"google.golang.org/genai\"\n \"os\"\n )\n\n func main() {\n ctx := context.Background()\n client, err := genai.NewClient(ctx, nil)\n if err != nil {\n log.Fatal(err)\n }\n\n thinkingLevelVal := \"low\"\n\n contents := genai.Text(\"Provide a list of 3 famous physicists and their key contributions\")\n model := \"gemini-3.8-flash\"\n resp, _ := client.Models.GenerateContent(ctx, model, contents, &genai.GenerateContentConfig{\n ThinkingConfig: &genai.ThinkingConfig{\n ThinkingLevel: &thinkingLevelVal,\n },\n })\n\n fmt.Println(resp.Text())\n }\n\n### REST\n\n curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent\" \\\n -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n -H 'Content-Type: application/json' \\\n -X POST \\\n -d '{\n \"contents\": [\n {\n \"parts\": [\n {\n \"text\": \"Provide a list of 3 famous physicists and their key contributions\"\n }\n ]\n }\n ],\n \"generationConfig\": {\n \"thinkingConfig\": {\n \"thinkingLevel\": \"low\"\n }\n }\n }'\n\nYou cannot disable thinking for Gemini 3.1 Pro. Gemini 3 Flash and Flash-Lite\nalso do not support full thinking-off.\nIf you don't specify a thinking level, Gemini will use the Gemini 3 models'\ndefault thinking level (e.g., `\"high\"` for Gemini 3.1 Pro, and `\"medium\"` for Gemini 3.5 Flash).\n\nGemini 2.5 series models don't support `thinkingLevel`; use `thinkingBudget`\ninstead.\n\n### Token limits and `max_output_tokens`\n\nThe [`max_output_tokens`](https://ai.google.dev/api/generate-content#v1beta.GenerationConfig)\ngeneration parameter sets the maximum number of tokens a response can generate,\nincluding thought tokens.\n\nWhen set, this parameter acts as a hard cutoff enforced by the infrastructure\nwithout changing how the model allocates its thinking budget\n(`thinking_level`).\n\nIf the model hits this limit while reasoning, it stops generating with\n`finish_reason: MAX_TOKENS` and returns truncated or empty output (while still\nbilling for any thinking tokens generated). To reduce cost or latency without\ntruncating responses, lower `thinking_level` (`low` or `medium`) instead of\nsetting a small `max_output_tokens`.\n\n### Thinking budgets\n\nThe `thinkingBudget` parameter, introduced with the Gemini 2.5 series, guides\nthe model on the specific number of thinking tokens to use for reasoning.\n\n> [!NOTE]\n> **Note:** Use the `thinkingLevel` parameter with Gemini 3 models. While `thinkingBudget` is accepted for backwards compatibility, using it with Gemini 3 Pro may result in unexpected performance.\n\nThe following are `thinkingBudget` configuration details for each model type.\nYou can disable thinking by setting `thinkingBudget` to 0.\nSetting the `thinkingBudget` to -1 turns\non **dynamic thinking**, meaning the model will adjust the budget based on the\ncomplexity of the request.\n\n| Model | Default setting (Thinking budget is not set) | Range | Disable thinking | Turn on dynamic thinking |\n|---|---|---|---|---|\n| **2.5 Pro** | Dynamic thinking | `128` to `32768` | N/A: Cannot disable thinking | `thinkingBudget = -1` (Default) |\n| **2.5 Flash** | Dynamic thinking | `0` to `24576` | `thinkingBudget = 0` | `thinkingBudget = -1` (Default) |\n| **2.5 Flash Preview** | Dynamic thinking | `0` to `24576` | `thinkingBudget = 0` | `thinkingBudget = -1` (Default) |\n| **2.5 Flash Lite** | Model does not think | `512` to `24576` | `thinkingBudget = 0` | `thinkingBudget = -1` |\n| **2.5 Flash Lite Preview** | Model does not think | `512` to `24576` | `thinkingBudget = 0` | `thinkingBudget = -1` |\n| **Robotics-ER 1.6 Preview** | Dynamic thinking | `0` to `24576` | `thinkingBudget = 0` | `thinkingBudget = -1` (Default) |\n| **2.5 Flash Live Native Audio Preview (09-2025)** | Dynamic thinking | `0` to `24576` | `thinkingBudget = 0` | `thinkingBudget = -1` (Default) |\n\n### Python\n\n from google import genai\n from google.genai import types\n\n client = genai.Client()\n\n response = client.models.generate_content(\n model=\"gemini-2.5-flash\",\n contents=\"Provide a list of 3 famous physicists and their key contributions\",\n config=types.GenerateContentConfig(\n thinking_config=types.ThinkingConfig(thinking_budget=1024)\n # Turn off thinking:\n # thinking_config=types.ThinkingConfig(thinking_budget=0)\n # Turn on dynamic thinking:\n # thinking_config=types.ThinkingConfig(thinking_budget=-1)\n ),\n )\n\n print(response.text)\n\n### JavaScript\n\n import { GoogleGenAI } from \"@google/genai\";\n\n const ai = new GoogleGenAI({});\n\n async function main() {\n const response = await ai.models.generateContent({\n model: \"gemini-2.5-flash\",\n contents: \"Provide a list of 3 famous physicists and their key contributions\",\n config: {\n thinkingConfig: {\n thinkingBudget: 1024,\n // Turn off thinking:\n // thinkingBudget: 0\n // Turn on dynamic thinking:\n // thinkingBudget: -1\n },\n },\n });\n\n console.log(response.text);\n }\n\n main();\n\n### Go\n\n package main\n\n import (\n \"context\"\n \"fmt\"\n \"google.golang.org/genai\"\n \"os\"\n )\n\n func main() {\n ctx := context.Background()\n client, err := genai.NewClient(ctx, nil)\n if err != nil {\n log.Fatal(err)\n }\n\n thinkingBudgetVal := int32(1024)\n\n contents := genai.Text(\"Provide a list of 3 famous physicists and their key contributions\")\n model := \"gemini-2.5-flash\"\n resp, _ := client.Models.GenerateContent(ctx, model, contents, &genai.GenerateContentConfig{\n ThinkingConfig: &genai.ThinkingConfig{\n ThinkingBudget: &thinkingBudgetVal,\n // Turn off thinking:\n // ThinkingBudget: int32(0),\n // Turn on dynamic thinking:\n // ThinkingBudget: int32(-1),\n },\n })\n\n fmt.Println(resp.Text())\n }\n\n### REST\n\n curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent\" \\\n -H \"x-goog-api-key: $GEMINI_API_KEY\" \\\n -H 'Content-Type: application/json' \\\n -X POST \\\n -d '{\n \"contents\": [\n {\n \"parts\": [\n {\n \"text\": \"Provide a list of 3 famous physicists and their key contributions\"\n }\n ]\n }\n ],\n \"generationConfig\": {\n \"thinkingConfig\": {\n \"thinkingBudget\": 1024\n }\n }\n }'\n\nDepending on the prompt, the model might overflow or underflow the token budget.\n\n## Thought signatures\n\n> [!IMPORTANT]\n> **Important:** The [Google GenAI SDK](https://ai.google.dev/gemini-api/docs/libraries) automatically handles the return of thought signatures for you. You only need to [manage thought signatures manually](https://ai.google.dev/gemini-api/docs/function-calling#thought-signatures) if you're modifying conversation history or using the REST API.\n\nThe Gemini API is stateless, so the model treats every API request independently\nand doesn't have access to thought context from previous turns in multi-turn\ninteractions.\n\nIn order to enable maintaining thought context across multi-turn interactions,\nGemini returns thought signatures, which are encrypted representations of the\nmodel's internal thought process.\n\n- **Gemini 2.5 models** return thought signatures when thinking is enabled and the request includes [function calling](https://ai.google.dev/gemini-api/docs/function-calling#thinking), specifically [function declarations](https://ai.google.dev/gemini-api/docs/function-calling#step-2).\n- **Gemini 3 models** may return thought signatures for all types of [parts](https://ai.google.dev/api/caching#Part). We recommend you always pass all signatures back as received, but it's *required* for function calling signatures. Read the [Thought Signatures](https://ai.google.dev/gemini-api/docs/thought-signatures) page to learn more.\n\nOther usage limitations to consider with function calling include:\n\n- Signatures are returned from the model within other parts in the response, for example function calling or text parts. [Return the entire response](https://ai.google.dev/gemini-api/docs/function-calling#step-4) with all parts back to the model in subsequent turns.\n- Don't concatenate parts with signatures together.\n- Don't merge one part with a signature with another part without a signature.\n\n## Pricing\n\n> [!NOTE]\n> **Note:** **Summaries** are available in the [free and paid tiers](https://ai.google.dev/gemini-api/docs/pricing) of the API. **Thought signatures** will increase the input tokens you are charged when sent back as part of the request.\n\nWhen thinking is turned on, response pricing is the sum of output\ntokens and thinking tokens. You can get the total number of generated thinking\ntokens from the `thoughtsTokenCount` field.\n\n### Python\n\n # ...\n print(\"Thoughts tokens:\", response.usage_metadata.thoughts_token_count)\n print(\"Output tokens:\", response.usage_metadata.candidates_token_count)\n\n### JavaScript\n\n // ...\n console.log(`Thoughts tokens: ${response.usageMetadata.thoughtsTokenCount}`);\n console.log(`Output tokens: ${response.usageMetadata.candidatesTokenCount}`);\n\n### Go\n\n // ...\n fmt.Println(\"Thoughts tokens:\", response.UsageMetadata.ThoughtsTokenCount)\n fmt.Println(\"Output tokens:\", response.UsageMetadata.CandidatesTokenCount)\n\nThinking models generate full thoughts to improve the quality of the final\nresponse, and then output [summaries](https://ai.google.dev/gemini-api/docs/generate-content/thinking#summaries) to provide insight into the\nthought process. So, pricing is based on the full thought tokens the\nmodel needs to generate to create a summary, despite only the summary being\noutput from the API.\n\n> [!NOTE]\n> **Note:** Because `max_output_tokens` applies to the combined total of thinking tokens and output tokens, setting a low limit can truncate responses. See [Token limits and `max_output_tokens`](https://ai.google.dev/gemini-api/docs/generate-content/thinking#token-limits) for details.\n\nYou can learn more about tokens in the [Token counting](https://ai.google.dev/gemini-api/docs/tokens)\nguide.\n\n## Best practices\n\nThis section includes some guidance for using thinking models efficiently.\nAs always, following our [prompting guidance and best practices](https://ai.google.dev/gemini-api/docs/prompting-strategies) will get you the best results.\n\n### Debugging and steering\n\n- **Review reasoning**: When you're not getting your expected response from the\n thinking models, it can help to carefully analyze Gemini's thought summaries.\n You can see how it broke down the task and arrived at its conclusion, and use\n that information to correct towards the right results.\n\n- **Provide Guidance in Reasoning** : If you're hoping for a particularly lengthy\n output, you may want to provide guidance in your prompt to constrain the\n [amount of thinking](https://ai.google.dev/gemini-api/docs/generate-content/thinking#set-budget) the model uses. This lets you reserve more\n of the token output for your response.\n\n### Task complexity\n\n- **Easy Tasks (Thinking could be OFF):** For straightforward requests where complex reasoning isn't required, such as fact retrieval or classification, thinking is not required. Examples include:\n - \"Where was DeepMind founded?\"\n - \"Is this email asking for a meeting or just providing information?\"\n- **Medium Tasks (Default/Some Thinking):** Many common requests benefit from a degree of step-by-step processing or deeper understanding. Gemini can flexibly use thinking capability for tasks like:\n - Analogize photosynthesis and growing up.\n - Compare and contrast electric cars and hybrid cars.\n- **Hard Tasks (Maximum Thinking Capability):** For truly complex challenges, such as solving complex math problems or coding tasks, we recommend setting a high thinking budget. These types of tasks require the model to engage its full reasoning and planning capabilities, often involving many internal steps before providing an answer. Examples include:\n - Solve problem 1 in AIME 2025: Find the sum of all integer bases b \\> 9 for which 17~b~ is a divisor of 97~b~.\n - Write Python code for a web application that visualizes real-time stock market data, including user authentication. Make it as efficient as possible.\n\n## Supported models, tools, and capabilities\n\nThinking features are supported on all 3 and 2.5 series models.\nYou can find all model capabilities on the\n[model overview](https://ai.google.dev/gemini-api/docs/models) page.\n\nThinking models work with all of Gemini's tools and capabilities. This allows\nthe models to interact with external systems, execute code, or access real-time\ninformation, incorporating the results into their reasoning and final response.\n\nYou can try examples of using tools with thinking models in the\n\\[Thinking cookbook\\]\\[Colab\\].\n\n## What's next?\n\n- Thinking coverage is available in our [OpenAI Compatibility](https://ai.google.dev/gemini-api/docs/openai#thinking) guide.\n\n\\[Colab\\]: https://colab.sandbox.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_started_thinking.ipynb",
10 "https://developers.openai.com/api/docs/models/gpt-6.1-sol.md": "# GPT-6.1 Sol\n\n> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.\n\n> Near-Astra performance for complex work at a lower cost.\n\nModel ID: `gpt-6.1-sol`\n\nGPT-6.1 Sol delivers near-Astra performance at a lower cost for complex coding,\ncomputer use, and professional work. Compare it with Astra on your tasks to\nassess the tradeoff between quality and cost.\n\n`reasoning.effort` supports `low`, `medium` (default), `high`, `xhigh`, and\n`max`. The `none` and `minimal` reasoning efforts are not supported.\n\nUse the Responses API for tool calling. Chat Completions is supported without\ntool calling.\n\nFor the fastest response speeds, use [Ultrafast mode](/api/docs/guides/ultrafast-mode)\nwith `model: \"gpt-6.1-sol\"` and `service_tier: \"ultrafast\"` in the Responses API.\n\nGPT-6.1 Sol supports US and EU data residency, including with Fast and Ultrafast\nmodes. See [data residency eligibility](/api/docs/guides/your-data#which-models-and-features-are-eligible-for-data-residency).\n\nSee [GPT-6.1 Sol in the GPT-6 guide](/api/docs/guides/latest-model?model=gpt-6-astra#gpt-61-sol) and\n[model-selection guidance](/api/docs/guides/model-selection#when-to-consider-gpt-61-sol).\n\n## Model details\n\n- Default snapshot: `gpt-6.1-sol`\n- Input modalities: text, image\n- Output modalities: text\n- Unsupported modalities: audio, video\n- 1,050,000 context window\n- Maximum input tokens: 922,000\n- 128,000 max output tokens\n- Apr 30, 2026 knowledge cutoff\n- Reasoning token support\n\n## Pricing\n\nPricing is based on the number of tokens used, or other metrics based on the model type. For tool-specific models, like search and computer use, there’s a fee per tool call. See details in the [pricing page](/api/docs/pricing).\n\n### Text tokens\n\n| Metric | Price | Unit |\n| --- | ---: | --- |\n| Input | $2 | 1M tokens |\n| Cached input | $0.1 | 1M tokens |\n| Cache writes | $2.5 | 1M tokens |\n| Output | $10 | 1M tokens |\n\n- Cached input tokens are priced at 5% of the uncached input token rate.\n- Cache writes are billed at 1.25x the uncached input token rate.\n- Prompts with more than 272K input tokens are priced at 2x input and cache rates and 1.5x output for the full request.\n- Fast mode prices are 2x Standard. Batch and Flex prices are 50% lower than Standard.\n- Ultrafast mode prices are 6x Standard.\n- Regional processing adds a 10% premium where available.\n\n## Endpoints\n\n| Endpoint | Route | Support |\n| --- | --- | --- |\n| Live | `v1/live/sessions` | Not supported |\n| Chat Completions | `v1/chat/completions` | Supported |\n| Responses | `v1/responses` | Supported |\n| Realtime | `v1/realtime` | Not supported |\n| Realtime translation | `v1/realtime/translations` | Not supported |\n| Realtime transcription | `v1/realtime/transcription_sessions` | Not supported |\n| Assistants | `v1/assistants` | Not supported |\n| Batch | `v1/batch` | Supported |\n| Fine-tuning | `v1/fine-tuning` | Not supported |\n| Embeddings | `v1/embeddings` | Not supported |\n| Image generation | `v1/images/generations` | Not supported |\n| Videos | `v1/videos` | Not supported |\n| Image edit | `v1/images/edits` | Not supported |\n| Speech generation | `v1/audio/speech` | Not supported |\n| Transcription | `v1/audio/transcriptions` | Not supported |\n| Translation | `v1/audio/translations` | Not supported |\n| Moderation | `v1/moderations` | Not supported |\n| Completions (legacy) | `v1/completions` | Not supported |\n\n## Supported features\n\n- streaming\n- structured_outputs\n- function_calling\n- file_search\n- image_input\n- web_search\n- prompt_caching\n\n## Unsupported features\n\n- fine_tuning\n- predicted_outputs\n\n## Supported tools\n\nTools supported by this model when using the Responses API.\n\n- web_search\n- file_search\n- image_generation\n- code_interpreter\n- hosted_shell\n- apply_patch\n- skills\n- computer_use\n- mcp\n- tool_search\n\n## Snapshots\n\nUse `gpt-6.1-sol` to select this model.\n\n- `gpt-6.1-sol`\n\n## Rate limits\n\nRate limits ensure fair and reliable access to the API by placing specific caps on requests, tokens, audio duration, or other usage within a given time period. Your usage tier determines how high these limits are set and automatically increases as you send more requests and spend more on the API.\n\n### Standard\n\n| Tier | RPM | TPM |\n| --- | ---: | ---: |\n| Build | 5,000 | 1,000,000 |\n| Launch | 10,000 | 4,000,000 |\n| Grow | 15,000 | 40,000,000 |\n",
11 "https://developers.openai.com/api/docs/models/gpt-5.2-codex.md": "# GPT-5.2-Codex\n\n> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.\n\n> Our most intelligent coding model optimized for long-horizon, agentic coding tasks.\n\nModel ID: `gpt-5.2-codex`\n\nGPT-5.2-Codex is an upgraded version of GPT-5.2 optimized for agentic coding tasks in [Codex](https://developers.openai.com/codex) or similar environments.\nGPT-5.2-Codex supports `low`, `medium`, `high`, and `xhigh` reasoning effort settings.\nIf you want to learn more about prompting GPT-5.2-Codex, refer to our [dedicated guide](/cookbook/examples/gpt-5/codex_prompting_guide).\n\n## Model details\n\n- Default snapshot: `gpt-5.2-codex`\n- Input modalities: text, image\n- Output modalities: text\n- 400,000 context window\n- Maximum input tokens: 272,000\n- 128,000 max output tokens\n- Aug 31, 2025 knowledge cutoff\n- Reasoning token support\n\n## Pricing\n\nPricing is based on the number of tokens used, or other metrics based on the model type. For tool-specific models, like search and computer use, there’s a fee per tool call. See details in the [pricing page](/api/docs/pricing).\n\n### Text tokens\n\n| Metric | Price | Unit |\n| --- | ---: | --- |\n| Input | $1.75 | 1M tokens |\n| Cached input | $0.175 | 1M tokens |\n| Output | $14 | 1M tokens |\n\n## Endpoints\n\n| Endpoint | Route | Support |\n| --- | --- | --- |\n| Live | `v1/live/sessions` | Not supported |\n| Chat Completions | `v1/chat/completions` | Not supported |\n| Responses | `v1/responses` | Supported |\n| Realtime | `v1/realtime` | Not supported |\n| Realtime translation | `v1/realtime/translations` | Not supported |\n| Realtime transcription | `v1/realtime/transcription_sessions` | Not supported |\n| Assistants | `v1/assistants` | Not supported |\n| Batch | `v1/batch` | Not supported |\n| Fine-tuning | `v1/fine-tuning` | Not supported |\n| Embeddings | `v1/embeddings` | Not supported |\n| Image generation | `v1/images/generations` | Not supported |\n| Videos | `v1/videos` | Not supported |\n| Image edit | `v1/images/edits` | Not supported |\n| Speech generation | `v1/audio/speech` | Not supported |\n| Transcription | `v1/audio/transcriptions` | Not supported |\n| Translation | `v1/audio/translations` | Not supported |\n| Moderation | `v1/moderations` | Not supported |\n| Completions (legacy) | `v1/completions` | Not supported |\n\n## Supported features\n\n- streaming\n- structured_outputs\n- function_calling\n- image_input\n- web_search\n- prompt_caching\n\n## Supported tools\n\nTools supported by this model when using the Responses API.\n\n- function_calling\n- web_search\n- hosted_shell\n- skills\n\n## Quick comparison\n\n| Model | Input | Cached input | Output |\n| --- | ---: | ---: | ---: |\n| GPT-5.2-Codex | $1.75 | $0.175 | $14 |\n| GPT-5.1-Codex | $1.25 | $0.125 | $10 |\n\n## Snapshots\n\nSnapshots let you lock in a specific version of the model so that performance and behavior remain consistent. Below is a list of all available snapshots and aliases for GPT-5.2-Codex.\n\n- `gpt-5.2-codex`\n\n## Rate limits\n\nRate limits ensure fair and reliable access to the API by placing specific caps on requests, tokens, audio duration, or other usage within a given time period. Your usage tier determines how high these limits are set and automatically increases as you send more requests and spend more on the API.\n\n### default\n\n| Tier | RPM | TPM | Batch queue limit |\n| --- | ---: | ---: | ---: |\n| Build | 5,000 | 1,000,000 | 3,000,000 |\n| Launch | 10,000 | 4,000,000 | 200,000,000 |\n| Grow | 15,000 | 40,000,000 | 15,000,000,000 |\n",
12 "https://developers.openai.com/api/docs/models/gpt-oss-120b.md": "# gpt-oss-120b\n\n> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.\n\n> Most powerful open-weight model, fits into an H100 GPU\n\nModel ID: `gpt-oss-120b`\n\n`gpt-oss-120b`is our most powerful open-weight model, which fits into a single \nH100 GPU (117B parameters with 5.1B active parameters).\n\n[Download gpt-oss-120b on HuggingFace](https://huggingface.co/openai/gpt-oss-120b).\n\n**Key features**\n\n- **Permissive Apache 2.0 license:** Build freely without copyleft restrictions or patent risk—ideal for experimentation, customization, and commercial deployment.\n- **Configurable reasoning effort:** Easily adjust the reasoning effort (low, medium, high) based on your specific use case and latency needs.\n- **Full chain-of-thought:** Gain complete access to the model's reasoning process, facilitating easier debugging and increased trust in outputs.\n- **Fine-tunable:** Fully customize models to your specific use case through parameter fine-tuning.\n- **Agentic capabilities:** Use the models' native capabilities for function calling, web browsing, Python code execution, and structured outputs.\n\n## Model details\n\n- Default snapshot: `gpt-oss-120b`\n- Input modalities: text\n- Output modalities: text\n- 131,072 context window\n- 131,072 max output tokens\n- Jun 01, 2024 knowledge cutoff\n- Reasoning token support\n\n## Endpoints\n\n| Endpoint | Route | Support |\n| --- | --- | --- |\n| Live | `v1/live/sessions` | Not supported |\n| Chat Completions | `v1/chat/completions` | Not supported |\n| Responses | `v1/responses` | Supported |\n| Realtime | `v1/realtime` | Not supported |\n| Realtime translation | `v1/realtime/translations` | Not supported |\n| Realtime transcription | `v1/realtime/transcription_sessions` | Not supported |\n| Assistants | `v1/assistants` | Not supported |\n| Batch | `v1/batch` | Supported |\n| Fine-tuning | `v1/fine-tuning` | Not supported |\n| Embeddings | `v1/embeddings` | Not supported |\n| Image generation | `v1/images/generations` | Not supported |\n| Videos | `v1/videos` | Not supported |\n| Image edit | `v1/images/edits` | Not supported |\n| Speech generation | `v1/audio/speech` | Not supported |\n| Transcription | `v1/audio/transcriptions` | Not supported |\n| Translation | `v1/audio/translations` | Not supported |\n| Moderation | `v1/moderations` | Not supported |\n| Completions (legacy) | `v1/completions` | Not supported |\n\n## Supported features\n\n- streaming\n- structured_outputs\n- function_calling\n\n## Supported tools\n\nTools supported by this model when using the Responses API.\n\n- function_calling\n- code_interpreter\n- mcp\n- web_search\n\n## Snapshots\n\nSnapshots let you lock in a specific version of the model so that performance and behavior remain consistent. Below is a list of all available snapshots and aliases for gpt-oss-120b.\n\n- `gpt-oss-120b`\n\n## Rate limits\n\nRate limits ensure fair and reliable access to the API by placing specific caps on requests, tokens, audio duration, or other usage within a given time period. Your usage tier determines how high these limits are set and automatically increases as you send more requests and spend more on the API.\n\n### default\n\n| Tier | RPM | TPM | Batch queue limit |\n| --- | ---: | ---: | ---: |\n| Build | 0 | 0 | 0 |\n| Launch | 0 | 0 | 0 |\n| Grow | 0 | 0 | 0 |\n",
13 "https://developers.openai.com/api/docs/models/gpt-6-astra.md": "# GPT-6 Astra\n\n> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.\n\n> Our most capable model for the most demanding work.\n\nModel ID: `gpt-6-astra`\n\nGPT-6 Astra is our most capable model for the most demanding work.\nUse it for complex reasoning, coding, computer use, research, and document creation.\n`reasoning.effort` supports `low`, `medium`, `high`, `xhigh`, and `max`.\n\nGet started with GPT-6 Astra using the [model guide](/api/docs/guides/latest-model?model=gpt-6-astra).\n\n## Model details\n\n- Default snapshot: `gpt-6-astra`\n- Input modalities: text, image\n- Output modalities: text\n- 1,050,000 context window\n- Maximum input tokens: 922,000\n- 128,000 max output tokens\n- Apr 30, 2026 knowledge cutoff\n- Reasoning token support\n\n## Pricing\n\nPricing is based on the number of tokens used, or other metrics based on the model type. For tool-specific models, like search and computer use, there’s a fee per tool call. See details in the [pricing page](/api/docs/pricing).\n\n### Text tokens\n\n| Metric | Price | Unit |\n| --- | ---: | --- |\n| Input | $10 | 1M tokens |\n| Cached input | $1 | 1M tokens |\n| Cache writes | $12.5 | 1M tokens |\n| Output | $50 | 1M tokens |\n\n- Prompts with more than 272K input tokens are priced at 2x input and cache rates and 1.5x output for the full request.\n- Cache writes are billed at 1.25x the uncached input token rate.\n- Batch and Flex are priced at 50% of Standard rates. Fast mode is priced at 2x the applicable rates.\n\n## Endpoints\n\n| Endpoint | Route | Support |\n| --- | --- | --- |\n| Live | `v1/live/sessions` | Not supported |\n| Chat Completions | `v1/chat/completions` | Supported |\n| Responses | `v1/responses` | Supported |\n| Realtime | `v1/realtime` | Not supported |\n| Realtime translation | `v1/realtime/translations` | Not supported |\n| Realtime transcription | `v1/realtime/transcription_sessions` | Not supported |\n| Assistants | `v1/assistants` | Not supported |\n| Batch | `v1/batch` | Supported |\n| Fine-tuning | `v1/fine-tuning` | Not supported |\n| Embeddings | `v1/embeddings` | Not supported |\n| Image generation | `v1/images/generations` | Not supported |\n| Videos | `v1/videos` | Not supported |\n| Image edit | `v1/images/edits` | Not supported |\n| Speech generation | `v1/audio/speech` | Not supported |\n| Transcription | `v1/audio/transcriptions` | Not supported |\n| Translation | `v1/audio/translations` | Not supported |\n| Moderation | `v1/moderations` | Not supported |\n| Completions (legacy) | `v1/completions` | Not supported |\n\n## Supported features\n\n- streaming\n- structured_outputs\n- function_calling\n- file_search\n- image_input\n- web_search\n- prompt_caching\n\n## Supported tools\n\nTools supported by this model when using the Responses API.\n\n- web_search\n- file_search\n- image_generation\n- code_interpreter\n- hosted_shell\n- apply_patch\n- skills\n- computer_use\n- mcp\n- tool_search\n\n## Snapshots\n\nSnapshots let you lock in a specific version of the model so that performance and behavior remain consistent. Below is a list of all available snapshots and aliases for GPT-6 Astra.\n\n- `gpt-6-astra`\n\n## Rate limits\n\nRate limits ensure fair and reliable access to the API by placing specific caps on requests, tokens, audio duration, or other usage within a given time period. Your usage tier determines how high these limits are set and automatically increases as you send more requests and spend more on the API.\n\n### Standard\n\n| Tier | RPM | TPM | Batch queue limit |\n| --- | ---: | ---: | ---: |\n| Build | 5,000 | 1,000,000 | 3,000,000 |\n| Launch | 10,000 | 4,000,000 | 200,000,000 |\n| Grow | 15,000 | 40,000,000 | 15,000,000,000 |\n",
14 "https://developers.openai.com/api/docs/models/gpt-6-luna.md": "# GPT-6 Luna\n\n> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.\n\n> Our most efficient model for focused, high-volume tasks.\n\nModel ID: `gpt-6-luna`\n\nGPT-6 Luna is our most efficient model for focused, high-volume tasks.\n\n`reasoning.effort` supports `none`, `low`, `medium` (default), `high`, `xhigh`, and `max`.\nUse the Responses API for built-in tools and function calling. Chat Completions supports function calling only with `reasoning_effort` set to `none`.\n\nEU data residency is available with Standard, Fast, Flex, and Batch processing.\nSee [data residency eligibility](/api/docs/guides/your-data#which-models-and-features-are-eligible-for-data-residency).\n\n## Model details\n\n- Default snapshot: `gpt-6-luna`\n- Input modalities: text, image\n- Output modalities: text\n- 1,050,000 context window\n- Maximum input tokens: 922,000\n- 128,000 max output tokens\n- May 18, 2026 knowledge cutoff\n- Reasoning token support\n\n## Pricing\n\nPricing is based on the number of tokens used, or other metrics based on the model type. For tool-specific models, like search and computer use, there’s a fee per tool call. See details in the [pricing page](/api/docs/pricing).\n\n### Text tokens\n\n| Metric | Price | Unit |\n| --- | ---: | --- |\n| Input | $0.1 | 1M tokens |\n| Cached input | $0.01 | 1M tokens |\n| Cache writes | $0.125 | 1M tokens |\n| Output | $0.5 | 1M tokens |\n\n- Cached input tokens are priced at 10% of the uncached input token rate.\n- Cache writes are billed at 1.25x the uncached input token rate.\n- Prompts with more than 272K input tokens are priced at 2x input and cache rates and 1.5x output for the full request.\n- Regional processing adds a 10% premium where available. EU data residency is available with Standard, Fast, Flex, and Batch processing.\n- Batch and Flex are priced at 50% of Standard rates. Fast mode is priced at 2x the applicable rates.\n\n## Endpoints\n\n| Endpoint | Route | Support |\n| --- | --- | --- |\n| Live | `v1/live/sessions` | Not supported |\n| Chat Completions | `v1/chat/completions` | Supported |\n| Responses | `v1/responses` | Supported |\n| Realtime | `v1/realtime` | Not supported |\n| Realtime translation | `v1/realtime/translations` | Not supported |\n| Realtime transcription | `v1/realtime/transcription_sessions` | Not supported |\n| Assistants | `v1/assistants` | Not supported |\n| Batch | `v1/batch` | Supported |\n| Fine-tuning | `v1/fine-tuning` | Not supported |\n| Embeddings | `v1/embeddings` | Not supported |\n| Image generation | `v1/images/generations` | Not supported |\n| Videos | `v1/videos` | Not supported |\n| Image edit | `v1/images/edits` | Not supported |\n| Speech generation | `v1/audio/speech` | Not supported |\n| Transcription | `v1/audio/transcriptions` | Not supported |\n| Translation | `v1/audio/translations` | Not supported |\n| Moderation | `v1/moderations` | Not supported |\n| Completions (legacy) | `v1/completions` | Not supported |\n\n## Supported features\n\n- streaming\n- structured_outputs\n- function_calling\n- file_search\n- image_input\n- web_search\n- prompt_caching\n\n## Supported tools\n\nTools supported by this model when using the Responses API.\n\n- web_search\n- file_search\n- image_generation\n- code_interpreter\n- hosted_shell\n- apply_patch\n- skills\n- computer_use\n- mcp\n- tool_search\n\n## Snapshots\n\nUse `gpt-6-luna` in your API requests.\n\n- `gpt-6-luna`\n\n## Rate limits\n\nRate limits ensure fair and reliable access to the API by placing specific caps on requests, tokens, audio duration, or other usage within a given time period. Your usage tier determines how high these limits are set and automatically increases as you send more requests and spend more on the API.\n\n### default\n\n| Tier | RPM | TPM | Batch queue limit |\n| --- | ---: | ---: | ---: |\n| Build | 5,000 | 2,000,000 | 20,000,000 |\n| Launch | 10,000 | 10,000,000 | 1,000,000,000 |\n| Grow | 30,000 | 180,000,000 | 15,000,000,000 |\n",
15 "https://openrouter.ai/api/v1/models": "{\"data\": [{\"id\": \"bytedance-seed/seed-2-1-turbo\", \"canonical_slug\": \"bytedance-seed/seed-2-1-turbo-20260810\", \"hugging_face_id\": null, \"name\": \"ByteDance Seed: Seed 2.1 Turbo\", \"created\": 1786552176, \"description\": \"Seed 2.1 Turbo is a multimodal model from ByteDance Seed for coding and long-horizon agent workflows. It is suited for end-to-end software delivery, multi-step task execution, and understanding visual and...\", \"context_length\": 262144, \"architecture\": {\"modality\": \"text+image+video->text\", \"input_modalities\": [\"text\", \"image\", \"video\"], \"output_modalities\": [\"text\"], \"tokenizer\": \"Other\", \"instruct_type\": null}, \"pricing\": {\"prompt\": \"0.0000005\", \"completion\": \"0.0000025\"}, \"top_provider\": {\"context_length\": 262144, \"max_completion_tokens\": 235929, \"is_moderated\": false}, \"per_request_limits\": null, \"supported_parameters\": [\"frequency_penalty\", \"include_reasoning\", \"max_tokens\", \"reasoning\", \"response_format\", \"stop\", \"structured_outputs\", \"temperature\", \"tool_choice\", \"tools\", \"top_p\"], \"default_parameters\": {}, \"supported_voices\": null, \"knowledge_cutoff\": null, \"expiration_date\": null, \"links\": {\"details\": \"/api/v1/models/bytedance-seed/seed-2-1-turbo-20260810/endpoints\"}, \"reasoning\": {\"mandatory\": false}}, {\"id\": \"poolside/laguna-s-2.1\", \"canonical_slug\": \"poolside/laguna-s-2.1-20260720\", \"hugging_face_id\": \"poolside/Laguna-S-2.1\", \"name\": \"Poolside: Laguna S 2.1\", \"created\": 1784652683, \"description\": \"Laguna S 2.1 is the latest coding agent model from [Poolside](<https://poolside.ai/>). Laguna S 2.1 is a 118B total parameter model with 8B active parameters, scoring 70.2% on Terminal-Bench 2.1 and...\", \"context_length\": 1048576, \"architecture\": {\"modality\": \"text->text\", \"input_modalities\": [\"text\"], \"output_modalities\": [\"text\"], \"tokenizer\": \"Other\", \"instruct_type\": null}, \"pricing\": {\"prompt\": \"0.00000009\", \"completion\": \"0.00000018\", \"input_cache_read\": \"0.000000009\"}, \"top_provider\": {\"context_length\": 1048576, \"max_completion_tokens\": 131072, \"is_moderated\": false}, \"per_request_limits\": null, \"supported_parameters\": [\"include_reasoning\", \"max_tokens\", \"reasoning\", \"temperature\", \"tool_choice\", \"tools\"], \"default_parameters\": {}, \"supported_voices\": null, \"knowledge_cutoff\": null, \"expiration_date\": \"2026-10-31\", \"links\": {\"details\": \"/api/v1/models/poolside/laguna-s-2.1-20260720/endpoints\"}, \"reasoning\": {\"mandatory\": false, \"default_enabled\": true}}, {\"id\": \"qwen/qwen3-max\", \"canonical_slug\": \"qwen/qwen3-max\", \"hugging_face_id\": \"\", \"name\": \"Qwen: Qwen3 Max\", \"created\": 1758662808, \"description\": \"Qwen3-Max is an updated release built on the Qwen3 series, offering major improvements in reasoning, instruction following, multilingual support, and long-tail knowledge coverage compared to the January 2025 version. It...\", \"context_length\": 262144, \"architecture\": {\"modality\": \"text->text\", \"input_modalities\": [\"text\"], \"output_modalities\": [\"text\"], \"tokenizer\": \"Qwen3\", \"instruct_type\": null}, \"pricing\": {\"prompt\": \"0.00000078\", \"completion\": \"0.0000039\", \"input_cache_read\": \"0.000000156\", \"input_cache_write\": \"0.000000975\", \"overrides\": [{\"min_prompt_tokens\": 32000, \"prompt\": \"0.00000156\", \"completion\": \"0.0000078\", \"input_cache_read\": \"0.000000312\", \"input_cache_write\": \"0.00000195\"}, {\"min_prompt_tokens\": 128000, \"prompt\": \"0.00000195\", \"completion\": \"0.00000975\", \"input_cache_read\": \"0.00000039\", \"input_cache_write\": \"0.0000024375\"}]}, \"top_provider\": {\"context_length\": 262144, \"max_completion_tokens\": 65536, \"is_moderated\": false}, \"per_request_limits\": null, \"supported_parameters\": [\"frequency_penalty\", \"logprobs\", \"max_tokens\", \"presence_penalty\", \"response_format\", \"seed\", \"stop\", \"structured_outputs\", \"temperature\", \"tool_choice\", \"tools\", \"top_k\", \"top_logprobs\", \"top_p\"], \"default_parameters\": {\"temperature\": 1, \"top_p\": 1, \"frequency_penalty\": null}, \"supported_voices\": null, \"knowledge_cutoff\": \"2025-06-30\", \"expiration_date\": \"2026-10-09\", \"links\": {\"details\": \"/api/v1/models/qwen/qwen3-max/endpoints\"}, \"benchmarks\": {\"design_arena\": [{\"arena\": \"models\", \"category\": \"3d\", \"elo\": 1079, \"win_rate\": 43.5, \"rank\": 92}, {\"arena\": \"models\", \"category\": \"asciiart\", \"elo\": 1136, \"win_rate\": 47.2, \"rank\": 51}, {\"arena\": \"models\", \"category\": \"codecategories\", \"elo\": 1113, \"win_rate\": 44, \"rank\": 92}, {\"arena\": \"models\", \"category\": \"dataviz\", \"elo\": 1103, \"win_rate\": 41.2, \"rank\": 92}, {\"arena\": \"models\", \"category\": \"gamedev\", \"elo\": 1101, \"win_rate\": 43.8, \"rank\": 90}, {\"arena\": \"models\", \"category\": \"svg\", \"elo\": 1010, \"win_rate\": 37.2, \"rank\": 82}, {\"arena\": \"models\", \"category\": \"uicomponent\", \"elo\": 1083, \"win_rate\": 40.2, \"rank\": 95}, {\"arena\": \"models\", \"category\": \"website\", \"elo\": 1123, \"win_rate\": 44.5, \"rank\": 95}], \"artificial_analysis\": {\"intelligence_index\": 15.6, \"coding_index\": null, \"agentic_index\": null}}, \"reasoning\": {\"mandatory\": false}}]}",
16 "https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest": "{\"name\": \"models/gemini-flash-latest\", \"version\": \"Gemini Flash Latest\", \"displayName\": \"Gemini Flash Latest\", \"description\": \"Latest release of Gemini Flash\", \"inputTokenLimit\": 1048576, \"outputTokenLimit\": 65536, \"supportedGenerationMethods\": [\"generateContent\", \"countTokens\", \"createCachedContent\", \"batchGenerateContent\"], \"temperature\": 1, \"topP\": 0.95, \"topK\": 64, \"maxTemperature\": 2, \"thinking\": true}",
17 "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-31b-it": "{\"name\": \"models/gemma-4-31b-it\", \"version\": \"001\", \"displayName\": \"Gemma 4 31B IT\", \"description\": \"Gemma 4 31B IT\", \"inputTokenLimit\": 262144, \"outputTokenLimit\": 32768, \"supportedGenerationMethods\": [\"generateContent\", \"countTokens\"], \"temperature\": 1, \"topP\": 0.95, \"topK\": 64, \"maxTemperature\": 2, \"thinking\": true}",
18 "https://docs.together.ai/docs/kimi-k3-quickstart.md": "> ## Documentation Index\n> Fetch the complete documentation index at: https://docs.together.ai/llms.txt\n> Use this file to discover all available pages before exploring further.\n\n# Kimi K3 quickstart\n\n> Call Kimi K3 on Together for long-horizon coding, vision-in-the-loop work, and deep reasoning.\n\nKimi K3 is Moonshot AI's flagship model and the first open-weight model in the 3-trillion-parameter class, at 2.8 trillion total parameters. It is built for frontier intelligence work: long-horizon coding, end-to-end knowledge work, and deep reasoning. It accepts both text and image inputs, thinks by default, and holds a 1.05M-token context window.\n\nThe model ID is `moonshotai/Kimi-K3`. Pricing is \\$3.00 per 1M input tokens, \\$15.00 per 1M output tokens, and \\$0.30 per 1M cached input tokens, flat across the full context window.\n\nTogether AI is working directly with the Moonshot team on this model.\n\n## Call Kimi K3\n\nThinking is on by default, so give `max_tokens` real headroom. The reasoning trace and the answer share the same completion budget, and a tight cap spends the whole allowance on reasoning and returns empty or truncated `content`.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n completion = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=[\n {\"role\": \"user\", \"content\": \"Introduce Kimi K3 in one sentence.\"}\n ],\n max_tokens=131072,\n )\n\n print(completion.choices[0].message.content)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const completion = await together.chat.completions.create({\n model: \"moonshotai/Kimi-K3\",\n messages: [\n { role: \"user\", content: \"Introduce Kimi K3 in one sentence.\" },\n ],\n max_tokens: 131072,\n });\n\n console.log(completion.choices[0].message.content);\n ```\n\n ```bash cURL theme={null}\n curl -X POST \"https://api.together.ai/v1/chat/completions\" \\\n -H \"Authorization: Bearer $TOGETHER_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"moonshotai/Kimi-K3\",\n \"messages\": [\n {\"role\": \"user\", \"content\": \"Introduce Kimi K3 in one sentence.\"}\n ],\n \"max_tokens\": 131072\n }'\n ```\n</CodeGroup>\n\n## Set the thinking effort\n\nK3 thinks by default at `reasoning_effort=\"max\"`. Lower the level to cut cost and latency:\n\n* `\"low\"`: shallow reasoning. Use for short, high-volume calls.\n* `\"high\"`: deep reasoning. Use for most coding and analysis work.\n* `\"max\"`: maximum reasoning, the default. Use for the hardest planning, architecture, and multi-step agentic problems, and set `max_tokens` generously.\n\nThe levels are coarse dials rather than a strictly monotonic scale, so measure token counts on your own prompts before you tune. Invalid effort strings are accepted silently instead of returning an error, so validate the value in your own code.\n\nTo skip thinking entirely on trivial turns, pass `reasoning={\"enabled\": False}`. No thinking tokens are generated or billed.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n # Adjust depth: \"low\" | \"high\" | \"max\"\n completion = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Prove that the square root of 2 is irrational.\",\n }\n ],\n reasoning_effort=\"max\",\n max_tokens=8192,\n )\n\n print(completion.choices[0].message.content)\n\n # Instant mode: no thinking tokens generated or billed\n fast = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=[{\"role\": \"user\", \"content\": \"What is the capital of France?\"}],\n reasoning={\"enabled\": False},\n max_tokens=256,\n )\n\n print(fast.choices[0].message.content)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n // Adjust depth: \"low\" | \"medium\" | \"high\" | \"max\"\n const completion = await together.chat.completions.create({\n model: \"moonshotai/Kimi-K3\",\n messages: [\n {\n role: \"user\",\n content: \"Prove that the square root of 2 is irrational.\",\n },\n ],\n reasoning_effort: \"max\",\n max_tokens: 8192,\n });\n\n console.log(completion.choices[0].message.content);\n\n // Instant mode: no thinking tokens generated or billed\n const fast = await together.chat.completions.create({\n model: \"moonshotai/Kimi-K3\",\n messages: [{ role: \"user\", content: \"What is the capital of France?\" }],\n reasoning: { enabled: false },\n max_tokens: 256,\n });\n\n console.log(fast.choices[0].message.content);\n ```\n</CodeGroup>\n\nFor broader guidance on reasoning controls and prompting, see [Reasoning](/docs/inference/chat/reasoning).\n\n## Stream the reasoning trace and the answer\n\nK3 returns two channels. The thinking trace arrives on `reasoning_content` and the final answer arrives on `content`. Handle both, and skip chunks where `choices` is empty, since Together emits a final usage-only chunk.\n\nK3 emits the trace under `reasoning_content` to match Moonshot, while other Together models use the newer `reasoning` alias. Reading both keys makes one handler work across models.\n\n<CodeGroup>\n ```python Python theme={null}\n from together import Together\n\n client = Together()\n\n stream = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=[{\"role\": \"user\", \"content\": \"Explain why the sky is blue.\"}],\n max_tokens=4096,\n stream=True,\n )\n\n in_answer = False\n for chunk in stream:\n if not chunk.choices:\n continue\n delta = chunk.choices[0].delta\n thinking = getattr(delta, \"reasoning_content\", None) or getattr(\n delta, \"reasoning\", None\n )\n if thinking:\n print(thinking, end=\"\", flush=True)\n if delta.content:\n if not in_answer:\n print(\"\\n--- answer ---\")\n in_answer = True\n print(delta.content, end=\"\", flush=True)\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n import type { ChatCompletionChunk } from \"together-ai/resources/chat/completions\";\n\n const together = new Together();\n\n // K3 emits the trace on reasoning_content; other models use reasoning\n type ReasoningDelta = ChatCompletionChunk.Choice.Delta & {\n reasoning_content?: string;\n reasoning?: string;\n };\n\n const stream = await together.chat.completions.create({\n model: \"moonshotai/Kimi-K3\",\n messages: [{ role: \"user\", content: \"Explain why the sky is blue.\" }],\n max_tokens: 4096,\n stream: true,\n });\n\n let inAnswer = false;\n for await (const chunk of stream) {\n if (!chunk.choices?.length) continue;\n const delta = chunk.choices[0]?.delta as ReasoningDelta;\n\n const thinking = delta?.reasoning_content || delta?.reasoning;\n if (thinking) process.stdout.write(thinking);\n\n if (delta?.content) {\n if (!inAnswer) {\n process.stdout.write(\"\\n--- answer ---\\n\");\n inAnswer = true;\n }\n process.stdout.write(delta.content);\n }\n }\n ```\n</CodeGroup>\n\nDisplay layers can render either channel. JSON parsers must read `content` only. History replay requires both, as described in [Preserve the thinking history](#preserve-the-thinking-history).\n\n## Send images\n\nK3 has native visual understanding. Pass `content` as an array of objects and supply the image as either a public URL or a base64 data URL. Together fetches public URLs server-side.\n\n<CodeGroup>\n ```python Python theme={null}\n import base64\n from pathlib import Path\n\n from together import Together\n\n client = Together()\n\n IMAGE_URL = \"https://raw.githubusercontent.com/pytorch/pytorch/main/docs/source/_static/img/pytorch-logo-dark.png\"\n\n # From a public URL\n completion = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n max_tokens=2048,\n messages=[\n {\n \"role\": \"user\",\n \"content\": [\n {\"type\": \"image_url\", \"image_url\": {\"url\": IMAGE_URL}},\n {\"type\": \"text\", \"text\": \"Describe this image.\"},\n ],\n }\n ],\n )\n\n print(completion.choices[0].message.content)\n\n # From a local file\n image_data = base64.b64encode(Path(\"image.png\").read_bytes()).decode()\n\n completion = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n max_tokens=2048,\n messages=[\n {\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"image_url\",\n \"image_url\": {\n \"url\": f\"data:image/png;base64,{image_data}\"\n },\n },\n {\"type\": \"text\", \"text\": \"Describe this image.\"},\n ],\n }\n ],\n )\n\n print(completion.choices[0].message.content)\n ```\n\n ```typescript TypeScript theme={null}\n import { readFileSync } from \"fs\";\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const IMAGE_URL =\n \"https://raw.githubusercontent.com/pytorch/pytorch/main/docs/source/_static/img/pytorch-logo-dark.png\";\n\n // From a public URL\n const completion = await together.chat.completions.create({\n model: \"moonshotai/Kimi-K3\",\n max_tokens: 2048,\n messages: [\n {\n role: \"user\",\n content: [\n { type: \"image_url\", image_url: { url: IMAGE_URL } },\n { type: \"text\", text: \"Describe this image.\" },\n ],\n },\n ],\n });\n\n console.log(completion.choices[0].message.content);\n\n // From a local file\n const imageData = readFileSync(\"image.png\").toString(\"base64\");\n\n const fromFile = await together.chat.completions.create({\n model: \"moonshotai/Kimi-K3\",\n max_tokens: 2048,\n messages: [\n {\n role: \"user\",\n content: [\n {\n type: \"image_url\",\n image_url: { url: `data:image/png;base64,${imageData}` },\n },\n { type: \"text\", text: \"Describe this image.\" },\n ],\n },\n ],\n });\n\n console.log(fromFile.choices[0].message.content);\n ```\n</CodeGroup>\n\nVision limits:\n\n* There is no limit on the number of images per request, but the whole request body must stay under 100 MB. This is the binding constraint when you inline base64.\n* 4K (4096x2160) is the recommended maximum resolution. Higher resolutions cost processing time and tokens without improving understanding.\n* Token cost scales with resolution.\n* A public URL is fetched with a plain server-side HTTP GET, so hosts that block unfamiliar clients return an error. Fall back to base64 for those.\n\nMoonshot also publishes [Perception Bench](https://www.kimi.com/blog/perception-bench), a visual reasoning benchmark, if you want to evaluate K3's visual understanding yourself.\n\n## Constrain the output to a schema\n\nPass a JSON schema through `response_format` with `\"strict\": True` to constrain the final `content`.\n\nKeep `max_tokens` generous. The whole thinking trace is spent before the first schema-constrained token is emitted, so a tight cap truncates the JSON rather than the reasoning. Parse `content` only, never `reasoning_content`.\n\n<CodeGroup>\n ```python Python theme={null}\n import json\n\n from together import Together\n\n client = Together()\n\n completion = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n max_tokens=4096,\n messages=[{\"role\": \"user\", \"content\": \"Ada Lovelace was 36 years old.\"}],\n response_format={\n \"type\": \"json_schema\",\n \"json_schema\": {\n \"name\": \"person\",\n \"strict\": True,\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"age\": {\"type\": \"integer\"},\n },\n \"required\": [\"name\", \"age\"],\n \"additionalProperties\": False,\n },\n },\n },\n )\n\n person = json.loads(completion.choices[0].message.content)\n print(person)\n # -> {'name': 'Ada Lovelace', 'age': 36}\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const completion = await together.chat.completions.create({\n model: \"moonshotai/Kimi-K3\",\n max_tokens: 4096,\n messages: [{ role: \"user\", content: \"Ada Lovelace was 36 years old.\" }],\n response_format: {\n type: \"json_schema\",\n json_schema: {\n name: \"person\",\n strict: true,\n schema: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n age: { type: \"integer\" },\n },\n required: [\"name\", \"age\"],\n additionalProperties: false,\n },\n },\n },\n });\n\n const person = JSON.parse(completion.choices[0].message.content ?? \"{}\");\n console.log(person);\n // -> { name: 'Ada Lovelace', age: 36 }\n ```\n</CodeGroup>\n\nThe looser `{\"type\": \"json_object\"}` mode also works when you only need syntactically valid JSON.\n\n## Call tools\n\nDeclare functions in `tools`. When the model returns `tool_calls`, append the complete assistant message to history, append one `tool` message per call with the matching `tool_call_id`, then call again.\n\n`tool_choice` accepts four forms:\n\n| Value | Effect |\n| - | - |\n| `\"auto\"` | The model decides. This is also what omitting the field means. |\n| `\"required\"` | The model must call at least one tool this turn. Declare at least one callable tool. |\n| `\"none\"` | Tool calls are forbidden this turn. |\n| `{\"type\": \"function\", \"function\": {\"name\": \"get_weather\"}}` | Force one specific tool. |\n\nSet `tool_choice=\"required\"` on the first turn to force a tool call, then switch back to `\"auto\"`. Changing `tool_choice` between turns does not invalidate the prefix cache.\n\n`message.model_dump(exclude_none=True)` is the line that matters below. It round-trips the assistant turn whole, including `reasoning_content`, which K3 depends on. See [Preserve the thinking history](#preserve-the-thinking-history).\n\n<CodeGroup>\n ```python Python theme={null}\n import json\n\n from together import Together\n\n client = Together()\n\n tools = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Get the current weather for a city.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"city\": {\n \"type\": \"string\",\n \"description\": \"City name, e.g. Paris\",\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\"celsius\", \"fahrenheit\"],\n },\n },\n \"required\": [\"city\"],\n \"additionalProperties\": False,\n },\n },\n }\n ]\n\n\n def get_weather(city, unit=\"celsius\"):\n return {\n \"city\": city,\n \"temperature\": 21,\n \"unit\": unit,\n \"conditions\": \"sunny\",\n }\n\n\n messages = [{\"role\": \"user\", \"content\": \"What's the weather in Paris?\"}]\n choice_mode = \"required\" # Force a tool call on turn one\n\n for _ in range(5):\n response = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=messages,\n tools=tools,\n tool_choice=choice_mode,\n max_tokens=8192,\n )\n choice = response.choices[0]\n message = choice.message\n\n # Append the complete assistant message, thinking trace included\n messages.append(message.model_dump(exclude_none=True))\n\n if choice.finish_reason != \"tool_calls\" or not message.tool_calls:\n print(message.content)\n break\n\n for call in message.tool_calls:\n try:\n args = json.loads(call.function.arguments)\n except json.JSONDecodeError:\n args = {}\n messages.append(\n {\n \"role\": \"tool\",\n \"tool_call_id\": call.id,\n \"content\": json.dumps(get_weather(**args)),\n }\n )\n\n choice_mode = \"auto\" # Hand control back after the forced turn\n ```\n\n ```typescript TypeScript theme={null}\n import Together from \"together-ai\";\n\n const together = new Together();\n\n const tools = [\n {\n type: \"function\" as const,\n function: {\n name: \"get_weather\",\n description: \"Get the current weather for a city.\",\n parameters: {\n type: \"object\",\n properties: {\n city: { type: \"string\", description: \"City name, e.g. Paris\" },\n unit: { type: \"string\", enum: [\"celsius\", \"fahrenheit\"] },\n },\n required: [\"city\"],\n additionalProperties: false,\n },\n },\n },\n ];\n\n function getWeather(city: string, unit = \"celsius\") {\n return { city, temperature: 21, unit, conditions: \"sunny\" };\n }\n\n const messages: any[] = [\n { role: \"user\", content: \"What's the weather in Paris?\" },\n ];\n let choiceMode: \"required\" | \"auto\" = \"required\";\n\n for (let i = 0; i < 5; i++) {\n const response = await together.chat.completions.create({\n model: \"moonshotai/Kimi-K3\",\n messages,\n tools,\n tool_choice: choiceMode,\n max_tokens: 8192,\n });\n\n const choice = response.choices[0];\n const message = choice.message;\n\n // Append the complete assistant message, thinking trace included\n messages.push(message);\n\n if (choice.finish_reason !== \"tool_calls\" || !message.tool_calls?.length) {\n console.log(message.content);\n break;\n }\n\n for (const call of message.tool_calls) {\n let args: { city: string; unit?: string };\n try {\n args = JSON.parse(call.function.arguments);\n } catch {\n args = { city: \"\" };\n }\n messages.push({\n role: \"tool\",\n tool_call_id: call.id,\n content: JSON.stringify(getWeather(args.city, args.unit)),\n });\n }\n\n choiceMode = \"auto\"; // Hand control back after the forced turn\n }\n ```\n</CodeGroup>\n\n## Load tools dynamically\n\nK3 can pick up a tool mid-conversation. Place a complete tool definition (full `name`, `description`, and `parameters`) inside a `system` message that carries a `tools` field and no `content`. The tool becomes available from that message's position onward.\n\nRules to follow:\n\n* Dynamic declarations use exactly the same format as the top-level `tools` field.\n* The system message must have empty content. Sending both `content` and `tools` on it returns `400: a system message with dynamic tools must have empty content`.\n* Declarations apply per request and are not retained by the server. Keep the message in later request history yourself. Keeping it preserves both the tool's availability and the cached prefix. Dropping it means the model can no longer call that tool and the changed prefix may miss the cache.\n* Append declarations at the tail of `messages`. Appending does not affect the cached prefix, while removing or modifying an earlier declaration may hurt cache hits from that point onward.\n* Keep at least one tool in the top-level `tools` array whenever you send `tool_choice`.\n\nDon't put dozens or hundreds of tool definitions into every request. They eat context and make the model more likely to pick the wrong tool. Use search-then-inject instead:\n\n1. At conversation start, declare a single `search_tools` function backed by your own catalog, plus a few core tools, and advertise the searchable domain tags in the system prompt.\n2. On the first turn, set `tool_choice=\"required\"` to force retrieval before answering.\n3. Inject the full definitions of the matching tools through a `system` message based on the retrieval results.\n4. Let the model call the loaded tools directly in later generations.\n\nDecide `reasoning_effort` before the conversation starts, since changing it mid-conversation costs you cache hits.\n\n```python Python theme={null}\nimport json\n\nfrom together import Together\n\nclient = Together()\n\nCATALOG = {\n \"convert_currency\": {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"convert_currency\",\n \"description\": \"Convert an amount from one currency to another.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"amount\": {\"type\": \"number\"},\n \"from_currency\": {\"type\": \"string\"},\n \"to_currency\": {\"type\": \"string\"},\n },\n \"required\": [\"amount\", \"from_currency\", \"to_currency\"],\n \"additionalProperties\": False,\n },\n },\n },\n}\n\nsearch_tools = {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"search_tools\",\n \"description\": \"Search the tool catalog. Tags: finance, travel, files.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\"query\": {\"type\": \"string\"}},\n \"required\": [\"query\"],\n \"additionalProperties\": False,\n },\n },\n}\n\nmessages = [{\"role\": \"user\", \"content\": \"Convert 100 USD to EUR.\"}]\n\n# 1. Force retrieval before answering\nfirst = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=messages,\n tools=[search_tools],\n tool_choice=\"required\",\n max_tokens=8192,\n)\ncall = first.choices[0].message.tool_calls[0]\nmessages.append(first.choices[0].message.model_dump(exclude_none=True))\nmessages.append(\n {\n \"role\": \"tool\",\n \"tool_call_id\": call.id,\n \"content\": json.dumps(list(CATALOG)),\n }\n)\n\n# 2. Inject matching definitions at the tail: tools field, no content\nmessages.append({\"role\": \"system\", \"tools\": [CATALOG[\"convert_currency\"]]})\n\n# 3. The model calls the freshly loaded tool directly\nsecond = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=messages,\n tools=[search_tools],\n tool_choice=\"auto\",\n max_tokens=8192,\n)\nprint(second.choices[0].message.tool_calls)\n# -> convert_currency({\"amount\":100,\"from_currency\":\"USD\",\"to_currency\":\"EUR\"})\n```\n\n## Work with the 1.05M context and the cache\n\nK3 accepts up to 1.05M input tokens on Together, and context caching is automatic. There is no cache ID, TTL, or extra parameter. Keep your long prefix (system prompt, knowledge base, repo dump) byte-stable across requests so later calls hit the cache. Moonshot reports cache hit rates above 90% in coding workloads, which pulls effective input cost toward the \\$0.30 floor.\n\nMoonshot recommends placing fixed bulk context such as knowledge documents at the very beginning of the `messages` array, ahead of the system message, then appending questions and replies after it.\n\nRead the usage counters defensively. The `*_details` objects come back as plain dicts on some responses, and `completion_tokens_details` is absent entirely when you disable reasoning.\n\n```python Python theme={null}\ndef _get(obj, key, default=None):\n if obj is None:\n return default\n if isinstance(obj, dict):\n return obj.get(key, default)\n return getattr(obj, key, default)\n\n\nusage = completion.usage\nreasoning_tokens = _get(\n _get(usage, \"completion_tokens_details\"), \"reasoning_tokens\", 0\n)\ncached_tokens = _get(\n _get(usage, \"prompt_tokens_details\"),\n \"cached_tokens\",\n _get(usage, \"cached_tokens\", 0),\n)\n\nprint(\n f\"prompt={usage.prompt_tokens} cached={cached_tokens} \"\n f\"completion={usage.completion_tokens} thinking={reasoning_tokens}\"\n)\n# -> prompt=86 cached=64 completion=133 thinking=111\n```\n\n## Preserve the thinking history\n\nK3 was trained in preserved thinking history mode, so the trace is state that the next turn depends on. Return the complete assistant message on every turn, `reasoning_content` included. If you keep only `content`, generation quality becomes unstable.\n\nTogether accepts the trace back under either `reasoning_content` (what K3 emits) or the newer `reasoning` alias.\n\n```python Python theme={null}\nfrom together import Together\n\nclient = Together()\n\nprompt = (\n \"Pick a random 5-digit number and commit to it. \" \"Reply with exactly: OK\"\n)\n\n# Turn 1: let K3 think\nfirst = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=[{\"role\": \"user\", \"content\": prompt}],\n max_tokens=4000,\n)\n\n# Replay the assistant turn whole: model_dump keeps reasoning_content\nhistory = [\n {\"role\": \"user\", \"content\": prompt},\n first.choices[0].message.model_dump(exclude_none=True),\n {\n \"role\": \"user\",\n \"content\": \"What number did you pick? Reply with just the number.\",\n },\n]\n\nsecond = client.chat.completions.create(\n model=\"moonshotai/Kimi-K3\",\n messages=history,\n max_tokens=4000,\n)\nprint(second.choices[0].message.content)\n```\n\nDrop the trace from the replay and the model answers with a freshly invented number instead, because the commitment lived in the reasoning rather than in `content`.\n\n<Warning>\n Don't switch an ongoing session over to K3 from another model. K3 inherits a history that contains no K3 thinking at all, and quality degrades. Start K3 sessions on K3.\n</Warning>\n\n## Sampling parameters\n\nMost sampling parameters are fixed server-side. Omit them and let the defaults apply.\n\n| Parameter | Behavior on Together |\n| - | - |\n| `temperature` | Fixed at 1.0. |\n| `top_p` | Fixed at 0.95. Any other value returns `400`. |\n| `n` | Fixed at 1. Best-of-n has to live in your own harness. |\n| `presence_penalty`, `frequency_penalty` | Fixed at 0. |\n| `logprobs` | Not supported. Returns `400`. |\n| `top_k`, `min_p`, `repetition_penalty`, `stop`, `seed` | Accepted. |\n| `max_tokens` | No ceiling below the 1.05M context limit. Cap it yourself for short answers. |\n| `reasoning_effort` | `\"low\"`, `\"medium\"`, `\"high\"`, or `\"max\"` (default). Invalid strings are accepted silently, so validate client-side. |\n| `reasoning` | `{\"enabled\": False}` disables thinking entirely. |\n\n## Architecture\n\nTwo architectural changes form K3's backbone, both aimed at moving information through longer sequences and deeper into the network:\n\n* **Kimi Delta Attention (KDA):** A hybrid linear attention mechanism that provides an efficient foundation for scaling attention across very long contexts. This is Moonshot's first model to support a 1.05M context window.\n* **Attention Residuals (AttnRes):** Selectively retrieves representations across model depth rather than accumulating them uniformly.\n\nOn top of that, Moonshot pushed mixture-of-experts (MoE) sparsity further with the Stable LatentMoE framework, activating 16 of 896 experts. At roughly 2% of experts active per token, routing and optimization become first-order problems, so four supporting techniques keep training stable at 2.8T scale:\n\n* **Quantile Balancing:** Derives expert allocation directly from router-score quantiles, which eliminates heuristic updates and a sensitive balancing hyperparameter.\n* **Per-Head Muon:** Extends the Muon optimizer to optimize attention heads independently for more adaptive learning at scale.\n* **Sigmoid Tanh Unit (SiTU):** Improves activation control.\n* **Gated MLA:** Improves attention selectivity.\n\nK3 continues a sustained scaling push: in nine of the 12 months from July 2025 to July 2026, Kimi models set the upper bound of open-model scale. At 2.8T parameters, K3 is the largest open-weight model released to date.\n\n## Use cases\n\nK3 is strongest where a task runs long and needs little supervision:\n\n* **Long-horizon coding:** Sustained engineering sessions, navigation of massive repositories, and orchestration of terminal tools.\n* **Vision in the loop:** Iterating between code and live screenshots for game development, frontend engineering, and CAD, using visual feedback rather than a written description of the render.\n* **Research pipelines:** Reviewing literature, implementing a numerical pipeline, cross-validating results, and producing an interactive deliverable in one run.\n* **End-to-end knowledge work:** Deep research reports with interactive charts, timelines, and slides rather than a paragraph of prose.\n* **Large-repository refactoring:** Cross-file, multi-step engineering work held together by the 1.05M context window.\n* **Agentic tool orchestration:** Long tool-calling loops with reasoning between steps and tools loaded on demand.\n\n## Limitations\n\n* **Cost on short, high-volume calls:** Thinking defaults to `\"max\"`, so a pipeline that never sets `reasoning_effort` pays the maximum reasoning bill on every call. Reasoning tokens bill as output at \\$15.00 per 1M. Drop trivial calls to `\"low\"` or disable reasoning outright.\n* **Excessive proactiveness:** K3's training emphasizes long, difficult tasks, so it may make decisions on your behalf when it hits a minor issue or ambiguous intent mid-task. State hard constraints explicitly in the system prompt or in `AGENTS.md`.\n* **Mid-session model swaps:** Switching an in-flight session to K3 from another model leaves it without any K3 thinking history and destabilizes output.\n* **Cache fragility:** Restructuring earlier messages or editing an earlier tool declaration breaks the prefix cache and reprices the affected input from \\$0.30 to \\$3.00 per 1M tokens.\n\n## Usage tips\n\n| Tip | Rationale |\n| - | - |\n| **Give `max_tokens` real headroom** | The trace shares the completion budget with the answer. A tight cap returns empty or truncated `content`. |\n| **Return the complete assistant message every turn** | `message.model_dump(exclude_none=True)` keeps `reasoning_content` in history, which K3 was trained to depend on. |\n| **Read both `reasoning_content` and `reasoning`** | K3 emits the trace on `reasoning_content`. Other Together models use the `reasoning` alias. One handler then covers both. |\n| **Parse `content` only** | Never run JSON parsing over the thinking trace. |\n| **Set `reasoning_effort` deliberately** | `\"max\"` is the default and the most expensive setting. Match the level to the task. |\n| **Keep prefixes byte-stable** | Caching is automatic, so stable prefixes are what pull effective input cost toward \\$0.30 per 1M tokens. |\n| **Put bulk context first** | Place knowledge documents at the very start of `messages`, ahead of the system message, then append the conversation. |\n| **Inject dynamic tools at the tail** | Appending is cache-safe. Editing an earlier declaration invalidates everything after it. |\n| **Omit the fixed sampling parameters** | `top_p`, `n`, and the penalties are fixed server-side and return `400` on any other value. |\n| **Think in goals, not steps** | K3 is agentic. Give high-level objectives and let it orchestrate sub-tasks and tool calls. |\n\n## Next steps\n\n<CardGroup cols={2}>\n <Card title=\"Reasoning\" icon=\"brain\" href=\"/docs/inference/chat/reasoning\">\n Control reasoning depth and handle reasoning output across models.\n </Card>\n\n <Card title=\"Function calling\" icon=\"tool\" href=\"/docs/inference/function-calling/overview\">\n Build tool-calling loops against any function-calling model.\n </Card>\n\n <Card title=\"Vision\" icon=\"photo\" href=\"/docs/inference/vision/overview\">\n Send images to vision models and read the results.\n </Card>\n\n <Card title=\"Serverless models\" icon=\"stack-2\" href=\"/docs/serverless/models\">\n Browse every model, context length, and price on serverless inference.\n </Card>\n</CardGroup>\n\n\nThis documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform."