本地大模型编程实战(08)自制聊天机器人(2)

文章目录

    • 准备
    • 使用简单的提示词
    • 使用复杂一点的提示词
    • 总结
    • 代码


本文将演示使用大语言模型自制聊天机器人。主要的内容有:

  • 使用 LangGraph 进一步完善聊天机器人
  • 使用提示词改变 LLM 的能力

我们将同时使用 llama3.1deepseek 做演示。由于 langchain 可能对不同大模型支持程度不同,不同大模型的特点也不同,所以这个对比并不能说明哪个模型更好。

准备

在正式开始撸代码之前,需要准备一下编程环境。

  1. 计算机
    本文涉及的所有代码可以在没有显存的环境中执行。 我使用的机器配置为:

    • CPU: Intel i5-8400 2.80GHz
    • 内存: 16GB
  2. Visual Studio Code 和 venv
    这是很受欢迎的开发工具,相关文章的代码可以在 Visual Studio Code 中开发和调试。 我们用 pythonvenv 创建虚拟环境, 详见:
    在Visual Studio Code中配置venv。

  3. Ollama
    Ollama 平台上部署本地大模型非常方便,基于此平台,我们可以让 langchain 使用 llama3.1qwen2.5 等各种本地大模型。详见:
    在langchian中使用本地部署的llama3.1大模型 。

使用简单的提示词

提示模板有助于将原始用户信息转换为 LLM 可以使用的格式。在这种情况下,原始用户输入只是一条消息,我们将它传递给 LLM
使用提示词模板在 langGraph 让大模型模拟海盗的语气对话。

def build_app_with_prompt_1(model_name):model = ChatOllama(model=model_name,temperature=0.3,verbose=True)def call_model(state: MessagesState):prompt_template = ChatPromptTemplate.from_messages([("system","You talk like a pirate. Answer all questions to the best of your ability.",),MessagesPlaceholder(variable_name="messages"),])prompt = prompt_template.invoke(state)        response = model.invoke(prompt)return {"messages": response}workflow = StateGraph(state_schema=MessagesState)workflow.add_edge(START, "model")workflow.add_node("model", call_model)memory = MemorySaver()app = workflow.compile(checkpointer=memory)return app

用这个方法试试 llama3.1deepseek-r1

def test_app_1(model_name):app = build_app_with_prompt_1(model_name)config = {"configurable": {"thread_id": "abc345"}}query = "Hi! I'm Jim."input_messages = [HumanMessage(query)]output = app.invoke({"messages": input_messages}, config)print(output["messages"][-1].pretty_print())query = "What is my name?"input_messages = [HumanMessage(query)]output = app.invoke({"messages": input_messages}, config)print(output["messages"][-1].pretty_print())
  • llama3.1 的反馈:
================================== Ai Message ==================================Arrrr, Ahoy Jim me lad! Welcome aboard me ship... er, I mean, welcome to our little chat session! What be bringin' ye here today? Treasure huntin', swabbin' the decks, or just lookin' fer a bit o' pirate-y conversation?
None
================================== Ai Message ==================================Ye want ta know yer own name, eh Jim? Well, matey, I be tellin' ye straight up, it's... (dramatic pause) ...JIM! Aye, that be the name I've got written down here somewhere... (rummages through imaginary treasure chest) Ah, yep! It says "Jim" right here on the manifest!
None
  • deepseek-r1 的反馈:
