轻松接入大语言模型API -04
2026年3月1日 19:46
前言
想在自己的应用中接入 AI 能力,但不知道从哪里开始?
云端 API 是最简单的切入点。无需本地算力,无需复杂配置,只需几行代码,就能让 GPT-4、Qwen、DeepSeek 等大模型为你所用。
今天我们来学习如何使用云端 LLM API,开启你的 AI 开发之旅。
1. 什么是云端 API
云端 API = 通过互联网调用大模型服务
┌─────────────┐ ┌─────────────┐
│ 你的应用 │──── 互联网请求 ────→│ 云端 LLM │
│ │←───────────────────│ 服务 │
└─────────────┘ 返回生成结果 └─────────────┘
云端 vs 本地
| 特点 | 云端 API | 本地部署 |
|---|---|---|
| 硬件要求 | 无需本地算力 | 需要显卡/内存 |
| 使用成本 | 按调用量付费 | 一次部署,无限使用 |
| 数据隐私 | 数据上传云端 | 完全私密 |
| 网络依赖 | 需要网络 | 可离线使用 |
| 上手难度 | 简单 | 需要配置 |
2. 案例
案例 1:主流 API 平台对比
国内平台:
| 平台 | 模型 | 价格 | 核心优势 |
|---|---|---|---|
| 阿里云百炼 | Qwen 系列 | ¥0.0008/1K tokens | 中文优化,稳定可靠 |
| DeepSeek | DeepSeek-V3 | ¥1/1M tokens | 性价比之王 |
| 智谱 GLM | GLM-4 | 按调用量计费 | 国产化,清华技术 |
| 百度文心 | ERNIE 系列 | 按调用量计费 | 中文能力强 |
国际平台:
| 平台 | 模型 | 价格 | 核心优势 |
|---|---|---|---|
| OpenAI | GPT-4 | $5/1M tokens | 综合最强 |
| Anthropic | Claude | $3/1M tokens | 长文本优秀 |
| Gemini | 按用量计费 | 多模态强 |
案例 2:阿里云百炼 API 使用流程
Step 1:申请 API Key
- 访问 阿里云百炼平台
- 登录阿里云账号
- 进入「API-KEY 管理」
- 创建新的 API Key
- 重要:复制并保存 Key(只显示一次)
Step 2:了解支持的模型
qwen-max # 旗舰模型,最强能力
qwen-plus # 通用模型,性价比高
qwen-turbo # 高速模型,快速响应(推荐新手)
qwen-long # 长文本模型,支持 100K+ tokens
Step 3:API 调用示例
const response = await fetch('https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${yourApiKey}`
},
body: JSON.stringify({
model: 'qwen-turbo',
messages: [{ role: 'user', content: '你好,请介绍一下你自己' }]
})
});
const data = await response.json();
console.log(data.choices[0].message.content);
案例 3:DeepSeek API 的极致性价比
为什么选择 DeepSeek?
- 价格极低:输入 ¥0.001/千 tokens,输出 ¥0.002/千 tokens
- 性能优秀:接近 GPT-4 水平
- 中文友好:专为中文优化
- 兼容性好:完全兼容 OpenAI API 格式
调用示例:
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${yourApiKey}`
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [{ role: 'user', content: '请用 Python 写一个快速排序' }]
})
});
案例 4:流式响应实现
让 LLM 逐字输出,提升用户体验:
async function streamChat(question: string) {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'qwen-turbo',
messages: [{ role: 'user', content: question }],
stream: true // 启用流式响应
})
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
// 实时处理每个数据块
console.log(chunk);
}
}
案例 5:参数调优
const response = await fetch(apiUrl, {
method: 'POST',
body: JSON.stringify({
model: 'qwen-turbo',
messages: messages,
// 参数控制
temperature: 0.7, // 0-1,越高越随机
max_tokens: 2000, // 最大输出长度
top_p: 0.9 // 核采样
})
});
参数说明:
| 参数 | 范围 | 效果 | 推荐值 |
|---|---|---|---|
| temperature | 0-1 | 控制随机性 | 0.7 |
| max_tokens | 1-∞ | 限制输出长度 | 根据需求 |
| top_p | 0-1 | 核采样 | 0.9 |
案例 6:成本估算与优化
成本计算:
场景:每天 100 次对话
每次平均:输入 100 tokens + 输出 500 tokens
每日成本(qwen-turbo):
输入:100 × 100 × 0.0008 / 1000 = ¥0.008
输出:100 × 500 × 0.002 / 1000 = ¥0.1
总计:¥0.108/天
每月成本(30天):¥3.24
节省成本技巧:
- 优化 Prompt:减少不必要的上下文
- 使用缓存:对相同问题使用缓存
- 选择合适模型:简单任务用小模型
- 控制输出长度:使用 max_tokens 参数
案例 7:错误处理最佳实践
async function safeChat(question: string) {
try {
const response = await axios.post(apiUrl, {
model: 'qwen-turbo',
messages: [{ role: 'user', content: question }]
}, {
timeout: 30000 // 30 秒超时
});
return response.data;
} catch (error) {
if (error.response) {
// 服务器返回错误
console.error('API Error:', error.response.data);
} else if (error.request) {
// 请求发送但没有响应
console.error('Network Error:', error.message);
}
throw error;
}
}
3. 总结
| 需求 | 推荐平台 | 理由 |
|---|---|---|
| 国内用户 | 阿里云百炼 | 延迟低,中文好 |
| 成本敏感 | DeepSeek | 价格最低 |
| 质量优先 | GPT-4 / Claude | 综合最强 |
| 中文优化 | Qwen / DeepSeek | 专为中文优化 |