Skip to content

月之暗面Kimi API完全指南

Kimi以其200万字超长上下文著称,是处理长文档的绝佳选择

概述

月之暗面(Moonshot AI)是一家专注于长上下文处理的AI公司,其Kimi模型以200万字超长上下文著称,特别适合处理长文档、代码库分析等场景。本教程将带你全面掌握Kimi API的使用方法。

为什么选择Kimi?

优势说明
超长上下文支持200万字上下文
文档处理长文档处理能力强
联网搜索支持实时联网获取信息
文件上传支持直接上传文件处理

Kimi模型概览

Moonshot模型家族:

moonshot-v1系列
├── moonshot-v1-8k      # 8K上下文
├── moonshot-v1-32k     # 32K上下文
└── moonshot-v1-128k    # 128K上下文

Kimi系列
└── kimi-latest         # 最新版本,支持超长上下文

基本概念

API Key

php
<?php
// 在月之暗面开放平台获取API Key
// https://platform.moonshot.cn/

// API Key格式
// sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

$apiKey = getenv('MOONSHOT_API_KEY');

兼容性

Kimi API完全兼容OpenAI API格式:

php
<?php
// Kimi API使用与OpenAI相同的接口格式
// 只需更改base_url即可
$baseUrl = 'https://api.moonshot.cn/v1';

环境准备

创建Kimi客户端

php
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class KimiClient
{
    private $client;
    private $apiKey;
    private $baseUrl = 'https://api.moonshot.cn/v1';

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->client = new Client([
            'base_uri' => $this->baseUrl,
            'timeout' => 120,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
        ]);
    }

    public function chat(
        array $messages,
        string $model = 'moonshot-v1-8k',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        if (isset($options['temperature'])) {
            $params['temperature'] = $options['temperature'];
        }

        if (isset($options['max_tokens'])) {
            $params['max_tokens'] = $options['max_tokens'];
        }

        try {
            $response = $this->client->post('/chat/completions', [
                'json' => $params,
            ]);

            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $errorBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'Unknown error';
            throw new Exception('Kimi API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$apiKey = getenv('MOONSHOT_API_KEY');
$client = new KimiClient($apiKey);

$result = $client->chat([
    ['role' => 'user', 'content' => '请用一句话介绍PHP语言']
]);

echo $result['choices'][0]['message']['content'];

运行结果:

PHP是一种开源的服务器端脚本语言,特别适合Web开发,可以嵌入HTML中执行。

文件上传处理

上传文件

php
<?php
class KimiFileClient
{
    private $client;
    private $apiKey;
    private $baseUrl = 'https://api.moonshot.cn/v1';

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->client = new Client([
            'base_uri' => $this->baseUrl,
            'timeout' => 300,
        ]);
    }

    public function uploadFile(string $filePath): array
    {
        $response = $this->client->post('/files', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
            ],
            'multipart' => [
                [
                    'name' => 'file',
                    'contents' => fopen($filePath, 'r'),
                    'filename' => basename($filePath),
                ],
                [
                    'name' => 'purpose',
                    'contents' => 'file-extract',
                ],
            ],
        ]);

        return json_decode($response->getBody(), true);
    }

    public function listFiles(): array
    {
        $response = $this->client->get('/files', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
            ],
        ]);

        return json_decode($response->getBody(), true);
    }

    public function deleteFile(string $fileId): array
    {
        $response = $this->client->delete("/files/{$fileId}", [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
            ],
        ]);

        return json_decode($response->getBody(), true);
    }

    public function getFileContent(string $fileId): string
    {
        $response = $this->client->get("/files/{$fileId}/content", [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
            ],
        ]);

        return $response->getBody()->getContents();
    }
}

// 使用示例
$fileClient = new KimiFileClient($apiKey);

// 上传文件
$file = $fileClient->uploadFile('document.pdf');
$fileId = $file['id'];

echo "文件ID: {$fileId}\n";

使用文件进行对话

php
<?php
class KimiDocumentChat
{
    private KimiClient $chatClient;
    private KimiFileClient $fileClient;

    public function __construct(string $apiKey)
    {
        $this->chatClient = new KimiClient($apiKey);
        $this->fileClient = new KimiFileClient($apiKey);
    }

