gitweixin
  • 首页
  • 小程序代码
    • 资讯读书
    • 工具类
    • O2O
    • 地图定位
    • 社交
    • 行业软件
    • 电商类
    • 互联网类
    • 企业类
    • UI控件
  • 大数据开发
    • Hadoop
    • Spark
    • Hbase
    • Elasticsearch
    • Kafka
    • Flink
    • 数据仓库
    • 数据挖掘
    • flume
    • Kafka
    • Hive
    • shardingsphere
    • solr
  • 开发博客
    • Android
    • php
    • python
    • 运维
    • 技术架构
    • 数据库
  • 程序员网赚
  • bug清单
  • 量化投资
  • 在线查询工具
    • 去行号
    • 在线时间戳转换工具
    • 免费图片批量修改尺寸在线工具
    • SVG转JPG在线工具

分类归档python

精品微信小程序开发门户,代码全部亲测可用

  • 首页   /  
  • 分类归档: "python"
python 6月 9,2025

详解Python当中的pip常用命令

引言:Python包管理的重要性与pip的地位

Python 包管理:有了 pip,开发效率直接起飞!

在 Python 的世界里,包管理就跟盖房子打地基一样重要。想象一下,你要用 Python 写个爬虫,需要用到 requests、BeautifulSoup4 这些库,或者要做数据分析,pandas、numpy 肯定是少不了的。如果没有一个好用的包管理工具,一个个手动下载、安装、管理依赖,那酸爽,谁用谁知道!

所以,pip 就应运而生了。它就像 Python 的御用管家,专门负责包的安装、卸载、升级等等。有了它,我们就可以把更多精力放在写代码上,而不是跟那些烦人的依赖问题死磕。

pip 其实也挺有历史的,它最早可以追溯到 2008 年,后来慢慢发展壮大,现在已经成了 Python 的标配。毫不夸张地说,pip 就是 Python 生态系统中最重要的工具之一。它简单易用,功能强大,几乎所有的 Python 开发者都在用它。

pip 安装与配置:磨刀不误砍柴工

想要用 pip,首先得把它装好。不同操作系统安装 pip 的方式略有差异,但都大同小异,跟着步骤走,保证没问题!

1. Windows 系统

Windows 系统通常自带 Python,但可能没有 pip。别慌,我们有办法:

* 确认 Python 是否安装: 在命令行输入 python –version,如果能看到 Python 的版本号,说明已经安装了。
* 下载 get-pip.py: 打开浏览器,访问 [https://bootstrap.pypa.io/get-pip.py](https://bootstrap.pypa.io/get-pip.py),把这个文件保存到你的电脑上,比如 D 盘根目录。
* 运行 get-pip.py: 打开命令行,切换到 get-pip.py 所在的目录(cd D:\),然后运行 python get-pip.py。


cd D:\
python get-pip.py

等待安装完成,看到 “Successfully installed pip…” 就说明安装成功了。
* 配置环境变量: 为了方便使用 pip,需要把 Python 的 Scripts 目录添加到环境变量中。找到 Python 的安装目录,里面有个 Scripts 目录,把它的路径复制下来。然后在系统设置里找到环境变量,编辑 Path 变量,把 Scripts 目录的路径添加进去。

比如我的 Python 安装在 C:\Python39,那么 Scripts 目录就是 C:\Python39\Scripts。

注意: 添加完环境变量后,需要重启命令行窗口才能生效。
* 验证安装: 重新打开命令行,输入 pip –version,如果能看到 pip 的版本号,说明安装成功了。

2. macOS 系统

macOS 系统通常也自带 Python,但版本可能比较老。建议安装 Homebrew,然后用 Homebrew 安装 Python:

* 安装 Homebrew: 如果你还没有安装 Homebrew,打开终端,运行以下命令:


/bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)”

按照提示操作即可。
* 安装 Python: 安装完 Homebrew 后,运行以下命令安装 Python 3:


brew install python3

* 验证安装: 安装完成后,运行 python3 –version 和 pip3 –version,确认 Python 和 pip 都已成功安装。

3. Linux 系统

Linux 系统安装 pip 的方式有很多种,这里介绍一种比较通用的方法:

* 更新软件包列表: 打开终端,运行以下命令:


sudo apt update

* 安装 pip: 运行以下命令安装 pip:


sudo apt install python3-pip

* 验证安装: 安装完成后,运行 pip3 –version,确认 pip 已成功安装。

配置 pip 镜像源

由于国内访问 PyPI(Python Package Index,官方的 Python 包仓库)速度比较慢,所以建议配置 pip 的镜像源,这样可以大大提高下载速度。

* 临时使用镜像源: 在使用 pip 安装包的时候,可以加上 -i 参数指定镜

pip安装与配置:为Python之旅铺平道路

像源:


pip install 包名 -i 镜像源地址

比如,使用清华大学的镜像源安装 requests 库:


pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple

* 永久配置镜像源: 为了避免每次都手动指定镜像源,可以永久配置 pip 的镜像源。

* Windows 系统: 在 %APPDATA%\pip 目录下创建一个 pip.ini 文件(如果目录不存在,手动创建),内容如下:

ini
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn

* macOS 和 Linux 系统: 在 ~/.pip 目录下创建一个 pip.conf 文件(如果目录不存在,手动创建),内容如下:

ini
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = pypi.tuna.tsinghua.edu.cn

常用镜像源推荐

* 清华大学: https://pypi.tuna.tsinghua.edu.cn/simple
* 阿里云: https://mirrors.aliyun.com/pypi/simple/
* 中国科技大学: https://pypi.mirrors.ustc.edu.cn/simple/
* 豆瓣: https://pypi.doubanio.com/simple/

选择一个你喜欢的镜像源,配置好 pip,就可以愉快地安装各种 Python 包啦!

pip 常用命令详解:玩转你的 Python 依赖

pip 的命令其实不多,但个个都很有用。掌握了这些命令,你就可以轻松管理你的 Python 依赖,再也不用担心包的版本冲突、安装失败等问题了。

1. pip install:安装包

这是 pip 最常用的命令,用于安装指定的 Python 包。

* 语法: pip install 包名

比如,安装 requests 库:


pip install requests

pip 会自动从 PyPI 下载 requests 库,并安装到你的 Python 环境中。
* 安装指定版本的包: 如果你需要安装指定版本的包,可以使用 == 符号指定版本号:


pip install requests==2.25.1

这样就会安装 requests 库的 2.25.1 版本。
* 安装多个包: 你可以一次性安装多个包,只需要把包名用空格隔开:


pip install requests beautifulsoup4 pandas

* 从 requirements 文件安装: 有时候,你的项目有很多依赖,一个个手动安装太麻烦了。你可以把所有依赖写到一个 requirements.txt 文件中,然后用 pip 一次性安装:


pip install -r requirements.txt

requirements.txt 文件的格式很简单,每行一个包名,可以指定版本号,也可以不指定:

requests==2.25.1
beautifulsoup4
pandas>=1.2.0

这种方式非常适合管理项目的依赖,可以保证所有开发者使用相同的依赖版本。

2. pip uninstall:卸载包

用于卸载指定的 Python 包。

* 语法: pip uninstall 包名

比如,卸载 requests 库:


pip uninstall requests

pip 会从你的 Python 环境中移除 requests 库。
* 卸载多个包: 同样可以一次性卸载多个包:


pip uninstall requests beautifulsoup4 pandas

* 自动确认卸载: 卸载包的时候,pip 会提示你确认是否卸载。如果你不想每次都手动确认,可以加上 -y 参数:


pip uninstall requests -y

3. pip update或pip install –upgrade:升级包

用于升级指定的 Python 包到最新版本。

* 语法: pip install –upgrade 包名

比如,升级 requests 库:


pip install –upgrade requests

pip 会检查 requests 库是否有新版本,如果有,就下载并安装最新版本。
* 升级所有包: 如果你想升级所有已安装的包,可以使用 pip list –outdated 命令查看哪些包需要升级,然后使用以下命令升级所有包:


pip install –upgrade $(pip list –outdated | awk ‘{print $1}’ | tail -n +3)

这条命令有点长,解释一下:

* pip list –outdated:列出所有需要升级的包。
* awk ‘{print $1}’:提取第一列,也就是包名。
* tail -n +3:去掉前两行(标题行)。
* $(…):把命令的输出作为参数传递给 pip install –upgrade。

注意: 升级所有包可能会导致一些兼容性问题,建议谨慎使用。

4. pip search:搜索包

用于在 PyPI 上搜索指定的 Python 包。

* 语法: pip search 关键词

比如,搜索包含 “image” 关键词的包:


pip search image

pip 会在 PyPI 上搜索包含 “image” 关键词的包,并显示搜索结果。

