当前位置: 首页 > news >正文

1.tree of thought (使用LangChain解决4x4数独问题)

本教程将介绍如何使用LangChain库和chatglm API来解决一个4x4的数独问题。我们将通过以下步骤实现这一目标:

  1. 初始化chatglm 的聊天模型。
  2. 定义数独问题和解决方案。
  3. 创建一个自定义的检查器来验证每一步的思考。
  4. 使用ToTChain来运行整个思考过程。

1. 初始化chatglm4 的聊天模型

首先,我们需要导入langchain_openai库中的ChatOpenAI类,并初始化一个聊天模型实例。

from langchain_openai import ChatOpenAIllm = ChatOpenAI(temperature=1,model="GLM-4-Plus",openai_api_key="your api key",openai_api_base="https://open.bigmodel.cn/api/paas/v4/",max_tokens=512,
)

2. 定义数独问题和解决方案

接下来,我们定义一个4x4的数独问题和其解决方案,并生成问题描述。

sudoku_puzzle = "3,*,*,2|1,*,3,*|*,1,*,3|4,*,*,1"
sudoku_solution = "3,4,1,2|1,2,3,4|2,1,4,3|4,3,2,1"
problem_description = f"""
{sudoku_puzzle}- This is a 4x4 Sudoku puzzle.
- The * represents a cell to be filled.
- The | character separates rows.
- At each step, replace one or more * with digits 1-4.
- There must be no duplicate digits in any row, column or 2x2 subgrid.
- Keep the known digits from previous valid thoughts in place.
- Each thought can be a partial or the final solution.
""".strip()
print(problem_description)

输出结果如下:

3,*,*,2|1,*,3,*|*,1,*,3|4,*,*,1- This is a 4x4 Sudoku puzzle.
- The * represents a cell to be filled.
- The | character separates rows.
- At each step, replace one or more * with digits 1-4.
- There must be no duplicate digits in any row, column or 2x2 subgrid.
- Keep the known digits from previous valid thoughts in place.
- Each thought can be a partial or the final solution.

3. 创建自定义检查器

我们需要创建一个自定义的检查器MyChecker,用于验证每一步的思考是否有效。

import re
from typing import Tuplefrom langchain_experimental.tot.checker import ToTChecker
from langchain_experimental.tot.thought import ThoughtValidityclass MyChecker(ToTChecker):def evaluate(self, problem_description: str, thoughts: Tuple[str, ...] = ()) -> ThoughtValidity:last_thought = thoughts[-1]clean_solution = last_thought.replace(" ", "").replace('"', "")regex_solution = clean_solution.replace("*", ".").replace("|", "\\|")if sudoku_solution in clean_solution:return ThoughtValidity.VALID_FINALelif re.search(regex_solution, sudoku_solution):return ThoughtValidity.VALID_INTERMEDIATEelse:return ThoughtValidity.INVALID

4. 测试检查器

我们可以通过一些断言来测试检查器的功能。

checker = MyChecker()
assert (checker.evaluate("", ("3,*,*,2|1,*,3,*|*,1,*,3|4,*,*,1",))== ThoughtValidity.VALID_INTERMEDIATE
)
assert (checker.evaluate("", ("3,4,1,2|1,2,3,4|2,1,4,3|4,3,2,1",))== ThoughtValidity.VALID_FINAL
)
assert (checker.evaluate("", ("3,4,1,2|1,2,3,4|2,1,4,3|4,3,*,1",))== ThoughtValidity.VALID_INTERMEDIATE
)
assert (checker.evaluate("", ("3,4,1,2|1,2,3,4|2,1,4,3|4,*,3,1",))== ThoughtValidity.INVALID
)

5. 运行ToTChain

最后,我们使用ToTChain来运行整个思考过程,并尝试解决数独问题。

from langchain_experimental.tot.base import ToTChaintot_chain = ToTChain(llm=llm, checker=MyChecker(), k=30, c=5, verbose=True, verbose_llm=False
)
tot_chain.run(problem_description=problem_description)

输出结果如下:

