AndreaAlessandrelli4 commited on
Commit
825db5a
·
verified ·
1 Parent(s): 34b6d12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -3
app.py CHANGED
@@ -2,6 +2,11 @@ import os
2
  from threading import Thread
3
  from typing import Iterator
4
 
 
 
 
 
 
5
  import gradio as gr
6
  import spaces
7
  import torch
@@ -23,6 +28,49 @@ if torch.cuda.is_available():
23
  tokenizer = AutoTokenizer.from_pretrained(model_id)
24
  tokenizer.use_default_system_prompt = False
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  @spaces.GPU
28
  def generate(
@@ -35,15 +83,20 @@ def generate(
35
  top_k: int = 50,
36
  repetition_penalty: float = 1.2,
37
  ) -> Iterator[str]:
 
 
 
 
 
38
  conversation = []
39
  conversation.append({"role": "system", "content":
40
- '''Sei un assistente AI di nome 'AvvoChat' specializzato nel rispondere a domande riguardanti la legge Italiana.
41
  Rispondi in lingua italiana in modo chiaro, semplice ed esaustivo alle domande che ti vengono fornite.
42
- Le risposte devono essere sintetiche e chiare di massimo 500 token o anche più corte.
43
  Firmati alla fine di ogni risposta '-AvvoChat'.'''})
44
  for user, assistant in chat_history:
45
  conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
46
- conversation.append({"role": "user", "content": message})
47
 
48
  input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
49
  if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
 
2
  from threading import Thread
3
  from typing import Iterator
4
 
5
+ import weaviate
6
+ from haystack.components.builders import PromptBuilder
7
+ from sentence_transformers import SentenceTransformer
8
+ from haystack import Pipeline
9
+
10
  import gradio as gr
11
  import spaces
12
  import torch
 
28
  tokenizer = AutoTokenizer.from_pretrained(model_id)
29
  tokenizer.use_default_system_prompt = False
30
 
31
+ model1 = SentenceTransformer('intfloat/multilingual-e5-large')
32
+
33
+ key='rJ2yBbVQedQvaSH3TABtf9KcuQsnLNRPXguq'
34
+ url = "https://mmchpi0yssanukk5t3ofta.c0.europe-west3.gcp.weaviate.cloud"
35
+ client = weaviate.Client(
36
+ url = url,
37
+ auth_client_secret=weaviate.auth.AuthApiKey(api_key=key),
38
+ )
39
+
40
+
41
+
42
+ def prompt_template(materiali, query):
43
+ mat = ''
44
+ for i, doc in enumerate(materiali):
45
+ mat += f'DOCUMENTO {i+1}: {doc['content']};\n'
46
+ prompt_template = f"""
47
+ Basandoti sulle tue conoscenze e usando le informazioni che ti fornisco di seguito.
48
+ CONTESTO:
49
+ {mat}
50
+
51
+ Rispondi alla seguente domanda in modo esaustivo e conciso in massimo 100 parole, evitando inutili giri di parole o ripetizioni, .
52
+ {query}
53
+ """
54
+ return prompt_template
55
+
56
+
57
+
58
+ def richiamo_materiali(query, vett_query, alpha=1.0, N_items=5):
59
+ try:
60
+ materiali = client.query.get("Default", ["content"]).with_hybrid(
61
+ query=text_query,
62
+ vector=vett_query,
63
+ alpha=alpha,
64
+ fusion_type=HybridFusion.RELATIVE_SCORE,
65
+ ).with_additional(["score"]).with_limit(N_items).do()
66
+
67
+ mat = [{'score':i['_additional']['score'],'content':i['content']} for i in materiali['data']['Get']['Default']]
68
+ except:
69
+ mat =[{'score':0, 'content':'NESSUN MATERIALE FORNITO'}]
70
+
71
+ return mat
72
+
73
+
74
 
75
  @spaces.GPU
76
  def generate(
 
83
  top_k: int = 50,
84
  repetition_penalty: float = 1.2,
85
  ) -> Iterator[str]:
86
+
87
+ embeddings_query = model1.encode('query: '+message, normalize_embeddings=True)
88
+ vettor_query = embeddings_query
89
+ materiali = richiamo_materiali(message, vettor_query)
90
+ prompt_finale = prompt_template(materiali, message)
91
  conversation = []
92
  conversation.append({"role": "system", "content":
93
+ '''Sei un an assistente AI di nome 'AvvoChat' specializzato nel rispondere a domande riguardanti la legge Italiana.
94
  Rispondi in lingua italiana in modo chiaro, semplice ed esaustivo alle domande che ti vengono fornite.
95
+ Le risposte devono essere sintetiche e chiare di massimo 100 parole o anche più corte.
96
  Firmati alla fine di ogni risposta '-AvvoChat'.'''})
97
  for user, assistant in chat_history:
98
  conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
99
+ conversation.append({"role": "user", "content": prompt_finale})
100
 
101
  input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
102
  if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH: