急速入门Prompt开发之跨国婚姻小助手

2024-05-05 18:28

本文主要是介绍急速入门Prompt开发之跨国婚姻小助手,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 前言
  • MoonShot
  • 编写提示词
  • 对接模型
  • WebUI编写
  • 完整代码

前言

整个活,同时分享技术~至于是啥活,懂得都懂,男孩子自强自尊自爱!!!
先看看实现效果吧:
在这里插入图片描述
那么这里的话,我们使用到的是国内的LLM,来自moonshot的大语言模型。那么废话不多少,快速开始吧。

MoonShot

现在我们来获取暗月之面的API,这里我们需要进入到开发平台:https://platform.moonshot.cn/console/info 这里你可能比较好奇,为什么使用这个LLM,实际上,是因为综合体验下来,它的中文效果较好,可以完成较为复杂的操作,相对于3.5或者其他模型来说。同时价格在能够接受的合理范围,当然,在我们接下来使用的中转站当中也可以直接使用GPT4.0但是使用成本将大大提升!
在这里插入图片描述
进入平台之后,按照平台提示即可完成创建,当然这里注意,免费用户有15元钱的token,但是存在并发限制,因此建议适开通付费提高并发量。

编写提示词

那么首先的话,我们来开始编写到提示词,这个非常简单:

# initalize the config of chatbot
api_key = "sk-FGivAMvTnxPSWlp7HrGfDD"
openai_api_base = "https://api.moonshot.cn/v1"
system_prompt = "你是跨国婚姻法律小助手,小汐,负责回答用户关于跨国婚姻的问题。你的回答要清晰明了,有逻辑性和条理性。请使用中文回答。"
default_model = "moonshot-v1-8k"
temperature = 0.5

对接模型

编写完毕提示词之后,这还远远不够,我们需要对接模型,这里的话因为接口是按照openai的范式来的,所以的话我们直接用OpenAI这个库就好了。

然后看到下面的代码:

client = OpenAI(api_key=api_key,base_url=openai_api_base)
class ChatBotHandler(object):def __init__(self, bot_name="chat"):self.bot_name = bot_nameself.current_message = Nonedef user_stream(self,user_message, history):self.current_message = user_messagereturn "", history + [[user_message, None]]def bot_stream(self,history):if(len(history)==0):history.append([self.current_message,None])bot_message = self.getResponse(history[-1][0],history)history[-1][1] = ""for character in bot_message:history[-1][1] += charactertime.sleep(0.02)yield historydef signChat(self,history):history_openai_format = []# 先加入系统信息history_openai_format.append({"role": "system","content": system_prompt},)# 再加入解析信息history_openai_format.extend(history)# print(history_openai_format)completion = client.chat.completions.create(model=default_model,messages=history_openai_format,temperature=temperature,)result = completion.choices[0].message.contentreturn resultdef getResponse(self,message,history):history_openai_format = []for human, assistant in history:# 基础对话的系统设置history_openai_format.append({"role": "system","content":system_prompt},)if(human!=None):history_openai_format.append({"role": "user", "content": human})if(assistant!=None):history_openai_format.append({"role": "assistant", "content": assistant})completion = client.chat.completions.create(model=default_model,messages=history_openai_format,temperature=temperature,)result = completion.choices[0].message.contentreturn resultdef chat(self,message, history):history_openai_format = []for human, assistant in history:history_openai_format.append({"role": "user", "content": human})history_openai_format.append({"role": "system", "content": assistant})history_openai_format.append({"role": "user", "content": message})response = client.chat.completions.create(model=default_model,messages=history_openai_format,temperature=1.0,stream=True)partial_message = ""for chunk in response:if chunk.choices[0].delta.content is not None:partial_message = partial_message + chunk.choices[0].delta.contentyield partial_message

WebUI编写

之后的话,就是提供webUI,这里的话还是直接使用到了streamlit

