Appearance
阿里通义千问API完全指南
通义千问是阿里云推出的大语言模型,与阿里云生态深度集成,适合企业级应用
概述
通义千问(Qwen)是阿里云推出的大语言模型系列,以其强大的中文能力、多模态支持和阿里云生态集成著称。本教程将带你全面掌握通义千问API的使用方法。
为什么选择通义千问?
| 优势 | 说明 |
|---|---|
| 中文能力强 | 专为中文优化,理解准确 |
| 多模态支持 | 支持文本、图像、音频、视频 |
| 阿里云集成 | 与阿里云产品深度集成 |
| 企业级服务 | 完善的企业级支持 |
通义千问模型概览
通义千问模型家族:
Qwen2.5系列(最新)
├── qwen-max # 最强能力
├── qwen-plus # 平衡版本
├── qwen-turbo # 快速版本
├── qwen-long # 长上下文版本
└── qwen-vl-max # 多模态版本
Qwen2系列(经典)
├── qwen2-72b-instruct # 开源大模型
└── qwen2-7b-instruct # 开源小模型
专业模型
├── qwen-coder-turbo # 代码专用
├── qwen-math-turbo # 数学专用
└── qwen-vl-ocr # OCR专用基本概念
API Key
php
<?php
// 在阿里云控制台获取API Key
// https://dashscope.console.aliyun.com/
// API Key格式
// sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
$apiKey = getenv('DASHSCOPE_API_KEY');DashScope API
通义千问通过DashScope API提供服务:
php
<?php
// DashScope API地址
$baseUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1';环境准备
创建通义千问客户端
php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class QwenClient
{
private $client;
private $apiKey;
private $baseUrl = 'https://dashscope.aliyuncs.com/compatible-mode/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 = 'qwen-turbo',
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'];
}
if (isset($options['top_p'])) {
$params['top_p'] = $options['top_p'];
}
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('Qwen API Error: ' . $errorBody);
}
}
}
// 使用示例
$apiKey = getenv('DASHSCOPE_API_KEY');
$client = new QwenClient($apiKey);
$result = $client->chat([
['role' => 'user', 'content' => '请用一句话介绍PHP语言']
]);
echo $result['choices'][0]['message']['content'];运行结果:
PHP是一种开源的服务器端脚本语言,特别适合Web开发,可以嵌入HTML中执行。多模态处理
图像理解
php
<?php
class QwenVLClient
{
private $client;
private $apiKey;
private $baseUrl = 'https://dashscope.aliyuncs.com/api/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 analyzeImage(string $imageUrl, string $question): string
{
$response = $this->client->post('/services/aigc/multimodal-generation/generation', [
'json' => [
'model' => 'qwen-vl-max',
'input' => [
'messages' => [
[
'role' => 'user',
'content' => [
['image' => $imageUrl],
['text' => $question],
],
],
],
],
],
]);
$result = json_decode($response->getBody(), true);
return $result['output']['choices'][0]['message']['content'][0]['text'];
}
public function ocr(string $imageUrl): string
{
return $this->analyzeImage($imageUrl, '请识别图片中的所有文字');
}
public function describeImage(string $imageUrl): string
{
return $this->analyzeImage($imageUrl, '请详细描述这张图片的内容');
}
}
// 使用示例
$vlClient = new QwenVLClient($apiKey);
$description = $vlClient->describeImage('https://example.com/image.jpg');
echo $description;高级参数配置
完整参数示例
php
<?php
class QwenClient
{
// ... 前面的代码 ...
public function chatAdvanced(
array $messages,
string $model = 'qwen-turbo',
array $options = []
): array {
$params = [
'model' => $model,
'messages' => $messages,
];
$optionalParams = [
'temperature',
'max_tokens',
'top_p',
'top_k',
'stop',
'seed',
'repetition_penalty',
];
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('/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('Qwen API Error: ' . $errorBody);
}
}
}
// 使用示例
$result = $client->chatAdvanced(
[['role' => 'user', 'content' => '今天有什么新闻?']],
'qwen-turbo',
[
'temperature' => 0.7,
'enable_search' => true, // 启用联网搜索
]
);参数详解
| 参数 | 范围 | 默认值 | 说明 |
|---|---|---|---|
| temperature | 0-2 | 1 | 控制随机性 |
| max_tokens | 1-6000 | 1500 | 最大输出Token |
| top_p | 0-1 | 0.8 | 核采样参数 |
| top_k | 0-100 | 0 | 只考虑前K个候选词 |
| seed | 整数 | - | 随机种子 |
| repetition_penalty | 1-2 | 1.1 | 重复惩罚 |
| enable_search | boolean | false | 启用联网搜索 |
流式响应处理
php
<?php
class QwenClient
{
// ... 前面的代码 ...
public function chatStream(
array $messages,
string $model = 'qwen-turbo'
): 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 "通义千问回复:";
foreach ($client->chatStream([['role' => 'user', 'content' => '讲一个程序员笑话']]) as $chunk) {
echo $chunk;
flush();
}长文本处理
使用qwen-long处理长文档
php
<?php
class LongDocumentProcessor
{
private QwenClient $client;
public function __construct(QwenClient $client)
{
$this->client = $client;
}
public function analyzeDocument(string $document, string $question): string
{
$result = $this->client->chat(
[
[
'role' => 'user',
'content' => "文档内容:\n{$document}\n\n问题:{$question}"
]
],
'qwen-long',
['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}"
]
],
'qwen-long'
);
return $result['choices'][0]['message']['content'];
}
}常见错误与踩坑点
错误1:模型名称错误
php
<?php
// ❌ 错误做法:使用不存在的模型
$result = $client->chat($messages, 'qwen-3');
// ✅ 正确做法:使用正确的模型名称
$result = $client->chat($messages, 'qwen-turbo');
$result = $client->chat($messages, 'qwen-plus');
$result = $client->chat($messages, 'qwen-max');错误2:忽略API配额
php
<?php
// ❌ 错误做法:不处理配额限制
$result = $client->chat($messages);
// ✅ 正确做法:处理配额错误
try {
$result = $client->chat($messages);
} catch (Exception $e) {
if (strpos($e->getMessage(), 'QuotaExhausted') !== false) {
echo 'API配额已用尽,请检查账户余额';
}
}错误3:忽略enable_search选项
php
<?php
// ❌ 错误做法:不启用搜索获取实时信息
$result = $client->chat([['role' => 'user', 'content' => '今天天气如何?']]);
// ✅ 正确做法:启用联网搜索
$result = $client->chatAdvanced(
[['role' => 'user', 'content' => '今天天气如何?']],
'qwen-turbo',
['enable_search' => true]
);常见应用场景
场景1:智能客服
php
<?php
class QwenCustomerService
{
private QwenClient $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'];
}
}场景2:文档问答
php
<?php
class QwenDocumentQA
{
private QwenClient $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}"
]
],
'qwen-long'
);
return $result['choices'][0]['message']['content'];
}
}场景3:代码助手
php
<?php
class QwenCodeAssistant
{
private QwenClient $client;
public function generateCode(string $description, string $language = 'PHP'): string
{
$result = $this->client->chat(
[
[
'role' => 'user',
'content' => "请生成{$language}代码:{$description}"
]
],
'qwen-coder-turbo'
);
return $result['choices'][0]['message']['content'];
}
}场景4:内容创作
php
<?php
class QwenContentCreator
{
private QwenClient $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'];
}
}场景5:图像分析
php
<?php
class QwenImageAnalyzer
{
private QwenVLClient $client;
public function describeImage(string $imageUrl): string
{
return $this->client->describeImage($imageUrl);
}
public function extractText(string $imageUrl): string
{
return $this->client->ocr($imageUrl);
}
public function analyzeChart(string $imageUrl): string
{
return $this->client->analyzeImage($imageUrl, '请分析这张图表的数据和趋势');
}
}常见问题答疑(FAQ)
Q1:通义千问的定价如何?
回答:
| 模型 | 输入价格 | 输出价格 |
|---|---|---|
| qwen-turbo | ¥0.3/百万Token | ¥0.6/百万Token |
| qwen-plus | ¥0.8/百万Token | ¥2/百万Token |
| qwen-max | ¥2/百万Token | ¥6/百万Token |
| qwen-long | ¥0.5/百万Token | ¥2/百万Token |
Q2:如何选择合适的模型?
回答:
| 场景 | 推荐模型 | 原因 |
|---|---|---|
| 快速响应 | qwen-turbo | 速度快,成本低 |
| 复杂任务 | qwen-max | 能力最强 |
| 长文档 | qwen-long | 支持长上下文 |
| 代码生成 | qwen-coder-turbo | 代码专用 |
| 图像理解 | qwen-vl-max | 多模态支持 |
Q3:如何启用联网搜索?
回答:
php
<?php
$result = $client->chatAdvanced(
[['role' => 'user', 'content' => '今天有什么新闻?']],
'qwen-turbo',
['enable_search' => true]
);Q4:如何处理API错误?
回答:
php
<?php
function handleQwenError(Exception $e): string
{
$message = $e->getMessage();
if (strpos($message, 'InvalidApiKey') !== false) {
return 'API Key无效';
}
if (strpos($message, 'QuotaExhausted') !== false) {
return 'API配额已用尽';
}
if (strpos($message, 'RateLimitExceeded') !== false) {
return '请求过于频繁';
}
return '服务暂时不可用';
}Q5:如何使用阿里云SDK?
回答:
php
<?php
// 安装阿里云SDK
// composer require alibabacloud/dashscope-sdk-php
use AlibabaCloud\SDK\Dashscope\Dashscope;
use AlibabaCloud\SDK\Dashscope\Models\ChatCompletionRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
$client = new Dashscope();
$request = new ChatCompletionRequest([
'model' => 'qwen-turbo',
'messages' => [
['role' => 'user', 'content' => '你好'],
],
]);
$response = $client->chatCompletion($request, new RuntimeOptions());
echo $response->body->choices[0]->message->content;Q6:如何实现多模态输入?
回答:
php
<?php
// 使用qwen-vl-max进行图像理解
$vlClient = new QwenVLClient($apiKey);
$result = $vlClient->analyzeImage('https://example.com/image.jpg', '这张图片里有什么?');实战练习
基础练习
练习1:编写一个简单的通义千问聊天程序。
参考代码:
php
<?php
$apiKey = getenv('DASHSCOPE_API_KEY');
$client = new QwenClient($apiKey);
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 ImageCaptionGenerator
{
private QwenVLClient $client;
public function generate(string $imageUrl, string $style = '简洁'): string
{
$prompt = "请用{$style}的语言描述这张图片:";
return $this->client->analyzeImage($imageUrl, $prompt);
}
}挑战练习
练习3:构建一个多模态文档分析系统。
参考代码:
php
<?php
class MultimodalDocumentAnalyzer
{
private QwenClient $textClient;
private QwenVLClient $vlClient;
public function analyze(array $content): array
{
$results = [];
foreach ($content as $item) {
if ($item['type'] === 'text') {
$results[] = $this->analyzeText($item['data']);
} elseif ($item['type'] === 'image') {
$results[] = $this->analyzeImage($item['data']);
}
}
return $results;
}
private function analyzeText(string $text): array
{
$result = $this->textClient->chat([
['role' => 'user', 'content' => "请分析以下文本:\n{$text}"]
]);
return ['type' => 'text', 'analysis' => $result['choices'][0]['message']['content']];
}
private function analyzeImage(string $imageUrl): array
{
return ['type' => 'image', 'analysis' => $this->vlClient->describeImage($imageUrl)];
}
}知识点总结
核心要点
- 中文能力强:专为中文优化,理解准确
- 多模态支持:支持文本、图像、音频、视频
- 阿里云集成:与阿里云产品深度集成
- 联网搜索:支持enable_search获取实时信息
- 长文本处理:qwen-long支持长上下文
易错点回顾
| 易错点 | 正确做法 |
|---|---|
| 模型名称错误 | 使用qwen-turbo/qwen-plus/qwen-max |
| 忽略API配额 | 处理QuotaExhausted错误 |
| 不启用搜索 | 使用enable_search获取实时信息 |
| 不使用专用模型 | 代码任务使用qwen-coder-turbo |
拓展参考资料
官方文档
进阶学习路径
💡 记住:通义千问与阿里云生态深度集成,适合需要企业级服务和阿里云产品的场景。善用enable_search可以获取实时信息。
