DocsGPT/application/llm/docsgpt_provider.py

45 lines
1.6 KiB
Python
Raw Normal View History

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
class DocsGPTAPILLM(BaseLLM):
2024-01-08 23:35:37 +00:00
2024-04-16 10:01:11 +00:00
def __init__(self, api_key=None, user_api_key=None, *args, **kwargs):
2024-04-15 09:33:00 +00:00
super().__init__(*args, **kwargs)
self.api_key = api_key
2024-04-16 10:01:11 +00:00
self.user_api_key = user_api_key
2024-04-15 09:33:00 +00:00
self.endpoint = "https://llm.docsgpt.co.uk"
2024-01-08 23:35:37 +00:00
def _raw_gen(self, baseself, model, messages, stream=False, *args, **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
def _raw_gen_stream(self, baseself, model, messages, stream=True, *args, **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"]