Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -2,28 +2,14 @@ import time, aiohttp, asyncio, json, os, multiprocessing, torch
|
|
2 |
from minivectordb.embedding_model import EmbeddingModel
|
3 |
from minivectordb.vector_database import VectorDatabase
|
4 |
from text_util_en_pt.cleaner import structurize_text, detect_language, Language
|
5 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
-
from transformers import StoppingCriteria, StoppingCriteriaList, TextIteratorStreamer
|
7 |
from webtextcrawler.webtextcrawler import extract_text_from_url
|
8 |
-
from threading import Thread
|
9 |
from duckduckgo_search import DDGS
|
10 |
import gradio as gr
|
11 |
|
12 |
torch.set_num_threads(2)
|
13 |
|
|
|
14 |
model = EmbeddingModel(use_quantized_onnx_model=True)
|
15 |
-
tokenizer = AutoTokenizer.from_pretrained("sreeramajay/TinyLlama-1.1B-orca-v1.0")
|
16 |
-
llm = AutoModelForCausalLM.from_pretrained("sreeramajay/TinyLlama-1.1B-orca-v1.0")
|
17 |
-
|
18 |
-
prompt_template = """<|system|>
|
19 |
-
You are a helpful assistant chatbot.</s>
|
20 |
-
<|user|>
|
21 |
-
$PROMPT</s>
|
22 |
-
<|assistant|>
|
23 |
-
"""
|
24 |
-
|
25 |
-
def count_tokens(text):
|
26 |
-
return len(tokenizer.encode(text))
|
27 |
|
28 |
def fetch_links(query, max_results=5):
|
29 |
with DDGS() as ddgs:
|
@@ -50,7 +36,7 @@ def index_and_search(query, text):
|
|
50 |
|
51 |
# Retrieval
|
52 |
start = time.time()
|
53 |
-
search_results = vector_db.find_most_similar(query_embedding, k =
|
54 |
retrieval_time = time.time() - start
|
55 |
return '\n'.join([s['sentence'] for s in search_results[2]]), embedding_time, retrieval_time
|
56 |
|
@@ -67,30 +53,7 @@ def retrieval_pipeline(query):
|
|
67 |
|
68 |
return context, websearch_time, webcrawl_time, embedding_time, retrieval_time, links
|
69 |
|
70 |
-
def
|
71 |
-
model_inputs = tokenizer([
|
72 |
-
prompt
|
73 |
-
], return_tensors="pt")
|
74 |
-
|
75 |
-
streamer = TextIteratorStreamer(tokenizer, timeout=120., skip_prompt=True, skip_special_tokens=True)
|
76 |
-
|
77 |
-
generate_kwargs = dict(
|
78 |
-
model_inputs,
|
79 |
-
streamer=streamer,
|
80 |
-
max_new_tokens=2048 - count_tokens(prompt),
|
81 |
-
do_sample=True,
|
82 |
-
temperature=0.7,
|
83 |
-
top_p=0.9,
|
84 |
-
repetition_penalty=2.5
|
85 |
-
)
|
86 |
-
t = Thread(target=llm.generate, kwargs=generate_kwargs)
|
87 |
-
t.start() # Starting the generation in a separate thread.
|
88 |
-
partial_message = ""
|
89 |
-
for new_token in streamer:
|
90 |
-
partial_message += new_token
|
91 |
-
yield partial_message
|
92 |
-
|
93 |
-
def predict(message, history):
|
94 |
context, websearch_time, webcrawl_time, embedding_time, retrieval_time, links = retrieval_pipeline(message)
|
95 |
|
96 |
if detect_language(message) == Language.ptbr:
|
@@ -98,14 +61,49 @@ def predict(message, history):
|
|
98 |
else:
|
99 |
prompt = f"Context:\n\n{context}\n\nBased on the context, answer: {message}"
|
100 |
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
full_response = ""
|
104 |
-
|
105 |
-
|
106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
|
108 |
final_metadata_block = ""
|
|
|
109 |
final_metadata_block += f"Links visited:\n"
|
110 |
for link in links:
|
111 |
final_metadata_block += f"{link}\n"
|
|
|
2 |
from minivectordb.embedding_model import EmbeddingModel
|
3 |
from minivectordb.vector_database import VectorDatabase
|
4 |
from text_util_en_pt.cleaner import structurize_text, detect_language, Language
|
|
|
|
|
5 |
from webtextcrawler.webtextcrawler import extract_text_from_url
|
|
|
6 |
from duckduckgo_search import DDGS
|
7 |
import gradio as gr
|
8 |
|
9 |
torch.set_num_threads(2)
|
10 |
|
11 |
+
openrouter_key = os.environ.get("OPENROUTER_KEY")
|
12 |
model = EmbeddingModel(use_quantized_onnx_model=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
def fetch_links(query, max_results=5):
|
15 |
with DDGS() as ddgs:
|
|
|
36 |
|
37 |
# Retrieval
|
38 |
start = time.time()
|
39 |
+
search_results = vector_db.find_most_similar(query_embedding, k = 12)
|
40 |
retrieval_time = time.time() - start
|
41 |
return '\n'.join([s['sentence'] for s in search_results[2]]), embedding_time, retrieval_time
|
42 |
|
|
|
53 |
|
54 |
return context, websearch_time, webcrawl_time, embedding_time, retrieval_time, links
|
55 |
|
56 |
+
async def predict(message, history):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
context, websearch_time, webcrawl_time, embedding_time, retrieval_time, links = retrieval_pipeline(message)
|
58 |
|
59 |
if detect_language(message) == Language.ptbr:
|
|
|
61 |
else:
|
62 |
prompt = f"Context:\n\n{context}\n\nBased on the context, answer: {message}"
|
63 |
|
64 |
+
url = "https://openrouter.ai/api/v1/chat/completions"
|
65 |
+
headers = { "Content-Type": "application/json",
|
66 |
+
"Authorization": f"Bearer {openrouter_key}" }
|
67 |
+
body = { "stream": True,
|
68 |
+
"models": [
|
69 |
+
"mistralai/mistral-7b-instruct:free",
|
70 |
+
"nousresearch/nous-capybara-7b:free",
|
71 |
+
"huggingfaceh4/zephyr-7b-beta:free"
|
72 |
+
],
|
73 |
+
"route": "fallback",
|
74 |
+
"max_tokens": 768,
|
75 |
+
"messages": [
|
76 |
+
{"role": "user", "content": prompt}
|
77 |
+
] }
|
78 |
|
79 |
full_response = ""
|
80 |
+
async with aiohttp.ClientSession() as session:
|
81 |
+
async with session.post(url, headers=headers, json=body) as response:
|
82 |
+
buffer = "" # A buffer to hold incomplete lines of data
|
83 |
+
async for chunk in response.content.iter_any():
|
84 |
+
buffer += chunk.decode()
|
85 |
+
while "\n" in buffer: # Process as long as there are complete lines in the buffer
|
86 |
+
line, buffer = buffer.split("\n", 1)
|
87 |
+
|
88 |
+
if line.startswith("data: "):
|
89 |
+
event_data = line[len("data: "):]
|
90 |
+
if event_data != '[DONE]':
|
91 |
+
try:
|
92 |
+
current_text = json.loads(event_data)['choices'][0]['delta']['content']
|
93 |
+
full_response += current_text
|
94 |
+
yield full_response
|
95 |
+
await asyncio.sleep(0.01)
|
96 |
+
except Exception:
|
97 |
+
try:
|
98 |
+
current_text = json.loads(event_data)['choices'][0]['text']
|
99 |
+
full_response += current_text
|
100 |
+
yield full_response
|
101 |
+
await asyncio.sleep(0.01)
|
102 |
+
except Exception:
|
103 |
+
pass
|
104 |
|
105 |
final_metadata_block = ""
|
106 |
+
|
107 |
final_metadata_block += f"Links visited:\n"
|
108 |
for link in links:
|
109 |
final_metadata_block += f"{link}\n"
|