class AssistantNovel(object):def __init__(self):self.chat = ChatBotHandler()def get_response(self,prompt, history):return self.chat.signChat(history)def clear_chat_history(self):st.session_state.messages = [{"role": "assistant", "content": "🍭🍡你好!我是跨国婚姻小助手,您可以咨询我关于这方面的任何法律问题🧐"}]def chat_fn(self):prompt = st.session_state.get("prompt-input")st.session_state.messages.append({"role": "user", "content": prompt})# 此时进入回答with self.con:with st.spinner("Thinking..."):try:response = self.get_response(prompt, st.session_state.messages)except Exception as e:print(e)response = "哦┗|`O′|┛ 嗷~~,出错了,您的请求太频繁,请稍后再试!😥"message = {"role": "assistant", "content": response}st.session_state.messages.append(message)def page(self):if "messages" not in st.session_state.keys():st.session_state.messages = [{"role": "assistant", "content": "🍭🍡你好!我是跨国婚姻小助手,您可以咨询我关于这方面的任何法律问题🧐"}]# 加载历史聊天记录,对最后一条记录进行特殊处理for message in st.session_state.messages:if message != st.session_state.messages[-1]:with st.chat_message(message["role"]):st.write(message["content"])else:placeholder = st.empty()full_response = ''for item in message["content"]:full_response += itemtime.sleep(0.01)placeholder.markdown(full_response)placeholder.markdown(full_response)# 主聊天对话窗口self.con  = st.container()with self.con:prompt = st.chat_input(placeholder="请输入对话",key="prompt-input",on_submit=self.chat_fn)st.button('清空历史对话', on_click=self.clear_chat_history)

完整代码

okey,最后还是直接看到完整代码吧:

"""
@FileName:layer.py
@Author:Huterox
@Description:Go For It
@Time:2024/5/5 13:49
@Copyright:©2018-2024 awesome!
"""#initialization the third-part model
import time
import streamlit as st
from openai import OpenAI
#finished the initialization# initalize the config of chatbot
api_key = "sk-FGivAMvdHnrqUwzZp29mD"
openai_api_base = "https://api.moonshot.cn/v1"
system_prompt = "你是跨国婚姻法律小助手,小汐,负责回答用户关于跨国婚姻的问题。你的回答要清晰明了,有逻辑性和条理性。请使用中文回答。"
default_model = "moonshot-v1-8k"
temperature = 0.5client = OpenAI(api_key=api_key,base_url=openai_api_base)
class ChatBotHandler(object):def __init__(self, bot_name="chat"):self.bot_name = bot_nameself.current_message = Nonedef user_stream(self,user_message, history):self.current_message = user_messagereturn "", history + [[user_message, None]]def bot_stream(self,history):if(len(history)==0):history.append([self.current_message,None])bot_message = self.getResponse(history[-1][0],history)history[-1][1] = ""for character in bot_message:history[-1][1] += charactertime.sleep(0.02)yield historydef signChat(self,history):history_openai_format = []# 先加入系统信息history_openai_format.append({"role": "system","content": system_prompt},)# 再加入解析信息history_openai_format.extend(history)# print(history_openai_format)completion = client.chat.completions.create(model=default_model,messages=history_openai_format,temperature=temperature,)result = completion.choices[0].message.contentreturn resultdef getResponse(self,message,history):history_openai_format = []for human, assistant in history:# 基础对话的系统设置history_openai_format.append({"role": "system","content":system_prompt},)if(human!=None):history_openai_format.append({"role": "user", "content": human})if(assistant!=None):history_openai_format.append({"role": "assistant", "content": assistant})completion = client.chat.completions.create(model=default_model,messages=history_openai_format,temperature=temperature,)result = completion.choices[0].message.contentreturn resultdef chat(self,message, history):history_openai_format = []for human, assistant in history:history_openai_format.append({"role": "user", "content": human})history_openai_format.append({"role": "system", "content": assistant})history_openai_format.append({"role": "user", "content": message})response = client.chat.completions.create(model=default_model,messages=history_openai_format,temperature=1.0,stream=True)partial_message = ""for chunk in response:if chunk.choices[0].delta.content is not None:partial_message = partial_message + chunk.choices[0].delta.contentyield partial_messageclass AssistantNovel(object):def __init__(self):self.chat = ChatBotHandler()def get_response(self,prompt, history):return self.chat.signChat(history)def clear_chat_history(self):st.session_state.messages = [{"role": "assistant", "content": "🍭🍡你好!我是跨国婚姻小助手,您可以咨询我关于这方面的任何法律问题🧐"}]def chat_fn(self):prompt = st.session_state.get("prompt-input")st.session_state.messages.append({"role": "user", "content": prompt})# 此时进入回答with self.con:with st.spinner("Thinking..."):try:response = self.get_response(prompt, st.session_state.messages)except Exception as e:print(e)response = "哦┗|`O′|┛ 嗷~~,出错了,您的请求太频繁,请稍后再试!😥"message = {"role": "assistant", "content": response}st.session_state.messages.append(message)def page(self):if "messages" not in st.session_state.keys():st.session_state.messages = [{"role": "assistant", "content": "🍭🍡你好!我是跨国婚姻小助手,您可以咨询我关于这方面的任何法律问题🧐"}]# 加载历史聊天记录,对最后一条记录进行特殊处理for message in st.session_state.messages:if message != st.session_state.messages[-1]:with st.chat_message(message["role"]):st.write(message["content"])else:placeholder = st.empty()full_response = ''for item in message["content"]:full_response += itemtime.sleep(0.01)placeholder.markdown(full_response)placeholder.markdown(full_response)# 主聊天对话窗口self.con  = st.container()with self.con:prompt = st.chat_input(placeholder="请输入对话",key="prompt-input",on_submit=self.chat_fn)st.button('清空历史对话', on_click=self.clear_chat_history)if __name__ == '__main__':st.set_page_config(page_title="跨国婚姻法律小助手",page_icon="🤖",layout="wide",initial_sidebar_state="auto",)a,b,c = st.columns([1,2,1])with b:assistant = AssistantNovel()assistant.page()