    public function chatWithFile(string $filePath, string $question): string
    {
        // 上传文件
        $file = $this->fileClient->uploadFile($filePath);
        $fileId = $file['id'];

        // 使用文件进行对话
        $result = $this->chatClient->chat([
            [
                'role' => 'system',
                'content' => '你是Kimi,由Moonshot AI提供的人工智能助手。'
            ],
            [
                'role' => 'system',
                'content' => json_encode(['file_id' => $fileId])
            ],
            [
                'role' => 'user',
                'content' => $question
            ]
        ], 'moonshot-v1-128k');

        // 清理文件
        $this->fileClient->deleteFile($fileId);

        return $result['choices'][0]['message']['content'];
    }

    public function analyzeDocument(string $filePath): string
    {
        return $this->chatWithFile($filePath, '请分析这份文档的主要内容,并给出关键要点。');
    }

    public function summarizeDocument(string $filePath, int $maxLength = 500): string
    {
        return $this->chatWithFile($filePath, "请将这份文档总结为不超过{$maxLength}字的摘要。");
    }
}

// 使用示例
$docChat = new KimiDocumentChat($apiKey);
$summary = $docChat->summarizeDocument('report.pdf');
echo $summary;

高级参数配置

完整参数示例

php
<?php
class KimiClient
{
    // ... 前面的代码 ...

    public function chatAdvanced(
        array $messages,
        string $model = 'moonshot-v1-8k',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        $optionalParams = ['temperature', 'max_tokens', 'top_p', 'stop', 'presence_penalty', 'frequency_penalty'];

        foreach ($optionalParams as $param) {
            if (isset($options[$param])) {
                $params[$param] = $options[$param];
            }
        }

        try {
            $response = $this->client->post('/chat/completions', [
                'json' => $params,
            ]);

            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $errorBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'Unknown error';
            throw new Exception('Kimi API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$result = $client->chatAdvanced(
    [['role' => 'user', 'content' => '写一首关于程序员的诗']],
    'moonshot-v1-8k',
    [
        'temperature' => 0.8,
        'max_tokens' => 500,
    ]
);

参数详解

参数范围默认值说明
temperature0-11控制随机性
max_tokens1-模型上限无限制最大输出Token
top_p0-11核采样参数
stop字符串或数组-停止序列
presence_penalty0-20存在惩罚
frequency_penalty0-20频率惩罚

流式响应处理

php
<?php
class KimiClient
{
    // ... 前面的代码 ...

    public function chatStream(
        array $messages,
        string $model = 'moonshot-v1-8k'
    ): Generator {
        $response = $this->client->post('/chat/completions', [
            'json' => [
                'model' => $model,
                'messages' => $messages,
                'stream' => true,
            ],
            'stream' => true,
        ]);

        $body = $response->getBody();
        $buffer = '';

        while (!$body->eof()) {
            $chunk = $body->read(1024);
            $buffer .= $chunk;

            while (($pos = strpos($buffer, "\n")) !== false) {
                $line = substr($buffer, 0, $pos);
                $buffer = substr($buffer, $pos + 1);

                $line = trim($line);
                if (empty($line) || $line === 'data: [DONE]') {
                    continue;
                }

                if (strpos($line, 'data: ') === 0) {
                    $json = substr($line, 6);
                    $data = json_decode($json, true);

                    if (isset($data['choices'][0]['delta']['content'])) {
                        yield $data['choices'][0]['delta']['content'];
                    }
                }
            }
        }
    }
}

// 使用示例
echo "Kimi回复:";
foreach ($client->chatStream([['role' => 'user', 'content' => '讲一个程序员笑话']]) as $chunk) {
    echo $chunk;
    flush();
}

长文本处理

使用128K上下文处理长文档

php
<?php
class LongDocumentProcessor
{
    private KimiClient $client;

    public function __construct(KimiClient $client)
    {
        $this->client = $client;
    }

    public function analyzeDocument(string $document, string $question): string
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'user',
                    'content' => "文档内容:\n{$document}\n\n问题:{$question}"
                ]
            ],
            'moonshot-v1-128k',
            ['max_tokens' => 4096]
        );

