1. 通义千问大模型调用实战指南
作为国内领先的大语言模型之一,通义千问提供了便捷的API接口供开发者调用。本文将详细介绍如何在Vue项目中集成通义千问API,并分享实际开发中的经验技巧。
1.1 环境准备与API配置
在开始调用前,我们需要完成以下准备工作:
- 获取API Key:
- 访问阿里云官网的API Key管理页面(https://help.aliyun.com/zh/model-studio/get-api-key)
- 登录后进入"访问控制"页面
- 创建新的AccessKey并妥善保存
重要提示:API Key相当于账号密码,切勿直接暴露在前端代码中。实际项目中应通过后端服务进行中转调用。
-
了解API文档:
通义千问的完整API参考文档位于:
https://help.aliyun.com/zh/model-studio/qwen-api-reference/特别关注以下核心参数:
model: 指定使用的模型版本(如qwen-plus)messages: 对话消息数组temperature: 控制生成随机性的参数
1.2 项目基础配置
建议使用Vue 3 + TypeScript的项目结构。确保已安装必要的依赖:
bash复制npm install axios
# 或使用项目中的luch-request
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. API封装实现详解
2.1 请求封装方案
以下是经过优化的TypeScript实现,增加了类型安全和错误处理:
typescript复制// src/api/ai.ts
import type { Result } from '@/types/public'
import Request from '@/utils/luch-request/luch-request/index'
interface QWenResponse {
output: {
text: string
}
usage: {
total_tokens: number
}
}
interface APIResult<T = any> {
data: T
code: number
message?: string
}
export const QWenAI = async (content: string): Promise<APIResult<QWenResponse>> => {
const http = new Request()
try {
http.config.header = {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.VUE_APP_QWEN_KEY}`,
}
const res = await http.post<Result<QWenResponse>>(
'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
{
model: 'qwen-plus',
messages: [{ role: 'user', content }],
temperature: 0.7, // 控制生成随机性
top_p: 0.8 // 核采样概率
}
)
return {
data: res.data,
code: 200
}
} catch (error) {
console.error('API调用失败:', error)
return {
data: null,
code: 500,
message: error instanceof Error ? error.message : '未知错误'
}
}
}
关键改进点:
- 增加了完整的TypeScript接口定义
- 从环境变量读取API Key,避免硬编码
- 添加了temperature和top_p参数控制生成效果
- 完善了错误处理逻辑
2.2 环境变量配置
在项目根目录创建.env文件:
code复制VUE_APP_QWEN_KEY=your_api_key_here
然后在vue.config.js中配置:
javascript复制const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
plugins: [
new webpack.DefinePlugin({
'process.env': require('./.env')
})
]
