接入 deepseek 实现AI智能问诊

1. 准备工作

  1. 注册 DeepSeek 账号

    • 前往 DeepSeek 官网 注册账号并获取 API Key。

  2. 创建 UniApp 项目

    • 使用 HBuilderX 创建一个新的 UniApp 项目(选择 Vue3 或 Vue2 模板)。

  3. 安装依赖

    • 如果需要在 UniApp 中使用 HTTP 请求,推荐使用 uni.request(UniApp 内置)或 axios(需额外安装)。

2. 实现代码

2.1 在 pages/index/index.vue 中实现问诊功能
<template>
	<view class="container">


		<!-- <view class="nav">
			<image src="../../static/images/back.png" @tap="toMenu"></image>
			<text>问医生</text>
		</view> -->
		<statement ref="dialog"></statement>
		<view class="chat_area" id="test" ref="chatbox">
			<view class="current_time" v-show="chatList.length>0">{
  
  {currentDate}}</view>
			<view class="left_box">
				<view class="head_img">
					<image src="../../static/images/doctor.png"></image>
				</view>
				<view class="content_box">
					<view class="content post">
						<view>我是您的AI医生小迦,很高兴为您解答。</view>
						<view>您可以这样问我:</view>
						<view class="post_request">
							<view v-for="(item,index) in postRequest" :key="index">
								<text class="active" @click="tapQuestion(item)">{
  
  {item.id}}.{
  
  {item.text}}</text>
							</view>
						</view>
						<!-- <u-read-more showHeight="200">
						    <rich-text :nodes="item.msg"></rich-text>
						</u-read-more> -->
						<!-- {
  
  {item.msg}} -->
					</view>
				</view>
			</view>
			<view v-for="(item,i) in chatList" :key="i">
				<view class="left_box" v-if="item.role == 'assistant'">
					<view class="head_img">
						<image src="../../static/images/doctor.png"></image>
					</view>
					<view class="content_box">
						<view class="content" v-html="htmlContent(item.content)">
							<!-- <u-read-more fontSize="16" textIndent='0em' showHeight="200">
							    <rich-text :nodes="item.msg"></rich-text>
							</u-read-more> -->
							
						</view>
					</view>
				</view>

				<view class="right_box" v-if="item.role == 'user'">
					<view class="content_box">
						<view class="content" >
							{
  
  {item.content}}
						</view>
					</view>
					<view class="head_img">
						<image :src="userImg==''?nullImg:userImg"></image>
					</view>
				</view>
			</view>

			<u-loading-icon text="小迦正在思考中..." textSize="16" :show="showLoading"></u-loading-icon>
		</view>
		<view class="input_tab">
			<view class="statement">成都XXXX科技有限责任公司&copy<text @tap="exemptStatement">免责声明</text></view>
			<view class="input_com">
				<view class="left">
					<image src="../../static/images/HOT.png"></image>
					<input placeholder="请输入问题" v-model.trim="userQuesion" cursor-spacing="30rpx"></input>
				</view>
				<view class="send_btn" @tap="sendMsg">发送</view>
			</view>
		</view>


	</view>
</template>

