uniapp+vue3 接入deepseek Ai

先注册deepseek开放平台账号,充值2元。

ai.js文件为封装的ai请求,其中'Authorization': 'Bearer (deepseek开放平台你自己注册的key)',

Bearer要保留并且后面留一个空格。

Ai.vue文件为对话页面。

ai.js全部代码:

复制代码
// ai.js

export function requestAI(prompt, history = []) {
  return new Promise((resolve, reject) => {
    // 构建消息历史
    const messages = [...history]
    if (messages.length === 0 || messages[messages.length - 1].role !== 'user') {
      messages.push({ role: "user", content: prompt })
    }

    uni.request({
      url: 'https://api.deepseek.com/chat/completions',
      method: 'POST',
      header: {
        'Authorization': 'Bearer (替换成自己的key)',
        'Content-Type': 'application/json'
      },
	  timeout: 300000, // 增加超时时间
      data: {
        model: "deepseek-chat",
        messages: messages,
        stream: false
      },
      success: (res) => {
		  console.log('ai:',res)
        if (res.statusCode === 200) {
          resolve(res.data.choices[0].message.content)
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

Ai.vue全部代码:

复制代码
<template>
	<view class="container">
		<scroll-view class="chat-container" scroll-y="true" :scroll-top="scrollTop">
			<view v-for="(msg, index) in messages" :key="index" style="display: flex;justify-content: flex-end;">
				<!-- ai头像 -->
				<image v-if="msg.role == 'assistant'" src="/static/logo.png" mode="" style="width: 30px;height: 30px;border-radius: 50%;margin-right: 10px;"></image>
				<!-- 对话内容 -->
				<view :class="['message', msg.role]">
					<text class="content">{{ msg.content }}</text>
				</view>
				<!-- 自己头像 -->
				<image v-if="msg.role == 'user'" src="/static/img/touxiang1x.png" mode="" style="width: 30px;height: 30px;border-radius: 50%;margin-left: 10px;"></image>
			</view>
			<view v-if="status" class="Thinking">
				<text class="fontSize26" style="margin-right: 5px;">深度思考</text>
				<uv-loading-icon color="#a3a3a3" size="16"></uv-loading-icon>
			</view>
		</scroll-view>
		<view class="input-area">
			<input v-model="userInput" placeholder="请输入问题" @confirm="sendMessage" />
			<button @click="sendMessage">发送</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		nextTick,
		onMounted
	} from 'vue'
	import {
		requestAI
	} from '@/common/ai.js'

	const userInput = ref('')
	const messages = reactive([])
	const scrollTop = ref(0)
	const status = ref(false)

	 // 页面加载时自动发送欢迎消息 
	onMounted(async () => { 
		messages.push({ role: 'assistant', content: '你好!我是AI助手,有什么我可以帮助你的吗?' }) 
		// 滚动到底部
		await nextTick() 
		scrollToBottom() 
	}) 
	// 添加用户消息
	const sendMessage = async () => {
		if (!userInput.value.trim()) return
		if (status.value) return

		// 添加用户消息
		messages.push({
			role: 'user',
			content: userInput.value
		})
		const userMessage = userInput.value
		userInput.value = ''

		// 滚动到底部
		await nextTick()
		scrollToBottom()
		status.value = true;//正在思考状态
		try {
			// 请求AI回复
			const res = await requestAI(userMessage, messages)
			messages.push({
				role: 'assistant',
				content: res
			})
		} catch (err) {
			console.error('调用AI失败:', err)
			messages.push({
				role: 'assistant',
				content: '抱歉,暂时无法获取回答'
			})
		}
		status.value = false;//正在思考状态
		// 滚动到底部
		await nextTick()
		scrollToBottom()
	}

	const scrollToBottom = () => {
		scrollTop.value = 999999
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		padding: 10px;
		background-color: #f5f5f5;
	}

	.chat-container {
		height: 100%;
		flex: 1;
		margin-bottom: 10px;
		padding-bottom: 100px;
	}

	.message {
		padding: 10px;
		margin-bottom: 10px;
		border-radius: 10px;
		max-width: 80%;
	}

	.message.user {
		background-color: #007AFF;
		color: white;
		margin-left: auto;
		width: max-content;
	}

	.message.assistant {
		background-color: #eaeaea;
		color: black;
		margin-right: auto;
		width: max-content;
	}

	.input-area {
		display: flex;
		background-color: #fff;
		gap: 10px;
		position: fixed;
		width: 100%;
		left: 0;
		bottom: 0;
		padding: 10px;
		box-sizing: border-box;
	}

	input {
		flex: 1;
		padding: 0 10px;
		height: 40px;
		line-height: 40px;
		font-size: 30rpx;
		border: 1px solid #ddd;
		border-radius: 20px;
	}

	button {
		background-color: #007AFF;
		color: white;
		padding: 0px 20px;
		height: 40px;
		line-height: 40px;
		border: none;
		border-radius: 32px;
		cursor: pointer;
		font-size: 30rpx;
	}
	.Thinking{
		display: flex;
		justify-content: flex-start;
		align-items: center;
		background-color: #fff;
		border-radius: 3px;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
		width: max-content;
		color: #666;
	}
</style>
相关推荐
FX1317887KP_2 小时前
KPF口语高频动词短语清单,搭配AI口语陪练工具,练熟练透
小程序·ket口语·pet口语·fce备考·剑桥英语
Sharewinfo_BJ2 小时前
从“看数据”到“做决策”:AI时代,BI的下一个形态是什么?
ai·数据分析·bi·智信bi
codigger4 小时前
AI 三分钟写完的代码,你凭什么敢直接上线?
ai·程序员·编程·ai编程·#人工智能
微订校园外卖系统17 小时前
自己做校园外卖跑腿小程序用什么系统:多商户与单店架构
小程序·架构·外卖系统·本地生活·微订
wflynn21 小时前
Google 观察到首个全自动化网络攻击,AI 框架已能独立完成漏洞利用
ai·技术
zdr尽职尽责1 天前
终端工具凭空消失:Codex + GPT-6 的一次完整排障复盘
数据库·gpt·学习·ai
佛系1891 天前
从服务端日志精确分离搜索抓取、监控探测与真实流量的实操清单
ai·大模型·seo·geo·结构化数据·indexnow
wuxianda10301 天前
uniapp 与跨端打包项目:壳子和框架层默认特征,相似是从哪里来的
uni-app
码间留白1 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
uni-app·harmonyos·鸿蒙·uts插件·微信商家转账
一起学安全技术1 天前
拆大模型 11|大模型面试拷问:12 问逐层拆
人工智能·ai·语言模型·面试·职场和发展·求职招聘