腾讯混元大模型集成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 表头不在首…...
【Go】3、Go语言进阶与依赖管理
前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课,做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程,它的核心机制是 Goroutine 协程、Channel 通道,并基于CSP(Communicating Sequential Processes࿰…...
uniapp中使用aixos 报错
问题: 在uniapp中使用aixos,运行后报如下错误: AxiosError: There is no suitable adapter to dispatch the request since : - adapter xhr is not supported by the environment - adapter http is not available in the build 解决方案&…...
重启Eureka集群中的节点,对已经注册的服务有什么影响
先看答案,如果正确地操作,重启Eureka集群中的节点,对已经注册的服务影响非常小,甚至可以做到无感知。 但如果操作不当,可能会引发短暂的服务发现问题。 下面我们从Eureka的核心工作原理来详细分析这个问题。 Eureka的…...
A2A JS SDK 完整教程:快速入门指南
目录 什么是 A2A JS SDK?A2A JS 安装与设置A2A JS 核心概念创建你的第一个 A2A JS 代理A2A JS 服务端开发A2A JS 客户端使用A2A JS 高级特性A2A JS 最佳实践A2A JS 故障排除 什么是 A2A JS SDK? A2A JS SDK 是一个专为 JavaScript/TypeScript 开发者设计的强大库ÿ…...
【JVM】Java虚拟机(二)——垃圾回收
目录 一、如何判断对象可以回收 (一)引用计数法 (二)可达性分析算法 二、垃圾回收算法 (一)标记清除 (二)标记整理 (三)复制 (四ÿ…...
提升移动端网页调试效率:WebDebugX 与常见工具组合实践
在日常移动端开发中,网页调试始终是一个高频但又极具挑战的环节。尤其在面对 iOS 与 Android 的混合技术栈、各种设备差异化行为时,开发者迫切需要一套高效、可靠且跨平台的调试方案。过去,我们或多或少使用过 Chrome DevTools、Remote Debug…...
协议转换利器,profinet转ethercat网关的两大派系,各有千秋
随着工业以太网的发展,其高效、便捷、协议开放、易于冗余等诸多优点,被越来越多的工业现场所采用。西门子SIMATIC S7-1200/1500系列PLC集成有Profinet接口,具有实时性、开放性,使用TCP/IP和IT标准,符合基于工业以太网的…...
DAY 45 超大力王爱学Python
来自超大力王的友情提示:在用tensordoard的时候一定一定要用绝对位置,例如:tensorboard --logdir"D:\代码\archive (1)\runs\cifar10_mlp_experiment_2" 不然读取不了数据 知识点回顾: tensorboard的发展历史和原理tens…...
网页端 js 读取发票里的二维码信息(图片和PDF格式)
起因 为了实现在报销流程中,发票不能重用的限制,发票上传后,希望能读出发票号,并记录发票号已用,下次不再可用于报销。 基于上面的需求,研究了OCR 的方式和读PDF的方式,实际是可行的ÿ…...
在Spring Boot中集成RabbitMQ的完整指南
前言 在现代微服务架构中,消息队列(Message Queue)是实现异步通信、解耦系统组件的重要工具。RabbitMQ 是一个流行的消息中间件,支持多种消息协议,具有高可靠性和可扩展性。 本博客将详细介绍如何在 Spring Boot 项目…...
