记录学习之uniapp-微信小程序 + python + 文心一言语言模型

        最近特别想了解下已经比较成熟的chatgpt,但是没有相关的服务器和手机号~就想到了百度的文心一言~那就拿它下手吧~

        斥“巨资”买了一丢丢token~~然后开干

        准备工作:一个服务器(本人是linux的云服务),python3,小程序主体,nginx巴拉巴拉~~

        注意:python3要安装对应的openssl(pip3 install pyOpenSSL),不然会在最终调取的时候报错,其余的就没什么了,正常的py部署。本人是找的这个大佬的liunx安装py3的流程,完全可行。地址:Linux系统之编译安装python3_linux安装python3-CSDN博客

        nginx的配置要保证可以实现text/eventstream的传输方式,如下:

location / {
  	proxy_set_header X-Real-IP $remote_addr;
    proxy_cache off;//重要!重要!重要!
    proxy_buffering off;//重要!重要!重要!
    proxy_pass http://127.0.0.1:5000/;
    client_max_body_size 1024m;
}

        需要注意的地方就这样了,然后就是简单的uniapp还有python的代码了。

        uniapp的:

<template>
	<view class="chat">
		<scroll-view  :style="{height: `${windowHeight}rpx`}"
		id="scrollview"
		scroll-y="true" 
		:scroll-top="scrollTop"
		:scroll-with-animation="true"
		class="scroll-view"
		>
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.userContent != ''" >
						<view class="content right">
						{{item.userContent}}
						</view>
						<view class="avatar">
							<view style="margin:auto">朕</view>
						</view>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-if="item.botContent != []"> 
						<view class="avatar">
							<view style="margin:auto">文</view>
						</view>
						<view class="content left">
							<view v-for="it in item.botContent">
								{{it}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位,防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom">
			<view class="send-msg">
                <view class="uni-textarea">
					<textarea v-model="chatMsg"
					  maxlength="100"
					  :show-confirm-bar="false"
					 auto-height></textarea>
				</view>
				<button @click="handleSend" class="send-btn" :disabled="senddis" :loading="senddis">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				//滚动距离
				scrollTop: 0,
				userId:'',
				//发送的消息
				chatMsg:"",
				msgList:[],
				senddis : false,
			}
		},
		computed: {
			windowHeight() {
			    return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			}
		},
		methods: {
			// px转换成rpx
			rpxTopx(px){
				let deviceWidth = wx.getSystemInfoSync().windowWidth
				let rpx = ( 750 / deviceWidth ) * Number(px)
				return Math.floor(rpx)
			},
			// 发送消息
			handleSend() {
				//如果消息不为空
				if(this.chatMsg != ""){
					this.senddis = true;
					this.gpt(this.chatMsg , null);
				}else {
					this.senddis = false;
					uni.showToast({
						title:"没有写内容哟!",
						icon:'none'
					})
				}
			},
			gpt(chatMsg , lookGG){
				let that = this;
				let myobj = {
					botContent: "",
					recordId: 0,
					titleId: 0,
					userContent: that.chatMsg,
					userId: 0
				}
				that.msgList.push(myobj);
				that.chatMsg = '';
				let key = that.msgList.length;
				
				let requestTask = uni.request({
					url: "",
					timeout: 15000,
					responseType: 'text',
					method: 'GET',
					enableChunked: true,  //配置这里
					data: {},
					success: response => {
						that.senddis = false;
						console.log(response)
					},
					fail: error => {}
				})
				requestTask.onHeadersReceived(function(res) {
					//console.log(res.header);
				});
				// 这里监听消息
				requestTask.onChunkReceived(function(res) {
					const uint8Array = new Uint8Array(res.data);
					let text = String.fromCharCode.apply(null, uint8Array);
					text = decodeURIComponent(escape(text));
					if(that.msgList[key] == null){
						let bot = new Array();
						bot.push(text);
						let obj = {
							botContent: bot,
							recordId: 0,
							titleId: 0,
							userContent: "",
							userId: 0
						}
						that.msgList.push(obj);
					}else{
						that.msgList[key].botContent.push(text);
					}
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;
	
	view,button,text,input,textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {
		.scroll-view {
			::-webkit-scrollbar {
					    display: none;
					    width: 0 !important;
					    height: 0 !important;
					    -webkit-appearance: none;
					    background: transparent;
					    color: transparent;
					  }
			
			// background-color: orange;
			background-color: #F6F6F6;
			
			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;
				
				.self {
					justify-content: flex-end;
				}
				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}
					.left {
						background-color: #FFFFFF;
					}
                    // 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 8rpx;
						overflow: hidden;
						color: #FFFFFF;
						image {
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 147rpx;
			background: #F4F5F7;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 147rpx;
				position: fixed;
				bottom: 0;
				background: #EDEDED;
			}

			.uni-textarea {
				padding-bottom: 70rpx;
                
				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 43rpx;
					padding: 5rpx 8rpx;
				}
			}
            
			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				background: $sendBtnbgc;
				border-radius: 8rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
		
	}
</style>

        python的比较简单,没有做多层的包装和加工,代码如下:

import erniebot
from flask import Flask, stream_with_context, request, Response 
from time import sleep
import ssl

erniebot.api_type = 'aistudio'
erniebot.access_token = 'xxx'

app = Flask(__name__)

@app.route('/getwenxinyy', methods=['get'])
def generate():

    @stream_with_context
    def getdata():
        # 接收前端数据
        data = request.args.get('ask')
        response_stream = erniebot.ChatCompletion.create(
            model='ernie-bot',
            messages=[{'role': 'user', 'content': data}],
            stream=True,
        )
        for response in response_stream:
            yield response.get_result()
            print(response.get_result())
            sleep(1)

    return Response(getdata(), mimetype='text/event-stream')

if __name__ == '__main__':
    app.run()

        以上基本可以完成最简单的调用和展示功能了~~

        附上小程序(很多菜单没开,怕wg~~啦啦啦),接下来想融入点其他算法~一步一步来吧

        

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值