HuggingFace - 使用 Inference API

mistralai/Mistral-7B-v0.1 为例:
https://huggingface.co/mistralai/Mistral-7B-v0.1

在这里插入图片描述


在这里插入图片描述


Python

import requests

API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-v0.1"
headers = {"Authorization": "Bearer hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}

def query(payload):
	response = requests.post(API_URL, headers=headers, json=payload)
	return response.json()
	
output = query({
	"inputs": "Can you please let us know more details about your ",
})

cURL 命令

curl https://api-inference.huggingface.co/models/mistralai/Mistral-7B-v0.1 \
	-X POST \
	-d '{"inputs": "Can you please let us know more details about your "}' \
	-H 'Content-Type: application/json' \
	-H "Authorization: Bearer hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Quick Links


2024-09-12(四)

### 调用Hugging Face API的方法 为了调用Hugging FaceAPI,通常有两种主要方式:通过官方提供的Python库`transformers`以及直接使用HTTP请求接口。 #### 使用Transformers库调用API 安装必要的依赖之后,可以利用`transformers`库中的工具来简化对API的操作。下面是一个简单的例子展示如何加载预训练模型并执行推理: ```python from transformers import pipeline # 创建一个pipeline对象用于特定的任务,比如情感分析 nlp = pipeline("sentiment-analysis") # 对输入文本进行预测 result = nlp("I love using Hugging Face's tools!") print(result) ``` 这段代码展示了如何快速设置好环境来进行自然语言处理任务[^1]。 对于更复杂的场景或者自定义需求,则可能需要直接访问RESTful风格的服务端点。这涉及到构建合适的URL路径、传递认证信息(如API密钥)、指定参数等操作。 #### 发送HTTP请求至Hugging Face Inference API 当希望通过编程的方式与服务交互而不局限于某个具体框架时,可以直接向Hugging Face提供的Inference API发送POST请求。这里给出了一种基于Python的标准做法: ```python import requests import json api_url = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english" headers = {"Authorization": f"Bearer YOUR_API_TOKEN"} data = { "inputs": ["This is an example sentence."], } response = requests.post(api_url, headers=headers, data=json.dumps(data)) output = response.json() print(output) ``` 请注意,在实际应用中应当替换掉示例中的`YOUR_API_TOKEN`为真实的令牌字符串,并根据所选模型调整API URL地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程乐园

请我喝杯伯爵奶茶~!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值