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

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明
LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造,完美适配AGV和无人叉车。同时,集成以太网与语音合成技术,为各类高级系统(如MES、调度系统、库位管理、立库等)提供高效便捷的语音交互体验。 L…...

调用支付宝接口响应40004 SYSTEM_ERROR问题排查
在对接支付宝API的时候,遇到了一些问题,记录一下排查过程。 Body:{"datadigital_fincloud_generalsaas_face_certify_initialize_response":{"msg":"Business Failed","code":"40004","sub_msg…...
STM32+rt-thread判断是否联网
一、根据NETDEV_FLAG_INTERNET_UP位判断 static bool is_conncected(void) {struct netdev *dev RT_NULL;dev netdev_get_first_by_flags(NETDEV_FLAG_INTERNET_UP);if (dev RT_NULL){printf("wait netdev internet up...");return false;}else{printf("loc…...

【JVM】- 内存结构
引言 JVM:Java Virtual Machine 定义:Java虚拟机,Java二进制字节码的运行环境好处: 一次编写,到处运行自动内存管理,垃圾回收的功能数组下标越界检查(会抛异常,不会覆盖到其他代码…...
LLM基础1_语言模型如何处理文本
基于GitHub项目:https://github.com/datawhalechina/llms-from-scratch-cn 工具介绍 tiktoken:OpenAI开发的专业"分词器" torch:Facebook开发的强力计算引擎,相当于超级计算器 理解词嵌入:给词语画"…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)
UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中,UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化…...

多种风格导航菜单 HTML 实现(附源码)
下面我将为您展示 6 种不同风格的导航菜单实现,每种都包含完整 HTML、CSS 和 JavaScript 代码。 1. 简约水平导航栏 <!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport&qu…...
聊一聊接口测试的意义有哪些?
目录 一、隔离性 & 早期测试 二、保障系统集成质量 三、验证业务逻辑的核心层 四、提升测试效率与覆盖度 五、系统稳定性的守护者 六、驱动团队协作与契约管理 七、性能与扩展性的前置评估 八、持续交付的核心支撑 接口测试的意义可以从四个维度展开,首…...

【 java 虚拟机知识 第一篇 】
目录 1.内存模型 1.1.JVM内存模型的介绍 1.2.堆和栈的区别 1.3.栈的存储细节 1.4.堆的部分 1.5.程序计数器的作用 1.6.方法区的内容 1.7.字符串池 1.8.引用类型 1.9.内存泄漏与内存溢出 1.10.会出现内存溢出的结构 1.内存模型 1.1.JVM内存模型的介绍 内存模型主要分…...
解决:Android studio 编译后报错\app\src\main\cpp\CMakeLists.txt‘ to exist
现象: android studio报错: [CXX1409] D:\GitLab\xxxxx\app.cxx\Debug\3f3w4y1i\arm64-v8a\android_gradle_build.json : expected buildFiles file ‘D:\GitLab\xxxxx\app\src\main\cpp\CMakeLists.txt’ to exist 解决: 不要动CMakeLists.…...