这篇关于急速入门Prompt开发之跨国婚姻小助手的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/962368

相关文章

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

Python使用smtplib库开发一个邮件自动发送工具

《Python使用smtplib库开发一个邮件自动发送工具》在现代软件开发中,自动化邮件发送是一个非常实用的功能,无论是系统通知、营销邮件、还是日常工作报告,Python的smtplib库都能帮助我们... 目录代码实现与知识点解析1. 导入必要的库2. 配置邮件服务器参数3. 创建邮件发送类4. 实现邮件

基于Python开发一个有趣的工作时长计算器

《基于Python开发一个有趣的工作时长计算器》随着远程办公和弹性工作制的兴起,个人及团队对于工作时长的准确统计需求日益增长,本文将使用Python和PyQt5打造一个工作时长计算器,感兴趣的小伙伴可... 目录概述功能介绍界面展示php软件使用步骤说明代码详解1.窗口初始化与布局2.工作时长计算核心逻辑3

Python中OpenCV与Matplotlib的图像操作入门指南

《Python中OpenCV与Matplotlib的图像操作入门指南》:本文主要介绍Python中OpenCV与Matplotlib的图像操作指南,本文通过实例代码给大家介绍的非常详细,对大家的学... 目录一、环境准备二、图像的基本操作1. 图像读取、显示与保存 使用OpenCV操作2. 像素级操作3.

python web 开发之Flask中间件与请求处理钩子的最佳实践

《pythonweb开发之Flask中间件与请求处理钩子的最佳实践》Flask作为轻量级Web框架,提供了灵活的请求处理机制,中间件和请求钩子允许开发者在请求处理的不同阶段插入自定义逻辑,实现诸如... 目录Flask中间件与请求处理钩子完全指南1. 引言2. 请求处理生命周期概述3. 请求钩子详解3.1

基于Python实现智能天气提醒助手

《基于Python实现智能天气提醒助手》这篇文章主要来和大家分享一个实用的Python天气提醒助手开发方案,这个工具可以方便地集成到青龙面板或其他调度框架中使用,有需要的小伙伴可以参考一下... 目录项目概述核心功能技术实现1. 天气API集成2. AI建议生成3. 消息推送环境配置使用方法完整代码项目特点

如何基于Python开发一个微信自动化工具

《如何基于Python开发一个微信自动化工具》在当今数字化办公场景中,自动化工具已成为提升工作效率的利器,本文将深入剖析一个基于Python的微信自动化工具开发全过程,有需要的小伙伴可以了解下... 目录概述功能全景1. 核心功能模块2. 特色功能效果展示1. 主界面概览2. 定时任务配置3. 操作日志演示

JavaScript实战:智能密码生成器开发指南

本文通过JavaScript实战开发智能密码生成器,详解如何运用crypto.getRandomValues实现加密级随机密码生成,包含多字符组合、安全强度可视化、易混淆字符排除等企业级功能。学习密码强度检测算法与信息熵计算原理,获取可直接嵌入项目的完整代码,提升Web应用的安全开发能力 目录

一文教你如何解决Python开发总是import出错的问题

《一文教你如何解决Python开发总是import出错的问题》经常朋友碰到Python开发的过程中import包报错的问题,所以本文将和大家介绍一下可编辑安装(EditableInstall)模式,可... 目录摘要1. 可编辑安装(Editable Install)模式到底在解决什么问题?2. 原理3.