[
  {
    "path": "LICENSE",
    "content": "Modified MIT License\n\nCopyright (c) 2025 Moonshot AI\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the “Software”), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\nOur only modification part is that, if the Software (or any derivative works\nthereof) is used for any of your commercial products or services that have\nmore than 100 million monthly active users, or more than 20 million US dollars\n(or equivalent in other currencies) in monthly revenue, you shall prominently\ndisplay \"Kimi K2\" on the user interface of such product or service.\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n  <picture>\n      <img src=\"figures/kimi-logo.png\" width=\"30%\" alt=\"Kimi K2: Open Agentic Intelligence\">\n  </picture>\n</div>\n\n<hr>\n\n<div align=\"center\" style=\"line-height:1\">\n  <a href=\"https://www.kimi.com\" target=\"_blank\"><img alt=\"Chat\" src=\"https://img.shields.io/badge/🤖%20Chat-Kimi%20K2-ff6b6b?color=1783ff&logoColor=white\"/></a>\n  <a href=\"https://www.moonshot.ai\" target=\"_blank\"><img alt=\"Homepage\" src=\"https://img.shields.io/badge/Homepage-Moonshot%20AI-white?logo=Kimi&logoColor=white\"/></a>\n</div>\n\n<div align=\"center\" style=\"line-height: 1;\">\n  <a href=\"https://huggingface.co/moonshotai\" target=\"_blank\"><img alt=\"Hugging Face\" src=\"https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Moonshot%20AI-ffc107?color=ffc107&logoColor=white\"/></a>\n  <a href=\"https://twitter.com/kimi_moonshot\" target=\"_blank\"><img alt=\"Twitter Follow\" src=\"https://img.shields.io/badge/Twitter-Kimi.ai-white?logo=x&logoColor=white\"/></a>\n    <a href=\"https://discord.gg/TYU2fdJykW\" target=\"_blank\"><img alt=\"Discord\" src=\"https://img.shields.io/badge/Discord-Kimi.ai-white?logo=discord&logoColor=white\"/></a>\n</div>\n\n<div align=\"center\" style=\"line-height: 1;\">\n  <a href=\"https://github.com/moonshotai/Kimi-K2/blob/main/LICENSE\"><img alt=\"License\" src=\"https://img.shields.io/badge/License-Modified_MIT-f5de53?&color=f5de53\"/></a>\n</div>\n\n<p align=\"center\">\n<b>📰&nbsp;&nbsp;<a href=\"https://moonshotai.github.io/Kimi-K2/\">Tech Blog</a></b> &nbsp;&nbsp;&nbsp; | &nbsp;&nbsp;&nbsp; <b>📄&nbsp;&nbsp;<a href=\"https://www.arxiv.org/abs/2507.20534\">Full Report</a></b>\n</p>\n\n## 1. Model Introduction\n\nKimi K2 is a state-of-the-art mixture-of-experts (MoE) language model with 32 billion activated parameters and 1 trillion total parameters. Trained with the Muon optimizer, Kimi K2 achieves exceptional performance across frontier knowledge, reasoning, and coding tasks while being meticulously optimized for agentic capabilities.\n\n### Key Features\n- Large-Scale Training: Pre-trained a 1T parameter MoE model on 15.5T tokens with zero training instability.\n- MuonClip Optimizer: We apply the Muon optimizer to an unprecedented scale, and develop novel optimization techniques to resolve instabilities while scaling up.\n- Agentic Intelligence: Specifically designed for tool use, reasoning, and autonomous problem-solving.\n\n### Model Variants\n- **Kimi-K2-Base**: The foundation model, a strong start for researchers and builders who want full control for fine-tuning and custom solutions.\n- **Kimi-K2-Instruct**: The post-trained model, best for drop-in, general-purpose chat and agentic experiences. It is a reflex-grade model without long thinking.\n\n<div align=\"center\">\n  <picture>\n      <img src=\"figures/banner.png\" width=\"80%\" alt=\"Evaluation Results\">\n  </picture>\n</div>\n\n## 2. Model Summary\n\n<div align=\"center\">\n\n\n| | |\n|:---:|:---:|\n| **Architecture** | Mixture-of-Experts (MoE) |\n| **Total Parameters** | 1T |\n| **Activated Parameters** | 32B |\n| **Number of Layers** (Dense layer included) | 61 |\n| **Number of Dense Layers** | 1 |\n| **Attention Hidden Dimension** | 7168 |\n| **MoE Hidden Dimension** (per Expert) | 2048 |\n| **Number of Attention Heads** | 64 |\n| **Number of Experts** | 384 |\n| **Selected Experts per Token** | 8 |\n| **Number of Shared Experts** | 1 |\n| **Vocabulary Size** | 160K |\n| **Context Length** | 128K |\n| **Attention Mechanism** | MLA |\n| **Activation Function** | SwiGLU |\n</div>\n\n## 3. Evaluation Results\n\n#### Instruction model evaluation results\n\n<div align=\"center\">\n<table>\n<thead>\n<tr>\n<th align=\"center\">Benchmark</th>\n<th align=\"center\">Metric</th>\n<th align=\"center\"><sup>Kimi K2 Instruct</sup></th>\n<th align=\"center\"><sup>DeepSeek-V3-0324</sup></th>\n<th align=\"center\"><sup>Qwen3-235B-A22B <br><sup>(non-thinking)</sup></sup></th>\n<th align=\"center\"><sup>Claude Sonnet 4 <br><sup>(w/o extended thinking)</sup></sup></th>\n<th align=\"center\"><sup>Claude Opus 4 <br><sup>(w/o extended thinking)</sup></sup></th>\n<th align=\"center\"><sup>GPT-4.1</sup></th>\n<th align=\"center\"><sup>Gemini 2.5 Flash <br> Preview (05-20)</sup></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"center\" colspan=9><strong>Coding Tasks</strong></td>\n</tr>\n<tr>\n<td align=\"center\">LiveCodeBench v6<br><sup>(Aug 24 - May 25)</sup></td>\n<td align=\"center\">Pass@1</td>\n<td align=\"center\"><strong>53.7</strong></td>\n<td align=\"center\">46.9</td>\n<td align=\"center\">37.0</td>\n<td align=\"center\">48.5</td>\n<td align=\"center\">47.4</td>\n<td align=\"center\">44.7</td>\n<td align=\"center\">44.7</td>\n</tr>\n<tr>\n<td align=\"center\">OJBench</td>\n<td align=\"center\">Pass@1</td>\n<td align=\"center\"><strong>27.1</strong></td>\n<td align=\"center\">24.0</td>\n<td align=\"center\">11.3</td>\n<td align=\"center\">15.3</td>\n<td align=\"center\">19.6</td>\n<td align=\"center\">19.5</td>\n<td align=\"center\">19.5</td>\n</tr>\n\n<tr>\n<td align=\"center\">MultiPL-E</td>\n<td align=\"center\">Pass@1</td>\n<td align=\"center\"><ins><strong>85.7</strong></ins></td>\n<td align=\"center\">83.1</td>\n<td align=\"center\">78.2</td>\n<td align=\"center\">88.6</td>\n<td align=\"center\"><strong>89.6</strong></td>\n<td align=\"center\">86.7</td>\n<td align=\"center\">85.6</td>\n</tr>\n\n<tr>\n<td align=\"center\">SWE-bench Verified <br/><sup>(Agentless Coding)</sup></td>\n<td align=\"center\">Single Patch w/o Test (Acc)</td>\n<td align=\"center\"><ins><strong>51.8</strong></ins></td>\n<td align=\"center\">36.6</td>\n<td align=\"center\">39.4</td>\n<td align=\"center\">50.2</td>\n<td align=\"center\"><strong>53.0</strong></td>\n<td align=\"center\">40.8</td>\n<td align=\"center\">32.6</td>\n</tr>\n\n<tr>\n<td align=\"center\" rowspan=\"2\">SWE-bench Verified <br/> <sup>(Agentic Coding)</sup></td>\n<td align=\"center\">Single Attempt (Acc)</td>\n<td align=\"center\"><ins><strong>65.8</strong></ins></td>\n<td align=\"center\">38.8</td>\n<td align=\"center\">34.4</td>\n<td align=\"center\"><strong>72.7</strong><sup>*</sup></td>\n<td align=\"center\">72.5<sup>*</sup></td>\n<td align=\"center\">54.6</td>\n<td align=\"center\">—</td>\n</tr>\n\n<tr>\n<!--<td align=\"center\">(Agentic Coding)</td>-->\n<td align=\"center\">Multiple Attempts (Acc)</td>\n<td align=\"center\"><ins><strong>71.6</strong></ins></td>\n<td align=\"center\">—</td>\n<td align=\"center\">—</td>\n<td align=\"center\"><strong>80.2</strong></td>\n<td align=\"center\">79.4<sup>*</sup></td>\n<td align=\"center\">—</td>\n<td align=\"center\">—</td>\n</tr>\n\n<tr>\n<td align=\"center\">SWE-bench Multilingual<br /> <sup>(Agentic Coding)</sup></td>\n<td align=\"center\">Single Attempt (Acc)</td>\n<td align=\"center\"><ins><strong>47.3</strong> </ins></td>\n<td align=\"center\">25.8</td>\n<td align=\"center\">20.9</td>\n<td align=\"center\"><strong>51.0</strong></td>\n<td align=\"center\">—</td>\n<td align=\"center\">31.5</td>\n<td align=\"center\">—</td>\n</tr>\n\n<tr>\n<td align=\"center\" rowspan=\"2\">TerminalBench</td>\n<td align=\"center\">Inhouse Framework (Acc)</td>\n<td align=\"center\"><ins><strong>30.0</strong></ins></td>\n<td align=\"center\">—</td>\n<td align=\"center\">—</td>\n<td align=\"center\">35.5</td>\n<td align=\"center\"><strong>43.2</strong></td>\n<td align=\"center\">8.3</td>\n<td align=\"center\">—</td>\n</tr>\n\n<tr>\n<!--<td align=\"center\">TerminalBench</td>-->\n<td align=\"center\">Terminus (Acc)</td>\n<td align=\"center\"><ins><strong>25.0</strong> </ins></td>\n<td align=\"center\">16.3</td>\n<td align=\"center\">6.6</td>\n<td align=\"center\">—</td>\n<td align=\"center\">—</td>\n<td align=\"center\"><strong>30.3</strong></td>\n<td align=\"center\">16.8</td>\n</tr>\n<tr>\n<td align=\"center\">Aider-Polyglot</td>\n<td align=\"center\">Acc</td>\n<td align=\"center\">60.0</td>\n<td align=\"center\">55.1</td>\n<td align=\"center\"><ins><strong>61.8</strong></ins></td>\n<td align=\"center\">56.4</td>\n<td align=\"center\"><strong>70.7</strong></td>\n<td align=\"center\">52.4</td>\n<td align=\"center\">44.0</td>\n</tr>\n<tr>\n<td align=\"center\" colspan=9><strong>Tool Use Tasks</strong></td>\n</tr>\n<tr>\n<td align=\"center\">Tau2 retail</td>\n<td align=\"center\">Avg@4</td>\n<td align=\"center\"><ins><strong>70.6</strong></ins></td>\n<td align=\"center\">69.1</td>\n<td align=\"center\">57.0</td>\n<td align=\"center\">75.0</td>\n<td align=\"center\"><strong>81.8</strong></td>\n<td align=\"center\">74.8</td>\n<td align=\"center\">64.3</td>\n</tr>\n<tr>\n<td align=\"center\">Tau2 airline</td>\n<td align=\"center\">Avg@4</td>\n<td align=\"center\"><ins><strong>56.5</strong></ins></td>\n<td align=\"center\">39.0</td>\n<td align=\"center\">26.5</td>\n<td align=\"center\">55.5</td>\n<td align=\"center\"><strong>60.0</strong></td>\n<td align=\"center\">54.5</td>\n<td align=\"center\">42.5</td>\n</tr>\n<tr>\n<td align=\"center\">Tau2 telecom</td>\n<td align=\"center\">Avg@4</td>\n<td align=\"center\"><strong>65.8</strong></td>\n<td align=\"center\">32.5</td>\n<td align=\"center\">22.1</td>\n<td align=\"center\">45.2</td>\n<td align=\"center\">57.0</td>\n<td align=\"center\">38.6</td>\n<td align=\"center\">16.9</td>\n</tr>\n<tr>\n<td align=\"center\">AceBench</td>\n<td align=\"center\">Acc</td>\n<td align=\"center\"><ins><strong>76.5</strong></ins></td>\n<td align=\"center\">72.7</td>\n<td align=\"center\">70.5</td>\n<td align=\"center\">76.2</td>\n<td align=\"center\">75.6</td>\n<td align=\"center\"><strong>80.1</strong></td>\n<td align=\"center\">74.5</td>\n</tr>\n<tr>\n<td align=\"center\" colspan=9><strong>Math &amp; STEM Tasks</strong></td>\n</tr>\n<tr>\n<td align=\"center\">AIME 2024</td>\n<td align=\"center\">Avg@64</td>\n<td align=\"center\"><strong>69.6</strong></td>\n<td align=\"center\">59.4<sup>*</sup></td>\n<td align=\"center\">40.1<sup>*</sup></td>\n<td align=\"center\">43.4</td>\n<td align=\"center\">48.2</td>\n<td align=\"center\">46.5</td>\n<td align=\"center\">61.3</td>\n</tr>\n<tr>\n<td align=\"center\">AIME 2025</td>\n<td align=\"center\">Avg@64</td>\n<td align=\"center\"><strong>49.5</strong></td>\n<td align=\"center\">46.7</td>\n<td align=\"center\">24.7<sup>*</sup></td>\n<td align=\"center\">33.1<sup>*</sup></td>\n<td align=\"center\">33.9<sup>*</sup></td>\n<td align=\"center\">37.0</td>\n<td align=\"center\">46.6</td>\n</tr>\n<tr>\n<td align=\"center\">MATH-500</td>\n<td align=\"center\">Acc</td>\n<td align=\"center\"><strong>97.4</strong></td>\n<td align=\"center\">94.0<sup>*</sup></td>\n<td align=\"center\">91.2<sup>*</sup></td>\n<td align=\"center\">94.0</td>\n<td align=\"center\">94.4</td>\n<td align=\"center\">92.4</td>\n<td align=\"center\">95.4</td>\n</tr>\n<tr>\n<td align=\"center\">HMMT 2025</td>\n<td align=\"center\">Avg@32</td>\n<td align=\"center\"><strong>38.8</strong></td>\n<td align=\"center\">27.5</td>\n<td align=\"center\">11.9</td>\n<td align=\"center\">15.9</td>\n<td align=\"center\">15.9</td>\n<td align=\"center\">19.4</td>\n<td align=\"center\">34.7</td>\n</tr>\n<tr>\n<td align=\"center\">CNMO 2024</td>\n<td align=\"center\">Avg@16</td>\n<td align=\"center\">74.3</td>\n<td align=\"center\"><ins><strong>74.7</strong></ins></td>\n<td align=\"center\">48.6</td>\n<td align=\"center\">60.4</td>\n<td align=\"center\">57.6</td>\n<td align=\"center\">56.6</td>\n<td align=\"center\"><strong>75.0</strong></td>\n</tr>\n<tr>\n<td align=\"center\">PolyMath-en</td>\n<td align=\"center\">Avg@4</td>\n<td align=\"center\"><strong>65.1</strong></td>\n<td align=\"center\">59.5</td>\n<td align=\"center\">51.9</td>\n<td align=\"center\">52.8</td>\n<td align=\"center\">49.8</td>\n<td align=\"center\">54.0</td>\n<td align=\"center\">49.9</td>\n</tr>\n\n<tr>\n<td align=\"center\">ZebraLogic</td>\n<td align=\"center\">Acc</td>\n<td align=\"center\"><strong>89.0</strong></td>\n<td align=\"center\">84.0</td>\n<td align=\"center\">37.7<sup>*</sup></td>\n<td align=\"center\">73.7</td>\n<td align=\"center\">59.3</td>\n<td align=\"center\">58.5</td>\n<td align=\"center\">57.9</td>\n</tr>\n\n<tr>\n<td align=\"center\">AutoLogi</td>\n<td align=\"center\">Acc</td>\n<td align=\"center\"><ins><strong>89.5</strong></ins></td>\n<td align=\"center\">88.9</td>\n<td align=\"center\">83.3</td>\n<td align=\"center\"><strong>89.8</strong></td>\n<td align=\"center\">86.1</td>\n<td align=\"center\">88.2</td>\n<td align=\"center\">84.1</td>\n</tr>\n\n<tr>\n<td align=\"center\">GPQA-Diamond</td>\n<td align=\"center\">Avg@8</td>\n<td align=\"center\"><strong>75.1</strong></td>\n<td align=\"center\">68.4<sup>*</sup></td>\n<td align=\"center\">62.9<sup>*</sup></td>\n<td align=\"center\">70.0<sup>*</sup></td>\n<td align=\"center\">74.9<sup>*</sup></td>\n<td align=\"center\">66.3</td>\n<td align=\"center\">68.2</td>\n</tr>\n\n<tr>\n<td align=\"center\">SuperGPQA</td>\n<td align=\"center\">Acc</td>\n<td align=\"center\"><strong>57.2</strong></td>\n<td align=\"center\">53.7</td>\n<td align=\"center\">50.2</td>\n<td align=\"center\">55.7</td>\n<td align=\"center\">56.5</td>\n<td align=\"center\">50.8</td>\n<td align=\"center\">49.6</td>\n</tr>\n\n<tr>\n<td align=\"center\">Humanity's Last Exam<br><sup>(Text Only)</sup></td>\n<td align=\"center\">-</td>\n<td align=\"center\">4.7</td>\n<td align=\"center\">5.2</td>\n<td align=\"center\"><ins><strong>5.7</strong></ins></td>\n<td align=\"center\">5.8</td>\n<td align=\"center\"><strong>7.1</strong></td>\n<td align=\"center\">3.7</td>\n<td align=\"center\">5.6</td>\n</tr>\n\n<tr>\n<td align=\"center\" colspan=9><strong>General Tasks</strong></td>\n</tr>\n\n<tr>\n<td align=\"center\">MMLU</td>\n<td align=\"center\">EM</td>\n<td align=\"center\"><ins><strong>89.5</strong></ins></td>\n<td align=\"center\">89.4</td>\n<td align=\"center\">87.0</td>\n<td align=\"center\">91.5</td>\n<td align=\"center\"><strong>92.9</strong></td>\n<td align=\"center\">90.4</td>\n<td align=\"center\">90.1</td>\n</tr>\n\n<tr>\n<td align=\"center\">MMLU-Redux</td>\n<td align=\"center\">EM</td>\n<td align=\"center\"><ins><strong>92.7</strong></ins></td>\n<td align=\"center\">90.5</td>\n<td align=\"center\">89.2</td>\n<td align=\"center\">93.6</td>\n<td align=\"center\"><strong>94.2</strong></td>\n<td align=\"center\">92.4</td>\n<td align=\"center\">90.6</td>\n</tr>\n\n<tr>\n<td align=\"center\">MMLU-Pro</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">81.1</td>\n<td align=\"center\"><ins><strong>81.2</strong></ins><sup>*</sup></td>\n<td align=\"center\">77.3</td>\n<td align=\"center\">83.7</td>\n<td align=\"center\"><strong>86.6</strong></td>\n<td align=\"center\">81.8</td>\n<td align=\"center\">79.4</td>\n</tr>\n\n<tr>\n<td align=\"center\">IFEval</td>\n<td align=\"center\">Prompt Strict</td>\n<td align=\"center\"><strong>89.8</strong></td>\n<td align=\"center\">81.1</td>\n<td align=\"center\">83.2<sup>*</sup></td>\n<td align=\"center\">87.6</td>\n<td align=\"center\">87.4</td>\n<td align=\"center\">88.0</td>\n<td align=\"center\">84.3</td>\n</tr>\n\n<tr>\n<td align=\"center\">Multi-Challenge</td>\n<td align=\"center\">Acc</td>\n<td align=\"center\"><strong>54.1</strong></td>\n<td align=\"center\">31.4</td>\n<td align=\"center\">34.0</td>\n<td align=\"center\">46.8</td>\n<td align=\"center\">49.0</td>\n<td align=\"center\">36.4</td>\n<td align=\"center\">39.5</td>\n</tr>\n\n<tr>\n<td align=\"center\">SimpleQA</td>\n<td align=\"center\">Correct</td>\n<td align=\"center\"><ins><strong>31.0</strong></ins></td>\n<td align=\"center\">27.7</td>\n<td align=\"center\">13.2</td>\n<td align=\"center\">15.9</td>\n<td align=\"center\">22.8</td>\n<td align=\"center\"><strong>42.3</strong></td>\n<td align=\"center\">23.3</td>\n</tr>\n\n<tr>\n<td align=\"center\">Livebench</td>\n<td align=\"center\">Pass@1</td>\n<td align=\"center\"><strong>76.4</strong></td>\n<td align=\"center\">72.4</td>\n<td align=\"center\">67.6</td>\n<td align=\"center\">74.8</td>\n<td align=\"center\">74.6</td>\n<td align=\"center\">69.8</td>\n<td align=\"center\">67.8</td>\n</tr>\n</tbody>\n</table>\n</div>\n<sup>\n• Bold denotes global SOTA, and underlined denotes open-source SOTA.\n</sup><br/><sup>\n• Data points marked with * are directly from the model's tech report or blog.\n</sup><br/><sup>\n• All metrics, except for SWE-bench Verified (Agentless), are evaluated with an 8k output token length. SWE-bench Verified (Agentless) is limited to a 16k output token length.\n</sup><br/><sup>\n• Kimi K2 achieves 65.8% pass@1 on the SWE-bench Verified tests with bash/editor tools (single-attempt patches, no test-time compute). It also achieves a 47.3% pass@1 on the SWE-bench Multilingual tests under the same conditions. Additionally, we report results on SWE-bench Verified tests (71.6%) that leverage parallel test-time compute by sampling multiple sequences and selecting the single best via an internal scoring model.\n</sup><br/><sup>\n• To ensure the stability of the evaluation, we employed avg@k on the AIME, HMMT, CNMO, PolyMath-en, GPQA-Diamond, EvalPlus, Tau2.\n</sup><br/><sup>\n• Some data points have been omitted due to prohibitively expensive evaluation costs.\n    </sup>\n\n---\n\n#### Base model evaluation results\n\n<div align=\"center\">\n\n<table>\n<thead>\n<tr>\n<th align=\"center\">Benchmark</th>\n<th align=\"center\">Metric</th>\n<th align=\"center\">Shot</th>\n<th align=\"center\">Kimi K2 Base</th>\n<th align=\"center\">Deepseek-V3-Base</th>\n<th align=\"center\">Qwen2.5-72B</th>\n<th align=\"center\">Llama 4 Maverick</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"center\" colspan=\"7\"><strong>General Tasks</strong></td>\n</tr>\n<tr>\n<td align=\"center\">MMLU</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\"><strong>87.8</strong></td>\n<td align=\"center\">87.1</td>\n<td align=\"center\">86.1</td>\n<td align=\"center\">84.9</td>\n</tr>\n<tr>\n<td align=\"center\">MMLU-pro</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\"><strong>69.2</strong></td>\n<td align=\"center\">60.6</td>\n<td align=\"center\">62.8</td>\n<td align=\"center\">63.5</td>\n</tr>\n<tr>\n<td align=\"center\">MMLU-redux-2.0</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\"><strong>90.2</strong></td>\n<td align=\"center\">89.5</td>\n<td align=\"center\">87.8</td>\n<td align=\"center\">88.2</td>\n</tr>\n<tr>\n<td align=\"center\">SimpleQA</td>\n<td align=\"center\">Correct</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\"><strong>35.3</strong></td>\n<td align=\"center\">26.5</td>\n<td align=\"center\">10.3</td>\n<td align=\"center\">23.7</td>\n</tr>\n<tr>\n<td align=\"center\">TriviaQA</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\"><strong>85.1</strong></td>\n<td align=\"center\">84.1</td>\n<td align=\"center\">76.0</td>\n<td align=\"center\">79.3</td>\n</tr>\n<tr>\n<td align=\"center\">GPQA-Diamond</td>\n<td align=\"center\">Avg@8</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\">48.1</td>\n<td align=\"center\"><strong>50.5</strong></td>\n<td align=\"center\">40.8</td>\n<td align=\"center\">49.4</td>\n</tr>\n<tr>\n<td align=\"center\">SuperGPQA</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\"><strong>44.7</strong></td>\n<td align=\"center\">39.2</td>\n<td align=\"center\">34.2</td>\n<td align=\"center\">38.8</td>\n</tr>\n<tr>\n<td align=\"center\" colspan=\"7\"><strong>Coding Tasks</strong></td>\n</tr>\n<tr>\n<td align=\"center\">LiveCodeBench v6</td>\n<td align=\"center\">Pass@1</td>\n<td align=\"center\">1-shot</td>\n<td align=\"center\"><strong>26.3</strong></td>\n<td align=\"center\">22.9</td>\n<td align=\"center\">21.1</td>\n<td align=\"center\">25.1</td>\n</tr>\n<tr>\n<td align=\"center\">EvalPlus</td>\n<td align=\"center\">Pass@1</td>\n<td align=\"center\">-</td>\n<td align=\"center\"><strong>80.3</strong></td>\n<td align=\"center\">65.6</td>\n<td align=\"center\">66.0</td>\n<td align=\"center\">65.5</td>\n</tr>\n<tr>\n<td align=\"center\" colspan=\"7\"><strong>Mathematics Tasks</strong></td>\n</tr>\n<tr>\n<td align=\"center\">MATH</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">4-shot</td>\n<td align=\"center\"><strong>70.2</strong></td>\n<td align=\"center\">60.1</td>\n<td align=\"center\">61.0</td>\n<td align=\"center\">63.0</td>\n</tr>\n<tr>\n<td align=\"center\">GSM8k</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">8-shot</td>\n<td align=\"center\"><strong>92.1</strong></td>\n<td align=\"center\">91.7</td>\n<td align=\"center\">90.4</td>\n<td align=\"center\">86.3</td>\n</tr>\n<tr>\n<td align=\"center\" colspan=\"7\"><strong>Chinese Tasks</strong></td>\n</tr>\n<tr>\n<td align=\"center\">C-Eval</td>\n<td align=\"center\">EM</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\"><strong>92.5</strong></td>\n<td align=\"center\">90.0</td>\n<td align=\"center\">90.9</td>\n<td align=\"center\">80.9</td>\n</tr>\n<tr>\n<td align=\"center\">CSimpleQA</td>\n<td align=\"center\">Correct</td>\n<td align=\"center\">5-shot</td>\n<td align=\"center\"><strong>77.6</strong></td>\n<td align=\"center\">72.1</td>\n<td align=\"center\">50.5</td>\n<td align=\"center\">53.5</td>\n</tr>\n</tbody>\n</table>\n</div>\n<sup>\n• We only evaluate open-source pretrained models in this work. We report results for Qwen2.5-72B because the base checkpoint for Qwen3-235B-A22B was not open-sourced at the time of our study.\n</sup><br/><sup>\n• All models are evaluated using the same evaluation protocol.\n\n</sup>\n\n\n## 4. Deployment\n> [!Note]\n> You can access Kimi K2's API on https://platform.moonshot.ai , we provide an OpenAI/Anthropic-compatible API for you.\n>\n> The Anthropic-compatible API maps temperature by `real_temperature = request_temperature * 0.6` for better compatiblity with existing applications.\n\nOur model checkpoints are stored in block-fp8 format, you can find it on [Huggingface](https://huggingface.co/moonshotai/Kimi-K2-Instruct).\n\nCurrently, it is recommended to run Kimi-K2 on the following inference engines:\n\n* vLLM\n* SGLang\n* KTransformers\n* TensorRT-LLM\n\nDeployment examples for vLLM and SGLang can be found in the [Model Deployment Guide](docs/deploy_guidance.md).\n\n---\n\n## 5. Model Usage\n\n### Chat Completion\n\nOnce the local inference service is set up, you can interact with it through the chat endpoint:\n\n```python\ndef simple_chat(client: OpenAI, model_name: str):\n    messages = [\n        {\"role\": \"system\", \"content\": \"You are Kimi, an AI assistant created by Moonshot AI.\"},\n        {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Please give a brief self-introduction.\"}]},\n    ]\n    response = client.chat.completions.create(\n        model=model_name,\n        messages=messages,\n        stream=False,\n        temperature=0.6,\n        max_tokens=256\n    )\n    print(response.choices[0].message.content)\n```\n\n> [!NOTE]\n> The recommended temperature for Kimi-K2-Instruct is `temperature = 0.6`.\n> If no special instructions are required, the system prompt is a good default.\n\n---\n\n### Tool Calling\n\nKimi-K2-Instruct has strong tool-calling capabilities.\nTo enable them, you need to pass the list of available tools in each request, then the model will autonomously decide when and how to invoke them.\n\nThe following example demonstrates calling a weather tool end-to-end:\n\n```python\n# Your tool implementation\ndef get_weather(city: str) -> dict:\n    return {\"weather\": \"Sunny\"}\n\n# Tool schema definition\ntools = [{\n    \"type\": \"function\",\n    \"function\": {\n        \"name\": \"get_weather\",\n        \"description\": \"Retrieve current weather information. Call this when the user asks about the weather.\",\n        \"parameters\": {\n            \"type\": \"object\",\n            \"required\": [\"city\"],\n            \"properties\": {\n                \"city\": {\n                    \"type\": \"string\",\n                    \"description\": \"Name of the city\"\n                }\n            }\n        }\n    }\n}]\n\n# Map tool names to their implementations\ntool_map = {\n    \"get_weather\": get_weather\n}\n\ndef tool_call_with_client(client: OpenAI, model_name: str):\n    messages = [\n        {\"role\": \"system\", \"content\": \"You are Kimi, an AI assistant created by Moonshot AI.\"},\n        {\"role\": \"user\", \"content\": \"What's the weather like in Beijing today? Use the tool to check.\"}\n    ]\n    finish_reason = None\n    while finish_reason is None or finish_reason == \"tool_calls\":\n        completion = client.chat.completions.create(\n            model=model_name,\n            messages=messages,\n            temperature=0.6,\n            tools=tools,          # tool list defined above\n            tool_choice=\"auto\"\n        )\n        choice = completion.choices[0]\n        finish_reason = choice.finish_reason\n        if finish_reason == \"tool_calls\":\n            messages.append(choice.message)\n            for tool_call in choice.message.tool_calls:\n                tool_call_name = tool_call.function.name\n                tool_call_arguments = json.loads(tool_call.function.arguments)\n                tool_function = tool_map[tool_call_name]\n                tool_result = tool_function(**tool_call_arguments)\n                print(\"tool_result:\", tool_result)\n\n                messages.append({\n                    \"role\": \"tool\",\n                    \"tool_call_id\": tool_call.id,\n                    \"name\": tool_call_name,\n                    \"content\": json.dumps(tool_result)\n                })\n    print(\"-\" * 100)\n    print(choice.message.content)\n```\n\nThe `tool_call_with_client` function implements the pipeline from user query to tool execution.\nThis pipeline requires the inference engine to support Kimi-K2’s native tool-parsing logic.\nFor streaming output and manual tool-parsing, see the [Tool Calling Guide](docs/tool_call_guidance.md).\n\n---\n\n## 6. License\n\nBoth the code and the model weights are released under the [Modified MIT License](LICENSE).\n\n---\n\n## 7. Citation\n\n```\n@misc{kimiteam2025kimik2openagentic,\n      title={Kimi K2: Open Agentic Intelligence}, \n      author={Kimi Team and Yifan Bai and Yiping Bao and Guanduo Chen and Jiahao Chen and Ningxin Chen and Ruijue Chen and Yanru Chen and Yuankun Chen and Yutian Chen and Zhuofu Chen and Jialei Cui and Hao Ding and Mengnan Dong and Angang Du and Chenzhuang Du and Dikang Du and Yulun Du and Yu Fan and Yichen Feng and Kelin Fu and Bofei Gao and Hongcheng Gao and Peizhong Gao and Tong Gao and Xinran Gu and Longyu Guan and Haiqing Guo and Jianhang Guo and Hao Hu and Xiaoru Hao and Tianhong He and Weiran He and Wenyang He and Chao Hong and Yangyang Hu and Zhenxing Hu and Weixiao Huang and Zhiqi Huang and Zihao Huang and Tao Jiang and Zhejun Jiang and Xinyi Jin and Yongsheng Kang and Guokun Lai and Cheng Li and Fang Li and Haoyang Li and Ming Li and Wentao Li and Yanhao Li and Yiwei Li and Zhaowei Li and Zheming Li and Hongzhan Lin and Xiaohan Lin and Zongyu Lin and Chengyin Liu and Chenyu Liu and Hongzhang Liu and Jingyuan Liu and Junqi Liu and Liang Liu and Shaowei Liu and T. Y. Liu and Tianwei Liu and Weizhou Liu and Yangyang Liu and Yibo Liu and Yiping Liu and Yue Liu and Zhengying Liu and Enzhe Lu and Lijun Lu and Shengling Ma and Xinyu Ma and Yingwei Ma and Shaoguang Mao and Jie Mei and Xin Men and Yibo Miao and Siyuan Pan and Yebo Peng and Ruoyu Qin and Bowen Qu and Zeyu Shang and Lidong Shi and Shengyuan Shi and Feifan Song and Jianlin Su and Zhengyuan Su and Xinjie Sun and Flood Sung and Heyi Tang and Jiawen Tao and Qifeng Teng and Chensi Wang and Dinglu Wang and Feng Wang and Haiming Wang and Jianzhou Wang and Jiaxing Wang and Jinhong Wang and Shengjie Wang and Shuyi Wang and Yao Wang and Yejie Wang and Yiqin Wang and Yuxin Wang and Yuzhi Wang and Zhaoji Wang and Zhengtao Wang and Zhexu Wang and Chu Wei and Qianqian Wei and Wenhao Wu and Xingzhe Wu and Yuxin Wu and Chenjun Xiao and Xiaotong Xie and Weimin Xiong and Boyu Xu and Jing Xu and Jinjing Xu and L. H. Xu and Lin Xu and Suting Xu and Weixin Xu and Xinran Xu and Yangchuan Xu and Ziyao Xu and Junjie Yan and Yuzi Yan and Xiaofei Yang and Ying Yang and Zhen Yang and Zhilin Yang and Zonghan Yang and Haotian Yao and Xingcheng Yao and Wenjie Ye and Zhuorui Ye and Bohong Yin and Longhui Yu and Enming Yuan and Hongbang Yuan and Mengjie Yuan and Haobing Zhan and Dehao Zhang and Hao Zhang and Wanlu Zhang and Xiaobin Zhang and Yangkun Zhang and Yizhi Zhang and Yongting Zhang and Yu Zhang and Yutao Zhang and Yutong Zhang and Zheng Zhang and Haotian Zhao and Yikai Zhao and Huabin Zheng and Shaojie Zheng and Jianren Zhou and Xinyu Zhou and Zaida Zhou and Zhen Zhu and Weiyu Zhuang and Xinxing Zu},\n      year={2025},\n      eprint={2507.20534},\n      archivePrefix={arXiv},\n      primaryClass={cs.LG},\n      url={https://arxiv.org/abs/2507.20534}, \n}\n```\n\n---\n\n## 8. Contact Us\n\nIf you have any questions or concerns, please reach out to us at [support@moonshot.cn](mailto:support@moonshot.cn).\n"
  },
  {
    "path": "docs/deploy_guidance.md",
    "content": "# Kimi-K2 Deployment Guide\n\n> [!Note]\n> This guide only provides some examples of deployment commands for Kimi-K2, which may not be the optimal configuration. Since inference engines are still being updated frequently,  please continue to follow the guidance from their homepage if you want to achieve better inference performance.\n\n\n## vLLM Deployment\nvLLM version v0.10.0rc1 or later is required.\n\nThe smallest deployment unit for Kimi-K2 FP8 weights with 128k seqlen on mainstream H200 or H20 platform is a cluster with 16 GPUs with either Tensor Parallel (TP) or \"data parallel + expert parallel\" (DP+EP).  \nRunning parameters for this environment are provided below. You may scale up to more nodes and increase expert-parallelism to enlarge the inference batch size and overall throughput.\n\n### Tensor Parallelism\n\nWhen the parallelism degree ≤ 16, you can run inference with pure Tensor Parallelism. A sample launch command is:\n\n``` bash\n# start ray on node 0 and node 1\n\n# node 0:\nvllm serve $MODEL_PATH \\\n  --port 8000 \\\n  --served-model-name kimi-k2 \\\n  --trust-remote-code \\\n  --tensor-parallel-size 16 \\\n  --enable-auto-tool-choice \\\n  --tool-call-parser kimi_k2\n```\n\n**Key parameter notes:**\n- `--tensor-parallel-size 16`: If using more than 16 GPUs, combine with pipeline-parallelism.\n- `--enable-auto-tool-choice`: Required when enabling tool usage.\n- `--tool-call-parser kimi_k2`: Required when enabling tool usage.\n\n### Data Parallelism + Expert Parallelism\n\nYou can install libraries like DeepEP and DeepGEMM as needed. Then run the command (example on H200):\n\n``` bash\n# node 0\nvllm serve $MODEL_PATH --port 8000 --served-model-name kimi-k2 --trust-remote-code --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-address $MASTER_IP --data-parallel-rpc-port $PORT --enable-expert-parallel --max-num-batched-tokens 8192 --max-num-seqs 256 --gpu-memory-utilization 0.85 --enable-auto-tool-choice --tool-call-parser kimi_k2\n\n# node 1\nvllm serve $MODEL_PATH --headless --data-parallel-start-rank 8 --port 8000 --served-model-name kimi-k2 --trust-remote-code --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-address $MASTER_IP --data-parallel-rpc-port $PORT --enable-expert-parallel --max-num-batched-tokens 8192 --max-num-seqs 256 --gpu-memory-utilization 0.85 --enable-auto-tool-choice --tool-call-parser kimi_k2\n```\n\n## SGLang Deployment\n\nSimilarly, we can use TP or DP+EP in SGLang for Deployment, here are the examples.\n\n\n### Tensor Parallelism\n\nHere is the simple example code to run TP16 with two nodes on H200:\n\n``` bash\n# Node 0\npython -m sglang.launch_server --model-path $MODEL_PATH --tp 16 --dist-init-addr $MASTER_IP:50000 --nnodes 2 --node-rank 0 --trust-remote-code --tool-call-parser kimi_k2\n\n# Node 1\npython -m sglang.launch_server --model-path $MODEL_PATH --tp 16 --dist-init-addr $MASTER_IP:50000 --nnodes 2 --node-rank 1 --trust-remote-code --tool-call-parser kimi_k2\n```\n\n**Key parameter notes:**\n- `--tool-call-parser kimi_k2`: Required when enabling tool usage.\n\n### Data Parallelism + Expert Parallelism\n\nHere is an example for large scale Prefill-Decode Disaggregation (4P12D H200) with DP+EP in SGLang:\n\n``` bash\n# for prefill node\nMC_TE_METRIC=true SGLANG_DISAGGREGATION_HEARTBEAT_INTERVAL=10000000 SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=100000 SGLANG_DISAGGREGATION_WAITING_TIMEOUT=100000 PYTHONUNBUFFERED=1 \\\npython -m sglang.launch_server --model-path $MODEL_PATH \\\n--trust-remote-code --disaggregation-mode prefill --dist-init-addr $PREFILL_NODE0$:5757 --tp-size 32 --dp-size 32 --enable-dp-attention --host $LOCAL_IP --decode-log-interval 1 --disable-radix-cache --enable-deepep-moe --moe-dense-tp-size 1 --enable-dp-lm-head --disable-shared-experts-fusion --watchdog-timeout 1000000 --enable-two-batch-overlap --disaggregation-ib-device $IB_DEVICE --chunked-prefill-size 131072 --mem-fraction-static 0.85 --deepep-mode normal --ep-dispatch-algorithm dynamic --eplb-algorithm deepseek --max-running-requests 1024 --nnodes 4 --node-rank $RANK --tool-call-parser kimi_k2\n\n\n# for decode node\nSGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=480 MC_TE_METRIC=true SGLANG_DISAGGREGATION_HEARTBEAT_INTERVAL=10000000 SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=100000 SGLANG_DISAGGREGATION_WAITING_TIMEOUT=100000 PYTHONUNBUFFERED=1 \\\npython -m sglang.launch_server --model-path $MODEL_PATH --trust-remote-code --disaggregation-mode decode --dist-init-addr $DECODE_NODE0:5757 --tp-size 96 --dp-size 96 --enable-dp-attention --host $LOCAL_IP --decode-log-interval 1 --context-length 2176 --disable-radix-cache --enable-deepep-moe --moe-dense-tp-size 1 --enable-dp-lm-head --disable-shared-experts-fusion --watchdog-timeout 1000000 --enable-two-batch-overlap --disaggregation-ib-device $IB_DEVICE  --deepep-mode low_latency --mem-fraction-static 0.8 --cuda-graph-bs 480 --max-running-requests 46080 --ep-num-redundant-experts 96 --nnodes 12 --node-rank $RANK --tool-call-parser kimi_k2\n\n# pdlb\nPYTHONUNBUFFERED=1 python -m sglang.srt.disaggregation.launch_lb --prefill http://${PREFILL_NODE0}:30000 --decode http://${DECODE_NODE0}:30000 \n```\n\n## KTransformers Deployment\n\nPlease copy all configuration files (i.e., everything except the .safetensors files) into the GGUF checkpoint folder at /path/to/K2. Then run:\n``` bash\npython ktransformers/server/main.py  --model_path /path/to/K2 --gguf_path /path/to/K2 --cache_lens 30000\n```\n\nTo enable AMX optimization, run:\n\n``` bash\npython ktransformers/server/main.py  --model_path /path/to/K2 --gguf_path /path/to/K2 --cache_lens 30000 --optimize_config_path ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat-fp8-linear-ggml-experts-serve-amx.yaml\n```\n\n## TensorRT-LLM Deployment\n### Prerequisite\nPlease refer to [this guide](https://nvidia.github.io/TensorRT-LLM/installation/build-from-source-linux.html) to build TensorRT-LLM v1.0.0-rc2 from source and start a TRT-LLM docker container. \n\ninstall blobfile by:\n```bash\npip install blobfile\n```\n### Multi-node Serving\nTensorRT-LLM supports multi-node inference. You can use mpirun to launch Kimi-K2 with multi-node jobs. We will use two nodes for this example.\n\n#### mpirun\nmpirun requires each node to have passwordless ssh access to the other node. We need to setup the environment inside the docker container. Run the container with host network and mount the current directory as well as model directory to the container.\n\n```bash\n# use host network\nIMAGE=<YOUR_IMAGE>\nNAME=test_2node_docker\n# host1\ndocker run -it --name ${NAME}_host1 --ipc=host --gpus=all --network host --privileged --ulimit memlock=-1 --ulimit stack=67108864 -v ${PWD}:/workspace -v <YOUR_MODEL_DIR>:/models/DeepSeek-V3 -w /workspace ${IMAGE}\n# host2\ndocker run -it --name ${NAME}_host2 --ipc=host --gpus=all --network host --privileged --ulimit memlock=-1 --ulimit stack=67108864 -v ${PWD}:/workspace -v <YOUR_MODEL_DIR>:/models/DeepSeek-V3 -w /workspace ${IMAGE}\n```\n\nSet up ssh inside the container\n\n```bash\napt-get update && apt-get install -y openssh-server\n\n# modify /etc/ssh/sshd_config\nPermitRootLogin yes\nPubkeyAuthentication yes\n# modify /etc/ssh/sshd_config, change default port 22 to another unused port\nport 2233\n\n# modify /etc/ssh\n```\n\nGenerate ssh key on host1 and copy to host2, vice versa.\n\n```bash\n# on host1\nssh-keygen -t ed25519 -f ~/.ssh/id_ed25519\nssh-copy-id -i ~/.ssh/id_ed25519.pub root@<HOST2>\n# on host2\nssh-keygen -t ed25519 -f ~/.ssh/id_ed25519\nssh-copy-id -i ~/.ssh/id_ed25519.pub root@<HOST1>\n\n# restart ssh service on host1 and host2\nservice ssh restart # or\n/etc/init.d/ssh restart # or\nsystemctl restart ssh\n```\n\nGenerate additional config for trtllm serve.\n```bash\ncat >/path/to/TensorRT-LLM/extra-llm-api-config.yml <<EOF\ncuda_graph_config:\n  padding_enabled: true\n  batch_sizes:\n    - 1\n    - 2\n    - 4\n    - 8\n    - 16\n    - 32\n    - 64\n    - 128\nprint_iter_log: true\nenable_attention_dp: true\nEOF\n```\n\n\nAfter the preparations,you can run the trtllm-serve on two nodes using mpirun:\n\n```bash\nmpirun -np 16 \\\n-H <HOST1>:8,<HOST2>:8 \\\n-mca plm_rsh_args \"-p 2233\" \\\n--allow-run-as-root \\\ntrtllm-llmapi-launch trtllm-serve serve \\\n--backend pytorch \\\n--tp_size 16 \\\n--ep_size 8 \\\n--kv_cache_free_gpu_memory_fraction 0.95 \\\n--trust_remote_code \\\n--max_batch_size 128 \\\n--max_num_tokens 4096 \\\n--extra_llm_api_options /path/to/TensorRT-LLM/extra-llm-api-config.yml \\\n--port 8000 \\\n<YOUR_MODEL_DIR> \n```\n\n## Others\n\nKimi-K2 reuses the `DeepSeekV3CausalLM` architecture and convert it's weight into proper shape to save redevelopment effort. To let inference engines distinguish it from DeepSeek-V3 and apply the best optimizations, we set `\"model_type\": \"kimi_k2\"` in `config.json`.\n\nIf you are using a framework that is not on the recommended list, you can still run the model by manually changing `model_type` to \"deepseek_v3\" in `config.json` as a temporary workaround. You may need to manually parse tool calls in case no tool call parser is available in your framework.\n"
  },
  {
    "path": "docs/tool_call_guidance.md",
    "content": "## Tool Calling\r\nTo enable the tool calling feature, you may need to set certain tool calling parser options when starting the service. See [deploy_guidance](./deploy_guidance.md) for details.\r\nIn Kimi-K2, a tool calling process includes:\r\n- Passing function descriptions to Kimi-K2\r\n- Kimi-K2 decides to make a function call and returns the necessary information for the function call to the user\r\n- The user performs the function call, collects the call results, and passes the function call results to Kimi-K2\r\n- Kimi-K2 continues to generate content based on the function call results until the model believes it has obtained sufficient information to respond to the user\r\n\r\n### Preparing Tools\r\nSuppose we have a function `get_weather` that can query the weather conditions in real-time. \r\nThis function accepts a city name as a parameter and returns the weather conditions. We need to prepare a structured description for it so that Kimi-K2 can understand its functionality.\r\n\r\n```python\r\ndef get_weather(city):\r\n    return {\"weather\": \"Sunny\"}\r\n\r\n# Collect the tool descriptions in tools\r\ntools = [{\r\n    \"type\": \"function\",\r\n    \"function\": {        \r\n        \"name\": \"get_weather\", \r\n        \"description\": \"Get weather information. Call this tool when the user needs to get weather information\", \r\n         \"parameters\": {\r\n              \"type\": \"object\",\r\n              \"required\": [\"city\"], \r\n              \"properties\": { \r\n                  \"city\": { \r\n                      \"type\": \"string\", \r\n                      \"description\": \"City name\", \r\n                }\r\n            }\r\n        }\r\n    }\r\n}]\r\n\r\n# Tool name->object mapping for easy calling later\r\ntool_map = {\r\n    \"get_weather\": get_weather\r\n}\r\n```\r\n### Chat with tools\r\nWe use `openai.OpenAI` to send messages to Kimi-K2 along with tool descriptions. Kimi-K2 will autonomously decide whether to use and how to use the provided tools. \r\nIf Kimi-K2 believes a tool call is needed, it will return a result with `finish_reason='tool_calls'`. At this point, the returned result includes the tool call information. \r\nAfter calling tools with the provided information, we then need to append the tool call results to the chat history and continue calling Kimi-K2. \r\nKimi-K2 may need to call tools multiple times until the model believes the current results can answer the user's question. We should check `finish_reason` until it is not `tool_calls`.\r\n\r\nThe results obtained by the user after calling the tools should be added to `messages` with `role='tool'`.\r\n\r\n```python\r\nimport json\r\nfrom openai import OpenAI\r\nmodel_name='moonshotai/Kimi-K2-Instruct'\r\nclient = OpenAI(base_url=endpoint, \r\n                        api_key='xxx')\r\n\r\nmessages = [\r\n{\"role\": \"user\", \"content\": \"What's the weather like in Beijing today? Let's check using the tool.\"}\r\n]\r\nfinish_reason = None\r\nwhile finish_reason is None or finish_reason == \"tool_calls\":\r\n    completion = client.chat.completions.create(\r\n        model=model_name,\r\n        messages=messages,\r\n        temperature=0.3,\r\n        tools=tools, \r\n        tool_choice=\"auto\",\r\n    )\r\n    choice = completion.choices[0]\r\n    finish_reason = choice.finish_reason\r\n    # Note: The finish_reason when tool calls end may vary across different engines, so this condition check needs to be adjusted accordingly\r\n    if finish_reason == \"tool_calls\": \r\n        messages.append(choice.message)\r\n        for tool_call in choice.message.tool_calls: \r\n            tool_call_name = tool_call.function.name\r\n            tool_call_arguments = json.loads(tool_call.function.arguments) \r\n            tool_function = tool_map[tool_call_name] \r\n            tool_result = tool_function(tool_call_arguments)\r\n            print(\"tool_result\", tool_result)\r\n\r\n            messages.append({\r\n                \"role\": \"tool\",\r\n                \"tool_call_id\": tool_call.id,\r\n                \"name\": tool_call_name,\r\n                \"content\": json.dumps(tool_result), \r\n            })\r\nprint('-' * 100)\r\nprint(choice.message.content)\r\n```\r\n### Tool Calling in Streaming Mode\r\nTool calling can also be used in streaming mode. In this case, we need to collect the tool call information returned in the stream until we have a complete tool call. Please refer to the code below:\r\n\r\n```python\r\nmessages = [\r\n    {\"role\": \"user\", \"content\": \"What's the weather like in Beijing today? Let's check using the tool.\"}\r\n]\r\nfinish_reason = None\r\nmsg = ''\r\nwhile finish_reason is None or finish_reason == \"tool_calls\":\r\n    completion = client.chat.completions.create(\r\n        model=model_name,\r\n        messages=messages,\r\n        temperature=0.3,\r\n        tools=tools,\r\n        tool_choice=\"auto\",\r\n        stream=True \r\n    )\r\n    tool_calls = []\r\n    for chunk in completion:\r\n        delta = chunk.choices[0].delta\r\n        if delta.content:\r\n            msg += delta.content\r\n        if delta.tool_calls:\r\n            for tool_call_chunk in delta.tool_calls:\r\n                if tool_call_chunk.index is not None:\r\n                    # Extend the tool_calls list\r\n                    while len(tool_calls) <= tool_call_chunk.index:\r\n                        tool_calls.append({\r\n                            \"id\": \"\",\r\n                            \"type\": \"function\",\r\n                            \"function\": {\r\n                                \"name\": \"\",\r\n                                \"arguments\": \"\"\r\n                            }\r\n                        })\r\n\r\n                    tc = tool_calls[tool_call_chunk.index]\r\n\r\n                    if tool_call_chunk.id:\r\n                        tc[\"id\"] += tool_call_chunk.id\r\n                    if tool_call_chunk.function.name:\r\n                        tc[\"function\"][\"name\"] += tool_call_chunk.function.name\r\n                    if tool_call_chunk.function.arguments:\r\n                        tc[\"function\"][\"arguments\"] += tool_call_chunk.function.arguments\r\n\r\n        finish_reason = chunk.choices[0].finish_reason\r\n    # Note: The finish_reason when tool calls end may vary across different engines, so this condition check needs to be adjusted accordingly\r\n    if finish_reason == \"tool_calls\":\r\n        for tool_call in tool_calls:\r\n            tool_call_name = tool_call['function']['name']\r\n            tool_call_arguments = json.loads(tool_call['function']['arguments'])\r\n            tool_function = tool_map[tool_call_name] \r\n            tool_result = tool_function(tool_call_arguments)\r\n            messages.append({\r\n                \"role\": \"tool\",\r\n                \"tool_call_id\": tool_call['id'],\r\n                \"name\": tool_call_name,\r\n                \"content\": json.dumps(tool_result),\r\n            })\r\n        # The text generated by the tool call is not the final version, reset msg\r\n        msg = ''\r\n\r\n    print(msg)\r\n```\r\n### Manually Parsing Tool Calls\r\nThe tool call requests generated by Kimi-K2 can also be parsed manually, which is especially useful when the service you are using does not provide a tool-call parser. \r\nThe tool call requests generated by Kimi-K2 are wrapped by `<|tool_calls_section_begin|>` and `<|tool_calls_section_end|>`, \r\nwith each tool call wrapped by `<|tool_call_begin|>` and `<|tool_call_end|>`. The tool ID and arguments are separated by `<|tool_call_argument_begin|>`. \r\nThe format of the tool ID is `functions.{func_name}:{idx}`, from which we can parse the function name.\r\n\r\nBased on the above rules, we can directly post a request to the completions interface and manually parse tool calls.\r\n\r\n```python\r\nimport requests\r\nfrom transformers import AutoTokenizer\r\nmessages = [\r\n    {\"role\": \"user\", \"content\": \"What's the weather like in Beijing today? Let's check using the tool.\"}\r\n]\r\nmsg = ''\r\ntokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)\r\nwhile True:\r\n    text = tokenizer.apply_chat_template(\r\n        messages,\r\n        tokenize=False,\r\n        tools=tools,\r\n        add_generation_prompt=True,\r\n    )\r\n    payload = {\r\n        \"model\": model_name,\r\n        \"prompt\": text,\r\n        \"max_tokens\": 512\r\n    }\r\n    response = requests.post(\r\n        f\"{endpoint}/completions\",\r\n        headers={\"Content-Type\": \"application/json\"},\r\n        json=payload,\r\n        stream=False,\r\n    )\r\n    raw_out = response.json()\r\n\r\n    raw_output = raw_out[\"choices\"][0][\"text\"]\r\n    tool_calls = extract_tool_call_info(raw_output)\r\n    if len(tool_calls) == 0:\r\n        # No tool calls\r\n        msg = raw_output\r\n        break\r\n    else:\r\n        for tool_call in tool_calls:\r\n            tool_call_name = tool_call['function']['name']\r\n            tool_call_arguments = json.loads(tool_call['function']['arguments'])\r\n            tool_function = tool_map[tool_call_name]\r\n            tool_result = tool_function(tool_call_arguments)\r\n\r\n            messages.append({\r\n                \"role\": \"tool\",\r\n                \"tool_call_id\": tool_call['id'],\r\n                \"name\": tool_call_name,\r\n                \"content\": json.dumps(tool_result), \r\n            })\r\nprint('-' * 100)          \r\nprint(msg)\r\n```\r\nHere, `extract_tool_call_info` parses the model output and returns the model call information. A simple implementation would be:\r\n```python\r\ndef extract_tool_call_info(tool_call_rsp: str):\r\n    if '<|tool_calls_section_begin|>' not in tool_call_rsp:\r\n        # No tool calls\r\n        return []\r\n    import re\r\n    pattern = r\"<\\|tool_calls_section_begin\\|>(.*?)<\\|tool_calls_section_end\\|>\"\r\n    \r\n    tool_calls_sections = re.findall(pattern, tool_call_rsp, re.DOTALL)\r\n    \r\n    # Extract multiple tool calls\r\n    func_call_pattern = r\"<\\|tool_call_begin\\|>\\s*(?P<tool_call_id>[\\w\\.]+:\\d+)\\s*<\\|tool_call_argument_begin\\|>\\s*(?P<function_arguments>.*?)\\s*<\\|tool_call_end\\|>\"\r\n    tool_calls = []\r\n    for match in re.findall(func_call_pattern, tool_calls_sections[0], re.DOTALL):\r\n        function_id, function_args = match\r\n        # function_id: functions.get_weather:0\r\n        function_name = function_id.split('.')[1].split(':')[0]\r\n        tool_calls.append(\r\n            {\r\n                \"id\": function_id,\r\n                \"type\": \"function\",\r\n                \"function\": {\r\n                    \"name\": function_name,\r\n                    \"arguments\": function_args\r\n                }\r\n            }\r\n        )  \r\n    return tool_calls\r\n```\r\n"
  }
]