注意: pip search 命令在较新版本的 pip 中已经被移除了,可以使用 pip install searchpackages 来安装 searchpackages 插件,然后使用 searchpackages 关键词 命令进行搜索。
或者可以考虑直接在 PyPI 官网([https://pypi.org/](https://pypi.org/))上搜索。

5. pip show:查看包信息

用于查看已安装的 Python 包的详细信息。

* 语法: pip show 包名

比如,查看 requests 库的信息:


pip show requests

pip 会显示 requests 库的版本号、作者、描述、依赖等信息。

6. pip list:列出已安装的包

用于列出所有已安装的 Python 包。

* 语法: pip list

pip 会列出所有已安装的 Python 包,并显示版本号。

* 列出可升级的包: 使用 pip list –outdated 命令可以列出所有需要升级的包。

7. pip freeze:生成 requirements 文件

用于生成 requirements.txt 文件,记录当前 Python 环境中的所有依赖。

* 语法: pip freeze > requirements.txt

这条命令会将当前 Python 环境中的所有依赖及其版本号写入到 requirements.txt 文件中。

这个命令非常有用,可以方便地复制项目的依赖到其他环境。

一些小技巧

* 使用 tab 键自动补全: 在命令行输入 pip 命令的时候,可以使用 tab 键自动补全包名,可以节省很多时间。
* 查看 pip 帮助: 如果你忘记了 pip 命令的用法,可以使用 pip –help 命令查看 pip 的帮助信息。
* 使用 -h 参数查看命令的帮助: 比如,查看 pip install 命令的帮助信息,可以使用 pip install -h 命令。

掌握了这些 pip 常用命令,你就可以轻松管理你的 Python 依赖,让你的 Python 开发更加高效!

pip 进阶技巧:更上一层楼

pip 除了基本的安装、卸载、升级功能,还有一些高级用法,可以帮助你更好地管理 Python 项目的依赖,提升开发效率。

1. 使用虚拟环境

虚拟环境是一个独立的 Python 运行环境,可以隔离不同项目的依赖,避免版本冲突。

* 创建虚拟环境: 使用 venv 模块创建虚拟环境:


python3 -m venv 虚拟环境名称

比如,创

pip进阶技巧:提升你的Python开发效率

建一个名为 “myenv” 的虚拟环境:


python3 -m venv myenv

会在当前目录下创建一个名为 “myenv” 的目录,里面包含了虚拟环境的 Python 解释器、pip 等工具。
* 激活虚拟环境:

* Windows 系统:


myenv\Scripts\activate

* macOS 和 Linux 系统:


source myenv/bin/activate

激活虚拟环境后,命令行前面会显示虚拟环境的名称,表示你已经进入了虚拟环境。
* 在虚拟环境中安装包: 在虚拟环境中安装包,只会安装到当前虚拟环境中,不会影响到全局的 Python 环境。


pip install requests

* 退出虚拟环境:


deactivate

退出虚拟环境后,命令行前面不再显示虚拟环境的名称。

使用虚拟环境可以避免不同项目之间的依赖冲突,保证项目的稳定性。建议每个 Python 项目都使用独立的虚拟环境。

2. 使用 pipenv 或 poetry

pipenv 和 poetry 是更现代的 Python 包管理工具,它们在 pip 的基础上做了很多改进,提供了更强大的功能。

* pipenv: pipenv 是 Kenneth Reitz(requests 库的作者)开发的,它集成了虚拟环境管理和依赖管理,可以自动创建和管理虚拟环境,并使用 Pipfile 文件来记录项目的依赖。

* 安装 pipenv:


pip install pipenv

* 创建虚拟环境: 在项目目录下运行 pipenv shell 命令,会自动创建虚拟环境,并激活。


pipenv shell

* 安装包: 使用 pipenv install 包名 命令安装包,会自动把包添加到 Pipfile 文件中。


pipenv install requests

* 生成 requirements.txt 文件:


pipenv lock -r > requirements.txt

* poetry: poetry 是另一种流行的 Python 包管理工具,它使用 pyproject.toml 文件来管理项目的依赖,并提供了更强大的依赖解析和版本控制功能。

* 安装 poetry:


pip install poetry

* 创建项目:


poetry new 项目名称

* 添加依赖:


poetry add requests

* 安装依赖:


poetry install

pipenv 和 poetry 都是非常优秀的 Python 包管理工具,可以根据自己的喜好选择使用。它们可以帮助你更好地管理项目的依赖,提高开发效率。

3. 自定义 pip 配置

pip 允许你自定义一些配置,可以改变 pip 的行为。

* 配置文件: pip 的配置文件位于:

* Windows 系统: %APPDATA%\pip\pip.ini
* macOS 和 Linux 系统: ~/.pip/pip.conf

* 常用配置项:

* index-url:指定 PyPI 的地址。
* trusted-host:指定可信任的 PyPI 主机。
* timeout:指定超时时间。
* retries:指定重试次数。

比如,设置超时时间为 60 秒,重试次数为 3 次:

ini
[global]
timeout = 60
retries = 3

通过自定义 pip 配置,可以更好地控制 pip 的行为,满足自己的需求。

掌握这些 pip 进阶技巧,你就可以更好地管理 Python 项目的依赖,提高开发效率,成为 Python 开发高手!

作者 east
python 4月 19,2025

解决’latin-1′ codec can’t encode characters in position 0-6: ordinal not in range(256)

这个错误主要是由于 HTTP 请求头中的某些字段中包含中文字符,而 HTTP 头部默认要求使用 ISO‑8859‑1(latin‑1)编码,导致无法编码中文字符。也就是说,错误并非发生在请求的 JSON 负载(payload)上,而是在请求头中,比如你设置的 "X-Title": "面试题问答助手" 字段。

以下是一些解决方案和建议:


1. 移除或修改包含非 ASCII 字符的 header

推荐方案: 如果这个 header 不是必需的,可以直接移除或者使用纯 ASCII 字符代替,例如:

self.headers = {     "Authorization": f"Bearer {self.api_key}",     "Content-Type": "application/json",     "HTTP-Referer": "https://your-website.com",     # 修改为ASCII字符     "X-Title": "InterviewQA Assistant" } 

如果这个 header 是必须的,而不能去掉,你可以考虑对其进行适当的编码(比如使用 RFC 2047 编码格式),不过这会让服务器端解析时复杂一些。


2. 使用 RFC 2047 对 header 进行编码

RFC 2047 允许你在邮件或 HTTP header 中使用非 ASCII 字符,格式类似于:

=?utf-8?B?base64_encoded_text?= 

例如,对于 "面试题问答助手" 你可以先用 Base64 编码:

import base64 title = "面试题问答助手" title_encoded = base64.b64encode(title.encode('utf-8')).decode('ascii') encoded_header = f"=?utf-8?B?{title_encoded}?=" 

然后将 header 设置为:

self.headers = {     "Authorization": f"Bearer {self.api_key}",     "Content-Type": "application/json",     "HTTP-Referer": "https://your-website.com",     "X-Title": encoded_header } 

注意: 这种方法要求服务器端能够正确解析 RFC 2047 编码的 header,否则可能会导致其它问题。


3. 总结

  • 问题根源: HTTP 请求头默认使用 ISO‑8859‑1 编码,导致中文字符无法直接编码。
  • 直接解决: 最简单的办法是确保所有请求头的值都是 ASCII 字符,如果不需要特别的中文描述,可以直接替换掉中文内容。
  • 高级处理: 如需保留中文描述,则可以采用 RFC 2047 编码,但这需要双方都支持并正确处理这种编码格式。

修改后,重新运行代码应该就不会出现 “’latin-1′ codec can’t encode characters” 的错误了。

作者 east
python 1月 14,2025

如何利用大模型(ChatGPT)辅助编写selenium代码

方法1:提出需求让大模型编写

例如要编写selenium.webdriver 如何执行Esc返回键的功能 ,由于对这方面不太熟悉,如果查看官方文档,自己一步步试,可能要花费几个小时,可以把明确需求提示给大模型:

方法2:对网页某个元素进行操作

有些网页很复杂,需要对某个元素进行操作,不知代码如何写。可以先在网页上检查,在元素的页面找到要操作元素的定位,然后复制这些前端代码。告诉大模型具体需求,并找出这个元素进行操作。

例如下面的例子:

大模型提问:

selenium.webdriver如何关闭下面的组件:<div class=”container-SfTLY8″><div><div class=”coding-skill-title-container-rWvOE0 coding-skill-title-container gray-WtixXh”><div class=”skill-title-content-OwSt2V”><div class=”icon-wrapper-qgAPoM”><span role=”img” class=”semi-icon semi-icon-default”><svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” fill=”none” viewBox=”0 0 24 24″><path fill=”currentColor” fill-rule=”evenodd” d=”M13.113 2.266a.936.936 0 0 1 .797 1.057l-2.476 17.614a.936.936 0 0 1-1.854-.26l2.476-17.615a.936.936 0 0 1 1.057-.796M6.811 6.744a.936.936 0 0 1 0 1.324l-3.55 3.55 3.55 3.551a.936.936 0 1 1-1.324 1.324l-4.213-4.212a.936.936 0 0 1 0-1.325l4.213-4.212a.936.936 0 0 1 1.324 0m15.447 4.213c.357.356.365.93.025 1.297a6.05 6.05 0 0 0-2.377-1.001l-3.185-3.185a.936.936 0 1 1 1.324-1.324zm-3.47 10.491a.48.48 0 0 0 .48-.425c.225-1.341.423-2.03.849-2.457.425-.426 1.11-.624 2.445-.849a.485.485 0 0 0 .438-.48.48.48 0 0 0-.44-.48c-1.332-.227-2.018-.425-2.443-.851-.426-.427-.624-1.115-.849-2.455a.48.48 0 0 0-.48-.428.49.49 0 0 0-.481.426c-.226 1.341-.423 2.03-.85 2.457-.424.426-1.108.624-2.44.85a.48.48 0 0 0-.442.481c0 .26.199.448.439.48 1.335.225 2.02.418 2.444.842.426.425.623 1.114.849 2.466.04.24.23.423.482.423″ clip-rule=”evenodd”></path></svg></span></div><div class=”content-yHNqH7″><div class=”title-SlDAMe”>AI 编程</div></div><div class=”middle-jf0OPw addon-before-SEgdLZ”><div class=”flex items-center”></div></div><div class=”right-gyA7ZQ”><div><div class=”close-btn-wrapper-HINk0h” data-testid=”skill_header_close_button” tabindex=”0″ aria-describedby=”bkks5ef” data-popupid=”bkks5ef”><span role=”img” class=”semi-icon semi-icon-default close-btn-svg-_cKb_A”><svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” fill=”none” viewBox=”0 0 24 24″><path fill=”currentColor” d=”M5.762 18.238a.8.8 0 0 1-.234-.404 1 1 0 0 1 0-.468.85.85 0 0 1 .234-.396l4.953-4.974L5.762 7.03a.8.8 0 0 1-.226-.396 1 1 0 0 1 0-.468.84.84 0 0 1 .226-.404.86.86 0 0 1 .412-.234 1 1 0 0 1 .467 0q.233.057.404.226l4.961 4.966 4.953-4.966a.76.76 0 0 1 .404-.226.95.95 0 0 1 .46 0 .9.9 0 0 1 .419.234.84.84 0 0 1 .226.404.86.86 0 0 1 0 .468.9.9 0 0 1-.226.404l-4.953 4.958 4.953 4.966a.9.9 0 0 1 .226.412.95.95 0 0 1 0 .46.84.84 0 0 1-.226.404.86.86 0 0 1-.412.234 1 1 0 0 1-.467 0 .84.84 0 0 1-.404-.226l-4.953-4.966-4.961 4.966a.84.84 0 0 1-.404.226 1 1 0 0 1-.467 0 .86.86 0 0 1-.412-.234″></path></svg></span></div></div></div></div></div></div><div class=”editor-container-Ikyh9n”><div role=”textbox” aria-multiline=”true” autocomplete=”off” data-testid=”chat_input_input” dir=”ltr” class=”container-lGWhkH editor-h8aPs4″ data-slate-editor=”true” data-slate-node=”value” contenteditable=”true” zindex=”-1″ style=”position: relative; white-space: pre-wrap; overflow-wrap: break-word; min-height: 28px;”><div data-slate-node=”element” class=”paragraph-GvBwll”><span data-slate-node=”text”><span data-slate-leaf=”true” style=”padding-left: 0.1px;”><span data-slate-placeholder=”true” contenteditable=”false” style=”position: absolute; top: 0px; pointer-events: none; width: 100%; max-width: 100%; display: block; opacity: 0.333; user-select: none; text-decoration: none;”>粘贴代码或描述你的问题</span><span data-slate-zero-width=”n” data-slate-length=”0″><br></span></span></span></div></div></div><div><div class=”skill-bottom-X9vRY0″><div class=”flex-1 flex”><div class=”btn-vRbV5q mr-10″><div class=”upload-btn-wrapper-h2mSyQ”><div class=”” aria-haspopup=”true” tabindex=”0″ aria-describedby=”15ykpw2″ data-popupid=”15ykpw2″><button class=”semi-button semi-button-primary samantha-button-aiwXEk tertiary-kH1mvr medium-UIYozi icon-a2WxRL semi-button-with-icon” type=”button” aria-disabled=”false”><span class=”semi-button-content”><span role=”img” class=”semi-icon semi-icon-default !text-16 text-s-color-text-secondary”><svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” fill=”none” viewBox=”0 0 24 24″><path fill=”currentColor” fill-rule=”evenodd” d=”M9.035 15.956a1.29 1.29 0 0 0 1.821-.004l6.911-6.911a3.15 3.15 0 0 0 0-4.457l-.034-.034a3.15 3.15 0 0 0-4.456 0l-7.235 7.234a5.031 5.031 0 0 0 7.115 7.115l6.577-6.577a1.035 1.035 0 0 1 1.463 1.464l-6.576 6.577A7.1 7.1 0 0 1 4.579 10.32l7.235-7.234a5.22 5.22 0 0 1 7.382 0l.034.034a5.22 5.22 0 0 1 0 7.383l-6.91 6.91a3.36 3.36 0 0 1-4.741.012l-.006-.005-.012-.011a3.346 3.346 0 0 1 0-4.732L12.76 7.48a1.035 1.035 0 0 1 1.464 1.463l-5.198 5.198a1.277 1.277 0 0 0 0 1.805z” clip-rule=”evenodd”></path></svg></span><span class=”semi-button-content-right” x-semi-prop=”children”><span style=”color: rgba(0, 0, 0, 0.8);”>上传文件</span></span></span></button></div></div><input type=”file” multiple=”” class=”input-Er4iXs”><input type=”file” directory=”true” mozdirectory=”true” webkitdirectory=”true” class=”input-Er4iXs”></div><div class=”btn-vRbV5q”><button class=”semi-button semi-button-primary samantha-button-aiwXEk tertiary-kH1mvr medium-UIYozi icon-a2WxRL upload-github-svg-oE359X semi-button-with-icon” type=”button” aria-disabled=”false”><span class=”semi-button-content”><span role=”img” class=”semi-icon semi-icon-default text-20 text-s-color-text-secondary”><svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” fill=”none” viewBox=”0 0 24 24″><path fill=”currentColor” d=”M18.608 5.027a.83.83 0 0 0-.444-.459c-.17-.073-1.674-.65-3.912.765H9.748c-2.241-1.418-3.744-.838-3.912-.765a.84.84 0 0 0-.444.459c-.512 1.293-.353 2.665-.154 3.455-.616.823-.738 1.586-.738 2.685 0 3.474 2.483 4.45 4.428 4.81a3.7 3.7 0 0 0-.254.909 1 1 0 0 0-.007.114v.754c-.381-.08-.801-.233-1.078-.51-.939-.94-1.91-1.91-3.089-1.91V17c.488 0 1.277.788 1.91 1.422.997.997 2.522 1.08 2.997 1.08q.092 0 .127-.003a.834.834 0 0 0 .8-.832v-1.604c.083-.483.394-.969.545-1.1a.833.833 0 0 0-.451-1.457c-2.699-.308-4.261-.954-4.261-3.34 0-1.037.11-1.381.616-1.939a.84.84 0 0 0 .156-.875c-.094-.232-.367-1.278-.127-2.295.404-.031 1.17.089 2.221.8.137.093.3.143.467.143h5c.167 0 .33-.05.467-.143 1.056-.714 1.816-.816 2.22-.804.241 1.02-.03 2.066-.125 2.299a.83.83 0 0 0 .157.877c.505.553.614.898.614 1.938 0 2.394-1.561 3.037-4.259 3.338a.834.834 0 0 0-.451 1.46c.386.332.544.633.544 1.035v2.5h1.666V17c0-.4-.076-.744-.19-1.038 1.895-.373 4.357-1.39 4.357-4.795 0-1.101-.122-1.866-.738-2.686.2-.79.357-2.159-.154-3.454″></path></svg></span><span class=”semi-button-content-right” x-semi-prop=”children”><span>引入 GitHub 仓库</span></span></span></button></div></div><div class=””><div class=”container-G7o3Dk”><div class=””><div class=”flex items-center”><div class=”left-area-UbioLp”><div class=”flex gap-8″><div class=”container-KtUMxI”><div data-testid=”asr_btn” class=”mic-container-uZJexl cursor-pointer” tabindex=”0″ aria-describedby=”30rnba0″ data-popupid=”30rnba0″><span role=”img” class=”semi-icon semi-icon-default icon-mic-NfScWD”><svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” fill=”none” viewBox=”0 0 24 24″><path fill=”currentColor” fill-rule=”evenodd” d=”M12 2.5A2.5 2.5 0 0 1 14.5 5v6a2.5 2.5 0 0 1-5 0V5A2.5 2.5 0 0 1 12 2.5M7.5 5a4.5 4.5 0 0 1 9 0v6a4.5 4.5 0 1 1-9 0zm-2 4a1 1 0 0 0-2 0v2c0 4.213 3.26 7.928 7.5 8.44V21H7.3a1 1 0 1 0 0 2h9.4a1 1 0 1 0 0-2H13v-1.56c4.24-.512 7.5-4.227 7.5-8.44V9a1 1 0 1 0-2 0v2c0 3.46-2.915 6.5-6.5 6.5S5.5 14.46 5.5 11z” clip-rule=”evenodd”></path></svg></span></div></div></div></div><div class=”splitLineWrapper-bVwctz”><div class=”splitLine-wCW4fL”></div></div><div class=”right-area-YZHkCa”><div class=”container-F3bkhm !hidden” data-testid=”chat_input_local_break_button” tabindex=”0″ aria-describedby=”vkk33zj” data-popupid=”vkk33zj”><span role=”img” class=”semi-icon semi-icon-default icon-eivsqq”><svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” fill=”none” viewBox=”0 0 24 24″><path fill=”currentColor” fill-rule=”evenodd” d=”M12 23c6.075 0 11-4.925 11-11S18.075 1 12 1 1 5.925 1 12s4.925 11 11 11m0-20a9 9 0 1 1 0 18 9 9 0 0 1 0-18m-2 5.5A1.5 1.5 0 0 0 8.5 10v4a1.5 1.5 0 0 0 1.5 1.5h4a1.5 1.5 0 0 0 1.5-1.5v-4A1.5 1.5 0 0 0 14 8.5z” clip-rule=”evenodd”></path></svg></span></div><div class=”container-e6cFq5 send-btn-wrapper coding-send-msg-button”><span class=”” tabindex=”0″ aria-describedby=”5u16go3″ data-popupid=”5u16go3″ style=”display: inline-block; cursor: not-allowed;”><button disabled=”” id=”flow-end-msg-send” aria-disabled=”true” aria-label=”发送” data-testid=”chat_input_send_button” class=”semi-button semi-button-disabled semi-button-primary-disabled send-btn-S_MjUh semi-button-with-icon semi-button-with-icon-only” type=”button” style=”pointer-events: none;”><span class=”semi-button-content”><span role=”img” class=”semi-icon semi-icon-default”><svg xmlns=”http://www.w3.org/2000/svg” width=”1em” height=”1em” fill=”currentColor” viewBox=”0 0 28 28″><path d=”M14.007 28q-2.881 0-5.418-1.11a14.3 14.3 0 0 1-4.453-3.026 14.5 14.5 0 0 1-3.04-4.453Q0 16.875 0 13.993q0-2.868 1.095-5.404Q2.191 6.053 4.121 4.12A14.5 14.5 0 0 1 8.59 1.095Q11.124 0 13.993 0t5.404 1.095q2.536 1.096 4.467 3.026A14.2 14.2 0 0 1 26.89 8.59Q28 11.124 28 13.993q0 2.881-1.095 5.418a14.3 14.3 0 0 1-3.027 4.453 14.2 14.2 0 0 1-4.467 3.026Q16.876 28 14.007 28m.015-6.917q.518 0 .835-.317.332-.332.332-.836v-6.816l-.13-2.969 1.37 1.672 1.599 1.643q.316.33.807.331.475 0 .792-.303a.99.99 0 0 0 .332-.763q0-.475-.332-.807L14.944 7.22q-.433-.447-.922-.447-.476 0-.908.447L8.43 11.918q-.317.317-.317.807 0 .461.317.763.318.303.778.303.49 0 .807-.331l1.629-1.658 1.326-1.642-.116 2.954v6.816q0 .504.332.836.331.317.836.317″></path></svg></span></span></button></span></div></div></div></div></div></div></div></div></div>

大模型回答:

要使用 Selenium WebDriver 关闭特定的组件(例如,带有类名 .close-btn-wrapper-HINk0h 的关闭按钮),可以通过定位该元素并模拟点击操作来实现。以下是详细的步骤和示例代码:

步骤:

  1. 导入必要的模块:
    • webdriver 用于控制浏览器。
    • By 用于元素定位。
    • time (可选)用于添加延时,以确保元素已加载。
  2. 初始化 WebDriver:
    • 以 Chrome 为例,确保已安装相应的 WebDriver 并配置好环境。
  3. 打开目标网页:
    • 使用 driver.get() 方法导航到目标 URL。
  4. 定位关闭按钮:
    • 使用合适的定位策略(如 By.CLASS_NAME、By.CSS_SELECTOR 或 By.XPATH)来定位关闭按钮。
  5. 模拟点击操作:
    • 使用 click() 方法点击关闭按钮,以关闭组件。
  6. 关闭浏览器:
    • 使用 driver.quit() 方法关闭浏览器窗口并释放资源。

示例代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# 初始化 WebDriver(以 Chrome 为例)
driver = webdriver.Chrome()

try:
    # 打开目标网页
    driver.get('https://www.example.com')

    # 等待页面加载(可根据需要调整时间或使用显式等待)
    time.sleep(2)

    # 定位关闭按钮
    # 方法一:使用 CSS 选择器
    close_button = driver.find_element(By.CSS_SELECTOR, '.close-btn-wrapper-HINk0h [role="img"]')
    
    # 方法二:使用 XPath
    # close_button = driver.find_element(By.XPATH, '//div[@class="close-btn-wrapper-HINk0h"]//*[@role="img"]')

    # 模拟点击关闭按钮
    close_button.click()

    # 等待观察效果(可选)
    time.sleep(2)

finally:
    # 关闭浏览器
    driver.quit()

说明:

  1. 定位策略:
    • 在示例中,使用了 CSS 选择器 .close-btn-wrapper-HINk0h [role="img"] 来定位关闭按钮。这个选择器首先定位具有类名 .close-btn-wrapper-HINk0h 的 div,然后在该 div 下查找具有 role="img" 属性的子元素,这通常是实际的关闭图标。
    • 你也可以使用 XPath 来定位,如注释中的方法二所示。
  2. 等待元素加载:
    • 使用 time.sleep(2) 是一种简单的等待方式,但在实际项目中,建议使用显式等待(WebDriverWait)来提高脚本的稳定性和效率。例如:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待关闭按钮可点击 close_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, '.close-btn-wrapper-HINk0h [role="img"]')) ) close_button.click()
  3. 异常处理:
    • 在实际应用中,建议添加异常处理,以应对元素未找到或其他潜在问题。例如:try: close_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, '.close-btn-wrapper-HINk0h [role="img"]')) ) close_button.click() except Exception as e: print(f"无法关闭组件: {e}")
  4. 确保元素可交互:
    • 确保在尝试点击关闭按钮之前,该按钮处于可见且可点击的状态。如果按钮被其他元素遮挡或尚未完全加载,点击操作可能会失败。