C:\Users\32564\AppData\Local\Temp\ipykernel_5080\1223294212.py:6: LangChainDeprecationWarning: The method `Chain.run` was deprecated in langchain 0.1.0 and will be removed in 1.0. Use :meth:`~invoke` instead.tot_chain.run(problem_description=problem_description)
d:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([1m> Entering new ToTChain chain...[0m
Starting the ToT solve procedure.
[33;1m[1;3mThought: 3,*,*,2|1,*,3,*|*,1,*,3|4,*,*,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([31;1m[1;3m    Thought: 3,1,*,2|1,*,3,*|*,1,*,3|4,*,*,1
[0m[31;1m[1;3m    Thought: 3,*,4,2|1,*,3,*|*,1,*,3|4,*,*,1
[0m[33;1m[1;3m    Thought: 3,*,*,2|1,2,3,*|*,1,*,3|4,*,*,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m        Thought: 3,*,*,2|1,2,3,4|*,1,*,3|4,*,*,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m            Thought: 3,*,*,2|1,2,3,4|2,1,*,3|4,*,*,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                Thought: 3,*,*,2|1,2,3,4|2,1,4,3|4,*,*,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                    Thought: 3,*,*,2|1,2,3,4|2,1,4,3|4,3,*,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                        Thought: 
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                            Thought: 
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                                Thought: 3,*,*,2|1,2,3,4|2,1,4,3|4,3,2,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                                    Thought: 3,*,*,2|1,2,3,4|2,1,4,3|4,3,2,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([31;1m[1;3m                                        Thought: 3,1,*,2|1,2,3,4|2,1,4,3|4,3,2,1
[0m[33;1m[1;3m                                        Thought: 3,4,*,2|1,2,3,4|2,1,4,3|4,3,2,1
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                                            Thought: 
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                                                Thought: 
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([33;1m[1;3m                                                    Thought: 
[0md:\soft\anaconda\envs\langchain\Lib\site-packages\langchain\chains\llm.py:341: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.warnings.warn([32;1m[1;3m                                                        Thought: 3,4,1,2|1,2,3,4|2,1,4,3|4,3,2,1
[0m
[1m> Finished chain.[0m'3,4,1,2|1,2,3,4|2,1,4,3|4,3,2,1'

通过以上步骤,我们成功地使用LangChain解决了一个4x4的数独问题。希望这个教程对你有所帮助!如果有任何问题,欢迎随时提问。

相关文章:

1.tree of thought (使用LangChain解决4x4数独问题)

本教程将介绍如何使用LangChain库和chatglm API来解决一个4x4的数独问题。我们将通过以下步骤实现这一目标: 初始化chatglm 的聊天模型。定义数独问题和解决方案。创建一个自定义的检查器来验证每一步的思考。使用ToTChain来运行整个思考过程。 1. 初始化chatglm4…...

网络基础(4)IP协议

经过之前的学习对传输协议的学习,对于传输协议从系统底层到应用层对于socket套接字的学习已经有了一套完整的理论。 对于网络的层状结构,现在已经学习到了应用层和传输层: 在之前的学习中,通信的双方都只考虑了双方的传输层的东西&#xff0…...

124. 二叉树中的最大路径和【 力扣(LeetCode) 】

文章目录 零、原题链接一、题目描述二、测试用例三、解题思路四、参考代码 零、原题链接 124. 二叉树中的最大路径和 一、题目描述 二叉树中的 路径 被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。同一个节点在一条路径序列中 至多出现一次 。该路径…...

echarts:简单实现默认显示两柱子折线,点击按钮后显示新的柱子

问&#xff1a; 用echarts实现&#xff1a;默认显示两柱子折线&#xff0c;点击“税率”按钮&#xff0c;显示税率柱子&#xff0c;之前的两柱子折线消失 回答&#xff1a; <!DOCTYPE html> <html lang"zh"> <head><meta charset"UTF-8…...

视频里的音频怎么提取出来成单独文件?音频提取照着这些方法做

在数字时代&#xff0c;视频与音频的分离与重组已成为日常需求之一。无论是出于制作背景音乐、保存讲座内容&#xff0c;还是编辑播客素材&#xff0c;提取视频中的音频并将其保存为单独文件都显得尤为重要。视频里的音频怎么提取出来成单独文件&#xff1f;本文将详细介绍几种…...

Excel——宏教程(精简版)

一、宏的简介 1、什么是宏&#xff1f; Excel宏是一种自动化工具&#xff0c;它允许用户录制一系列操作并将其转换为VBA(Visual Basic for Applications)代码。这样&#xff0c;用户可以在需要时执行这些操作&#xff0c;以自动化Excel任务。 2、宏的优点 我们可以利用宏来…...

C++中的std::tuple和std::pair

在C标准库中&#xff0c;std::tuple和std::pair是两种极具实用性的数据结构&#xff0c;它们都具备存储多个元素的功能&#xff0c;但各自有其独特的适用环境和特性。本文旨在深入探讨这两者之间的区别&#xff0c;并阐述在不同应用场景下应如何合理选择使用。 一、基本概念 s…...

引力搜索算法

引力搜索算法过程&#xff0c;包括了初始化、适应度评估、质量计算、加速度计算、更新速度和位置的一些步骤。 import numpy as np import random as rd from math import exp, sqrt import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotli…...

【时间之外】IT人求职和创业应知【35】-RTE三进宫

目录 新闻一&#xff1a;京东工业发布11.11战报&#xff0c;多项倍增数据体现工业经济信心提升 新闻二&#xff1a;阿里云100万核算力支撑天猫双11&#xff0c;弹性计算规模刷新纪录 新闻三&#xff1a;声网CEO赵斌&#xff1a;RTE将成为生成式AI时代AI Infra的关键部分 认知…...

Linux的目录结构

/ ├── bin # Binary - 存放用户可以直接使用的基本二进制可执行文件 ├── sbin # System Binaries - 存放系统管理员专用的二进制可执行文件 ├── usr # Unix System Resources - 存放用户使用的软件和库文件 │ ├── bin # Binary - 用户级应用程序…...

python: generator IDAL and DAL using sql server 2019

其它数据库也是一样的思维方式 create IDAL # encoding: utf-8 # 版权所有 2024 ©涂聚文有限公司 # 许可信息查看&#xff1a;言語成了邀功盡責的功臣&#xff0c;還需要行爲每日來值班嗎 # 描述&#xff1a; # Author : geovindu,Geovin Du 涂聚文. # IDE : P…...

命令执行简单

前言&#xff1a;小迪安全2022第一节反弹shell&#xff0c;小迪用的是两台都是云服务器&#xff0c;没有服务器可以在自己的主机上搭建也是可以的&#xff0c;主机上搭两个网站 思路&#xff1a;生成一个木马文件&#xff0c;下载到本机&#xff0c;然后利用本机上传到目标主机…...

【一句话经验】亚马逊云EC2 ubuntu24.04.1开启ROOT登录Permission denied (publickey)

按照常规的方法SSH登录会一直报错&#xff1a; Permission denied (publickey) 因为亚马逊云的默认配置不是在/etc/ssh/sshd_config&#xff0c;而是在引入的文件里了&#xff0c;所以在instance控制台输入这行命令来解除登录限制&#xff1a; sudo sed -i s/^PasswordAuthe…...

百度智能云千帆大模型平台引领企业创新增长

本文整理自百度世界大会 2024——「智能跃迁 产业加速」论坛的同名演讲。 更多大会演讲内容&#xff0c;请访问&#xff1a; https://baiduworld.baidu.com 首先&#xff0c;跟大家分享一张图&#xff0c;这个是我们目前大模型应用落地的场景分布。可以看到&#xff0c;大模型…...

【Linux】深入理解GCC/G++编译流程及库文件管理

目录 1.背景知识 2.gcc/g如何完成编译 (1) 预处理&#xff08;进行宏替换&#xff09; (2) 编译&#xff08;生成汇编&#xff09; (3) 汇编&#xff08;生成机器可识别代码&#xff09; (4) 链接&#xff08;生成可执行文件或库文件&#xff09; (5) 总结 (6) 函数库 …...

【Unity基础】对比Unity中两种粒子系统

在Unity中&#xff0c;Particle System和Visual Effect Graph (VFX) 都是用于创建粒子效果的工具&#xff0c;但它们的设计目标、使用场景和功能特点有所不同。以下是详细对比&#xff1a; 1. Particle System 特点 传统粒子系统&#xff0c;Unity自带的模块化粒子特效工具。…...

琐碎笔记——pytest实现前置、后置、参数化、跳过用例执行以及重试

pytest的fixture中文介绍可参考&#xff08;不过文档稍微有点老&#xff09;&#xff1a; https://www.osgeo.cn/pytest/fixture.html#what-fixtures-are pytest各个作用域的fixture scope “function” 可作用于每个用例 fixture使用的声明放在类定义前面&#xff0c;类中的…...

C# 深层副本与浅层副本 深拷贝与浅拷贝

C# 深层副本与浅层副本 数据复制是编程中的重要任务。 对象是 OOP 中的复合数据类型。 对象中的成员字段可以按值或按引用存储。 可以以两种方式执行复制。 浅表副本将所有值和引用复制到新实例中。 引用所指向的数据不会被复制&#xff1b; 仅指针被复制。 新的引用指向原始…...

CH06_Lambda表达式

第6章&#xff1a;Lambda表达式 本章目标 为什么要学习C#编程语言 了解C#相关常识 C#开发工具Visual Studio安装 掌握C#程序的开发步骤 掌握C#的注释 掌握C#的常用转义符 本章内容 lambda表达式演变史 C# 匿名函数的演变历史可以追溯到 C# 语言的不同版本&#xff0c;…...

大模型本地部署实践:Ollama+Open-WebUI(MacOS)

目录 什么是Ollama Ollama安装 对话界面可视化&#xff1f;Open-WebUI&#xff01; 安装Open-WebUI 什么是Ollama Ollama是一个为简化大语言模型本地部署与交互的开源框架。它提供了用户友好的接口&#xff0c;帮助开发者和模型爱好者在没有依赖外部API的基础上高效地运行、…...

Python|GIF 解析与构建(5):手搓截屏和帧率控制

目录 Python&#xff5c;GIF 解析与构建&#xff08;5&#xff09;&#xff1a;手搓截屏和帧率控制 一、引言 二、技术实现&#xff1a;手搓截屏模块 2.1 核心原理 2.2 代码解析&#xff1a;ScreenshotData类 2.2.1 截图函数&#xff1a;capture_screen 三、技术实现&…...

OpenLayers 可视化之热力图

注&#xff1a;当前使用的是 ol 5.3.0 版本&#xff0c;天地图使用的key请到天地图官网申请&#xff0c;并替换为自己的key 热力图&#xff08;Heatmap&#xff09;又叫热点图&#xff0c;是一种通过特殊高亮显示事物密度分布、变化趋势的数据可视化技术。采用颜色的深浅来显示…...

Unity3D中Gfx.WaitForPresent优化方案

前言 在Unity中&#xff0c;Gfx.WaitForPresent占用CPU过高通常表示主线程在等待GPU完成渲染&#xff08;即CPU被阻塞&#xff09;&#xff0c;这表明存在GPU瓶颈或垂直同步/帧率设置问题。以下是系统的优化方案&#xff1a; 对惹&#xff0c;这里有一个游戏开发交流小组&…...

前端导出带有合并单元格的列表

// 导出async function exportExcel(fileName "共识调整.xlsx") {// 所有数据const exportData await getAllMainData();// 表头内容let fitstTitleList [];const secondTitleList [];allColumns.value.forEach(column > {if (!column.children) {fitstTitleL…...

土地利用/土地覆盖遥感解译与基于CLUE模型未来变化情景预测;从基础到高级,涵盖ArcGIS数据处理、ENVI遥感解译与CLUE模型情景模拟等

&#x1f50d; 土地利用/土地覆盖数据是生态、环境和气象等诸多领域模型的关键输入参数。通过遥感影像解译技术&#xff0c;可以精准获取历史或当前任何一个区域的土地利用/土地覆盖情况。这些数据不仅能够用于评估区域生态环境的变化趋势&#xff0c;还能有效评价重大生态工程…...

大学生职业发展与就业创业指导教学评价

这里是引用 作为软工2203/2204班的学生&#xff0c;我们非常感谢您在《大学生职业发展与就业创业指导》课程中的悉心教导。这门课程对我们即将面临实习和就业的工科学生来说至关重要&#xff0c;而您认真负责的教学态度&#xff0c;让课程的每一部分都充满了实用价值。 尤其让我…...

Unity UGUI Button事件流程

场景结构 测试代码 public class TestBtn : MonoBehaviour {void Start(){var btn GetComponent<Button>();btn.onClick.AddListener(OnClick);}private void OnClick(){Debug.Log("666");}}当添加事件时 // 实例化一个ButtonClickedEvent的事件 [Formerl…...

【前端异常】JavaScript错误处理:分析 Uncaught (in promise) error

在前端开发中&#xff0c;JavaScript 异常是不可避免的。随着现代前端应用越来越多地使用异步操作&#xff08;如 Promise、async/await 等&#xff09;&#xff0c;开发者常常会遇到 Uncaught (in promise) error 错误。这个错误是由于未正确处理 Promise 的拒绝&#xff08;r…...

Unity中的transform.up

2025年6月8日&#xff0c;周日下午 在Unity中&#xff0c;transform.up是Transform组件的一个属性&#xff0c;表示游戏对象在世界空间中的“上”方向&#xff08;Y轴正方向&#xff09;&#xff0c;且会随对象旋转动态变化。以下是关键点解析&#xff1a; 基本定义 transfor…...

Java求职者面试指南:Spring、Spring Boot、Spring MVC与MyBatis技术解析

Java求职者面试指南&#xff1a;Spring、Spring Boot、Spring MVC与MyBatis技术解析 一、第一轮基础概念问题 1. Spring框架的核心容器是什么&#xff1f;它的作用是什么&#xff1f; Spring框架的核心容器是IoC&#xff08;控制反转&#xff09;容器。它的主要作用是管理对…...