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>
相关推荐
gentle coder2 小时前
【Prompt】 提示词工程(持续更新中~)
ai·prompt·agent·提示词工程·#广告顾问
imbackneverdie2 小时前
AI赋能下的下一代检索工具:DeepSearch与传统数据库/搜索引擎有何本质不同?
人工智能·搜索引擎·ai·自然语言处理·aigc·ai写作·ai工具
2501_915106322 小时前
iOS开发中CPU功耗监控的实现与工具使用
android·macos·ios·小程序·uni-app·cocoa·iphone
码农小白猿2 小时前
提升压力容器改造方案报告标准条款审核效率,IACheck助力合规与安全
运维·人工智能·安全·ai·自动化·iacheck
计算机毕设指导63 小时前
基于微信小程序的博物馆文创系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea
绿鸳3 小时前
uniapp安装uview-plus
uni-app
come112343 小时前
OpenAI Codex CLI 使用文档 (2025 最新版)
ai
哥不是小萝莉12 小时前
Claude Skills MCP 技术解析
ai·mcp·skills
哥布林学者13 小时前
吴恩达深度学习课程四:计算机视觉 第四周:卷积网络应用 (二) 图像风格转换
深度学习·ai