Appearance
百度文心一言API完全指南
文心一言是百度推出的大语言模型,与百度生态深度集成,适合企业级应用
概述
文心一言(ERNIE)是百度推出的大语言模型系列,以其强大的中文理解能力、知识图谱支持和百度生态集成著称。本教程将带你全面掌握文心一言API的使用方法。
为什么选择文心一言?
| 优势 | 说明 |
|---|---|
| 中文能力强 | 专为中文优化,理解准确 |
| 知识图谱 | 百度知识图谱支持 |
| 百度生态 | 与百度搜索、百度云等集成 |
| 企业级服务 | 完善的企业级支持 |
ERNIE模型概览
ERNIE模型家族:
ERNIE 4.0系列(最新)
├── ERNIE-4.0-8K # 最新旗舰模型
├── ERNIE-4.0-Turbo-8K # 快速版本
└── ERNIE-4.0-8K-Preview # 预览版本
ERNIE 3.5系列(经典)
├── ERNIE-3.5-8K # 经典版本
└── ERNIE-3.5-Turbo-8K # 快速版本
专业模型
├── ERNIE-Speed-8K # 高速模型
├── ERNIE-Lite-8K # 轻量模型
└── ERNIE-Tiny-8K # 微型模型基本概念
API Key
php
<?php
// 在百度智能云控制台获取API Key和Secret Key
// https://console.bce.baidu.com/qianfan/
$apiKey = getenv('ERNIE_API_KEY');
$secretKey = getenv('ERNIE_SECRET_KEY');Access Token
文心一言使用Access Token认证:
php
<?php
function getAccessToken(string $apiKey, string $secretKey): string
{
$client = new Client();
$response = $client->get('https://aip.baidubce.com/oauth/2.0/token', [
'query' => [
'grant_type' => 'client_credentials',
'client_id' => $apiKey,
'client_secret' => $secretKey,
],
]);
$result = json_decode($response->getBody(), true);
return $result['access_token'];
}环境准备
创建文心一言客户端
php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class ErnieClient
{
private $client;
private $accessToken;
private $baseUrl = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat';
public function __construct(string $apiKey, string $secretKey)
{
$this->accessToken = $this->getAccessToken($apiKey, $secretKey);
$this->client = new Client([
'timeout' => 120,
]);
}
private function getAccessToken(string $apiKey, string $secretKey): string
{
$response = $this->client->get('https://aip.baidubce.com/oauth/2.0/token', [
'query' => [
'grant_type' => 'client_credentials',
'client_id' => $apiKey,
'client_secret' => $secretKey,
],
]);
$result = json_decode($response->getBody(), true);
return $result['access_token'];
}
public function chat(
array $messages,
string $model = 'ernie-speed-8k',
array $options = []
): array {
$url = "{$this->baseUrl}/{$model}?access_token={$this->accessToken}";
$params = [
'messages' => $messages,
];
if (isset($options['temperature'])) {
$params['temperature'] = $options['temperature'];
}
if (isset($options['max_output_tokens'])) {
$params['max_output_tokens'] = $options['max_output_tokens'];
}
try {
$response = $this->client->post($url, [
'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('ERNIE_API_KEY');
$secretKey = getenv('ERNIE_SECRET_KEY');
$client = new ErnieClient($apiKey, $secretKey);
$result = $client->chat([
['role' => 'user', 'content' => '请用一句话介绍PHP语言']
]);
echo $result['result'];运行结果:
PHP是一种开源的服务器端脚本语言,特别适合Web开发,可以嵌入HTML中执行。高级参数配置
完整参数示例
php
<?php
class ErnieClient
{
// ... 前面的代码 ...
public function chatAdvanced(
array $messages,
string $model = 'ernie-speed-8k',
array $options = []
): array {
$url = "{$this->baseUrl}/{$model}?access_token={$this->accessToken}";
$params = [
'messages' => $messages,
];
$optionalParams = [
'temperature',
'top_p',
'max_output_tokens',
'stop',
'penalty_score',
];
foreach ($optionalParams as $param) {
if (isset($options[$param])) {
$params[$param] = $options[$param];
}
}
// 启用搜索增强
if (!empty($options['enable_search'])) {
$params['enable_search'] = true;
}
try {
$response = $this->client->post($url, [
'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' => '今天有什么新闻?']],
'ernie-speed-8k',
[
'temperature' => 0.7,
'enable_search' => true, // 启用搜索增强
]
);参数详解
| 参数 | 范围 | 默认值 | 说明 |
|---|---|---|---|
| temperature | 0-1 | 0.95 | 控制随机性 |
| top_p | 0-1 | 0.8 | 核采样参数 |
| max_output_tokens | 1-模型上限 | 1024 | 最大输出Token |
| stop | 字符串数组 | - | 停止序列 |
| penalty_score | 1-2 | 1 | 重复惩罚 |
| enable_search | boolean | false | 启用搜索增强 |
流式响应处理
php
<?php
class ErnieClient
{
// ... 前面的代码 ...
public function chatStream(
array $messages,
string $model = 'ernie-speed-8k'
): Generator {
$url = "{$this->baseUrl}/{$model}?access_token={$this->accessToken}";
$response = $this->client->post($url, [
'json' => [
'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)) {
continue;
}
$data = json_decode($line, true);
if (isset($data['result'])) {
yield $data['result'];
}
}
}
}
}
// 使用示例
echo "文心一言回复:";
foreach ($client->chatStream([['role' => 'user', 'content' => '讲一个程序员笑话']]) as $chunk) {
echo $chunk;
flush();
}常见错误与踩坑点
错误1:Access Token过期
php
<?php
// ❌ 错误做法:长时间使用同一个Token
$client = new ErnieClient($apiKey, $secretKey);
// Token有效期30天,但建议定期刷新
// ✅ 正确做法:定期刷新Token
class ErnieClient
{
private int $tokenExpireTime = 0;
private function ensureValidToken(): void
{
if (time() >= $this->tokenExpireTime) {
$this->refreshToken();
}
}
}错误2:模型名称错误
php
<?php
// ❌ 错误做法:使用不存在的模型
$result = $client->chat($messages, 'ernie-4');
// ✅ 正确做法:使用正确的模型名称
$result = $client->chat($messages, 'ernie-4.0-8k');
$result = $client->chat($messages, 'ernie-speed-8k');错误3:忽略搜索增强
php
<?php
// ❌ 错误做法:不启用搜索获取实时信息
$result = $client->chat([['role' => 'user', 'content' => '今天天气如何?']]);
// ✅ 正确做法:启用搜索增强
$result = $client->chatAdvanced(
[['role' => 'user', 'content' => '今天天气如何?']],
'ernie-speed-8k',
['enable_search' => true]
);常见应用场景
场景1:智能客服
php
<?php
class ErnieCustomerService
{
private ErnieClient $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' => 'user',
'content' => "知识库:\n{$context}\n\n客户问题:{$query}"
]
]);
return $result['result'];
}
}场景2:内容创作
php
<?php
class ErnieContentCreator
{
private ErnieClient $client;
public function generateArticle(string $topic, int $wordCount = 800): string
{
$result = $this->client->chat([
[
'role' => 'user',
'content' => "请写一篇关于{$topic}的文章,字数约{$wordCount}字。"
]
]);
return $result['result'];
}
}场景3:代码助手
php
<?php
class ErnieCodeAssistant
{
private ErnieClient $client;
public function generateCode(string $description, string $language = 'PHP'): string
{
$result = $this->client->chat([
[
'role' => 'user',
'content' => "请生成{$language}代码:{$description}"
]
]);
return $result['result'];
}
}场景4:文档问答
php
<?php
class ErnieDocumentQA
{
private ErnieClient $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['result'];
}
}场景5:翻译助手
php
<?php
class ErnieTranslator
{
private ErnieClient $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['result'];
}
}常见问题答疑(FAQ)
Q1:文心一言的定价如何?
回答:
| 模型 | 输入价格 | 输出价格 |
|---|---|---|
| ERNIE-4.0-8K | ¥0.12/千Token | ¥0.12/千Token |
| ERNIE-3.5-8K | ¥0.04/千Token | ¥0.08/千Token |
| ERNIE-Speed-8K | ¥0.004/千Token | ¥0.008/千Token |
| ERNIE-Lite-8K | ¥0.003/千Token | ¥0.006/千Token |
Q2:如何选择合适的模型?
回答:
| 场景 | 推荐模型 | 原因 |
|---|---|---|
| 快速响应 | ERNIE-Speed-8K | 速度快,成本低 |
| 复杂任务 | ERNIE-4.0-8K | 能力最强 |
| 日常对话 | ERNIE-3.5-8K | 平衡选择 |
| 边缘设备 | ERNIE-Tiny-8K | 最小模型 |
Q3:如何获取Access Token?
回答:
php
<?php
function getAccessToken(string $apiKey, string $secretKey): string
{
$client = new Client();
$response = $client->get('https://aip.baidubce.com/oauth/2.0/token', [
'query' => [
'grant_type' => 'client_credentials',
'client_id' => $apiKey,
'client_secret' => $secretKey,
],
]);
$result = json_decode($response->getBody(), true);
return $result['access_token'];
}Q4:如何处理API错误?
回答:
php
<?php
function handleErnieError(Exception $e): string
{
$message = $e->getMessage();
if (strpos($message, 'invalid_client') !== false) {
return 'API Key或Secret Key无效';
}
if (strpos($message, 'access_token_expired') !== false) {
return 'Access Token已过期';
}
if (strpos($message, 'rate_limit_exceeded') !== false) {
return '请求过于频繁';
}
return '服务暂时不可用';
}Q5:如何启用搜索增强?
回答:
php
<?php
$result = $client->chatAdvanced(
[['role' => 'user', 'content' => '今天有什么新闻?']],
'ernie-speed-8k',
['enable_search' => true]
);Q6:如何实现多轮对话?
回答:
php
<?php
class ErnieChatSession
{
private ErnieClient $client;
private array $messages = [];
public function chat(string $message): string
{
$this->messages[] = ['role' => 'user', 'content' => $message];
$result = $this->client->chat($this->messages);
$response = $result['result'];
$this->messages[] = ['role' => 'assistant', 'content' => $response];
return $response;
}
}实战练习
基础练习
练习1:编写一个简单的文心一言聊天程序。
参考代码:
php
<?php
$apiKey = getenv('ERNIE_API_KEY');
$secretKey = getenv('ERNIE_SECRET_KEY');
$client = new ErnieClient($apiKey, $secretKey);
echo "文心一言聊天助手 (输入 'quit' 退出)\n";
while (true) {
echo "\n你: ";
$input = trim(fgets(STDIN));
if ($input === 'quit') {
break;
}
$result = $client->chat([['role' => 'user', 'content' => $input]]);
echo "文心一言: " . $result['result'] . "\n";
}进阶练习
练习2:实现一个文档摘要工具。
参考代码:
php
<?php
class DocumentSummarizer
{
private ErnieClient $client;
public function summarize(string $document, int $maxLength = 500): string
{
$result = $this->client->chat([
['role' => 'user', 'content' => "请将以下文档总结为不超过{$maxLength}字:\n\n{$document}"]
]);
return $result['result'];
}
}挑战练习
练习3:构建一个智能问答系统。
参考代码:
php
<?php
class IntelligentQA
{
private ErnieClient $client;
public function answer(string $question, bool $enableSearch = false): string
{
$result = $this->client->chatAdvanced(
[['role' => 'user', 'content' => $question]],
'ernie-speed-8k',
['enable_search' => $enableSearch]
);
return $result['result'];
}
}知识点总结
核心要点
- Access Token:使用OAuth认证获取Access Token
- 中文能力强:专为中文优化
- 搜索增强:支持enable_search获取实时信息
- 百度生态:与百度搜索、百度云等集成
- 知识图谱:百度知识图谱支持
易错点回顾
| 易错点 | 正确做法 |
|---|---|
| Access Token过期 | 定期刷新Token |
| 模型名称错误 | 使用正确的模型名称 |
| 不启用搜索 | 使用enable_search获取实时信息 |
拓展参考资料
官方文档
进阶学习路径
💡 记住:文心一言使用Access Token认证,善用enable_search可以获取实时信息,百度知识图谱支持使其在中文理解方面表现出色。
