大模型-Tool call、检索增强
大模型
Tool call
心知天气:https://www.seniverse.com/
例子:调用天气接口 API
from openai import OpenAI
import requests
import json
"""
##### 天气接口 API 密钥获取:https://www.free-api.com/doc/558 #####
"""# 定义调用天气 API 的函数
def get_weather(location, language="zh-Hans", unit="c"):url = "https://api.seniverse.com/v3/weather/now.json"params = {"key": "123", # 替换为心知天气 Seniverse API Key"location": location,"language": language,"unit": unit,}response = requests.get(url, params=params)return response.json()# # 初始化 OpenAI 客户端
# client = OpenAI(
# api_key="", # 替换为你的 OpenAI API Key
# base_url="https://api.deepseek.com", # DeepSeek 的 API 地址
# )client = OpenAI(api_key="123", # 在这里将 MOONSHOT_API_KEY 替换为你从 Kimi 开放平台申请的 API Keybase_url="https://api.moonshot.cn/v1",
)
model="moonshot-v1-8k"# 发送消息并处理工具调用
def send_messages_with_tools(messages):response = client.chat.completions.create(model=model, # 使用的模型messages=messages,tools=tools,)return response.choices[0].message# 发送消息并处理工具调用
def send_messages_without_tools(messages):response = client.chat.completions.create(model=model, # 使用的模型messages=messages,)return response.choices[0].message# 定义工具(function calling)
tools = [{"type": "function","function": {"name": "get_weather","description": "Get the current weather for a specific location.","parameters": {"type": "object","properties": {"location": {"type": "string","description": "The city or region, e.g. Beijing",},"language": {"type": "string","description": "The language of the response, e.g. zh-Hans","default": "zh-Hans",},"unit": {"type": "string","description": "The unit of temperature, c for Celsius or f for Fahrenheit","default": "c",},},"required": ["location"], # location 是必填参数},},}
]# 初始化对话
messages = [{"role": "user", "content": "上海现在的天气怎么样?"}]
print(f"User>\t {messages[0]['content']}")# 发送消息并获取模型响应
message = send_messages_with_tools(messages)# 检查是否有工具调用
if message.tool_calls:tool_call = message.tool_calls[0]print(f"Function Call>\t {tool_call}")messages.append(message) # 将模型的消息添加到对话历史中# 调用天气 API 名字 参数 调用if tool_call.function.name == "get_weather":function_args = json.loads(tool_call.function.arguments) weather_data = get_weather(**function_args)print(f"Weather Data>\t {weather_data}")# 将 API 返回的结果添加到对话历史中messages.append({"role": "tool","tool_call_id": tool_call.id,"content": str(weather_data), # 将天气数据转换为字符串})print(f"Messages>\t {messages}")# 再次发送消息,获取模型的最终响应final_response = send_messages_without_tools(messages)print(f"Model>\t {final_response.content}")
检索增强RAG
例子:分析文件内容并回答问题
代码:
import numpy as np
from langchain.document_loaders import TextLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import Chroma
from transformers import pipeline# Load documents 加载文档
loader = TextLoader("data/Jay_Chou.txt")
documentation = loader.load()# Split documents into chunks 将文档分割成块
text_splitter = CharacterTextSplitter(chunk_size=128, chunk_overlap=0)
documentation = text_splitter.split_documents(documentation)# Define embedding model 定义嵌入模型
model_name = "sentence-transformers/all-MiniLM-L6-v2"
# model_name = "data/models--sentence-transformers--all-MiniLM-L6-v2"
model_kwargs = {'device': 'cpu'}
encode_kwargs = {'normalize_embeddings': True}
embeddings = HuggingFaceEmbeddings(model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs)# Create vector store 创建向量存储
db = Chroma.from_documents(documentation, embeddings)# Perform similarity search 执行相似性搜索
query = "Who is Jay Chou's wife?" # 周杰伦的妻子是谁
results = db.similarity_search(query)# Print retrieved document content 打印检索到的文档内容
print("Retrieved document content:", results[0].page_content)# Load Hugging Face pipeline for question answering 加载Hugging Face问答管道
qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad", tokenizer="distilbert-base-uncased-distilled-squad")# Manually format the context for the pipeline 手动格式化管道的上下文
context = results[0].page_content # Access the content of the most relevant document 访问最相关文档的内容
input_data = {"context": context,"question": query
}# Print input to the model 将输入打印到模型
print("Input to the model:", input_data)# Get the answer using Hugging Face pipeline 使用Hugging Face管道获取答案
answer = qa_pipeline(input_data)# Print the result 打印结果
print("Answer from the model模型的答案:", answer['answer'])
分析数据:Jay_Chou.txt
Jay Chou, born on January 18, 1979, in New Taipei City, Taiwan, is a renowned singer, songwriter, music producer, director, and actor from Taiwan. He is one of the most influential figures in Chinese pop music and is often referred to as the "King of Chinese Pop" or a representative figure of the genre.Musical Achievements:
Jay Chou's music style is unique, blending various elements such as pop, R&B, rock, hip hop, and electronic music, while emphasizing poetic and profound lyrics. His works not only break the boundaries of traditional Chinese pop music but also skillfully integrate Western musical elements, creating a new trend in music.In 2000, Jay Chou released his debut album Jay, which instantly made him famous and earned him numerous music awards. Since then, every album he has released has sparked great responses and become an important milestone in Chinese pop music. His representative songs include Blue and White Porcelain, Simple Love, Rice Fragrance, East Wind Breaks, Listen to Mama, and others.Songwriting Style:
Jay Chou's songs have a modern feel while often incorporating elements of traditional Chinese culture, especially in his ancient-style songs such as East Wind Breaks and Chrysanthemum Terrace, which reflect his unique understanding and inheritance of Chinese culture. Additionally, his lyrics are often creative and full of personality, sometimes carrying humor or philosophical meanings, and his linguistic style is distinctive, often praised by his fans.Film Career:
In addition to music, Jay Chou has also ventured into the film industry, taking on roles as a director, screenwriter, and actor. His self-written, directed, and starred film Secret (2007) achieved great success, showcasing not only his musical talents but also his potential in filmmaking. He has also appeared in several films, such as Initial D and Kung Fu Dunk, further expanding his influence in the entertainment industry.Personal Life:
Jay Chou leads a low-key private life. In 2005, he married his wife, Hannah Quinlivan, and they have a son and a daughter. Hannah is both his wife and a partner in his career, and the two share a deep relationship, often posting their life moments on social media.Influence and Honors:
Jay Chou is regarded as one of the innovators of Chinese pop music, and his works have a widespread influence among Chinese-speaking communities worldwide. He has won countless music awards and successfully brought Chinese pop music to international stages. His musical style and influence transcend different eras and regions, making him beloved by audiences of all ages.In summary, Jay Chou is not only a superstar in the Chinese music scene but also a symbol of Chinese pop culture due to his innovative spirit and musical talent.
导入各种包:pip install XXX
如果无法连接到https://huggingface.co/,需要设置国内镜像:set HF_ENDPOINT=https://hf-mirror.com
文档:https://hf-mirror.com/
相关文章:
大模型-Tool call、检索增强
大模型 Tool call 心知天气:https://www.seniverse.com/ 例子:调用天气接口 API from openai import OpenAI import requests import json """ ##### 天气接口 API 密钥获取:https://www.free-api.com/doc/558 ##### &quo…...
【算法】【区间和】acwing算法基础 802. 区间和 【有点复杂,但思路简单】
题目 假定有一个无限长的数轴,数轴上每个坐标上的数都是 0。 现在,我们首先进行 n 次操作,每次操作将某一位置 x 上的数加 c。 接下来,进行 m 次询问,每个询问包含两个整数 l 和 r,你需要求出在区间 [l,r] …...
Ubuntu22.04通过Docker部署Jeecgboot
程序发布环境包括docker、mysql、redis、maven、nodejs、npm等。 一、安装docker 1、用如下命令卸载旧Docker: for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do sudo apt-get remove $pkg; done 2、安装APT环境依赖包…...
HTML4
HTML 初体验 1.鼠标右键 > 新建 > 文本文档 > 输入以下内容,并保存 2.修改后缀为 .html ,然后双击打开即可 这里的后缀名,使用 .htm 也可以,但推荐使用更标准的 .html <marquee>尚硅谷,让天下没有难…...
STM32F10X 启动文件完整分析
最近在准备面试相关 顺便复盘总结一下之前的内容 启动文件在基于ARM的芯片是很重要的组成部分,它主要负责完成芯片上电启动时的一系列初始化工作和各种异常及中断的入口地址。 也是理解bootloader自举的关键点,所以需要理解一下 1. 向量表定义 启动文件…...
typescript快速入门之安装与运行
安装 安装ts环境,最好全局安装,这样就不需要开一个项目又安装 npm i -g typescript初始化 可以运行初始化配置文件,也可以手动生成;不生成的话会运行默认配置 使用默认配置 把ts文件转成js文件使用的是es3语言,语…...
React源码解读
配置React源码本地调试环境 本次环境构建采用了node版本为16、react-scripts 版本号为 3.4.4,源码下载地址 react源码调试: react源码调试环境 使用 create-react-app 脚手架创建项目 npx create-react-app react-test 进入刚刚下载的目录,弹射 crea…...
【DeepSeek-R1】 API申请(火山方舟联网版)
DeepSeek-R1 API申请(火山方舟联网版) 1、新建联网版应用2、开通信息增强服务3、开启联网内容插件4、创建接入点5、获取模型名称6、获取API Key 如果第一次注册账号,请先按照文章《【Deepseek-R1】 API申请(火山方舟)》…...
负载均衡集群——LVS-DR配置
一、简介 1.1 什么是集群? 两台及以上的计算机完成一个任务的模式称为集群。 常见的集群类型包括: LB(负载均衡)集群:按照不同的算法将前端的访问转发给后端计算点,使节点负载相对平衡。提高并发能力 缺…...
数据结构篇
链表 用数组模拟链表,看该链表结构,有几个域则用几个数组分别存储 单链表是只知道下一个元素位置,双链表还知道上一个链表位置 单链表 双向链表 左移右移 栈 模拟栈 判断括号序列 队列 模拟队列 递归 集合和哈希 集合就是哈希表 哈希表的实现…...
「软件设计模式」建造者模式(Builder)
深入解析建造者模式:用C打造灵活对象构建流水线 引言:当对象构建遇上排列组合 在开发复杂业务系统时,你是否经常面对这样的类:它有20个成员变量,其中5个是必填项,15个是可选项。当用户需要创建豪华套餐A&…...
Matlab 机器人 雅可比矩阵
工业机器人运动学与Matlab正逆解算法学习笔记(用心总结一文全会)(四)——雅可比矩阵_staubli机器人正逆向运动学实例验证matlab-CSDN博客 matlab求雅可比矩阵_六轴机械臂 矢量积法求解雅可比矩阵-CSDN博客 (63 封私信 / 80 条消息…...
DeepSeek 助力 Vue 开发:打造丝滑的面包屑导航(Breadcrumbs)
前言:哈喽,大家好,今天给大家分享一篇文章!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏关注哦 💕 目录 Deep…...
IntelliJ IDEA 2024.1.4版无Tomcat配置
IntelliJ IDEA 2024.1.4 (Ultimate Edition) 安装完成后,调试项目发现找不到Tomcat服务: 按照常规操作添加,发现服务插件中没有Tomcat。。。 解决方法 1、找到IDE设置窗口 2、点击Plugins按钮,进入插件窗口,搜索T…...
chrome://version/
浏览器输入: chrome://version/ Google浏览器版本号以及安装路径 Google Chrome131.0.6778.205 (正式版本) (64 位) (cohort: Stable) 修订版本81b36b9535e3e3b610a52df3da48cd81362ec860-refs/branch-heads/6778_155{#8}操作系统Windows…...
知识图谱数据库 Neo4j in Docker笔记
下载 docker pull neo4j:community官方说明 https://neo4j.com/docs/operations-manual/2025.01/docker/introduction/ 启动 docker run \--restart always \--publish7474:7474 --publish7687:7687 \--env NEO4J_AUTHneo4j/your_password \--volumeD:\files\knowledgegrap…...
【动手学强化学习】02多臂老虎机
问题定义 强化学习关注的是在于环境交互中学习,是一种试错学习的范式。在正式进入强化学习之前,我们先来了解多臂老虎机问题。该问题也被看作简化版的强化学习,帮助我们更快地过度到强化学习阶段。 有一个拥有 K K K 根拉杆的老虎机&#…...
【网络编程】之Udp网络通信步骤
【网络编程】之Udp网络通信步骤 TCP网络通信TCP网络通信的步骤对于服务器端对于客户端 TCP实现echo功能代码实现服务器端getsockname函数介绍 客户端效果展示 对比两组函数 TCP网络通信 TCP网络通信的步骤 对于服务器端 创建监听套接字。(调用socket函数ÿ…...
Java 基于 SpringBoot+Vue 的家政服务管理平台设计与实现
博主介绍:✌程序员徐师兄、8年大厂程序员经历。全网粉丝12w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战*✌ 🍅文末获取源码联系🍅 👇🏻 精彩专栏推荐订阅👇…...
架构——Nginx功能、职责、原理、配置示例、应用场景
以下是关于 Nginx 的功能、职责、原理、配置示例、应用场景及其高性能原因的详细说明: 一、Nginx 的核心功能 1. 静态资源服务 功能:直接返回静态文件(如 HTML、CSS、JS、图片、视频等)。配置示例:server {listen 80…...
LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明
LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造,完美适配AGV和无人叉车。同时,集成以太网与语音合成技术,为各类高级系统(如MES、调度系统、库位管理、立库等)提供高效便捷的语音交互体验。 L…...
业务系统对接大模型的基础方案:架构设计与关键步骤
业务系统对接大模型:架构设计与关键步骤 在当今数字化转型的浪潮中,大语言模型(LLM)已成为企业提升业务效率和创新能力的关键技术之一。将大模型集成到业务系统中,不仅可以优化用户体验,还能为业务决策提供…...
在Ubuntu中设置开机自动运行(sudo)指令的指南
在Ubuntu系统中,有时需要在系统启动时自动执行某些命令,特别是需要 sudo权限的指令。为了实现这一功能,可以使用多种方法,包括编写Systemd服务、配置 rc.local文件或使用 cron任务计划。本文将详细介绍这些方法,并提供…...
Redis数据倾斜问题解决
Redis 数据倾斜问题解析与解决方案 什么是 Redis 数据倾斜 Redis 数据倾斜指的是在 Redis 集群中,部分节点存储的数据量或访问量远高于其他节点,导致这些节点负载过高,影响整体性能。 数据倾斜的主要表现 部分节点内存使用率远高于其他节…...
关键领域软件测试的突围之路:如何破解安全与效率的平衡难题
在数字化浪潮席卷全球的今天,软件系统已成为国家关键领域的核心战斗力。不同于普通商业软件,这些承载着国家安全使命的软件系统面临着前所未有的质量挑战——如何在确保绝对安全的前提下,实现高效测试与快速迭代?这一命题正考验着…...
【Java学习笔记】BigInteger 和 BigDecimal 类
BigInteger 和 BigDecimal 类 二者共有的常见方法 方法功能add加subtract减multiply乘divide除 注意点:传参类型必须是类对象 一、BigInteger 1. 作用:适合保存比较大的整型数 2. 使用说明 创建BigInteger对象 传入字符串 3. 代码示例 import j…...
Go语言多线程问题
打印零与奇偶数(leetcode 1116) 方法1:使用互斥锁和条件变量 package mainimport ("fmt""sync" )type ZeroEvenOdd struct {n intzeroMutex sync.MutexevenMutex sync.MutexoddMutex sync.Mutexcurrent int…...
c++第七天 继承与派生2
这一篇文章主要内容是 派生类构造函数与析构函数 在派生类中重写基类成员 以及多继承 第一部分:派生类构造函数与析构函数 当创建一个派生类对象时,基类成员是如何初始化的? 1.当派生类对象创建的时候,基类成员的初始化顺序 …...
Qt 事件处理中 return 的深入解析
Qt 事件处理中 return 的深入解析 在 Qt 事件处理中,return 语句的使用是另一个关键概念,它与 event->accept()/event->ignore() 密切相关但作用不同。让我们详细分析一下它们之间的关系和工作原理。 核心区别:不同层级的事件处理 方…...
git: early EOF
macOS报错: Initialized empty Git repository in /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/.git/ remote: Enumerating objects: 2691797, done. remote: Counting objects: 100% (1760/1760), done. remote: Compressing objects: 100% (636/636…...