        return $result['choices'][0]['message']['content'];
    }

    public function summarizeDocument(string $document, int $maxLength = 500): string
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'user',
                    'content' => "请将以下文档总结为不超过{$maxLength}字:\n\n{$document}"
                ]
            ],
            'moonshot-v1-128k'
        );

        return $result['choices'][0]['message']['content'];
    }

    public function extractKeyPoints(string $document): array
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'user',
                    'content' => "请从以下文档中提取关键要点,以JSON数组格式返回:\n\n{$document}"
                ]
            ],
            'moonshot-v1-128k'
        );

        return json_decode($result['choices'][0]['message']['content'], true);
    }
}

常见错误与踩坑点

错误1:文件格式不支持

php
<?php
// ❌ 错误做法:上传不支持的文件格式
$file = $fileClient->uploadFile('document.xyz');

// ✅ 正确做法:使用支持的格式
// 支持的格式:pdf, txt, doc, docx, xls, xlsx, ppt, pptx, png, jpg, jpeg
$file = $fileClient->uploadFile('document.pdf');

错误2:忽略文件大小限制

php
<?php
// ❌ 错误做法:上传超大文件
$file = $fileClient->uploadFile('large_file.pdf'); // 超过100MB

// ✅ 正确做法:检查文件大小
function checkFileSize(string $filePath, int $maxSizeMB = 100): bool
{
    $sizeMB = filesize($filePath) / (1024 * 1024);
    return $sizeMB <= $maxSizeMB;
}

if (checkFileSize('document.pdf')) {
    $file = $fileClient->uploadFile('document.pdf');
}

错误3:不清理上传的文件

php
<?php
// ❌ 错误做法:不清理文件
$file = $fileClient->uploadFile('document.pdf');
// 文件会一直占用存储空间

// ✅ 正确做法:使用后删除文件
$file = $fileClient->uploadFile('document.pdf');
$fileId = $file['id'];
// 使用文件...
$fileClient->deleteFile($fileId);

常见应用场景

场景1:文档问答系统

php
<?php
class KimiDocumentQA
{
    private KimiDocumentChat $docChat;

    public function loadDocument(string $filePath): void
    {
        $this->docChat = new KimiDocumentChat(getenv('MOONSHOT_API_KEY'));
        $this->currentFile = $filePath;
    }

    public function ask(string $question): string
    {
        return $this->docChat->chatWithFile($this->currentFile, $question);
    }
}

场景2:论文分析

php
<?php
class PaperAnalyzer
{
    private KimiDocumentChat $docChat;

    public function analyze(string $filePath): array
    {
        $summary = $this->docChat->chatWithFile($filePath, '请总结这篇论文的主要内容和贡献。');
        $methodology = $this->docChat->chatWithFile($filePath, '请分析这篇论文的研究方法。');
        $conclusions = $this->docChat->chatWithFile($filePath, '请总结这篇论文的结论。');

        return [
            'summary' => $summary,
            'methodology' => $methodology,
            'conclusions' => $conclusions,
        ];
    }
}

场景3:合同审查

php
<?php
class ContractReviewer
{
    private KimiDocumentChat $docChat;

    public function review(string $filePath): array
    {
        $risks = $this->docChat->chatWithFile($filePath, '请识别这份合同中的风险条款。');
        $suggestions = $this->docChat->chatWithFile($filePath, '请给出修改建议。');

        return [
            'risks' => $risks,
            'suggestions' => $suggestions,
        ];
    }
}

场景4:代码库分析

php
<?php
class CodebaseAnalyzer
{
    private KimiClient $client;

    public function analyze(string $codebase): string
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'user',
                    'content' => "请分析以下代码库的结构和功能:\n\n{$codebase}"
                ]
            ],
            'moonshot-v1-128k'
        );

        return $result['choices'][0]['message']['content'];
    }
}

场景5:智能客服

php
<?php
class KimiCustomerService
{
    private KimiClient $client;
    private array $knowledgeBase = [];

    public function addKnowledge(string $category, string $content): void
    {
        $this->knowledgeBase[$category] = $content;
    }

    public function handleQuery(string $query): string
    {
        $context = implode("\n\n", $this->knowledgeBase);

        $result = $this->client->chat([
            [
                'role' => 'system',
                'content' => '你是一个友好的客服助手。请根据知识库回答问题。'
            ],
            [
                'role' => 'user',
                'content' => "知识库:\n{$context}\n\n客户问题:{$query}"
            ]
        ], 'moonshot-v1-32k');

        return $result['choices'][0]['message']['content'];
    }
}