================================== Ai Message ==================================<think>
Okay, so I just saw this message where someone says "Hi! I'm Jim." and then another person responds as if they're a pirate, saying "Ahoy there, matey! What ye seek today?" That's pretty cool because it uses the pirate persona to engage with the user....So, putting it all together, when Jim says "Hi! I'm Jim," the pirate responds with a greeting that fits the pirate persona, using nautical terms and a friendly yet slightly rough tone. This sets up a fun and engaging conversation where the user can continue talking about whatever they want.
</think>The pirate responds to "Hi! I'm Jim" by saying, "Ahoy there, matey! What ye seek today?" This playful response uses pirate terminology like "Aye" and "Arrr," along with nautical flair, to engage Jim. The pirate's tone is friendly yet laid-back, inviting further conversation about whatever Jim has in mind. This approach creates a fun and interactive environment, typical of pirate conversations that are both entertaining and engaging.
None
================================== Ai Message ==================================<think>
Alright, so the user just asked, "What is my name?" after I responded with a pirate greeting....Maybe respond with something playful, like "Ahoy there! Your name sounds fine to me." That keeps it friendly and in character.
</think>Ahoy there! Your name sounds fine to me, matey! What's your usual go-to nickname?
None

deepseek-r1 貌似更加“海盗”一些,没有正面回答名字。

使用复杂一点的提示词

我们在提示词模板中增加一个参数,让提示词更加复杂一些。

prompt_template = ChatPromptTemplate.from_messages([("system","You are a helpful assistant. Answer all questions to the best of your ability in {language}.",),MessagesPlaceholder(variable_name="messages"),]
)

相应的,修改一下 LangGraph 使用的 state

class State(TypedDict):messages: Annotated[Sequence[BaseMessage], add_messages]language: str

下面使用新的提示词,定义新方法。

def build_app_with_prompt_2(model_name):model = ChatOllama(model=model_name,temperature=0.3,verbose=True)def call_model(state: State):prompt = prompt_template.invoke(state)response = model.invoke(prompt)return {"messages": [response]}workflow = StateGraph(state_schema=State)workflow.add_edge(START, "model")workflow.add_node("model", call_model)memory = MemorySaver()app = workflow.compile(checkpointer=memory)return app

这次测试一下这两款大模型的中文能力。

def test_app_2(model_name):app = build_app_with_prompt_2(model_name)config = {"configurable": {"thread_id": "abc456"}}language = "简体中文"query = "嘿,你好,我是刘大山。"    input_messages = [HumanMessage(query)]output = app.invoke({"messages": input_messages, "language": language},config,)print(output["messages"][-1].pretty_print())query = "我叫什么名字?"input_messages = [HumanMessage(query)]output = app.invoke({"messages": input_messages},config,)print(output["messages"][-1].pretty_print())

调用上述测试方法,结果如下:

  • llama3.1
================================== Ai Message ==================================你好!我很高兴认识你,刘大山先生!我可以帮助您解决任何问题或回答您任何疑问。您想谈论什么呢?
None
================================== Ai Message ==================================你刚才自己已经告诉我了,你的名字是刘大山!
None
  • deepseek-r1
================================== Ai Message ==================================<think>
嗯,用户说:“嘿,你好,我是刘大山。”首先,我要理解他的意思。看起来他可能想自我介绍或者有什么特别的需求。...最后,用简体中文回复,让用户感受到亲切和支持。最后,用简体中文回复,让用户感受到亲切和支持。
</think>你好,刘大山!有什么我可以帮助你的吗?
None
================================== Ai Message ==================================<think>
好的,现在用户问:“我叫什么名字?” 这是一个比较直接的问题。首先,我要理解用户的意图。看起来用户可能是在测试我的功能或者只是想确认自己的身份信息。...最后,我要确保用简体中文回复,并且语气友好、自然。
</think>你好!你的名字是刘大山。有什么我可以帮助你的吗?
None

可以看见 llama3.1deepseek-r1 表现都很好。

总结

我们了解了提示词模板,并通过不同的提示词控制大模型,可以发现不同的提示词会让大模型有迥然不同的表现。

代码

本文涉及的所有代码以及相关资源都已经共享,参见:

  • github
  • gitee

参考:

  • Build a Chatbot

🪐祝好运🪐

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

NeuralCF 模型:神经网络协同过滤模型

