急速入门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开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优