腾讯混元大模型集成LangChain
腾讯混元大模型集成LangChain
获取API密钥
登录控制台–>访问管理–>API密钥管理–>新建密钥,获取到SecretId和SecretKey。访问链接:https://console.cloud.tencent.com/cam/capi
python SDK方式调用大模型
可参考腾讯官方API
import json
import typesfrom tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.hunyuan.v20230901 import hunyuan_client, modelstry:cred = credential.Credential("SecretId", "SecretKey")httpProfile = HttpProfile()httpProfile.endpoint = "hunyuan.tencentcloudapi.com"clientProfile = ClientProfile()clientProfile.httpProfile = httpProfileclient = hunyuan_client.HunyuanClient(cred, "", clientProfile)# 实例化一个请求对象,每个接口都会对应一个request对象req = models.ChatCompletionsRequest()params = {"TopP": 1,"Temperature": 1,"Model": "hunyuan-pro","Messages": [{"Role": "system","Content": "将英文单词转换为包括中文翻译、英文释义和一个例句的完整解释。请检查所有信息是否准确,并在回答时保持简洁,不需要任何其他反馈。"},{"Role": "user","Content": "nice"}]}req.from_json_string(json.dumps(params))resp = client.ChatCompletions(req)if isinstance(resp, types.GeneratorType): # 流式响应for event in resp:print(event)else: # 非流式响应print(resp)except TencentCloudSDKException as err:print(err)
注:需要将上述"SecretId"和"SecretKey"替换成自己创建的API密钥。
集成LangChain
import jsonfrom langchain.llms.base import LLM
from typing import Any, List, Mapping, Optionalfrom pydantic import Field
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.hunyuan.v20230901 import hunyuan_client, modelsclass HunyuanAI(LLM):secret_id: str = Field(..., description="Tencent Cloud Secret ID")secret_key: str = Field(..., description="Tencent Cloud Secret Key")@propertydef _llm_type(self) -> str:return "hunyuan"def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:try:cred = credential.Credential(self.secret_id, self.secret_key)httpProfile = HttpProfile()httpProfile.endpoint = "hunyuan.tencentcloudapi.com"clientProfile = ClientProfile()clientProfile.httpProfile = httpProfileclient = hunyuan_client.HunyuanClient(cred, "", clientProfile)req = models.ChatCompletionsRequest()params = {"TopP": 1,"Temperature": 1,"Model": "hunyuan-pro","Messages": [{"Role": "user","Content": prompt}]}req.from_json_string(json.dumps(params))resp = client.ChatCompletions(req)return resp.Choices[0].Message.Contentexcept TencentCloudSDKException as err:raise ValueError(f"Error calling Hunyuan AI: {err}")try:# 创建 HunyuanAI 实例llm = HunyuanAI(secret_id=SecretId, secret_key=SecretKey)question = input("请输入问题:")# 运行链result = llm.invoke(question)# 打印结果print(result)except Exception as err:print(f"An error occurred: {err}")
注:需要将上述"SecretId"和"SecretKey"替换成自己创建的API密钥。
集成LangChain且自定义输入提示模板
import jsonfrom langchain.llms.base import LLM
from langchain.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate
from langchain.schema import HumanMessage, SystemMessage
from langchain.chains import LLMChain
from typing import Any, List, Mapping, Optional, Dictfrom pydantic import Field
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.hunyuan.v20230901 import hunyuan_client, modelsclass HunyuanAI(LLM):secret_id: str = Field(..., description="Tencent Cloud Secret ID")secret_key: str = Field(..., description="Tencent Cloud Secret Key")@propertydef _llm_type(self) -> str:return "hunyuan"def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:# 将 prompt 解析为消息列表messages = self._parse_prompt(prompt)try:cred = credential.Credential(self.secret_id, self.secret_key)httpProfile = HttpProfile()httpProfile.endpoint = "hunyuan.tencentcloudapi.com"clientProfile = ClientProfile()clientProfile.httpProfile = httpProfileclient = hunyuan_client.HunyuanClient(cred, "", clientProfile)req = models.ChatCompletionsRequest()params = {"TopP": 1,"Temperature": 1,"Model": "hunyuan-pro","Messages": messages}req.from_json_string(json.dumps(params))resp = client.ChatCompletions(req)return resp.Choices[0].Message.Contentexcept TencentCloudSDKException as err:raise ValueError(f"Error calling Hunyuan AI: {err}")def _parse_prompt(self, prompt: str) -> List[Dict[str, str]]:"""将 LangChain 格式的 prompt 解析为 Hunyuan API 所需的消息格式"""messages = []for message in prompt.split('Human: '):if message.startswith('System: '):messages.append({"Role": "system", "Content": message[8:]})elif message:messages.append({"Role": "user", "Content": message})return messagestry:# 创建 HunyuanAI 实例llm = HunyuanAI(secret_id=SecretId, secret_key=SecretKey)# 创建系统消息模板system_template = "你是一个英语词典助手。你的任务是提供以下信息:\n1. 单词的中文翻译\n2. 英文释义\n3. 一个例句\n请保持回答简洁明了。"system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)# 创建人类消息模板human_template = "请为英文单词 '{word}' 提供解释。如果这个词有多个常见含义,请列出最常见的 2-3 个含义。"human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)# 将系统消息和人类消息组合成聊天提示模板chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])# 创建 LLMChainchain = LLMChain(llm=llm, prompt=chat_prompt)# 运行链word = input("请输入要查询的英文单词: ")result = chain.invoke(input={"word": word})# 打印结果print(result)except Exception as err:print(f"An error occurred: {err}")
注:需要将上述"SecretId"和"SecretKey"替换成自己创建的API密钥。
相关文章:
腾讯混元大模型集成LangChain
腾讯混元大模型集成LangChain 获取API密钥 登录控制台–>访问管理–>API密钥管理–>新建密钥,获取到SecretId和SecretKey。访问链接:https://console.cloud.tencent.com/cam/capi python SDK方式调用大模型 可参考腾讯官方API import json…...

