gufett0 commited on
Commit
08c9e9f
·
1 Parent(s): a6e8f41

added text streamer

Browse files
Files changed (1) hide show
  1. backend.py +23 -12
backend.py CHANGED
@@ -41,15 +41,24 @@ parser = SentenceSplitter.from_defaults(
41
  chunk_size=256, chunk_overlap=64, paragraph_separator="\n\n"
42
  )
43
 
 
 
 
 
 
 
 
 
 
 
 
44
 
 
45
 
46
  @spaces.GPU(duration=20)
47
  def handle_query(query_str, chathistory):
48
 
49
- # build the vector
50
- documents = SimpleDirectoryReader(input_files=["data/blockchainprova.txt"]).load_data()
51
- nodes = parser.get_nodes_from_documents(documents)
52
- index = VectorStoreIndex(nodes)
53
 
54
  qa_prompt_str = (
55
  "Context information is below.\n"
@@ -71,17 +80,19 @@ def handle_query(query_str, chathistory):
71
  text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
72
 
73
  try:
74
- result = index.as_query_engine(text_qa_template=text_qa_template, streaming=True).query(query_str)
 
75
 
76
- for text in result.response_gen:
77
- print(text)
78
- yield text
79
-
80
 
81
- # Remove any unwanted tokens like <end_of_turn>
82
- #cleaned_result = response_text#.replace("<end_of_turn>", "").strip()
83
 
84
- #yield cleaned_result
 
 
 
 
85
 
86
  except Exception as e:
87
  yield f"Error processing query: {str(e)}"
 
41
  chunk_size=256, chunk_overlap=64, paragraph_separator="\n\n"
42
  )
43
 
44
+ @spaces.GPU(duration=20)
45
+ def build_index():
46
+ # Load documents from a file
47
+ documents = SimpleDirectoryReader(input_files=["data/blockchainprova.txt"]).load_data()
48
+ # Parse the documents into nodes
49
+ nodes = parser.get_nodes_from_documents(documents)
50
+ # Build the vector store index from the nodes
51
+ index = VectorStoreIndex(nodes)
52
+
53
+ return index
54
+
55
 
56
+ index = build_index()
57
 
58
  @spaces.GPU(duration=20)
59
  def handle_query(query_str, chathistory):
60
 
61
+
 
 
 
62
 
63
  qa_prompt_str = (
64
  "Context information is below.\n"
 
80
  text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
81
 
82
  try:
83
+ # Create a streaming query engine
84
+ query_engine = index.as_query_engine(text_qa_template=text_qa_template, streaming=True)
85
 
86
+ # Execute the query
87
+ streaming_response = query_engine.query(query_str)
 
 
88
 
89
+ streaming_response.print_response_stream()
 
90
 
91
+
92
+ # Stream the response
93
+ for text in streaming_response.response_gen:
94
+ yield text
95
+
96
 
97
  except Exception as e:
98
  yield f"Error processing query: {str(e)}"