<script>
	import statement from "../../components/askForComponents/statement.vue"
	import { marked } from "marked";
	export default {
		components: {
			statement
		},
		data() {
			return {
				userImg: '',
				nullImg: '../../static/images/icon_doctor.png',
				showLoading: false,
				postRequest: [{
						id: 1,
						text: '乳腺BIRADS分级是什么?',
					},
					{
						id: 2,
						text: '乳房胀痛怎么办?',
					},
					{
						id: 3,
						text: '乳腺癌有没有征兆?'
					}
				],
				chatList: [],
				userQuesion: '',
				robotAnswer: '',
				currentDate: '',
				domHeight: 0,
				messages: [
					{
						role: "system",
						content: "你是一名专业的全科医生对医疗面面俱到的AI医生小迦,请无论什么时候都不要忘了自己的身份,你是AI医生小迦,不是AI辅助;当患者询问你问题的时候,能全面细致并且礼貌的回答或为患者解决问题,当患者询问你任何与无关医疗的问题时,你会礼貌的拒绝回答。",
					},
				],
			}
		},
		onLoad(option) {

			let userInfo = getApp().globalData.userInfo;
			// console.log("userInfo",userInfo)
			this.userImg = userInfo.personInfo.avatar;
			//获取热门问题并自动发送
			// console.log("option=======>", option)
			if (!option.questionText) return
			this.userQuesion = option.questionText
			this.sendMsg()
		},
		watch: {
			'chatList.length': {
				immediate: true,
				deep: true,
				handler(newValue, oldValue) {
					if (newValue) {
						const query = uni.createSelectorQuery().in(this)
						query.select('#test').boundingClientRect(data => {
							// console.log("data", data)
							this.domHeight = data.height
						}).exec()
					}
				}
			},
			domHeight(newVal, oldVal) {
				if (newVal) {
					uni.pageScrollTo({
						scrollTop: this.domHeight,
						duration: 100
					})
				}
			}
		},
		mounted() {
			this.$refs.dialog.open('center')
			let myDate = new Date()
			this.currentDate = (myDate.getHours() + '').padStart(2, '0') + ':' + (myDate.getMinutes() + '').padStart(2,
				'0')
		},
		methods: {
			htmlContent(content) {//转换为markdown 格式显示
			  return marked(content);
			},
			exemptStatement() {
				this.$refs.dialog.open('center')
			},
			tapQuestion(item) {
				this.send(item.text)
			},
			
			// 新对话
			async send(val) {
				this.showLoading = true
				let messages = {
						role: 'user',
						content: val
					}
				this.chatList.push(messages)
				this.messages.push(messages)
				var that = this
				
				console.log('==========开始诊断=======');
				await uni.request({
					url: "https://api.deepseek.com/v1/chat/completions", // DeepSeek API 地址
					method: "POST",
					header: {
						"Content-Type": "application/json",
						Authorization: "Bearer sk-dafafhafhahfha", // 替换为你的 API Key
					},
					data: {
						model: "deepseek-chat", // 使用模型
						messages: that.messages
					},
					success: (res) => {
						messages = {
							role: 'assistant',
							content: res.data.choices[0].message.content
						}
						that.chatList.push(messages)
						that.messages.push(messages)
						that.showLoading = false
					    console.log('诊断结果:', res.data);
					},
					fail: (err) => {
					    console.error('请求失败:', err);
						messages = {
							role: 'assistant',
							content: '服务器繁忙,请稍后再试。'
						}
						that.chatList.push(messages)
						that.messages.push(messages)
						that.showLoading = false
					}
				});
			},
			sendMsg() {
				this.send(this.userQuesion)
				this.userQuesion = null
				this.robotAnswer = null
			}
		}
	}
</script>

<style lang="scss">
	.container {
		padding: 28rpx;
	}

	.nav {
		height: 80rpx;
		width: 100%;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;

		image {
			margin: 0 20rpx;
			width: 40rpx;
			height: 40rpx;

		}

		text {
			color: #838383;
			font-size: 40rpx;
		}
	}


	.chat_area {
		padding-bottom: 200rpx;

		// padding-top: 60rpx;
		.current_time {
			display: flex;
			justify-content: center;
			font-size: 20rpx;
			color: #9d9d9d;
		}

		.left_box,
		.right_box {
			display: flex;

			.head_img {
				width: 90rpx;
				height: 90rpx;
				margin: 20rpx 0;

				image {
					width: 90rpx;
					height: 90rpx;
					border-radius: 50%;
				}
			}

			.content_box {
				margin: 20rpx;
				color: #5a5a5a;
				background-color: #e5e5e5;
				padding: 20rpx;
				border-radius: 8rpx;

				.post {}

				.content {
					text-align: justify;
					font-size: 30rpx;
					max-width: 460rpx;
					white-space: normal;
					word-wrap: break-word;

					.post_request {
						// text-indent: 2em;
						color: #996699;
						display: flex;
						flex-direction: column;

						.active:active {
							width: 100%;
							background-color: #FFFFFF;
							opacity: 0.6;
						}
					}
				}

			}
		}

		.right_box {
			display: flex;
			justify-content: flex-end;
		}

		.right_box>.content_box {
			background-color: #1b1263;
			color: #FFFFFF;
		}


	}

	.input_tab {
		background-color: #ffffff;
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		flex-direction: column;

		.statement {
			margin: 0 auto;
			font-size: 20rpx;
			color: #838383;

			text {
				color: #1b1263;
				text-decoration: underline;
			}
		}

		.input_com {
			display: flex;
			justify-content: space-between;
			padding: 20rpx;
			margin: 20rpx;

			.left {
				width: 500rpx;
				max-width: 500rpx;
				border: 2rpx solid #e3e3e3;
				display: flex;
				align-items: center;

				image {
					width: 20rpx;
					height: 20rpx;
					margin: 0 20rpx;
				}

				input {
					width: 100%;
					font-size: 24rpx;
				}
			}

			.send_btn {
				padding: 20rpx 40rpx;
				color: #FFFFFF;
				border-radius: 8rpx;
				background-color: #1b1263;
			}
		}
	}