C++心决之stl中那些你不知道的秘密(string篇)
目录 1. 为什么学习string类? 1.1 C语言中的字符串 2. 标准库中的string类 2.1 string类 2.2 string类的常用接口说明 1. string类对象的常见构造 2. string类对象的操作 3.vs和g下string结构的说明 3. string类的模拟实现 3.2 浅拷贝 3.3 深拷贝 3.4 写…...
date 命令学习
文章目录 date 命令学习1. 命令简介2. 语法参数2.1 使用语法2.2 说明2.3 参数说明 3. 使用案例:arrow_right: 星期名缩写 %a:arrow_right: 星期名全写 %A:arrow_right: 月名缩写 %b:arrow_right: 月名全称 %B:arrow_right: 日期和时间 %c:arrow_right: 世纪 %C:arrow_right: 按…...

前端vue后端java使用easyexcel框架下载表格xls数据工具类
一 使用alibaba开源的 easyexcel框架,后台只需一个工具类即可实现下载 后端下载实现 依赖 pom.xml <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependen…...
C#,开发过程中技术点GPT问答记录
6、为什么说GUI编程是事件驱动的? GUI(图形用户界面)编程是一种以图形方式构建用户界面的编程方法,它主要采用事件驱动模型进行程序逻辑的组织。在事件驱动的编程中,程序并不按照固定的顺序线性执行,而是等…...
wifi中的PSR技术
在Wi-Fi网络中,PSR(Preferred Spatial Reuse)是一种新兴技术,旨在提高频谱利用效率,特别是在高密度网络环境中。PSR通过允许多个接入点(AP)和设备在相同频谱资源上同时进行通信,从而…...

电子签章 签到 互动 打卡 创意印章 支持小程序 H5 App
电子签章 签到 互动 打卡 创意印章 支持小程序 H5 App 定制化...
Vscode插件推荐——智能切换输入法(Smart IME)
前言 相信广大程序员朋友在写代码的时候一定会遇到过一个令人非常头疼的事情——切换输入法,特别是对于那些勤于写注释的朋友,简直就是噩梦,正所谓懒人推动世界发展,这不,今天就向大家推荐一款好用的vscode插件&#…...