作者 east
python 1月 14,2025

selenium.webdriver 如何执行Esc返回键的功能(python实现)

在使用 Selenium WebDriver 进行自动化测试时,有时需要模拟键盘操作,例如按下 Esc 键来执行返回或取消操作。Selenium 提供了多种方法来实现这一点,以下是几种常见的方法:

方法一:使用 send_keys 方法

send_keys 方法允许你向当前聚焦的元素发送按键事件。要模拟按下 Esc 键,可以使用 Keys.ESCAPE。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# 初始化 WebDriver(以 Chrome 为例)
driver = webdriver.Chrome()

try:
    # 打开目标网页
    driver.get('https://www.example.com')

    # 等待页面加载
    time.sleep(2)

    # 向当前聚焦的元素发送 Esc 键
    driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.ESCAPE)

    # 或者,如果你知道具体的元素,可以定位后发送
    # element = driver.find_element(By.ID, 'some-element-id')
    # element.send_keys(Keys.ESCAPE)

    # 等待观察效果
    time.sleep(2)

finally:
    # 关闭浏览器
    driver.quit()

方法二:使用 ActionChains

ActionChains 提供了更复杂的用户交互方式,包括键盘操作。你可以使用 send_keys 方法来发送 Esc 键。

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time

# 初始化 WebDriver(以 Chrome 为例)
driver = webdriver.Chrome()

