大模型-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…...
深入剖析AI大模型:大模型时代的 Prompt 工程全解析
今天聊的内容,我认为是AI开发里面非常重要的内容。它在AI开发里无处不在,当你对 AI 助手说 "用李白的风格写一首关于人工智能的诗",或者让翻译模型 "将这段合同翻译成商务日语" 时,输入的这句话就是 Prompt。…...
ffmpeg(四):滤镜命令
FFmpeg 的滤镜命令是用于音视频处理中的强大工具,可以完成剪裁、缩放、加水印、调色、合成、旋转、模糊、叠加字幕等复杂的操作。其核心语法格式一般如下: ffmpeg -i input.mp4 -vf "滤镜参数" output.mp4或者带音频滤镜: ffmpeg…...
Python爬虫(二):爬虫完整流程
爬虫完整流程详解(7大核心步骤实战技巧) 一、爬虫完整工作流程 以下是爬虫开发的完整流程,我将结合具体技术点和实战经验展开说明: 1. 目标分析与前期准备 网站技术分析: 使用浏览器开发者工具(F12&…...
数据链路层的主要功能是什么
数据链路层(OSI模型第2层)的核心功能是在相邻网络节点(如交换机、主机)间提供可靠的数据帧传输服务,主要职责包括: 🔑 核心功能详解: 帧封装与解封装 封装: 将网络层下发…...
Java编程之桥接模式
定义 桥接模式(Bridge Pattern)属于结构型设计模式,它的核心意图是将抽象部分与实现部分分离,使它们可以独立地变化。这种模式通过组合关系来替代继承关系,从而降低了抽象和实现这两个可变维度之间的耦合度。 用例子…...
深入浅出深度学习基础:从感知机到全连接神经网络的核心原理与应用
文章目录 前言一、感知机 (Perceptron)1.1 基础介绍1.1.1 感知机是什么?1.1.2 感知机的工作原理 1.2 感知机的简单应用:基本逻辑门1.2.1 逻辑与 (Logic AND)1.2.2 逻辑或 (Logic OR)1.2.3 逻辑与非 (Logic NAND) 1.3 感知机的实现1.3.1 简单实现 (基于阈…...
C++.OpenGL (20/64)混合(Blending)
混合(Blending) 透明效果核心原理 #mermaid-svg-SWG0UzVfJms7Sm3e {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-SWG0UzVfJms7Sm3e .error-icon{fill:#552222;}#mermaid-svg-SWG0UzVfJms7Sm3e .error-text{fill…...
如何更改默认 Crontab 编辑器 ?
在 Linux 领域中,crontab 是您可能经常遇到的一个术语。这个实用程序在类 unix 操作系统上可用,用于调度在预定义时间和间隔自动执行的任务。这对管理员和高级用户非常有益,允许他们自动执行各种系统任务。 编辑 Crontab 文件通常使用文本编…...
mac 安装homebrew (nvm 及git)
mac 安装nvm 及git 万恶之源 mac 安装这些东西离不开Xcode。及homebrew 一、先说安装git步骤 通用: 方法一:使用 Homebrew 安装 Git(推荐) 步骤如下:打开终端(Terminal.app) 1.安装 Homebrew…...
Vite中定义@软链接
在webpack中可以直接通过符号表示src路径,但是vite中默认不可以。 如何实现: vite中提供了resolve.alias:通过别名在指向一个具体的路径 在vite.config.js中 import { join } from pathexport default defineConfig({plugins: [vue()],//…...