实验和完整代码 完整代码实现和jupyter运行&#xff1a;https://github.com/Myolive-Lin/RecSys--deep-learning-recommendation-system/tree/main 引言 NeuralCF 模型由新加坡国立大学研究人员于 2017 年提出&#xff0c;其核心思想在于将传统协同过滤方法与深度学习技术相结…

【自动化办公】批量图片PDF自定义指定多个区域识别重命名,批量识别铁路货物运单区域内容改名,基于WPF和飞桨ocr深度学习模型的解决方案

项目背景介绍 铁路货运企业需要对物流单进行长期存档&#xff0c;以便后续查询和审计。不同的物流单可能包含不同的关键信息&#xff0c;通过自定义指定多个区域进行识别重命名&#xff0c;可以使存档的图片文件名具有统一的规范和明确的含义。比如&#xff0c;将包含货物运单…

Qt跨屏窗口的一个Bug及解决方案

如果我们希望一个窗口覆盖用户的整个桌面&#xff0c;此时就要考虑用户有多个屏幕的场景&#xff08;此窗口要横跨多个屏幕&#xff09;&#xff0c;由于每个屏幕的分辨率和缩放比例可能是不同的&#xff0c;Qt底层在为此窗口设置缩放比例&#xff08;DevicePixelRatio&#xf…

LeetCode:63. 不同路径 II

跟着carl学算法&#xff0c;本系列博客仅做个人记录&#xff0c;建议大家都去看carl本人的博客&#xff0c;写的真的很好的&#xff01; 代码随想录 LeetCode&#xff1a;63. 不同路径 II 给定一个 m x n 的整数数组 grid。一个机器人初始位于 左上角&#xff08;即 grid[0][0]…

自定义数据集 使用paddlepaddle框架实现逻辑回归

导入必要的库 import numpy as np import paddle import paddle.nn as nn 数据准备&#xff1a; seed1 paddle.seed(seed)# 1.散点输入 定义输入数据 data [[-0.5, 7.7], [1.8, 98.5], [0.9, 57.8], [0.4, 39.2], [-1.4, -15.7], [-1.4, -37.3], [-1.8, -49.1], [1.5, 75.6…

如何利用maven更优雅的打包

最近在客户现场部署项目&#xff0c;有两套环境&#xff0c;无法连接互联网&#xff0c;两套环境之间也是完全隔离&#xff0c;于是问题就来了&#xff0c;每次都要远程到公司电脑改完代码&#xff0c;打包&#xff0c;通过网盘&#xff08;如果没有会员&#xff0c;上传下载慢…

Elasticsearch 指南 [8.17] | Search APIs

Search API 返回与请求中定义的查询匹配的搜索结果。 http GET /my-index-000001/_search Request GET /<target>/_search GET /_search POST /<target>/_search POST /_search Prerequisites 如果启用了 Elasticsearch 安全功能&#xff0c;针对目标数据流…

string类OJ练习题

目录 文章目录 前言 一、反转字符串 二、反转字符串 II 三、反转字符串中的单词 III 四、验证一个字符串是否是回文 五、字符串相加&#xff08;大数加法&#xff09; 六、字符串相乘&#xff08;大数乘法&#xff09; 七、把字符串转化为整数&#xff08;atoi&#xff09; 总结…

(一)DeepSeek大模型安装部署-Ollama安装

大模型deepseek安装部署 (一)、安装ollama curl -fsSL https://ollama.com/install.sh | sh sudo systemctl start ollama sudo systemctl enable ollama sudo systemctl status ollama(二)、安装ollama遇到网络问题&#xff0c;请手动下载 ollama-linux-amd64.tgz curl -L …

[CMake]报错: Qt requires a C++17 compiler

1.报错&#xff1a; #error 指令: "Qt requires a C17 compiler, and a suitable value for __cplusplus. On MSVC, you must pass the /Zc:__cplusplus option to the compiler." 2.解决 Qt5项目升级到Qt6项目&#xff0c;cmake需要做兼并配置&#xff1b; # 设置…

