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

ops/2024/9/23 6:34:34/

文章目录

  • 前言
  • 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()

http://www.ppmy.cn/ops/33792.html

相关文章

Linux内核深入学习 - 内核同步

目录 内核抢占 同步原语 per-CPU变量 API Per CPU 变量的应用 per CPU 变量在多文件下的用法 原子操作 API 优化和内存屏障 自旋锁 自旋锁 API 函数 读写锁 API RCU 信号量 API 1. 信号量的结构: 2. 初始化函数sema_init 3. 可中断获取信号量函数…

学习mysql相关知识记录

执行一条select语句,期间发生了什么? MySQL的执行流程: 连接器 TCP连接 查询缓存 很鸡肋被取消 解析SQL 解析器 语法分析词法分析 执行SQL 预处理器 检查是否存在将 select * 中的 * 符号,扩展为表上的所有列 优化器 优化器主要…

删除虚拟机存储策略中vSAN默认存储策略

登录vSphere Client,展开左上角设置-策略和配置文件-虚拟机存储策略,可以查看系统默认创建的虚拟机存储策略。这些存储策略由系统自动生成,其中有一部分存储策略仅用于vSAN数据存储,作为vSAN 默认存储策略以应用于,当在…

【iOS】KVO

文章目录 前言一、KVO使用1.基本使用2.context使用3.移除KVO通知的必要性4.KVO观察可变数组 二、代码调试探索1.KVO对属性观察2.中间类3.中间类的方法3.dealloc中移除观察者后,isa指向是谁,以及中间类是否会销毁?总结 三、KVO本质GNUStep窥探…

dynamic_cast 静态转换

dynamic_cast 静态转换 const_cast 常量转换 重新解释转换(reinterpret_cast) 最不安全

docker的安装以及docker-compose

什么事docker Docker是一种轻量级的容器技术,可以帮助开发者更加方便地打包、发布和管理应用程序。在Linux系统上安装Docker非常容易. 安装和使用docker 1:首先安装必须的管理工具,使用Linux 终端命令 sudo yum install -y yum-utils device-mapper-per…

程序的机器级表示——Intel x86 汇编讲解

往期地址: 操作系统系列一 —— 操作系统概述操作系统系列二 —— 进程操作系统系列三 —— 编译与链接关系操作系统系列四 —— 栈与函数调用关系操作系统系列五 —— 目标文件详解操作系统系列六 —— 详细解释【静态链接】操作系统系列七 —— 装载操作系统系列…

美团KV存储squirrel和Celler学习

文章目录 美团在KV存储squirrel优化和改进在水平方向1、对Gossip协议进行优化 在垂直扩展方面1、forkless RDB数据复制优化2、使用多线程,充分利用机器的多核能力 在高可用方面 美团持久化kv存储celler优化和改进水平扩展优化1、使用bulkload进行数据导入2、线程模型…