当前位置: 首页 > news >正文

大模型-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.鼠标右键 > 新建 > 文本文档 > 输入以下内容&#xff0c;并保存 2.修改后缀为 .html &#xff0c;然后双击打开即可 这里的后缀名&#xff0c;使用 .htm 也可以&#xff0c;但推荐使用更标准的 .html <marquee>尚硅谷&#xff0c;让天下没有难…...

STM32F10X 启动文件完整分析

最近在准备面试相关 顺便复盘总结一下之前的内容 启动文件在基于ARM的芯片是很重要的组成部分&#xff0c;它主要负责完成芯片上电启动时的一系列初始化工作和各种异常及中断的入口地址。 也是理解bootloader自举的关键点&#xff0c;所以需要理解一下 1. 向量表定义 启动文件…...

typescript快速入门之安装与运行

安装 安装ts环境&#xff0c;最好全局安装&#xff0c;这样就不需要开一个项目又安装 npm i -g typescript初始化 可以运行初始化配置文件&#xff0c;也可以手动生成&#xff1b;不生成的话会运行默认配置 使用默认配置 把ts文件转成js文件使用的是es3语言&#xff0c;语…...

React源码解读

配置React源码本地调试环境 本次环境构建采用了node版本为16、react-scripts 版本号为 3.4.4&#xff0c;源码下载地址 react源码调试: react源码调试环境 使用 create-react-app 脚手架创建项目 npx create-react-app react-test 进入刚刚下载的目录&#xff0c;弹射 crea…...

【DeepSeek-R1】 API申请(火山方舟联网版)

DeepSeek-R1 API申请&#xff08;火山方舟联网版&#xff09; 1、新建联网版应用2、开通信息增强服务3、开启联网内容插件4、创建接入点5、获取模型名称6、获取API Key 如果第一次注册账号&#xff0c;请先按照文章《【Deepseek-R1】 API申请&#xff08;火山方舟&#xff09;》…...

负载均衡集群——LVS-DR配置

一、简介 1.1 什么是集群&#xff1f; 两台及以上的计算机完成一个任务的模式称为集群。 常见的集群类型包括&#xff1a; LB&#xff08;负载均衡&#xff09;集群&#xff1a;按照不同的算法将前端的访问转发给后端计算点&#xff0c;使节点负载相对平衡。提高并发能力 缺…...

数据结构篇

链表 用数组模拟链表&#xff0c;看该链表结构&#xff0c;有几个域则用几个数组分别存储 单链表是只知道下一个元素位置&#xff0c;双链表还知道上一个链表位置 单链表 双向链表 左移右移 栈 模拟栈 判断括号序列 队列 模拟队列 递归 集合和哈希 集合就是哈希表 哈希表的实现…...

「软件设计模式」建造者模式(Builder)

深入解析建造者模式&#xff1a;用C打造灵活对象构建流水线 引言&#xff1a;当对象构建遇上排列组合 在开发复杂业务系统时&#xff0c;你是否经常面对这样的类&#xff1a;它有20个成员变量&#xff0c;其中5个是必填项&#xff0c;15个是可选项。当用户需要创建豪华套餐A&…...

Matlab 机器人 雅可比矩阵

工业机器人运动学与Matlab正逆解算法学习笔记&#xff08;用心总结一文全会&#xff09;&#xff08;四&#xff09;——雅可比矩阵_staubli机器人正逆向运动学实例验证matlab-CSDN博客 matlab求雅可比矩阵_六轴机械臂 矢量积法求解雅可比矩阵-CSDN博客 (63 封私信 / 80 条消息…...

DeepSeek 助力 Vue 开发:打造丝滑的面包屑导航(Breadcrumbs)

前言&#xff1a;哈喽&#xff0c;大家好&#xff0c;今天给大家分享一篇文章&#xff01;并提供具体代码帮助大家深入理解&#xff0c;彻底掌握&#xff01;创作不易&#xff0c;如果能帮助到大家或者给大家一些灵感和启发&#xff0c;欢迎收藏关注哦 &#x1f495; 目录 Deep…...

IntelliJ IDEA 2024.1.4版无Tomcat配置

IntelliJ IDEA 2024.1.4 (Ultimate Edition) 安装完成后&#xff0c;调试项目发现找不到Tomcat服务&#xff1a; 按照常规操作添加&#xff0c;发现服务插件中没有Tomcat。。。 解决方法 1、找到IDE设置窗口 2、点击Plugins按钮&#xff0c;进入插件窗口&#xff0c;搜索T…...

chrome://version/

浏览器输入&#xff1a; chrome://version/ Google浏览器版本号以及安装路径 Google Chrome131.0.6778.205 (正式版本) &#xff08;64 位&#xff09; (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多臂老虎机

问题定义 强化学习关注的是在于环境交互中学习&#xff0c;是一种试错学习的范式。在正式进入强化学习之前&#xff0c;我们先来了解多臂老虎机问题。该问题也被看作简化版的强化学习&#xff0c;帮助我们更快地过度到强化学习阶段。 有一个拥有 K K K 根拉杆的老虎机&#…...

【网络编程】之Udp网络通信步骤