</style>
2.2 实现效果

3. 示例说明

3.1 单轮对话(仅 user 角色)

如果不需要设置系统指令,可以只传递 user 角色的消息:

messages: [
  {
    role: "user",
    content: "我最近三天持续发烧38.5度,伴有咳嗽",
  },
];
3.2 多轮对话(包含 system 和 user 角色)

如果需要设置系统指令,可以包含 system 角色:

messages: [
  {
    role: "system",
    content: "你是一名专业的全科医生,请根据患者描述进行问诊。",
  },
  {
    role: "user",
    content: "我最近三天持续发烧38.5度,伴有咳嗽",
  },
];
3.3 多轮对话(包含历史记录)

如果需要支持多轮对话,可以将历史记录添加到 messages 中:

messages: [
  {
    role: "system",
    content: "你是一名专业的全科医生,请根据患者描述进行问诊。",
  },
  {
    role: "user",
    content: "我最近三天持续发烧38.5度,伴有咳嗽",
  },
  {
    role: "assistant",
    content: "请问您是否有其他症状,如喉咙痛或头痛?",
  },
  {
    role: "user",
    content: "还有喉咙痛,但没有头痛。",
  },
];

4. 代码示例

4.1 单轮对话
methods: {
  async getDiagnosis() {
    const response = await uni.request({
      url: "https://api.deepseek.com/v1/chat/completions",
      method: "POST",
      header: {
        "Content-Type": "application/json",
        Authorization: "Bearer your_api_key_here",
      },
      data: {
        model: "medical-model-1.0",
        messages: [
          {
            role: "user",
            content: this.userInput,
          },
        ],
      },
    });

    if (response.statusCode === 200) {
      this.diagnosisResponse = response.data.choices[0].message.content;
    }
  },
},
4.2 多轮对话
data() {
  return {
    conversationHistory: [], // 对话历史
  };
},
methods: {
  async getDiagnosis() {
    // 添加用户输入到对话历史
    this.conversationHistory.push({
      role: "user",
      content: this.userInput,
    });

    const response = await uni.request({
      url: "https://api.deepseek.com/v1/chat/completions",
      method: "POST",
      header: {
        "Content-Type": "application/json",
        Authorization: "Bearer your_api_key_here",
      },
      data: {
        model: "medical-model-1.0",
        messages: this.conversationHistory,
      },
    });

    if (response.statusCode === 200) {
      const assistantReply = response.data.choices[0].message.content;
      // 添加助手回复到对话历史
      this.conversationHistory.push({
        role: "assistant",
        content: assistantReply,
      });
      this.diagnosisResponse = assistantReply;
    }
  },
},

5. 注意事项

  1. system 角色的作用

    • 用于设置对话的背景或指令。

    • 如果不需要,可以省略。

  2. user 角色的必要性

    • 必须包含 user 角色的消息,否则 API 无法生成回复。

  3. 对话历史长度

    • 每次请求都会消耗 token,因此需要控制对话历史的长度。

    • 可以通过截断历史记录或设置最大 token 数来优化。

  4. 多轮对话的实现

    • 将每次的用户输入和助手回复添加到 messages 中。

    • 确保对话历史的顺序正确。