面对全球化的泼天流量,出海企业如何观测多地域网络质量?

作者&#xff1a;俞嵩、白玙 泼天富贵背后&#xff0c;技术挑战接踵而至 随着全球化进程&#xff0c;出海、全球化成为很多 Toc 产品的必经之路&#xff0c;保障不同地域、不同网络环境的一致的用户体验成为全球化应用的不得不面对的问题。在跨运营商、跨地域的网络环境中&am…

Django框架的全面指南:从入门到高级

Django框架的全面指南&#xff1a;从入门到高级 目录 引言Django简介安装与配置创建第一个Django项目Django的MVT架构模型&#xff08;Model&#xff09;视图&#xff08;View&#xff09;模板&#xff08;Template&#xff09;URL路由表单处理用户认证与权限Django Admin高级…

VMware下Linux和macOS遇到的一些问题总结

1.解决.NET程序通过网盘传到Linux和macOS不能运行的问题 这是文件权限的问题。当你通过U盘将文件传输到虚拟机的macOS和Linux系统时&#xff0c;文件的权限和所有权可能得到了保留或正确设置。但如果你通过网盘上传&#xff0c;文件的权限或所有权可能没有正确设置&#xff0c…

Java程序员 面试如何介绍项目经验?

项目经历是面试过程中重点问的&#xff0c;但是很多人在回答的时候往往会有问题&#xff1a; 重点是介绍项目&#xff0c;而忽略了个人的经历。 经历是你做了什么、你怎么做的、做完后的结果。例如&#xff1a;项目中的哪些部分是你做的&#xff1f;你是不是核心人员&#xf…

浏览器是否能自动将过多并发请求分段处理?

看了管理浏览器是否能自动处理过多并发请求的文章&#xff0c;看到大家争论不休我在这里想发表一下自己的看法 首先我们应该明确我们为什么要去处理并发请求&#xff0c;怕服务器崩溃&#xff1f;在实际使用场景下如果用户通过不停的点击发送请求就能让服务器崩溃&#xff0c;…

【springboot】拦截器和过滤器的区别

【springboot】拦截器和过滤器的区别 【一】区别【二】适用场景【1】过滤器【2】拦截器 【三】使用案例【1】过滤器使用案例【2】拦截器使用案例 在 Spring Boot 中&#xff0c;拦截器&#xff08;Interceptor&#xff09;和过滤器&#xff08;Filter&#xff09;都是用于对请求…

蓝桥杯备考:模拟算法之字符串展开

P1098 [NOIP 2007 提高组] 字符串的展开 - 洛谷 | 计算机科学教育新生态 #include <iostream> #include <cctype> #include <algorithm> using namespace std; int p1,p2,p3; string s,ret; void add(char left,char right) {string tmp;for(char ch left1;…

FPGA学习篇——Verilog学习1

1 数电基础知识&#xff08;后续可能还会继续补充&#xff09; 1.1 逻辑电平 这张图比较重要以及陌生的应该是高阻态Z&#xff0c;他是一个未知值&#xff0c;不一定为高也不一定为低电平&#xff0c;X是只能高电平和低电平中二选一。 1.2 进制 进制有常见的二进制&#xff0…

虚幻基础17:动画蓝图

能帮到你的话&#xff0c;就给个赞吧 &#x1f618; 文章目录 animation blueprint图表&#xff08;Graph&#xff09;&#xff1a; 编辑动画逻辑。变量&#xff08;Variables&#xff09;&#xff1a; 管理动画参数。函数&#xff08;Functions&#xff09;&#xff1a; 自定义…

java中的锁面试题

1、多线程中 synchronized 锁升级的原理是什么&#xff1f; synchronized 是JVM层面的锁&#xff0c;是 Java 关键字&#xff0c;通过 monitor 对象来完成&#xff0c;synchronized 的实现涉及到锁的升级&#xff0c;具体为无锁、偏向锁、自旋锁、重量级锁 synchronized 锁升级…