Skip to content

字节豆包API完全指南

豆包是字节跳动推出的大语言模型,与字节生态深度集成,适合内容创作场景

概述

豆包是字节跳动推出的大语言模型,以其强大的内容创作能力、多模态支持和字节生态集成著称。本教程将带你全面掌握豆包API的使用方法。

为什么选择豆包?

优势说明
内容创作内容生成能力强
多模态支持文本、图像、语音
字节生态与抖音、今日头条等集成
高性价比价格实惠

豆包模型概览

豆包模型家族:

Doubao系列
├── doubao-pro-32k      # 专业版,32K上下文
├── doubao-pro-128k     # 专业版,128K上下文
├── doubao-lite-32k     # 轻量版,32K上下文
└── doubao-lite-128k    # 轻量版,128K上下文

专业模型
├── doubao-embedding    # 嵌入模型
└── doubao-vision       # 多模态模型

基本概念

API Key

php
<?php
// 在火山引擎控制台获取API Key
// https://console.volcengine.com/ark

// 需要创建推理接入点获取Endpoint ID

$apiKey = getenv('DOUBAO_API_KEY');
$endpointId = getenv('DOUBAO_ENDPOINT_ID');

火山引擎API

豆包通过火山引擎ARK平台提供服务:

php
<?php
// 火山引擎API地址
$baseUrl = 'https://ark.cn-beijing.volces.com/api/v3';

环境准备

创建豆包客户端

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

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

class DoubaoClient
{
    private $client;
    private $apiKey;
    private $endpointId;
    private $baseUrl = 'https://ark.cn-beijing.volces.com/api/v3';

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

    public function chat(
        array $messages,
        array $options = []
    ): array {
        $params = [
            'model' => $this->endpointId,
            '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('豆包 API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$apiKey = getenv('DOUBAO_API_KEY');
$endpointId = getenv('DOUBAO_ENDPOINT_ID');
$client = new DoubaoClient($apiKey, $endpointId);

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

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

运行结果:

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

高级参数配置

完整参数示例

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

    public function chatAdvanced(
        array $messages,
        array $options = []
    ): array {
        $params = [
            'model' => $this->endpointId,
            'messages' => $messages,
        ];

        $optionalParams = ['temperature', 'max_tokens', 'top_p', 'stop', 'frequency_penalty', 'presence_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('豆包 API Error: ' . $errorBody);
        }
    }
}

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

参数详解

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

流式响应处理

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

    public function chatStream(array $messages): Generator
    {
        $response = $this->client->post('/chat/completions', [
            'json' => [
                'model' => $this->endpointId,
                '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 "豆包回复:";
foreach ($client->chatStream([['role' => 'user', 'content' => '讲一个程序员笑话']]) as $chunk) {
    echo $chunk;
    flush();
}

常见错误与踩坑点

错误1:缺少Endpoint ID

php
<?php
// ❌ 错误做法:不使用Endpoint ID
$client = new DoubaoClient($apiKey, '');

// ✅ 正确做法:创建推理接入点获取Endpoint ID
$endpointId = 'ep-xxxxxxxxxxxx';
$client = new DoubaoClient($apiKey, $endpointId);

错误2:忽略模型版本

php
<?php
// ❌ 错误做法:不区分模型版本

// ✅ 正确做法:根据需求选择合适的模型
// doubao-pro-32k: 专业版,能力强
// doubao-lite-32k: 轻量版,速度快

错误3:忽略区域限制

php
<?php
// ❌ 错误做法:使用错误的区域
$baseUrl = 'https://ark.us-east-1.volces.com/api/v3';

// ✅ 正确做法:使用正确的区域
$baseUrl = 'https://ark.cn-beijing.volces.com/api/v3';

常见应用场景

场景1:内容创作

php
<?php
class DoubaoContentCreator
{
    private DoubaoClient $client;

    public function generateArticle(string $topic, int $wordCount = 800): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请写一篇关于{$topic}的文章,字数约{$wordCount}字。"
            ]
        ]);

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

    public function generateHeadlines(string $topic, int $count = 5): array
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请为{$topic}生成{$count}个吸引人的标题,以JSON数组格式返回。"
            ]
        ]);

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

场景2:智能客服

php
<?php
class DoubaoCustomerService
{
    private DoubaoClient $client;
    private array $knowledgeBase = [];

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