SpringBoot实战:轻松实现接口数据脱敏
一、接口数据脱敏概述 1.1 接口数据脱敏的定义 接口数据脱敏是Web应用程序中一种保护敏感信息不被泄露的关键措施。在API接口向客户端返回数据时,系统会对包含敏感信息(如个人身份信息、财务数据等)的字段进行特殊处理。这种处理通过应用特…...

我们水冷使制动电阻功率密度成倍增加-水冷电阻设计工厂
先进陶瓷 我们后来发现工业应用中对占用空间最小的水冷电阻器的工业需求,推出了适用于中压工业应用的水冷电阻器。它的特点是两块由具有特殊性能的先进陶瓷制成的板。 使用工业电驱动装置的一个重要好处是,可靠的再生和动态制动系统可以补充或取代传统…...
模板语法指令语法——02
//指令语法: 1.什么是指定,有什么作用? 指令的职责是,当表达式的值改变时,将其产生的连带影响,响应式的作用语DOM 2.vue框架中的所有指令的名字都以v-开始的 3.插值是写在标签当中用的,指令…...

Comparable 和 Comparator 接口的区别
Comparable 和 Comparator 接口的区别 1、Comparable 接口1.1 compareTo() 方法 2、Comparator 接口2.1 compare() 方法 3、 Comparable 和 Comparator 的区别总结 💖The Begin💖点点关注,收藏不迷路💖 在Java中,Compa…...

Python requests爬虫
Python的requests库是一个强大且易于使用的HTTP库,用于发送HTTP请求和处理响应。它是Python中最受欢迎的网络爬虫框架之一,被广泛用于从网页中提取数据、爬取网站和进行API调用。 使用requests库,你可以轻松地发送各种HTTP请求,包…...

Docker 基本管理及部署
目录 1.Docker概述 1.1 Docker是什么? 1.2 Docker的宗旨 1.3 容器的优点 1.4 Docker与虚拟机的区别 1.5 容器在内核中支持的两种技术 1.6 namespace的六大类型 2.Docker核心概念 2.1 镜像 2.2 容器 2.3 仓库 3.安装Docker 3.1 查看 docker 版本信息 4.…...
Ubuntu下安装配置和调优Docker,支持IPV6
今天在阿贝云的免费云服务器上折腾了一番Docker的配置和优化,这家免费云服务器可真不错啊。1核1G 10G硬盘,5M带宽,配置虽然简单但够用了。作为一个免费的云服务器,阿贝云的性能可以说是非常不错的了,完全能胜任日常的开发和部署工作。 让我们开始吧。首先,简单介绍一下Docker吧…...

Proteus + Keil单片机仿真教程(六)多位LED数码管的动态显示
上一节我们通过锁存器和八个八位数码管实现了多个数码管的静态显示,这节主要讲解多位数码管的动态显示,所谓的动态显示就是对两个锁存器的控制。考虑一个问题,现在给WS位锁存器增加一个循环,让它从1111 1110到0111 1111会发生什么事情?话不多说,先上代码: #include<…...
WEB开发-HTML页面更新部分内容
1 需求 2 接口 3 示例 在HTML页面中,如果你想要改变部分内容而不是整个页面,有几种方法可以实现这一目标,主要包括: JavaScript 的 DOM 操作 JavaScript允许你动态地修改HTML文档中的元素内容。你可以使用document.getElementB…...

休息时间c++
题目描述 小杨计划在某个时刻开始学习,并决定在学习k秒后开始休息。 小杨想知道自己开始休息的时刻是多少。 输入 前三行每行包含一个整数,分别表示小杨开始学习时刻的时h、分m、秒s(h,m,s的值符合1≤h≤12,0≤m≤59,0≤s≤59)…...

