我尝试使用htrr包在R中复制一个Python API调用。
huggingface中的Python代码:
import json
import requests
API_TOKEN = ""
def query(payload='',parameters=None,options={'use_cache': False}):
API_URL = "https://api-inference.huggingface.co/models/EleutherAI/gpt-neo-2.7B"
headers = {"Authorization": "TOKEN"}
body = {"inputs":payload,'parameters':parameters,'options':options}
response = requests.request("POST", API_URL, headers=headers, data= json.dumps(body))
try:
response.raise_for_status()
except requests.exceptions.HTTPError:
return "Error:"+" ".join(response.json()['error'])
else:
return response.json()[0]['generated_text']
parameters = {
'max_new_tokens':25, # number of generated tokens
'temperature': 0.5, # controlling the randomness of generations
'end_sequence': "###" # stopping sequence for generation
}
prompt="Tweet: \"I hate it when my phone battery dies.\"\n" + \
"Sentiment: Negative\n" + \
"###\n" + \
"Tweet: \"My day has been 👍\"\n" + \
"Sentiment: Positive\n" + \
"###\n" + \
"Tweet: \"This is the link to the article\"\n" + \
"Sentiment: Neutral\n"+ \
"###\n" + \
"Tweet: \"This new music video was incredible\"\n" + \
"Sentiment:" # few-shot prompt
data = query(prompt,parameters,options)
这是可行的-模型通常使用字符串“Positive”来完成提示。
我在R中的尝试:
library(httr)
headers <- c(
`Authorization` = "TOKEN",
`Content-Type` = "application/x-www-form-urlencoded"
)
# this was guessed manually from https://huggingface.co/blog/few-shot-learning-gpt-neo-and-inference-api
# does not quite work yet?
# removing \"´does not make a difference
prompt <- "Tweet: I hate it when my phone battery dies.
Sentiment: Negative
###
Tweet: My day has been 👍
Sentiment: Positive
###
Tweet: This is the link to the article
Sentiment: Neutral
###
Tweet: This new music video was incredible
Sentiment:"
data <- c(`inputs` = prompt,
`max_new_tokens` = 3,
`temperature` = 0.5,
`end_sequence` = "###")
res <- httr::POST(url = "https://api-inference.huggingface.co/models/EleutherAI/gpt-neo-2.7B",
httr::add_headers(.headers=headers), body = data)
content(res)[[1]][[1]]
[1] "Tweet: I hate it when my phone battery dies.\nSentiment: Negative\n###\nTweet: My day has been 👍\nSentiment: Positive\n###\nTweet: This is the link to the article\nSentiment: Neutral\n###\nTweet: This new music video was incredibile\nSentiment:\n3\n0.5\n###\n"
R的输出是“\n3\n0.5\n###\n”-随机的换行符和数字。我怀疑可能是编码或httpr如何解析来自API的json输出有问题。
1条答案
按热度按时间abithluo1#
为您提供
httr2
包和数据清理建议数据清理