6. 总结

  • 必须包含 user 角色,用于传递用户输入。

  • system 角色可选,用于设置对话背景。

  • 多轮对话需要将历史记录添加到 messages 中。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/966309.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

TypeScript 中的对象类型:深入理解接口和类型别名

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

Vinorine合成酶的晶体结构-文献精读110

Crystal structure of vinorine synthase, the first representative of the BAHD superfamily Vinorine合成酶的晶体结构&#xff1a;BAHD超级家族的首个代表 摘要 Vinorine合成酶是一种酰基转移酶&#xff0c;在植物Rauvolfia中抗心律失常单萜吲哚生物碱ajmaline的生物合成…

Kokoro 开源文本转语音引擎上线!多语言支持,无需联网,浏览器内极速运行

Kokoro 是一款轻量级的开源文本转语音(TTS)引擎,凭借其高效能和轻量化设计,迅速在技术社区中引起关注。本文将详细介绍 Kokoro 的主要特点,并提供在浏览器和 Python 环境中的代码示例,帮助您快速上手。 1. Kokoro:可在浏览器中运行的 TTS 引擎 1.1 简介 Kokoro 是一个…

Qt+海康虚拟相机的调试

做机器视觉项目的时候&#xff0c;在没有相机或需要把现场采集的图片在本地跑一下做测试时&#xff0c;可以使用海康的虚拟相机调试。以下是设置步骤&#xff1a; 1.安装好海康MVS软件&#xff0c;在菜单栏->工具选择虚拟相机工具&#xff0c;如下图&#xff1a; 2.打开虚拟…

38、【OS】【Nuttx】OSTest分析(3):参数传递

背景 接之前 blog 36、【OS】【Nuttx】OSTest分析&#xff08;2&#xff09;&#xff1a;环境变量测试 37、【OS】【Nuttx】OSTest分析&#xff08;2&#xff09;&#xff1a;任务创建 分析完环境变量测试&#xff0c;和任务创建的一些关键要素&#xff0c;OSTest 进入下一阶段…

Linux常用命令——压缩和解压类

文章目录 gzip/gunzip 压缩zip/unzip 压缩tar 打包 gzip/gunzip 压缩 基本语法 gzip 文件&#xff08;功能描述&#xff1a;压缩文件&#xff0c;只能将文件压缩为*.gz 文件&#xff09; gunzip 文件.gz &#xff08;功能描述&#xff1a;解压缩文件命令&#xff09;经验技巧 …

Python多版本管理

关注后回复 python 获取相关资料 ubuntu18.04 # ubuntu18 默认版本 Python 2.7.17 apt install python python-dev python-pip# ubuntu18 默认版本 Python 3.6.9 apt install python3 python3-dev python3-pip# ubuntu18 使用 python3.8 apt install python3.8 python3.8-dev#…

五、OSG学习笔记-矩阵变换

一、矩阵变换的三种方式 二、 示例代码&#xff1a; #include<windows.h> #include<osg/Node> #include<osgViewer/Viewer> #include<osgViewer/ViewerEventHandlers> #include<osgDB/ReadFile> #include<osgGA/TrackballManipulator>// …

数据结构与算法-递归