try:
    # 打开目标网页
    driver.get('https://www.example.com')

    # 创建 ActionChains 对象
    actions = ActionChains(driver)

    # 向当前聚焦的元素发送 Esc 键
    actions.send_keys(Keys.ESCAPE).perform()

    # 或者,指定某个元素
    # element = driver.find_element(By.ID, 'some-element-id')
    # actions.move_to_element(element).send_keys(Keys.ESCAPE).perform()

    # 等待观察效果
    time.sleep(2)

finally:
    # 关闭浏览器
    driver.quit()

方法三:使用 JavaScript 执行(适用于某些特定场景)

在某些情况下,直接使用 JavaScript 来触发 Esc 键的效果可能更为有效,尤其是当涉及到模态窗口、弹出层等需要关闭的 UI 元素时。

from selenium import webdriver
import time

# 初始化 WebDriver(以 Chrome 为例)
driver = webdriver.Chrome()

try:
    # 打开目标网页
    driver.get('https://www.example.com')

    # 等待页面加载
    time.sleep(2)

    # 使用 JavaScript 触发 Esc 键的效果
    driver.execute_script("document.activeElement.blur();")  # 失去焦点
    driver.execute_script("window.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape', code: 'Escape', bubbles: true}));")

    # 等待观察效果
    time.sleep(2)

finally:
    # 关闭浏览器
    driver.quit()

注意事项

  1. 等待元素加载:在执行键盘操作之前,确保目标元素已经加载并且可以被操作。可以使用显式等待(WebDriverWait)来代替 time.sleep,以提高脚本的稳定性和效率。
  2. 元素定位:确保你定位的元素是当前聚焦的元素,或者明确指定要发送 Esc 键的元素。
  3. 浏览器兼容性:不同浏览器对键盘事件的处理可能略有不同,确保在目标浏览器上进行测试。
  4. 权限和安全性:某些网站可能会检测到自动化工具并阻止其操作,确保遵守网站的使用条款,并在合法范围内使用自动化测试。
作者 east
python 9月 18,2024

selenium解决调用Chrome str’ object has no attribute ‘capabilities’ Process finished

使用selenium调用chrome进行自动化测试,时不时报错:

原来代码如下:

path_to_chromedriver = 'C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe'
5driver = webdriver.Chrome(executable_path=path_to_chromedriver)

报错如下:

上面的代码修改后报错:Traceback (most recent call last): File “D:\program files\Python\Python39\lib\site-packages\selenium\webdriver\common\driver_finder.py”, line 38, in get_path path = SeleniumManager().driver_location(options) if path is None else path File “D:\program files\Python\Python39\lib\site-packages\selenium\webdriver\common\selenium_manager.py”, line 76, in driver_location browser = options.capabilities[“browserName”] AttributeError: ‘str’ object has no attribute ‘capabilities’ During handling of the above exception, another exception occurred: Traceback (most recent call last): File “D:\newcode\pythonProject\gpt\doubao_csdn.py”, line 130, in <module> reader = FunnyScriptsReader(directory) File “D:\newcode\pythonProject\gpt\doubao_csdn.py”, line 21, in __init__ self.driver = webdriver.Chrome(“executable_path=C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe”) File “D:\program files\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py”, line 45, in __init__ super().__init__( File “D:\program files\Python\Python39\lib\site-packages\selenium\webdriver\chromium\webdriver.py”, line 51, in __init__ self.service.path = DriverFinder.get_path(self.service, options) File “D:\program files\Python\Python39\lib\site-packages\selenium\webdriver\common\driver_finder.py”, line 40, in get_path msg = f”Unable to obtain driver for {options.capabilities[‘browserName’]} using Selenium Manager.” AttributeError: ‘str’ object has no attribute ‘capabilities’ Process finished with exit code 1

在最新版本的Selenium中,推荐的做法是使用 service 模块,并且不再推荐使用 executable_path。因此,更好的实践是创建一个 Service 实例,,并传入 ChromeDriver 的路径:(
顺利解决了上面的问题 )


from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 替换为实际的ChromeDriver路径
path_to_chromedriver = ‘C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe’
service = Service(executable_path=path_to_chromedriver)

# 创建WebDriver实例
driver = webdriver.Chrome(service=service)

作者 east
python 9月 14,2024

python AttributeError: ‘NoneType’ object has no attribute ‘open’

在写python关闭数据库连接时,代码报错: AttributeError: ‘NoneType’ object has no attribute ‘open’ 。这是因为 connection 在 finally 块中可能仍然是 None,而尝试对 None 类型的对象调用 .open 方法会引发此错误。

为了修复这个问题,我们需要更精确地控制 connection 的使用。在 finally 块中,应该确保 connection 既不为 None 也必须是一个有效的连接对象。因此,可以通过检查 connection 是否不为 None 来避免此错误,同时简化 finally 块的处理逻辑。

修改后的正确代码如下:

  def get_charge_electric(self, day, bms_pid_system_code, charge_type):
        connection = None
        cursor = None
        try:
            connection = pymysql.connect(**self.db_config)
            cursor = connection.cursor(pymysql.cursors.DictCursor)

            # 判断charge_type是charge_electric还是discharge_electric,并在query替换
            if charge_type == 'charge_electric':
                query = """
                    SELECT charge_electric 
                    FROM bigdata_test_electric_day 
                    WHERE day = %s AND bms_pid_system_code = %s
                """
            else:
                query = """
                    SELECT discharge_electric
                    FROM bigdata_test_electric_day 
                    WHERE day = %s AND bms_pid_system_code = %s
                """

            cursor.execute(query, (day, bms_pid_system_code))
            result = cursor.fetchone()

            return result[charge_type] if result else None
        except pymysql.MySQLError as e:
            print(f"Error: {e}")
            return None
        finally:
            if cursor is not None:
                cursor.close()
            if connection is not None:
                connection.close()
作者 east
python 8月 6,2024

python3报错 name ‘unicode’ is not defined

一份在python2运行正常的代码,在python3运行报错:

 # 首先尝试最常见的预期格式
    if isinstance(date_input, unicode):  # Python 2.7特有的检查
        date_input = date_input.encode('utf-8')  # 转换unicode为str

原来在 Python 3.x 中,字符串默认为 Unicode 字符串,因此不再需要对 unicode 类型进行特殊处理。所以在python3不用对date_input 做特殊处理,删除上面那2行果然运行正常了。

作者 east
python 6月 14,2024

python2.7格式化数据库返回日期字段

数据库不同表的日期字段格式多种多样,有的日期字段定义为date、datetime,有的定义varchar(16)返回unicode类型,有的是yyyyMMdd格式,有的是yyyy-MM-dd格式,要统一格式化为
yyyy-MM-dd格式 。
在Python 2.7中,str 和 unicode 是两种不同的字符串类型。 但在
 Python 3,那么 unicode 类型已经被移除,str 类型现在就是 Unicode 字符串,因此不需要对 unicode 进行特殊处理。在 Python 3 中,你可以直接使用 str 来检查所有字符串类型。 参考源代码如下:

def format_date(date_input):
    # 首先尝试最常见的预期格式
    if isinstance(date_input, unicode):  # Python 2.7特有的检查
        date_input = date_input.encode('utf-8')  # 转换unicode为str
    if isinstance(date_input, datetime):
        return date_input.strftime('%Y-%m-%d')
    elif isinstance(date_input, date):
        return date_input.strftime('%Y-%m-%d')
    elif isinstance(date_input, str):  # 在Python 2.7中使用basestring
        try:
            return datetime.strptime(date_input, '%Y-%m-%d').strftime('%Y-%m-%d')
        except ValueError:
            return datetime.strptime(date_input, '%Y%m%d').strftime('%Y-%m-%d')
        except ValueError:
            # 如果常见的格式不匹配,尝试去掉可能的前后空格再次匹配
            # 注意:这里没有提供额外的格式匹配,因为表结构明确了'%Y-%m-%d'
            # 如果确实需要处理其他格式,请在此处添加额外的尝试逻辑
            raise TypeError("Unsupported date type: %s with value %s" % (type(date_input), date_input))
    else:
        raise TypeError("Unsupported date type: %s with value %s" % (type(date_input), date_input))
作者 east
python, 海豚调度器 6月 7,2024

海豚调度器调用api接口来获取工作流信息(获取processDefinitionId)

​

 在前面一文,海豚调度器调用api接口启动工作流(亲试可用),详细介绍processDefinitionId通过t_ds_process_definition来获取,并没有详细介绍如何用api调用。下面详细介绍如何用api获取。

获取工作流的信息:

#查询流程定义通过项目ID
def queryProcessDefinitionAllByProjectId(token,project_name, project_id):
    url = f"{dolphin_scheduler_base_url}/projects/{project_name}/process/queryProcessDefinitionAllByProjectId"
    params = {
        "projectId": project_id
    }
    headers = {
        "Content-Type": "application/json",
        "token": token
    }
    response = requests.get(url, headers=headers, params=params)

    if response.status_code == 200:
        return response.json()
    else:
        return None

解析工作流的信息,获取工作流名称和processDefinitionId的字典:

def extract_name_id_mapping(json_data):
    name_id_mapping = {}
    data_list = json_data.get('data', [])
    for item in data_list:
        name = item.get('name')
        id = item.get('id')
        if name and id:
            name_id_mapping[name] = id
    return name_id_mapping

调用如下:

 json_data = queryProcessDefinitionAllByProjectId(token,project_name, project_id)
        name_id_mapping = extract_name_id_mapping(json_data)
        print(name_id_mapping)

​

作者 east
python 6月 7,2024

CentOS Python 2.7 离线安装 Requests 库保姆级教程

在内网或无网络连接的环境中,Python 开发者经常需要离线安装第三方库。本文将详细介绍如何在 CentOS 系统上,使用 Python 2.7 版本离线安装 Requests 库。Requests 是一个简单易用的 HTTP 库,用于发送各种 HTTP 请求。

前提条件
CentOS 系统已安装 Python 2.7。
已下载 Requests 库及其依赖的离线安装包。
环境准备

  1. 下载必要的安装包
    首先,需要从互联网上下载 Requests 库及其所有依赖的安装包。以下是需要下载的包列表:

setuptools
pip
certifi
chardet
idna
urllib3
requests
你可以从 Python Package Index 或其他可信的源下载这些包的 .tar.gz 或 .whl 文件。

这里有打包好的完整下载包,包括依赖包。一键下载地址

  1. 上传至 CentOS
    使用 rz 或 scp 命令将下载的文件上传至 CentOS 系统的某个目录下,例如 /usr/local。
  2. 解压安装包
    在 /usr/local 目录下,使用以下命令解压安装包:

tar -zxvf setuptools-41.1.0.post1.tar.gz tar -zxvf pip-19.2.2.tar.gz tar -zxvf requests-2.22.0.tar.gz # 解压其他依赖包

安装 setuptools
Setuptools 是 Python 的一个包,用于简化构建、分发、安装 Python 包的过程。

tar -zxvf setuptools-41.1.0.post1.tar.gz
cd setuptools-41.1.0.post1/
python setup.py install
安装 pip
Pip 是 Python 的包管理工具,用于安装和管理 Python 库。

tar -zxvf pip-19.2.2.tar.gz
cd pip-19.2.2/
python setup.py install
安装 Requests 的依赖包
Requests 库有一些依赖包,需要先安装这些依赖包。

安装 certifi
Certifi 是一个 Python 包,提供 Mozilla 的 CA 证书包。

pip install certifi-2019.11.28-py2.py3-none-any.whl

安装 chardet
Chardet 是一个字符编码检测器。

pip install chardet-3.0.4-py2.py3-none-any.whl

安装 idna
IDN-A 是一个国际域名解析库。

pip install idna-2.5-py2.py3-none-any.whl

安装 urllib3
Urllib3 是一个强大的 HTTP 客户端库。

pip install urllib3-1.25.8-py2.py3-none-any.whl

安装 Requests 库
在安装完所有依赖后,可以安装 Requests 库。

pip install requests-2.23.0-py2.py3-none-any。whl

验证安装
安装完成后,可以通过以下方式验证 Requests 库是否安装成功:

python >>> import requests >>> requests.version

如果能够成功导入 requests 并且打印出版本号,则表示安装成功。

常见问题
权限问题:在安装过程中,如果遇到权限问题,可以使用 sudo 来获取管理员权限。

依赖冲突:如果在安装过程中提示依赖冲突,可能需要先卸载旧版本的依赖包。

作者 east
python 9月 24,2023

selenium自动输入特殊表情符号报错:selenium.common.exceptions.WebDriverException: Message: unknown error: ChromeDriver only supports characters in the BMP

最近在利用selenium调用chatgpt时报错:selenium.common.exceptions.WebDriverException: Message: unknown error: ChromeDriver only supports characters in the BMP。

由于我的应用场景是不需要表情符号的,所以考虑简单粗暴去除表情符号避开这个问题。

一个常用的库是emoji,它提供了一些有用的函数来处理和删除表情符号。

首先,我们需要安装该库。可以使用以下命令来安装emoji库:

pip install emoji

我们可以导入emoji库并使用其中的demojize函数来去除特殊表情符号。

示例如下:

import emoji

text = "I like Python! 😊❤️🐍"
clean_text = emoji.demojize(text)
print(clean_text)
作者 east
python 9月 12,2023

camel-ai的role_playing代码解读

这段代码定义了一个名为RolePlaying的类,用于两个角色之间的角色扮演。

该类接受以下参数:

  • assistant_role_name (str): 助手扮演的角色名称。
  • user_role_name (str): 用户扮演的角色名称。
  • critic_role_name (str): 评论家扮演的角色名称。带有”:obj:"human"“的角色名称会将评论家设置为Human代理,否则将创建一个CriticAgent。
  • task_prompt (str, optional): 需要执行的任务的提示信息。
  • with_task_specify (bool, optional): 是否使用任务指定代理。
  • with_task_planner (bool, optional): 是否使用任务规划器代理。
  • with_critic_in_the_loop (bool, optional): 是否在循环中包括评论家。
  • critic_criteria (str, optional): 评论家代理的评估标准。如果未指定,则设置评估标准以提高任务性能。
  • model_type (ModelType, optional): 用于角色扮演的模型类型。如果指定,将覆盖所有代理中的模型。
  • task_type (TaskType, optional): 执行的任务类型。
  • assistant_agent_kwargs (Dict, optional): 传递给助手代理的附加参数。
  • user_agent_kwargs (Dict, optional): 传递给用户代理的附加参数。
  • task_specify_agent_kwargs (Dict, optional): 传递给任务指定代理的附加参数。
  • task_planner_agent_kwargs (Dict, optional): 传递给任务规划器代理的附加参数。
  • critic_kwargs (Dict, optional): 传递给评论家的附加参数。
  • sys_msg_generator_kwargs (Dict, optional): 传递给系统消息生成器的附加参数。
  • extend_sys_msg_meta_dicts (List[Dict], optional): 用于扩展系统消息元数据字典的字典列表。
  • extend_task_specify_meta_dict (Dict, optional): 用于扩展任务指定元数据字典的字典。
  • output_language (str, optional): 代理输出的语言。

初始化时可以接收很多参数,下面解析一下各个参数的含义和用途:

  • assistant_role_name (str): 机器人角色的名称,通常是assistant
  • user_role_name (str): 用户角色的名称,通常是user
  • critic_role_name: 批评家角色的名称,默认为critic
  • task_prompt (str): 任务描述或者指示
  • with_task_specify (bool): 是否使用TaskSpecifyAgent来生成特定的任务提示
  • with_task_planner (bool): 是否使用TaskPlannerAgent来规划任务
  • with_critic_in_the_loop (bool): 是否让批评家参与对话过程(默认不参与)
  • critic_criteria (Optional[str]): 批评家参与时需要满足的条件,如不为空,则批评家只会在满足条件时参与对话
  • model_type (Optional[ModelType]): 语言模型类型,如GPT-3等,可以为空
  • task_type (TaskType): 任务类型,默认为AI社交任务
  • assistant_agent_kwargs (Optional[Dict]): 机器人agent的配置
  • user_agent_kwargs (Optional[Dict]): 用户agent的配置
  • task_specify_agent_kwargs (Optional[Dict]): 任务指示agent的配置
  • task_planner_agent_kwargs (Optional[Dict]): 任务规划agent的配置
  • critic_kwargs (Optional[Dict]): 批评家agent的配置
  • sys_msg_generator_kwargs (Optional[Dict]): 系统消息生成器的配置
  • extend_sys_msg_meta_dicts (Optional[List[Dict]]): 系统消息的元数据
  • extend_task_specify_meta_dict (Optional[Dict]): 任务指示的元数据
  • output_language (Optional[str]): 输出的语言,可以为空

代码主要功能是初始化Chatbot,其中有一些重要的方法,如init_specified_task_prompt用来生成特定的任务提示,init_planned_task_prompt用来规划任务提示,还有init_critic来初始化批评家。整个类的逻辑比较复杂,需要根据不同的需求进行配置和使用。

init_planned_task_prompt方法用于使用任务规划(agent)来生成一个计划好的任务提示(task prompt),并将其添加到原始任务提示(task prompt)后面。如果没有任务规划(agent),则不会生成计划好的任务提示。

参数说明:

  • task_planner_agent_kwargs:任务规划(agent)的额外参数,在初始化TaskPlannerAgent时传递。
  • output_language:输出语言,agents输出语言的设置。

方法实现:

  1. 根据self.with_task_planner属性判断是否启用了任务规划。
  2. 如果启用了任务规划(agent)且指定了语言模型类型(model_type),则将model_type添加到task_planner_agent_kwargs中。
  3. 使用TaskPlannerAgent初始化一个任务规划(agent)。
  4. 通过调用task_planner_agent.run方法传入任务提示(task prompt)获取计划好的任务提示,并将其附加到任务提示中。
  5. 如果没有启用任务规划(agent),则将self.planned_task_prompt置为None。

get_sys_message_info方法用于获取初始的机器人和用户系统消息,并返回包含系统消息和元数据的元组。

参数说明:

  • assistant_role_name:机器人角色的名称。
  • user_role_name:用户角色的名称。
  • sys_msg_generator:系统消息生成器。
  • extend_sys_msg_meta_dicts:扩展的系统消息元数据字典的列表。

方法实现:

  1. 创建一个由两个字典组成的列表,每个字典都包含任务提示(task prompt)作为键。
  2. 如果extend_sys_msg_meta_dicts为空并且任务类型是AI社交任务或MISALIGNMENT任务,则创建一个包含角色名称的字典列表。
  3. 如果extend_sys_msg_meta_dicts不为空,则将原始的系统消息元数据字典和扩展的系统消息元数据字典进行合并。
  4. 使用sys_msg_generator.from_dicts方法将元数据字典转换为机器人和用户的初始系统消息。
  5. 返回机器人和用户的初始系统消息以及系统消息元数据字典的列表。

init_agents方法用于初始化助手(agent)和用户(agent),并设置它们的初始系统消息。

参数说明:

  • init_assistant_sys_msg:助手(agent)的初始系统消息。
  • assistant_agent_kwargs:传递给助手(agent)的额外参数。
  • init_user_sys_msg:用户(agent)的初始系统消息。
  • user_agent_kwargs:传递给用户(agent)的额外参数。
  • output_language:agents输出语言的设置。

方法实现:

  1. 如果指定了语言模型类型(model_type),则将其添加到助手(agent)和用户(agent)的额外参数中。
  2. 使用ChatAgent初始化助手(agent),并将助手的系统消息保存在self.assistant_sys_msg中。
  3. 使用ChatAgent初始化用户(agent),并将用户的系统消息保存在self.user_sys_msg中。

init_critic方法用于初始化评论者(agent)。如果评论者角色名称是”human”,则创建一个人类评论者,否则根据指定的评论者准则创建一个评论者(agent)。如果没有指定评论者准则,则默认为改善任务性能。

参数说明:

  • critic_role_name:评论者所扮演角色的名称。
  • critic_criteria:评论者(agent)的评价准则。如果没有指定,则将评价准则设置为改善任务性能。
  • critic_kwargs:传递给评论者(agent)的额外参数。
  • sys_msg_generator:用于生成系统消息的生成器。
  • sys_msg_meta_dicts:系统消息元数据字典的列表。

方法实现:

  1. 如果启用了评论者(agent)循环且评论者角色名称是”human”,则创建一个人类评论者。
  2. 否则,根据指定的评论者准则和角色名称创建一个CriticAgent评论者(agent)。如果没有指定评论者准则,则默认为改善任务性能。
  3. 如果指定了语言模型类型(model_type),则将其添加到评论者(agent)的额外参数中。
  4. 使用评论者准则、角色名称和系统消息元数据字典创建评论者的系统消息。
  5. 将评论者的系统消息保存在self.critic_sys_msg中。
  6. 使用CriticAgent初始化评论者(agent)。

init_chat方法用于初始化对话,通过重置助手(agent)和用户(agent),并向它们发送系统消息来重新开始对话。返回助手的介绍性消息和用户的回复消息列表。

方法实现:

  1. 重置助手(agent)和用户(agent)。
  2. 使用chat消息将系统消息再次发送给助手(agent)和用户(agent)。
  3. 创建助手的介绍性消息,其中包含用户系统消息的内容和一些指令。
  4. 创建用户的回复消息,其内容为助手系统消息的内容。
  5. 使用用户的回复消息调用助手(agent)的step方法,返回助手的响应消息。
  6. 如果助手(agent)的响应消息已结束或没有消息,则抛出ValueError异常。
  7. 返回助手的介绍性消息和助手的响应消息列表。

reduce_message_options方法用于处理一系列对话消息,并返回处理后的消息。如果提供了多个消息且with_critic_in_the_loop为False,则抛出ValueError异常。如果未提供任何消息,则抛出ValueError异常。

方法实现:

  1. 如果消息数量为0,则抛出ValueError异常。
  2. 如果消息数量大于1且with_critic_in_the_loop为False,则抛出ValueError异常。
  3. 否则,如果启用了评论者(agent)循环且评论者存在,则调用评论者的reduce_step方法,返回评论者的响应消息,并将其作为处理后的消息。
  4. 否则,将第一个消息作为处理后的消息返回。

RolePlaying类中的step方法。该方法用于推进对话,接收助手发来的消息,使用用户(agent)处理该消息,然后使用助手(agent)处理生成的回复消息。返回一个元组,其中包含助手生成的消息、助手是否终止了对话以及其他助手相关的信息;还有一个元组,其中包含用户生成的消息、用户是否终止了对话以及其他用户相关的信息。

方法实现:

  1. 使用助手(agent)发送的消息调用用户(agent)的step方法,返回用户(agent)的响应。
  2. 如果用户(agent)的响应已经终止或没有消息,则创建一个空的ChatAgentResponse结构体表示助手的消息,并将用户(agent)的终止信息和额外信息作为ChatAgentResponse结构体的一部分返回。
  3. 否则,根据用户(agent)的响应消息使用reduce_message_options方法处理获取用户的消息。
  4. 将处理后的用户消息提交给用户(agent)。
  5. 使用用户消息调用助手(agent)的step方法,返回助手(agent)的响应。
  6. 如果助手(agent)的响应已终止或没有消息,则创建一个空的ChatAgentResponse结构体表示用户的消息,并将助手(agent)的终止信息和额外信息作为ChatAgentResponse结构体的一部分返回。
  7. 否则,根据助手(agent)的响应消息使用reduce_message_options方法处理获取助手的消息。
  8. 将处理后的助手消息提交给助手(agent)。
  9. 返回一个元组,第一个元素为助手的响应消息、助手是否终止了对话以及其他助手相关的信息,第二个元素为用户的响应消息、用户是否终止了对话以及其他用户相关的信息。

源码如下:

# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
# Licensed under the Apache License, Version 2.0 (the “License”);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an “AS IS” BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
from typing import Dict, List, Optional, Sequence, Tuple, Union

from camel.agents import (
    ChatAgent,
    CriticAgent,
    TaskPlannerAgent,
    TaskSpecifyAgent,
)
from camel.agents.chat_agent import ChatAgentResponse
from camel.generators import SystemMessageGenerator
from camel.human import Human
from camel.messages import BaseMessage
from camel.prompts import TextPrompt
from camel.typing import ModelType, RoleType, TaskType


class RolePlaying:
    r"""Role playing between two agents.

    Args:
        assistant_role_name (str): The name of the role played by the
            assistant.
        user_role_name (str): The name of the role played by the user.
        critic_role_name (str): The name of the role played by the critic.
            Role name with :obj:`"human"` will set critic as a :obj:`Human`
            agent, else will create a :obj:`CriticAgent`.
            (default: :obj:`"critic"`)
        task_prompt (str, optional): A prompt for the task to be performed.
            (default: :obj:`""`)
        with_task_specify (bool, optional): Whether to use a task specify
            agent. (default: :obj:`True`)
        with_task_planner (bool, optional): Whether to use a task planner
            agent. (default: :obj:`False`)
        with_critic_in_the_loop (bool, optional): Whether to include a critic
            in the loop. (default: :obj:`False`)
        critic_criteria (str, optional): Critic criteria for the critic agent.
            If not specified, set the criteria to improve task performance.
        model_type (ModelType, optional): Model type that will be used for
            role playing. If specified, it will override the model in all
            agents. (default: :obj:`None`)
        task_type (TaskType, optional): The type of task to perform.
            (default: :obj:`TaskType.AI_SOCIETY`)
        assistant_agent_kwargs (Dict, optional): Additional arguments to pass
            to the assistant agent. (default: :obj:`None`)
        user_agent_kwargs (Dict, optional): Additional arguments to pass to
            the user agent. (default: :obj:`None`)
        task_specify_agent_kwargs (Dict, optional): Additional arguments to
            pass to the task specify agent. (default: :obj:`None`)
        task_planner_agent_kwargs (Dict, optional): Additional arguments to
            pass to the task planner agent. (default: :obj:`None`)
        critic_kwargs (Dict, optional): Additional arguments to pass to the
            critic. (default: :obj:`None`)
        sys_msg_generator_kwargs (Dict, optional): Additional arguments to
            pass to the system message generator. (default: :obj:`None`)
        extend_sys_msg_meta_dicts (List[Dict], optional): A list of dicts to
            extend the system message meta dicts with. (default: :obj:`None`)
        extend_task_specify_meta_dict (Dict, optional): A dict to extend the
            task specify meta dict with. (default: :obj:`None`)
        output_language (str, optional): The language to be output by the
            agents. (default: :obj:`None`)
    """

    def __init__(
        self,
        assistant_role_name: str,
        user_role_name: str,
        *,
        critic_role_name: str = "critic",
        task_prompt: str = "",
        with_task_specify: bool = True,
        with_task_planner: bool = False,
        with_critic_in_the_loop: bool = False,
        critic_criteria: Optional[str] = None,
        model_type: Optional[ModelType] = None,
        task_type: TaskType = TaskType.AI_SOCIETY,
        assistant_agent_kwargs: Optional[Dict] = None,
        user_agent_kwargs: Optional[Dict] = None,
        task_specify_agent_kwargs: Optional[Dict] = None,
        task_planner_agent_kwargs: Optional[Dict] = None,
        critic_kwargs: Optional[Dict] = None,
        sys_msg_generator_kwargs: Optional[Dict] = None,
        extend_sys_msg_meta_dicts: Optional[List[Dict]] = None,
        extend_task_specify_meta_dict: Optional[Dict] = None,
        output_language: Optional[str] = None,
    ) -> None:
        self.with_task_specify = with_task_specify
        self.with_task_planner = with_task_planner
        self.with_critic_in_the_loop = with_critic_in_the_loop
        self.model_type = model_type
        self.task_type = task_type
        self.task_prompt = task_prompt

        self.specified_task_prompt: Optional[TextPrompt] = None
        self.init_specified_task_prompt(assistant_role_name, user_role_name,
                                        task_specify_agent_kwargs,
                                        extend_task_specify_meta_dict,
                                        output_language)

        self.planned_task_prompt: Optional[TextPrompt] = None
        self.init_planned_task_prompt(task_planner_agent_kwargs,
                                      output_language)

        sys_msg_generator = SystemMessageGenerator(
            task_type=self.task_type, **(sys_msg_generator_kwargs or {}))

        (init_assistant_sys_msg, init_user_sys_msg,
         sys_msg_meta_dicts) = self.get_sys_message_info(
             assistant_role_name, user_role_name, sys_msg_generator,
             extend_sys_msg_meta_dicts)

        self.assistant_agent: ChatAgent
        self.user_agent: ChatAgent
        self.assistant_sys_msg: BaseMessage
        self.user_sys_msg: BaseMessage
        self.init_agents(
            init_assistant_sys_msg,
            assistant_agent_kwargs,
            init_user_sys_msg,
            user_agent_kwargs,
            output_language,
        )
        self.critic: Optional[Union[CriticAgent, Human]] = None
        self.critic_sys_msg: Optional[BaseMessage] = None
        self.init_critic(critic_role_name, critic_criteria, critic_kwargs,
                         sys_msg_generator, sys_msg_meta_dicts)

    def init_specified_task_prompt(
            self, assistant_role_name: str, user_role_name: str,
            task_specify_agent_kwargs: Optional[Dict],
            extend_task_specify_meta_dict: Optional[Dict],
            output_language: Optional[str]):
        r"""Use a task specify agent to generate a specified task prompt.
        Generated specified task prompt will be used to replace original
        task prompt. If there is no task specify agent, specified task
        prompt will not be generated.

        Args:
            assistant_role_name (str): The name of the role played by the
                assistant.
            user_role_name (str): The name of the role played by the user.
            task_specify_agent_kwargs (Dict, optional): Additional arguments
                to pass to the task specify agent.
            extend_task_specify_meta_dict (Dict, optional): A dict to extend
                the task specify meta dict with.
            output_language (str, optional): The language to be output by the
                agents.
        """
        if self.with_task_specify:
            task_specify_meta_dict = dict()
            if self.task_type in [TaskType.AI_SOCIETY, TaskType.MISALIGNMENT]:
                task_specify_meta_dict.update(
                    dict(assistant_role=assistant_role_name,
                         user_role=user_role_name))
            task_specify_meta_dict.update(extend_task_specify_meta_dict or {})
            if self.model_type is not None:
                if task_specify_agent_kwargs is None:
                    task_specify_agent_kwargs = {}
                task_specify_agent_kwargs.update(dict(model=self.model_type))
            task_specify_agent = TaskSpecifyAgent(
                task_type=self.task_type,
                output_language=output_language,
                **(task_specify_agent_kwargs or {}),
            )
            self.specified_task_prompt = task_specify_agent.run(
                self.task_prompt,
                meta_dict=task_specify_meta_dict,
            )
            self.task_prompt = self.specified_task_prompt

    def init_planned_task_prompt(self,
                                 task_planner_agent_kwargs: Optional[Dict],
                                 output_language: Optional[str]):
        r"""Use a task plan agent to append a planned task prompt to task
        prompt. The planned task prompt is generated based on the task
        prompt, which can be original task prompt or specified task prompt
        if available. If there is no task plan agent, planned task prompt
        will not be generated.

        Args:
            task_planner_agent_kwargs (Dict, optional): Additional arguments
                to pass to the task planner agent.
            output_language (str, optional): The language to be output by the
                agents.
        """
        if self.with_task_planner:
            if self.model_type is not None:
                if task_planner_agent_kwargs is None:
                    task_planner_agent_kwargs = {}
                task_planner_agent_kwargs.update(dict(model=self.model_type))
            task_planner_agent = TaskPlannerAgent(
                output_language=output_language,
                **(task_planner_agent_kwargs or {}),
            )
            self.planned_task_prompt = task_planner_agent.run(self.task_prompt)
            self.task_prompt = (f"{self.task_prompt}\n"
                                f"{self.planned_task_prompt}")
        else:
            self.planned_task_prompt = None

    def get_sys_message_info(
        self,
        assistant_role_name: str,
        user_role_name: str,
        sys_msg_generator: SystemMessageGenerator,
        extend_sys_msg_meta_dicts: Optional[List[Dict]] = None,
    ) -> Tuple[BaseMessage, BaseMessage, List[Dict]]:
        r"""Get initial assistant and user system message with a list of
        system message meta dicts.

        Args:
            assistant_role_name (str): The name of the role played by the
                assistant.
            user_role_name (str): The name of the role played by the user.
            sys_msg_generator (SystemMessageGenerator): A system message
                generator for agents.
            extend_sys_msg_meta_dicts (List[Dict], optional): A list of dicts
                to extend the system message meta dicts with.

        Returns:
            A tuple containing a `BaseMessage` representing the assistant's
            initial system message, a `BaseMessage` representing the user's
            initial system message, and a list of system message meta dicts.
        """
        sys_msg_meta_dicts = [dict(task=self.task_prompt) for _ in range(2)]
        if (extend_sys_msg_meta_dicts is None and self.task_type in [
                TaskType.AI_SOCIETY,
                TaskType.MISALIGNMENT,
        ]):
            extend_sys_msg_meta_dicts = [
                dict(assistant_role=assistant_role_name,
                     user_role=user_role_name) for _ in range(2)
            ]

        if extend_sys_msg_meta_dicts is not None:
            sys_msg_meta_dicts = [{
                **sys_msg_meta_dict,
                **extend_sys_msg_meta_dict
            } for sys_msg_meta_dict, extend_sys_msg_meta_dict in zip(
                sys_msg_meta_dicts, extend_sys_msg_meta_dicts)]

        init_assistant_sys_msg, init_user_sys_msg = (
            sys_msg_generator.from_dicts(
                meta_dicts=sys_msg_meta_dicts,
                role_tuples=[
                    (assistant_role_name, RoleType.ASSISTANT),
                    (user_role_name, RoleType.USER),
                ],
            ))
        return init_assistant_sys_msg, init_user_sys_msg, sys_msg_meta_dicts

    def init_agents(
        self,
        init_assistant_sys_msg: BaseMessage,
        assistant_agent_kwargs: Optional[Dict],
        init_user_sys_msg: BaseMessage,
        user_agent_kwargs: Optional[Dict],
        output_language: Optional[str],
    ):
        r"""Initialize assistant and user agents with their system messages.

        Args:
            init_assistant_sys_msg (BaseMessage): Assistant agent's initial
                system message.
            assistant_agent_kwargs (Dict, optional): Additional arguments to
                pass to the assistant agent.
            init_user_sys_msg (BaseMessage): User agent's initial system
                message.
            user_agent_kwargs (Dict, optional): Additional arguments to
                pass to the user agent.
            output_language (str, optional): The language to be output by the
                agents.
        """
        if self.model_type is not None:
            if assistant_agent_kwargs is None:
                assistant_agent_kwargs = {}
            assistant_agent_kwargs.update(dict(model=self.model_type))
            if user_agent_kwargs is None:
                user_agent_kwargs = {}
            user_agent_kwargs.update(dict(model=self.model_type))

        self.assistant_agent = ChatAgent(
            init_assistant_sys_msg,
            output_language=output_language,
            **(assistant_agent_kwargs or {}),
        )
        self.assistant_sys_msg = self.assistant_agent.system_message

        self.user_agent = ChatAgent(
            init_user_sys_msg,
            output_language=output_language,
            **(user_agent_kwargs or {}),
        )
        self.user_sys_msg = self.user_agent.system_message

    def init_critic(self, critic_role_name: str,
                    critic_criteria: Optional[str],
                    critic_kwargs: Optional[Dict],
                    sys_msg_generator: SystemMessageGenerator,
                    sys_msg_meta_dicts: List[Dict]):
        r"""Initialize critic agent. If critic role name is :obj:`"human"`,
        create a :obj:`Human` critic agent. Else, create a :obj:`CriticAgent`
        critic agent with specified critic criteria. If the critic criteria
        is not specified, set it to improve task performance.

        Args:
            critic_role_name (str): The name of the role played by the critic.
            critic_criteria (str, optional): Critic criteria for the
                critic agent. If not specified, set the criteria to
                improve task performance.
            critic_kwargs (Dict, optional): Additional arguments to
                pass to the critic.
            sys_msg_generator (SystemMessageGenerator): A system message
                generator for agents.
            sys_msg_meta_dicts (list): A list of system message meta dicts.
        """
        if self.with_critic_in_the_loop:
            if critic_role_name.lower() == "human":
                self.critic = Human(**(critic_kwargs or {}))
            else:
                critic_criteria = (critic_criteria
                                   or "improving the task performance")
                critic_msg_meta_dict = dict(critic_role=critic_role_name,
                                            criteria=critic_criteria,
                                            **sys_msg_meta_dicts[0])
                self.critic_sys_msg = sys_msg_generator.from_dict(
                    critic_msg_meta_dict,
                    role_tuple=(critic_role_name, RoleType.CRITIC),
                )
                if self.model_type is not None:
                    if critic_kwargs is None:
                        critic_kwargs = {}
                    critic_kwargs.update(dict(model=self.model_type))
                self.critic = CriticAgent(
                    self.critic_sys_msg,
                    **(critic_kwargs or {}),
                )

    def init_chat(self) -> Tuple[BaseMessage, List[BaseMessage]]:
        r"""Initializes the chat by resetting both of the assistant and user
        agents, and sending the system messages again to the agents using
        chat messages. Returns the assistant's introductory message and the
        user's response messages.

        Returns:
            A tuple containing a `BaseMessage` representing the assistant's
            introductory message, and a list of `BaseMessage` representing
            the user's response messages.
        """
        self.assistant_agent.reset()
        self.user_agent.reset()

        # Send the system messages again to the agents using chat messages
        assistant_msg = BaseMessage.make_assistant_message(
            role_name=self.assistant_sys_msg.role_name,
            content=(f"{self.user_sys_msg.content}. "
                     "Now start to give me instructions one by one. "
                     "Only reply with Instruction and Input."))

        user_msg = BaseMessage.make_user_message(
            role_name=self.user_sys_msg.role_name,
            content=f"{self.assistant_sys_msg.content}")
        assistant_response = self.assistant_agent.step(user_msg)
        if assistant_response.terminated or assistant_response.msgs is None:
            raise ValueError(f"Assistant agent terminated unexpectedly. "
                             f"Error info: {assistant_response.info}")

        return assistant_msg, assistant_response.msgs

    def reduce_message_options(
        self,
        messages: Sequence[BaseMessage],
    ) -> BaseMessage:
        r"""Processes a sequence of chat messages, returning the processed
        message. If multiple messages are provided and
        `with_critic_in_the_loop` is `False`, raises a `ValueError`.
        If no messages are provided, a `ValueError` will be raised.

        Args:
            messages: A sequence of `BaseMessage` objects to process.

        Returns:
            A single `BaseMessage` representing the processed message.
        """
        if len(messages) == 0:
            raise ValueError("No messages to process.")
        if len(messages) > 1 and not self.with_critic_in_the_loop:
            raise ValueError("Got than one message to process. "
                             f"Num of messages: {len(messages)}.")
        elif self.with_critic_in_the_loop and self.critic is not None:
            critic_response = self.critic.reduce_step(messages)
            processed_msg = critic_response.msg
        else:
            processed_msg = messages[0]

        return processed_msg

    def step(
        self,
        assistant_msg: BaseMessage,
    ) -> Tuple[ChatAgentResponse, ChatAgentResponse]:
        r"""Advances the conversation by taking a message from the assistant,
        processing it using the user agent, and then processing the resulting
        message using the assistant agent. Returns a tuple containing the
        resulting assistant message, whether the assistant agent terminated
        the conversation, and any additional assistant information, as well as
        a tuple containing the resulting user message, whether the user agent
        terminated the conversation, and any additional user information.

        Args:
            assistant_msg: A `BaseMessage` representing the message from the
                assistant.

        Returns:
            A tuple containing two ChatAgentResponse: the first struct contains
            the resulting assistant message, whether the assistant agent
            terminated the conversation, and any additional assistant
            information; the second struct contains the resulting user message,
            whether the user agent terminated the conversation, and any
            additional user information.
        """
        user_response = self.user_agent.step(assistant_msg)
        if user_response.terminated or user_response.msgs is None:
            return (ChatAgentResponse([], False, {}),
                    ChatAgentResponse([], user_response.terminated,
                                      user_response.info))
        user_msg = self.reduce_message_options(user_response.msgs)
        self.user_agent.submit_message(user_msg)

        assistant_response = self.assistant_agent.step(user_msg)
        if assistant_response.terminated or assistant_response.msgs is None:
            return (ChatAgentResponse([], assistant_response.terminated,
                                      assistant_response.info),
                    ChatAgentResponse([user_msg], False, user_response.info))
        assistant_msg = self.reduce_message_options(assistant_response.msgs)
        self.assistant_agent.submit_message(assistant_msg)

        return (
            ChatAgentResponse([assistant_msg], assistant_response.terminated,
                              assistant_response.info),
            ChatAgentResponse([user_msg], user_response.terminated,
                              user_response.info),
        )
作者 east

1 2 … 4 下一个

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。回复”chatgpt”获取免注册可用chatgpt。回复“大数据”获取多本大数据电子书

标签

AIGC AI创作 bert chatgpt github GPT-3 gpt3 GTP-3 hive mysql O2O tensorflow UI控件 不含后台 交流 共享经济 出行 图像 地图定位 外卖 多媒体 娱乐 小程序 布局 带后台完整项目 开源项目 搜索 支付 效率 教育 日历 机器学习 深度学习 物流 用户系统 电商 画图 画布(canvas) 社交 签到 联网 读书 资讯 阅读 预订

官方QQ群

小程序开发群:74052405

大数据开发群: 952493060

近期文章

  • 详解Python当中的pip常用命令
  • AUTOSAR如何在多个供应商交付的配置中避免ARXML不兼容?
  • C++thread pool(线程池)设计应关注哪些扩展性问题?
  • 各类MCAL(Microcontroller Abstraction Layer)如何与AUTOSAR工具链解耦?
  • 如何设计AUTOSAR中的“域控制器”以支持未来扩展?
  • C++ 中避免悬挂引用的企业策略有哪些?
  • 嵌入式电机:如何在低速和高负载状态下保持FOC(Field-Oriented Control)算法的电流控制稳定?
  • C++如何在插件式架构中使用反射实现模块隔离?
  • C++如何追踪内存泄漏(valgrind/ASan等)并定位到业务代码?
  • C++大型系统中如何组织头文件和依赖树?

文章归档

  • 2025年6月
  • 2025年5月
  • 2025年4月
  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年1月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年7月
  • 2018年6月

分类目录

  • Android (73)
  • bug清单 (79)
  • C++ (34)
  • Fuchsia (15)
  • php (4)
  • python (43)
  • sklearn (1)
  • 云计算 (20)
  • 人工智能 (61)
    • chatgpt (21)
      • 提示词 (6)
    • Keras (1)
    • Tensorflow (3)
    • 大模型 (1)
    • 智能体 (4)
    • 深度学习 (14)
  • 储能 (44)
  • 前端 (4)
  • 大数据开发 (488)
    • CDH (6)
    • datax (4)
    • doris (30)
    • Elasticsearch (15)
    • Flink (78)
    • flume (7)
    • Hadoop (19)
    • Hbase (23)
    • Hive (40)
    • Impala (2)
    • Java (71)
    • Kafka (10)
    • neo4j (5)
    • shardingsphere (6)
    • solr (5)
    • Spark (99)
    • spring (11)
    • 数据仓库 (9)
    • 数据挖掘 (7)
    • 海豚调度器 (10)
    • 运维 (34)
      • Docker (3)
  • 小游戏代码 (1)
  • 小程序代码 (139)
    • O2O (16)
    • UI控件 (5)
    • 互联网类 (23)
    • 企业类 (6)
    • 地图定位 (9)
    • 多媒体 (6)
    • 工具类 (25)
    • 电商类 (22)
    • 社交 (7)
    • 行业软件 (7)
    • 资讯读书 (11)
  • 嵌入式 (70)
    • autosar (63)
    • RTOS (1)
    • 总线 (1)
  • 开发博客 (16)
    • Harmony (9)
  • 技术架构 (6)
  • 数据库 (32)
    • mongodb (1)
    • mysql (13)
    • pgsql (2)
    • redis (1)
    • tdengine (4)
  • 未分类 (6)
  • 程序员网赚 (20)
    • 广告联盟 (3)
    • 私域流量 (5)
    • 自媒体 (5)
  • 量化投资 (4)
  • 面试 (14)

功能

  • 登录
  • 文章RSS
  • 评论RSS
  • WordPress.org

All Rights Reserved by Gitweixin.本站收集网友上传代码, 如有侵犯版权,请发邮件联系yiyuyos@gmail.com删除.