zabbix 自定义监控项及触发器
1. 在zabbix客户端定义脚本 /etc/zabbix/zabbix_agent2.d/目录下创建自定义监控项脚本 ]# cat /etc/zabbix/zabbix_agent2.d/web.conf #UserParameterkey,cmd #UserParameterngx.port,sh /server/scripts/xxx.sh UserParameterngx.port,ss -lntup|grep -w *:80|wc -lUserPar…...

easyExcel 不规则模板导入数据
文章目录 前言一、需求和效果二、难点和思路三、全部代码踩坑 前言 之前分享的 EasyExcel 批量导入并校验数据,仅支持规则excel,即首行表头,下面对应数据,无合并单元格情况。 本篇主要解决问题: 模板excel 表头不在首…...
HTML 语义化
目录 HTML 语义化HTML5 新特性HTML 语义化的好处语义化标签的使用场景最佳实践 HTML 语义化 HTML5 新特性 标准答案: 语义化标签: <header>:页头<nav>:导航<main>:主要内容<article>&#x…...
在rocky linux 9.5上在线安装 docker
前面是指南,后面是日志 sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io -y docker version sudo systemctl start docker sudo systemctl status docker …...

CMake基础:构建流程详解
目录 1.CMake构建过程的基本流程 2.CMake构建的具体步骤 2.1.创建构建目录 2.2.使用 CMake 生成构建文件 2.3.编译和构建 2.4.清理构建文件 2.5.重新配置和构建 3.跨平台构建示例 4.工具链与交叉编译 5.CMake构建后的项目结构解析 5.1.CMake构建后的目录结构 5.2.构…...
第25节 Node.js 断言测试
Node.js的assert模块主要用于编写程序的单元测试时使用,通过断言可以提早发现和排查出错误。 稳定性: 5 - 锁定 这个模块可用于应用的单元测试,通过 require(assert) 可以使用这个模块。 assert.fail(actual, expected, message, operator) 使用参数…...
高防服务器能够抵御哪些网络攻击呢?
高防服务器作为一种有着高度防御能力的服务器,可以帮助网站应对分布式拒绝服务攻击,有效识别和清理一些恶意的网络流量,为用户提供安全且稳定的网络环境,那么,高防服务器一般都可以抵御哪些网络攻击呢?下面…...

Maven 概述、安装、配置、仓库、私服详解
目录 1、Maven 概述 1.1 Maven 的定义 1.2 Maven 解决的问题 1.3 Maven 的核心特性与优势 2、Maven 安装 2.1 下载 Maven 2.2 安装配置 Maven 2.3 测试安装 2.4 修改 Maven 本地仓库的默认路径 3、Maven 配置 3.1 配置本地仓库 3.2 配置 JDK 3.3 IDEA 配置本地 Ma…...

STM32---外部32.768K晶振(LSE)无法起振问题
晶振是否起振主要就检查两个1、晶振与MCU是否兼容;2、晶振的负载电容是否匹配 目录 一、判断晶振与MCU是否兼容 二、判断负载电容是否匹配 1. 晶振负载电容(CL)与匹配电容(CL1、CL2)的关系 2. 如何选择 CL1 和 CL…...
Oracle11g安装包
Oracle 11g安装包 适用于windows系统,64位 下载路径 oracle 11g 安装包...

Xela矩阵三轴触觉传感器的工作原理解析与应用场景
Xela矩阵三轴触觉传感器通过先进技术模拟人类触觉感知,帮助设备实现精确的力测量与位移监测。其核心功能基于磁性三维力测量与空间位移测量,能够捕捉多维触觉信息。该传感器的设计不仅提升了触觉感知的精度,还为机器人、医疗设备和制造业的智…...

医疗AI模型可解释性编程研究:基于SHAP、LIME与Anchor
1 医疗树模型与可解释人工智能基础 医疗领域的人工智能应用正迅速从理论研究转向临床实践,在这一过程中,模型可解释性已成为确保AI系统被医疗专业人员接受和信任的关键因素。基于树模型的集成算法(如RandomForest、XGBoost、LightGBM)因其卓越的预测性能和相对良好的解释性…...