腾讯混元大模型集成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 表头不在首…...
龙虎榜——20250610
上证指数放量收阴线,个股多数下跌,盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型,指数短线有调整的需求,大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的:御银股份、雄帝科技 驱动…...
Spark 之 入门讲解详细版(1)
1、简介 1.1 Spark简介 Spark是加州大学伯克利分校AMP实验室(Algorithms, Machines, and People Lab)开发通用内存并行计算框架。Spark在2013年6月进入Apache成为孵化项目,8个月后成为Apache顶级项目,速度之快足见过人之处&…...
黑马Mybatis
Mybatis 表现层:页面展示 业务层:逻辑处理 持久层:持久数据化保存 在这里插入图片描述 Mybatis快速入门 配置HarmonyOS SDK 5.0确保Node.js版本≥14 项目初始化: ohpm init harmony/hospital-report-app 二、核心功能模块实现 1. 报告列表…...
什么是EULA和DPA
文章目录 EULA(End User License Agreement)DPA(Data Protection Agreement)一、定义与背景二、核心内容三、法律效力与责任四、实际应用与意义 EULA(End User License Agreement) 定义: EULA即…...
Redis数据倾斜问题解决
Redis 数据倾斜问题解析与解决方案 什么是 Redis 数据倾斜 Redis 数据倾斜指的是在 Redis 集群中,部分节点存储的数据量或访问量远高于其他节点,导致这些节点负载过高,影响整体性能。 数据倾斜的主要表现 部分节点内存使用率远高于其他节…...
DeepSeek 技术赋能无人农场协同作业:用 AI 重构农田管理 “神经网”
目录 一、引言二、DeepSeek 技术大揭秘2.1 核心架构解析2.2 关键技术剖析 三、智能农业无人农场协同作业现状3.1 发展现状概述3.2 协同作业模式介绍 四、DeepSeek 的 “农场奇妙游”4.1 数据处理与分析4.2 作物生长监测与预测4.3 病虫害防治4.4 农机协同作业调度 五、实际案例大…...
Yolov8 目标检测蒸馏学习记录
yolov8系列模型蒸馏基本流程,代码下载:这里本人提交了一个demo:djdll/Yolov8_Distillation: Yolov8轻量化_蒸馏代码实现 在轻量化模型设计中,**知识蒸馏(Knowledge Distillation)**被广泛应用,作为提升模型…...
Web中间件--tomcat学习
Web中间件–tomcat Java虚拟机详解 什么是JAVA虚拟机 Java虚拟机是一个抽象的计算机,它可以执行Java字节码。Java虚拟机是Java平台的一部分,Java平台由Java语言、Java API和Java虚拟机组成。Java虚拟机的主要作用是将Java字节码转换为机器代码&#x…...