单路递归 二分查找 /*** 主函数&#xff1a;执行二分查找。* * param a 要搜索的数组&#xff08;必须是已排序的&#xff09;* param target 目标值* return 返回目标值在数组中的索引&#xff1b;如果未找到&#xff0c;则返回 -1*/ public static int binarySearch(int[] …

使用python构建局域网HTTP服务进行文件共享

网上有很多参考&#xff0c;在此作为归纳和自己的笔记 首先确保python的目录在系统环境变量中&#xff0c;如果同时有python2.和python3.版本可以将python程序改名进行区分&#xff0c;譬如python2的解释器程序从python.exe改为python2.exe&#xff0c;python3改为python3c.ex…

深入理解小波变换:信号处理的强大工具

引言 在科学与工程领域&#xff0c;信号处理一直是关键环节&#xff0c;傅里叶变换与小波变换作为重要的分析工具&#xff0c;在其中发挥着重要作用。本文将深入探讨小波变换&#xff0c;阐述其原理、优势以及与傅里叶变换的对比&#xff0c;并通过具体案例展示其应用价值。 一…

洛谷P8681 [蓝桥杯 2019 省 AB] 完全二叉树的权值

虽然是简单题&#xff0c;就是log2的运用&#xff0c;然后对于同层的数据累加取最大值 #include<bits/stdc.h>using namespace std;const int N100010; int a[N];int main(){int n;cin>>n;int MAX-1;for( int i1;i<n;i){int j;cin>>j;// cout<<(in…

Java基础知识(七) -- 集合

1.概述 集合是 Java 中提供的一种容器&#xff0c;可以用来存储多个数据。集合主要分为两大系列&#xff1a;Collection和Map&#xff0c;Collection 表示一组对象&#xff0c;Map表示一组映射关系或键值对。集合和数组既然都是容器&#xff0c;它们有啥区别呢&#xff1f; 数…

C++Primer学习(2.1)

前言&#xff1a;与大多数编程语言一样&#xff0c;C的对象类型决定了能对该对象进行的操作&#xff0c;一条表达式是否合法依赖于其中参与运算的对象的类型。一些语言&#xff0c;如Smalltalk和Python 等&#xff0c;在程序运行时检查数据类型;与之相反&#xff0c;C是一种静态…

TensorFlow深度学习实战(7)——分类任务详解

TensorFlow深度学习实战&#xff08;7&#xff09;——分类任务详解 0. 前言1. 分类任务1.1 分类任务简介1.2 分类与回归的区别 2. 逻辑回归3. 使用 TensorFlow 实现逻辑回归小结系列链接 0. 前言 分类任务 (Classification Task) 是机器学习中的一种监督学习问题&#xff0c;…

国产编辑器EverEdit - 查找功能详解

1 查找功能详解 1.1 应用场景 查找关键词应该是整个文本编辑/阅读活动中&#xff0c;操作频度非常高的一项&#xff0c;用好查找功能&#xff0c;不仅可以可以搜索到关键字&#xff0c;还可以帮助用户高效完成一些特定操作。 1.2 基础功能 1.2.1 基础查找功能 选择主菜单查…

5分钟了解回归测试

1. 什么是回归测试&#xff08;Regression Testing&#xff09; 回归测试是一个系统的质量控制过程&#xff0c;用于验证最近对软件的更改或更新是否无意中引入了新错误或对以前的功能方面产生了负面影响&#xff08;比如你在家中安装了新的空调系统&#xff0c;发现虽然新的空…

【AI】卷积神经网络CNN

不定期更新&#xff0c;建议关注收藏点赞。 目录 零碎小组件经验总结早期的CNN 最重要的模型架构无非是cnn 或 transformer 零碎小组件 全连接神经网络 目前已经被替代。 每个神经元都有参与&#xff0c;但由于数据中的特征点变化大&#xff0c;全连接神经网络把所有数据特征都…

企业FTP替代升级,实现传输大文件提升100倍!

随着信息技术的飞速发展&#xff0c;网络安全环境也变得越来越复杂。在这种背景下&#xff0c;传统的FTP&#xff08;文件传输协议&#xff09;已经很难满足现代企业对文件传输的需求了。FTP虽然用起来简单&#xff0c;但它的局限性和安全漏洞让它在面对高效、安全的数据交换时…

LabVIEW铅酸蓄电池测试系统

本文介绍了基于LabVIEW的通用飞机铅酸蓄电池测试系统的设计与实现。系统通过模块化设计&#xff0c;利用多点传感器采集与高效的数据处理技术&#xff0c;显著提高了蓄电池测试的准确性和效率。 ​ 项目背景 随着通用航空的快速发展&#xff0c;对飞机铅酸蓄电池的测试需求也…