    public function handleQuery(string $query): string
    {
        $context = '';
        foreach ($this->knowledgeBase as $category => $content) {
            $context .= "【{$category}】\n{$content}\n\n";
        }

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

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

场景3:代码助手

php
<?php
class DoubaoCodeAssistant
{
    private DoubaoClient $client;

    public function generateCode(string $description, string $language = 'PHP'): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请生成{$language}代码:{$description}"
            ]
        ]);

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

    public function explainCode(string $code): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请解释以下代码:\n```\n{$code}\n```"
            ]
        ]);

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

场景4:文档问答

php
<?php
class DoubaoDocumentQA
{
    private DoubaoClient $client;
    private string $document;

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

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

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

场景5:翻译助手

php
<?php
class DoubaoTranslator
{
    private DoubaoClient $client;

    public function translate(string $text, string $from, string $to): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "将以下{$from}文本翻译成{$to}:\n\n{$text}"
            ]
        ]);

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

常见问题答疑(FAQ)

Q1:豆包的定价如何?

回答

模型输入价格输出价格
doubao-pro-32k¥0.8/百万Token¥2/百万Token
doubao-pro-128k¥5/百万Token¥9/百万Token
doubao-lite-32k¥0.3/百万Token¥0.6/百万Token
doubao-lite-128k¥0.8/百万Token¥1/百万Token

Q2:如何获取Endpoint ID?

回答

  1. 登录火山引擎控制台
  2. 进入ARK平台
  3. 创建推理接入点
  4. 选择模型版本
  5. 获取Endpoint ID

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

回答

场景推荐模型原因
快速响应doubao-lite-32k速度快,成本低
复杂任务doubao-pro-32k能力强
长文档doubao-pro-128k长上下文
内容创作doubao-pro-32k创作能力强

Q4:如何处理API错误?

回答

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

    if (strpos($message, 'InvalidApiKey') !== false) {
        return 'API Key无效';
    }
    if (strpos($message, 'EndpointNotFound') !== false) {
        return 'Endpoint不存在';
    }
    if (strpos($message, 'RateLimitExceeded') !== false) {
        return '请求过于频繁';
    }

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

Q5:支持哪些区域?

回答

区域API地址
北京https://ark.cn-beijing.volces.com/api/v3
上海https://ark.cn-shanghai.volces.com/api/v3

Q6:如何实现多轮对话?

回答

php
<?php
class DoubaoChatSession
{
    private DoubaoClient $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:编写一个简单的豆包聊天程序。

参考代码

php
<?php
$apiKey = getenv('DOUBAO_API_KEY');
$endpointId = getenv('DOUBAO_ENDPOINT_ID');
$client = new DoubaoClient($apiKey, $endpointId);

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

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

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

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

进阶练习

练习2:实现一个内容生成器。

参考代码

php
<?php
class ContentGenerator
{
    private DoubaoClient $client;

    public function generateArticle(string $topic): string
    {
        $result = $this->client->chat([
            ['role' => 'user', 'content' => "请写一篇关于{$topic}的文章"]
        ]);

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

挑战练习

练习3:构建一个智能写作助手。

参考代码

php
<?php
class WritingAssistant
{
    private DoubaoClient $client;

    public function generateOutline(string $topic): string
    {
        return $this->client->chat([
            ['role' => 'user', 'content' => "请为{$topic}生成一个文章大纲"]
        ])['choices'][0]['message']['content'];
    }

    public function expandSection(string $outline, string $section): string
    {
        return $this->client->chat([
            ['role' => 'user', 'content' => "根据以下大纲,展开{$section}部分:\n{$outline}"]
        ])['choices'][0]['message']['content'];
    }

    public function polishContent(string $content): string
    {
        return $this->client->chat([
            ['role' => 'user', 'content' => "请润色以下内容:\n{$content}"]
        ])['choices'][0]['message']['content'];
    }
}

知识点总结

核心要点

  1. Endpoint ID:需要创建推理接入点获取
  2. 火山引擎:通过火山引擎ARK平台提供服务
  3. 内容创作:内容生成能力强
  4. 多模态:支持文本、图像、语音
  5. 字节生态:与抖音、今日头条等集成

易错点回顾

易错点正确做法
缺少Endpoint ID创建推理接入点获取
忽略模型版本根据需求选择合适的模型
忽略区域限制使用正确的区域

拓展参考资料

官方文档

进阶学习路径

  1. 本知识点 → 豆包API基础使用
  2. 下一步百度文心一言
  3. 进阶错误处理与重试
  4. 高级安全与鉴权

💡 记住:豆包需要通过火山引擎ARK平台创建推理接入点,善用其内容创作能力可以大大提升写作效率。