常见问题答疑(FAQ)

Q1:Kimi的定价如何?

回答

模型输入价格输出价格
moonshot-v1-8k¥12/百万Token¥12/百万Token
moonshot-v1-32k¥14/百万Token¥14/百万Token
moonshot-v1-128k¥60/百万Token¥60/百万Token

Q2:如何选择合适的模型?

回答

场景推荐模型原因
短文本对话moonshot-v1-8k成本低
中等长度文档moonshot-v1-32k平衡选择
长文档处理moonshot-v1-128k超长上下文
文件上传moonshot-v1-128k支持文件处理

Q3:支持的文件格式有哪些?

回答

类型支持格式
文档pdf, txt, doc, docx
表格xls, xlsx
演示ppt, pptx
图片png, jpg, jpeg

Q4:如何处理API错误?

回答

php
<?php
function handleKimiError(Exception $e): string
{
    $message = $e->getMessage();

    if (strpos($message, 'invalid_api_key') !== false) {
        return 'API Key无效';
    }
    if (strpos($message, 'rate_limit') !== false) {
        return '请求过于频繁';
    }
    if (strpos($message, 'context_length_exceeded') !== false) {
        return '上下文长度超限';
    }

    return '服务暂时不可用';
}

Q5:文件上传大小限制是多少?

回答

  • 单个文件最大:100MB
  • 单次请求最大:500MB
  • 文件数量限制:无明确限制

Q6:如何实现多轮对话?

回答

php
<?php
class KimiChatSession
{
    private KimiClient $client;
    private array $messages = [];

    public function chat(string $message): string
    {
        $this->messages[] = ['role' => 'user', 'content' => $message];

        $result = $this->client->chat($this->messages);
        $response = $result['choices'][0]['message']['content'];

        $this->messages[] = ['role' => 'assistant', 'content' => $response];

        return $response;
    }
}

实战练习

基础练习

练习1:编写一个简单的Kimi聊天程序。

参考代码

php
<?php
$apiKey = getenv('MOONSHOT_API_KEY');
$client = new KimiClient($apiKey);

echo "Kimi聊天助手 (输入 'quit' 退出)\n";

while (true) {
    echo "\n你: ";
    $input = trim(fgets(STDIN));

    if ($input === 'quit') {
        break;
    }

    $result = $client->chat([['role' => 'user', 'content' => $input]]);
    echo "Kimi: " . $result['choices'][0]['message']['content'] . "\n";
}

进阶练习

练习2:实现一个文档摘要工具。

参考代码

php
<?php
class DocumentSummarizer
{
    private KimiDocumentChat $docChat;

    public function summarize(string $filePath, int $maxLength = 500): string
    {
        return $this->docChat->chatWithFile(
            $filePath,
            "请将这份文档总结为不超过{$maxLength}字的摘要。"
        );
    }
}

挑战练习

练习3:构建一个智能文档问答系统。

参考代码

php
<?php
class IntelligentDocumentQA
{
    private KimiDocumentChat $docChat;
    private string $currentFile;

    public function loadDocument(string $filePath): void
    {
        $this->currentFile = $filePath;
    }

    public function ask(string $question): string
    {
        return $this->docChat->chatWithFile($this->currentFile, $question);
    }

    public function getSummary(): string
    {
        return $this->ask('请总结这份文档的主要内容');
    }

    public function getKeyPoints(): array
    {
        $result = $this->ask('请列出这份文档的关键要点,以JSON数组格式返回');
        return json_decode($result, true);
    }
}

知识点总结

核心要点

  1. 超长上下文:支持200万字上下文
  2. 文件上传:支持直接上传文件处理
  3. API兼容:完全兼容OpenAI API格式
  4. 文档处理:长文档处理能力强
  5. 联网搜索:支持实时联网获取信息

易错点回顾

易错点正确做法
文件格式不支持使用支持的格式
忽略文件大小限制检查文件大小
不清理上传的文件使用后删除文件
不使用长上下文模型长文档使用128K模型

拓展参考资料

官方文档

进阶学习路径

  1. 本知识点 → Kimi API基础使用
  2. 下一步字节豆包
  3. 进阶错误处理与重试
  4. 高级Token优化策略

💡 记住:Kimi的超长上下文能力使其成为处理长文档的绝佳选择,善用文件上传功能可以简化文档处理流程。