大模型-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…...
Android Wi-Fi 连接失败日志分析
1. Android wifi 关键日志总结 (1) Wi-Fi 断开 (CTRL-EVENT-DISCONNECTED reason3) 日志相关部分: 06-05 10:48:40.987 943 943 I wpa_supplicant: wlan0: CTRL-EVENT-DISCONNECTED bssid44:9b:c1:57:a8:90 reason3 locally_generated1解析: CTR…...
Qt Widget类解析与代码注释
#include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this); }Widget::~Widget() {delete ui; }//解释这串代码,写上注释 当然可以!这段代码是 Qt …...
Mysql中select查询语句的执行过程
目录 1、介绍 1.1、组件介绍 1.2、Sql执行顺序 2、执行流程 2.1. 连接与认证 2.2. 查询缓存 2.3. 语法解析(Parser) 2.4、执行sql 1. 预处理(Preprocessor) 2. 查询优化器(Optimizer) 3. 执行器…...
return this;返回的是谁
一个审批系统的示例来演示责任链模式的实现。假设公司需要处理不同金额的采购申请,不同级别的经理有不同的审批权限: // 抽象处理者:审批者 abstract class Approver {protected Approver successor; // 下一个处理者// 设置下一个处理者pub…...
莫兰迪高级灰总结计划简约商务通用PPT模版
莫兰迪高级灰总结计划简约商务通用PPT模版,莫兰迪调色板清新简约工作汇报PPT模版,莫兰迪时尚风极简设计PPT模版,大学生毕业论文答辩PPT模版,莫兰迪配色总结计划简约商务通用PPT模版,莫兰迪商务汇报PPT模版,…...
PLC入门【4】基本指令2(SET RST)
04 基本指令2 PLC编程第四课基本指令(2) 1、运用上接课所学的基本指令完成个简单的实例编程。 2、学习SET--置位指令 3、RST--复位指令 打开软件(FX-TRN-BEG-C),从 文件 - 主画面,“B: 让我们学习基本的”- “B-3.控制优先程序”。 点击“梯形图编辑”…...
初级程序员入门指南
初级程序员入门指南 在数字化浪潮中,编程已然成为极具价值的技能。对于渴望踏入程序员行列的新手而言,明晰入门路径与必备知识是开启征程的关键。本文将为初级程序员提供全面的入门指引。 一、明确学习方向 (一)编程语言抉择 编…...
SFTrack:面向警务无人机的自适应多目标跟踪算法——突破小尺度高速运动目标的追踪瓶颈
【导读】 本文针对无人机(UAV)视频中目标尺寸小、运动快导致的多目标跟踪难题,提出一种更简单高效的方法。核心创新在于从低置信度检测启动跟踪(贴合无人机场景特性),并改进传统外观匹配算法以关联此类检测…...
HarmonyOS-ArkUI 自定义弹窗
自定义弹窗 自定义弹窗是界面开发中最为常用的一种弹窗写法。在自定义弹窗中, 布局样式完全由您决定,非常灵活。通常会被封装成工具类,以使得APP中所有弹窗具备相同的设计风格。 自定义弹窗具备的能力有 打开弹窗自定义布局,以…...
matlab模糊控制实现路径规划
路径规划是机器人和自动驾驶系统中的重要问题之一,它涉及确定如何在给定环境中找到最优路径以达到特定目标。模糊控制是一种有效的控制方法,可以应用于路径规划问题。 路径规划算法的目标是在避免障碍物的情况下,找到机器人或车辆从起点到终…...
