-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
55 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
# SPDX-FileCopyrightText: 2023-present Massimiliano Pippi <[email protected]> | ||
# | ||
# SPDX-License-Identifier: MIT | ||
import os | ||
import html | ||
|
||
import requests | ||
from jinja2 import nodes | ||
from jinja2.ext import Extension | ||
|
||
|
||
class HFInferenceEndpointsExtension(Extension): | ||
""" | ||
`inference_endpoint` can be used to call the Hugging Face Inference Endpoint API | ||
passing a prompt to get back some content. | ||
Example: | ||
``` | ||
{% inference_endpoint "write a tweet with positive sentiment", "https://foo.aws.endpoints.huggingface.cloud" %} | ||
Life is beautiful, full of opportunities & positivity | ||
``` | ||
""" | ||
|
||
# a set of names that trigger the extension. | ||
tags = {"inference_endpoint"} | ||
|
||
def parse(self, parser): | ||
# We get the line number of the first token so that we can give | ||
# that line number to the nodes we create by hand. | ||
lineno = next(parser.stream).lineno | ||
|
||
# The args passed to the extension: | ||
# - the prompt text used to generate new text | ||
args = [parser.parse_expression()] | ||
# - second param after the comma, the inference endpoint URL | ||
parser.stream.skip_if("comma") | ||
args.append(parser.parse_expression()) | ||
|
||
return nodes.Output([self.call_method("_call_endpoint", args)]).set_lineno(lineno) | ||
|
||
def _call_endpoint(self, text, endpoint): | ||
""" | ||
Helper callback. | ||
""" | ||
access_token = os.environ.get("HF_ACCESS_TOKEN") | ||
response = requests.post(endpoint, json={"inputs": text}, headers={'Authorization': f'Bearer {access_token}'}) | ||
response_body = response.json() | ||
|
||
if response_body: | ||
return html.unescape(response_body[0].get("generated_text", "")) | ||
return "" |