2024-01-08 23:35:37 +00:00
|
|
|
from application.llm.base import BaseLLM
|
|
|
|
import json
|
|
|
|
import requests
|
2024-04-15 09:33:00 +00:00
|
|
|
from application.usage import gen_token_usage, stream_token_usage
|
2024-01-08 23:35:37 +00:00
|
|
|
|
|
|
|
|
2024-04-15 09:33:00 +00:00
|
|
|
class DocsGPTAPILLM(BaseLLM):
|
2024-01-08 23:35:37 +00:00
|
|
|
|
2024-04-15 09:33:00 +00:00
|
|
|
def __init__(self, api_key, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.api_key = api_key
|
|
|
|
self.endpoint = "https://llm.docsgpt.co.uk"
|
2024-01-08 23:35:37 +00:00
|
|
|
|
2024-04-15 09:33:00 +00:00
|
|
|
@gen_token_usage
|
2024-04-09 13:02:33 +00:00
|
|
|
def gen(self, model, messages, stream=False, **kwargs):
|
2024-04-15 09:33:00 +00:00
|
|
|
context = messages[0]["content"]
|
|
|
|
user_question = messages[-1]["content"]
|
2024-01-08 23:35:37 +00:00
|
|
|
prompt = f"### Instruction \n {user_question} \n ### Context \n {context} \n ### Answer \n"
|
|
|
|
|
|
|
|
response = requests.post(
|
2024-04-15 09:33:00 +00:00
|
|
|
f"{self.endpoint}/answer", json={"prompt": prompt, "max_new_tokens": 30}
|
2024-01-08 23:35:37 +00:00
|
|
|
)
|
2024-04-15 09:33:00 +00:00
|
|
|
response_clean = response.json()["a"].replace("###", "")
|
2024-01-08 23:35:37 +00:00
|
|
|
|
|
|
|
return response_clean
|
|
|
|
|
2024-04-15 09:33:00 +00:00
|
|
|
@stream_token_usage
|
2024-04-09 13:02:33 +00:00
|
|
|
def gen_stream(self, model, messages, stream=True, **kwargs):
|
2024-04-15 09:33:00 +00:00
|
|
|
context = messages[0]["content"]
|
|
|
|
user_question = messages[-1]["content"]
|
2024-01-08 23:35:37 +00:00
|
|
|
prompt = f"### Instruction \n {user_question} \n ### Context \n {context} \n ### Answer \n"
|
|
|
|
|
|
|
|
# send prompt to endpoint /stream
|
|
|
|
response = requests.post(
|
|
|
|
f"{self.endpoint}/stream",
|
2024-04-15 09:33:00 +00:00
|
|
|
json={"prompt": prompt, "max_new_tokens": 256},
|
|
|
|
stream=True,
|
2024-01-08 23:35:37 +00:00
|
|
|
)
|
2024-04-15 09:33:00 +00:00
|
|
|
|
2024-01-08 23:35:37 +00:00
|
|
|
for line in response.iter_lines():
|
|
|
|
if line:
|
2024-04-15 09:33:00 +00:00
|
|
|
# data = json.loads(line)
|
|
|
|
data_str = line.decode("utf-8")
|
2024-01-08 23:35:37 +00:00
|
|
|
if data_str.startswith("data: "):
|
|
|
|
data = json.loads(data_str[6:])
|
2024-04-15 09:33:00 +00:00
|
|
|
yield data["a"]
|