【网络编程】之Udp网络通信步骤 TCP网络通信TCP网络通信的步骤对于服务器端对于客户端 TCP实现echo功能代码实现服务器端getsockname函数介绍 客户端效果展示 对比两组函数 TCP网络通信 TCP网络通信的步骤 对于服务器端 创建监听套接字。&#xff08;调用socket函数&#xff…...

Java 基于 SpringBoot+Vue 的家政服务管理平台设计与实现

博主介绍&#xff1a;✌程序员徐师兄、8年大厂程序员经历。全网粉丝12w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战*✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447…...

架构——Nginx功能、职责、原理、配置示例、应用场景

以下是关于 Nginx 的功能、职责、原理、配置示例、应用场景及其高性能原因的详细说明&#xff1a; 一、Nginx 的核心功能 1. 静态资源服务 功能&#xff1a;直接返回静态文件&#xff08;如 HTML、CSS、JS、图片、视频等&#xff09;。配置示例&#xff1a;server {listen 80…...

多模态商品数据接口:融合图像、语音与文字的下一代商品详情体验

一、多模态商品数据接口的技术架构 &#xff08;一&#xff09;多模态数据融合引擎 跨模态语义对齐 通过Transformer架构实现图像、语音、文字的语义关联。例如&#xff0c;当用户上传一张“蓝色连衣裙”的图片时&#xff0c;接口可自动提取图像中的颜色&#xff08;RGB值&…...

【算法训练营Day07】字符串part1

文章目录 反转字符串反转字符串II替换数字 反转字符串 题目链接&#xff1a;344. 反转字符串 双指针法&#xff0c;两个指针的元素直接调转即可 class Solution {public void reverseString(char[] s) {int head 0;int end s.length - 1;while(head < end) {char temp …...

【AI学习】三、AI算法中的向量

在人工智能&#xff08;AI&#xff09;算法中&#xff0c;向量&#xff08;Vector&#xff09;是一种将现实世界中的数据&#xff08;如图像、文本、音频等&#xff09;转化为计算机可处理的数值型特征表示的工具。它是连接人类认知&#xff08;如语义、视觉特征&#xff09;与…...

Spring Boot面试题精选汇总

&#x1f91f;致敬读者 &#x1f7e9;感谢阅读&#x1f7e6;笑口常开&#x1f7ea;生日快乐⬛早点睡觉 &#x1f4d8;博主相关 &#x1f7e7;博主信息&#x1f7e8;博客首页&#x1f7eb;专栏推荐&#x1f7e5;活动信息 文章目录 Spring Boot面试题精选汇总⚙️ **一、核心概…...

成都鼎讯硬核科技!雷达目标与干扰模拟器,以卓越性能制胜电磁频谱战

在现代战争中&#xff0c;电磁频谱已成为继陆、海、空、天之后的 “第五维战场”&#xff0c;雷达作为电磁频谱领域的关键装备&#xff0c;其干扰与抗干扰能力的较量&#xff0c;直接影响着战争的胜负走向。由成都鼎讯科技匠心打造的雷达目标与干扰模拟器&#xff0c;凭借数字射…...

tree 树组件大数据卡顿问题优化

问题背景 项目中有用到树组件用来做文件目录&#xff0c;但是由于这个树组件的节点越来越多&#xff0c;导致页面在滚动这个树组件的时候浏览器就很容易卡死。这种问题基本上都是因为dom节点太多&#xff0c;导致的浏览器卡顿&#xff0c;这里很明显就需要用到虚拟列表的技术&…...

【开发技术】.Net使用FFmpeg视频特定帧上绘制内容

目录 一、目的 二、解决方案 2.1 什么是FFmpeg 2.2 FFmpeg主要功能 2.3 使用Xabe.FFmpeg调用FFmpeg功能 2.4 使用 FFmpeg 的 drawbox 滤镜来绘制 ROI 三、总结 一、目的 当前市场上有很多目标检测智能识别的相关算法&#xff0c;当前调用一个医疗行业的AI识别算法后返回…...

音视频——I2S 协议详解

I2S 协议详解 I2S (Inter-IC Sound) 协议是一种串行总线协议&#xff0c;专门用于在数字音频设备之间传输数字音频数据。它由飞利浦&#xff08;Philips&#xff09;公司开发&#xff0c;以其简单、高效和广泛的兼容性而闻名。 1. 信号线 I2S 协议通常使用三根或四根信号线&a…...

C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)

名人说:路漫漫其修远兮,吾将上下而求索。—— 屈原《离骚》 创作者:Code_流苏(CSDN)(一个喜欢古诗词和编程的Coder😊) 专栏介绍:《编程项目实战》 目录 一、为什么要开发一个日历程序?1. 深入理解时间算法2. 练习面向对象设计3. 学习数据结构应用二、核心算法深度解析…...

4. TypeScript 类型推断与类型组合

一、类型推断 (一) 什么是类型推断 TypeScript 的类型推断会根据变量、函数返回值、对象和数组的赋值和使用方式&#xff0c;自动确定它们的类型。 这一特性减少了显式类型注解的需要&#xff0c;在保持类型安全的同时简化了代码。通过分析上下文和初始值&#xff0c;TypeSc…...