腾讯混元大模型集成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 表头不在首…...

前端调试技巧(npm Link,vscode调试,浏览器调试等)
Npm Link 功能: 在本地开发npm模块的时候,我们可以使用npm link命令,将npm 模块链接到对应的运行项目中去,方便地对模块进行调试和测试 断点调试 vscode调试 Debug Vue2 Project 目标:在VSCode中调试项目代码…...

SSL证书到期自动巡检脚本-推送钉钉告警
1. 编写SSL证书巡检脚本 cat /hao/batch_check_ssl_expire.sh #!/bin/bash# 域名列表文件绝对路径 domains_file"/hao/domains.txt"#钉钉webhook webhook_url"https://oapi.dingtalk.com/robot/send?access_token99999999999999999999999999999999999999999…...

Winform打印编程基础
1、目的 进行打印设置、打印预览、及实现打印功能 2、代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Linq; using System.Te…...

Python编程实例-Python的隐藏特性
Python的隐藏特性 文章目录 Python的隐藏特性1、Python中的下划线(_)2、通过解析树进行正则表达式调试3、省略号(...)4、dir()函数5、Lambda 函数6、链式比较运算符7、zip()函数8、修饰器9、上下文管理器和with语句10、生成器和yield语句11、元类(Metaclass)12、小结Python…...

防火墙安全策略利用
拓扑图: 办公区为10.0.1.0/24 生产部为:10.0.2.0/24 办公区为vlan2,生产区为vlan3 DMZ区域为10.0.3.0/24、10.0.3.10为HTTP服务器 游客区:210.0.0./24 ISP:12.0.0.0/24 要求3: 添加安全策略…...

SystemUIService启动-Android13
SystemUIService启动-Android13 1、SystemUIService启动2、其他SystemUI services启动2.1 Dagger依赖注入2.2 Recents为例 1、SystemUIService启动 SystemUI启动,及其SystemUIService启动 <!-- SystemUi service component --><string name"config_s…...

linux权限深度解析——探索原理
前言:本节内容主要讲述的是linux权限相关的内容, linux的权限如果使用root账号是感受不到的, 所以我们要使用普通账号对本节相关内容进行学习,以及一些实验的测试。 然后, 通过linux权限的学习我们可以知道为什么有时候…...

Qt学生管理系统(付源码)
Qt学生管理系统 一、前言1.1 项目介绍1.2 项目目标 2、需求说明2.1 功能性说明2.2 非功能性说明 三、UX设计3.1 登录界面3.2 学生数据展示3.3 信息插入和更新 三、架构说明3.1 客户端结构如下3.2 数据流程图3.2.1 数据管理3.2.2 管理员登录 四、 设计说明3.1 数据库设计3.2 结构…...

重磅!新公司法正式实施,这些变化你必须知道! ️
新公司法来了!企业设立和经营必知的关键变动 🏛️🚀 大家好,我是猫头虎,科技自媒体博主。今天我们来聊聊一件大事——新公司法的实施,这对企业设立和经营带来了哪些重大影响?跟着我,…...

[Flask笔记]一个完整的Flask程序
前面讲过Flask是一个轻量级Web开发框架,为什么说是轻量级的呢,因为它用短短几行代码就能运行起来,我们一起来看看最简单的flask框架。 安装Flask 在看Flask框架之前我们需要先安装flask模块,学过python的肯定都知道,…...