Spaces:
Sleeping
Sleeping
source localtest
Browse files- app.log +21 -0
- app.py +1 -1
- app_localtest.py +275 -0
- utils/sources.py +3 -1
app.log
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
2025-11-09 22:16:41,642 - __main__ - INFO - Initializing Gradio interface
|
| 2 |
+
2025-11-09 22:16:41,725 - httpx - INFO - HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 "
|
| 3 |
+
2025-11-09 22:16:41,743 - __main__ - INFO - Starting ChatFed Generation Module server
|
| 4 |
+
2025-11-09 22:16:41,743 - __main__ - INFO - FastAPI server will be available at http://0.0.0.0:7860
|
| 5 |
+
2025-11-09 22:16:41,743 - __main__ - INFO - Gradio UI will be available at http://0.0.0.0:7860/gradio
|
| 6 |
+
2025-11-09 22:16:41,743 - __main__ - INFO - ChatUI endpoints: /generate (non-streaming), /generate/stream (streaming)
|
| 7 |
+
2025-11-09 22:16:41,957 - httpx - INFO - HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK"
|
| 8 |
+
2025-11-09 22:16:46,848 - __main__ - INFO - Initializing Gradio interface
|
| 9 |
+
2025-11-09 22:16:46,932 - httpx - INFO - HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 "
|
| 10 |
+
2025-11-09 22:16:46,949 - __main__ - INFO - Starting ChatFed Generation Module server
|
| 11 |
+
2025-11-09 22:16:46,949 - __main__ - INFO - FastAPI server will be available at http://0.0.0.0:7860
|
| 12 |
+
2025-11-09 22:16:46,949 - __main__ - INFO - Gradio UI will be available at http://0.0.0.0:7860/gradio
|
| 13 |
+
2025-11-09 22:16:46,949 - __main__ - INFO - ChatUI endpoints: /generate (non-streaming), /generate/stream (streaming)
|
| 14 |
+
2025-11-09 22:16:47,152 - httpx - INFO - HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK"
|
| 15 |
+
2025-11-09 22:17:05,441 - __main__ - INFO - Initializing Gradio interface
|
| 16 |
+
2025-11-09 22:17:05,526 - httpx - INFO - HTTP Request: GET https://checkip.amazonaws.com/ "HTTP/1.1 200 "
|
| 17 |
+
2025-11-09 22:17:05,547 - __main__ - INFO - Starting ChatFed Generation Module server
|
| 18 |
+
2025-11-09 22:17:05,547 - __main__ - INFO - FastAPI server will be available at http://0.0.0.0:7860
|
| 19 |
+
2025-11-09 22:17:05,547 - __main__ - INFO - Gradio UI will be available at http://0.0.0.0:7860/gradio
|
| 20 |
+
2025-11-09 22:17:05,547 - __main__ - INFO - ChatUI endpoints: /generate (non-streaming), /generate/stream (streaming)
|
| 21 |
+
2025-11-09 22:17:05,739 - httpx - INFO - HTTP Request: GET https://api.gradio.app/pkg-version "HTTP/1.1 200 OK"
|
app.py
CHANGED
|
@@ -189,4 +189,4 @@ if __name__ == "__main__":
|
|
| 189 |
logger.info("Gradio UI will be available at http://0.0.0.0:7860/gradio")
|
| 190 |
logger.info("ChatUI endpoints: /generate (non-streaming), /generate/stream (streaming)")
|
| 191 |
|
| 192 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 189 |
logger.info("Gradio UI will be available at http://0.0.0.0:7860/gradio")
|
| 190 |
logger.info("ChatUI endpoints: /generate (non-streaming), /generate/stream (streaming)")
|
| 191 |
|
| 192 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
app_localtest.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import asyncio
|
| 3 |
+
import logging
|
| 4 |
+
import json
|
| 5 |
+
from fastapi import FastAPI, Request
|
| 6 |
+
from fastapi.responses import StreamingResponse
|
| 7 |
+
from utils.generator import generate_streaming, generate, _call_llm, _call_llm_streaming
|
| 8 |
+
from utils.sources import _process_context, _build_messages, clean_citations, _parse_citations, _extract_sources, _create_sources_list
|
| 9 |
+
from utils.prompts import system_prompt
|
| 10 |
+
from typing import AsyncGenerator
|
| 11 |
+
|
| 12 |
+
context = [{'answer': 'List of projects and activities approved for funding HCFC phase out plan, Agency. = . HCFC phase out plan, ODP.(tonnes) = . HCFC phase out plan, C.E. Total.Support Funds approved (US$).Project = . HCFC phase out plan, C.E. Total.Support Funds approved (US$). = . HCFC phase out plan, C.E. Total.. = . HCFC phase out plan, C.E. Total..(US$/kg) = . HCFC phase-out management plan (stage II, first tranche) (project management, monitoring and coordination) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to 2021 to reduce HCFC consumption by 65 per cent of the baseline. Noted that the Government: has committed to reduce HCFC consumption of the baseline by 60 per cent in 2020 and 65 per, Agency. = UNDP. HCFC phase-out management plan (stage II, first tranche) (project management, monitoring and coordination) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to 2021 to reduce HCFC consumption by 65 per cent of the baseline. Noted that the Government: has committed to reduce HCFC consumption of the baseline by 60 per cent in 2020 and 65 per, ODP.(tonnes) = . HCFC phase-out management plan (stage II, first tranche) (project management, monitoring and coordination) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to 2021 to reduce HCFC consumption by 65 per cent of the baseline. Noted that the Government: has committed to reduce HCFC consumption of the baseline by 60 per cent in 2020 and 65 per, C.E. Total.Support Funds approved (US$).Project = $245,325. HCFC phase-out management plan (stage II, first tranche) (project management, monitoring and coordination) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to 2021 to reduce HCFC consumption by 65 per cent of the baseline. Noted that the Government: has committed to reduce HCFC consumption of the baseline by 60 per cent in 2020 and 65 per, C.E. Total.Support Funds approved (US$). = $17,173. HCFC phase-out management plan (stage II, first tranche) (project management, monitoring and coordination) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to 2021 to reduce HCFC consumption by 65 per cent of the baseline. Noted that the Government: has committed to reduce HCFC consumption of the baseline by 60 per cent in 2020 and 65 per, C.E. Total.. = $262,498. HCFC phase-out management plan (stage II, first tranche) (project management, monitoring and coordination) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to 2021 to reduce HCFC consumption by 65 per cent of the baseline. Noted that the Government: has committed to reduce HCFC consumption of the baseline by 60 per cent in 2020 and 65 per, C.E. Total..(US$/kg) = UNEP/OzL.Pro/ExCom/75/85 Annex XII 13 HCFC phase-out management plan (stage II, first tranche) (foam sector) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to, Agency = UNDP. HCFC phase-out management plan (stage II, first tranche) (foam sector) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to, ODP (tonnes) = 48.2. HCFC phase-out management plan (stage II, first tranche) (foam sector) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to, C.E. Total Funds approved (US$).Project = $1,279,881. HCFC phase-out management plan (stage II, first tranche) (foam sector) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to, C.E. Total Funds approved (US$).Support = $89,592. HCFC phase-out management plan (stage II, first tranche) (foam sector) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to, C.E. Total Funds approved (US$). = $1,369,473. HCFC phase-out management plan (stage II, first tranche) (foam sector) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2015 to, C.E. Total Funds approved (US$).(US$/kg) = 2.92 UNEP/OzL.Pro/ExCom/75/85 Annex XII 14', 'answer_metadata': {'Meeting': '75', 'chunk_length': 688.0, 'document_type': 'annex', 'page': 13.0, 'heading': ['List of projects and activities approved for funding'], 'page_count': 46.0, 'filename': '7585 ax12 list approvals.pdf', 'raw_docs_rel_path': 'raw/Montreal/Annexes/Annexes_ 1_92 _meetings/75/Final Annexes/7585 ax12 list approvals.pdf', 'document_url': 'https://huggingface.co/datasets/GIZ/mlf_annexes/blob/main/Annexes_%201_92%20_meetings/75/Final%20Annexes/7585%20ax12%20list%20approvals.pdf', 'meeting_id': '75'}}, {'answer': 'List of projects and activities approved for funding 2030 for the complete phase-out of HCFC consumption, on the understanding that no more funding from the Multilateral Fund would be provided for the phase-out of HCFCs. Noted the commitment of the Government to reduce HCFC consumption by, ODP/Metric.(tonnes)* = 0.1. HCFC phase out plan HCFC phase-out management plan (stage II, first tranche) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2022 to 2030 for the complete phase-out of HCFC consumption, on the understanding that no more funding from the Multilateral Fund would be provided for the phase-out of HCFCs. Noted the commitment of the Government to reduce HCFC consumption by, Support Project Funds approved (US$). = $105,000. HCFC phase out plan HCFC phase-out management plan (stage II, first tranche) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2022 to 2030 for the complete phase-out of HCFC consumption, on the understanding that no more funding from the Multilateral Fund would be provided for the phase-out of HCFCs. Noted the commitment of the Government to reduce HCFC consumption by, Support Project Funds approved (US$). = $9,450. HCFC phase out plan HCFC phase-out management plan (stage II, first tranche) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2022 to 2030 for the complete phase-out of HCFC consumption, on the understanding that no more funding from the Multilateral Fund would be provided for the phase-out of HCFCs. Noted the commitment of the Government to reduce HCFC consumption by, Support Project Funds approved (US$).Total = $114,450. HCFC phase out plan HCFC phase-out management plan (stage II, first tranche) Approved in accordance with the Agreement between the Government and the Executive Committee for the period 2022 to 2030 for the complete phase-out of HCFC consumption, on the understanding that no more funding from the Multilateral Fund would be provided for the phase-out of HCFCs. Noted the commitment of the Government to reduce HCFC consumption by, C.E..(US$/kg) = * HCFC in ODP tonnes. HFC in metric tonnes 8 Project Title pproved (US$) UNEP/OzL.Pro/ExCom/91/72 Annex XVI', 'answer_metadata': {'Meeting': '91', 'chunk_length': 361.0, 'document_type': 'annex', 'page': 8.0, 'heading': ['List of projects and activities approved for funding'], 'page_count': 38.0, 'filename': '16-ApprovalsList-rev.pdf', 'raw_docs_rel_path': 'raw/Montreal/Annexes/Annexes_ 1_92 _meetings/91/91/9172axs_PDF/16-ApprovalsList-rev.pdf', 'document_url': 'https://huggingface.co/datasets/GIZ/mlf_annexes/blob/main/Annexes_%201_92%20_meetings/91/91/9172axs_PDF/16-ApprovalsList-rev.pdf', 'meeting_id': '91'}}, {'answer': '<p>The Executive Committee decided:</p><ol class="bracketed-list list-type-a" type="a"><li>To note that the revised starting point for sustained aggregate reduction in HCFC consumption for Jamaica was 10.58 ODP tonnes, based on the best estimates of consumption in the country in 2009 and 2010; and that the maximum remaining funding for which the country was eligible for the total phase-out of HCFCs was US $390,000, based on the difference between the maximum level of funding eligible for the complete phaseÔÇæout of US $950,000, in line with <a href="/resources/decisions/decision-7450">decision 74/50</a>(c)(xii), and the funding approved under stage I of US $560,000;</li><li>To approve, in principle, stage II of the HCFC phase-out management plan (HPMP) for Jamaica for the period from 2020 to 2030 for the complete phase-out of HCFC consumption, in the amount of US $390,000, plus agency support costs of US $27,300 for UNDP, on the understanding that no more funding from the Multilateral Fund would be provided for the phase-out of HCFCs;</li><li>To note the commitment of the Government of Jamaica:<ol class="bracketed-list list-type-i" type="i"><li>To phase out HCFCs completely by 1 January 2030 and that HCFCs would not be imported after that date, except for those allowed for a servicing tail between 2030 and 2040, where required, consistent with the provisions of the Montreal Protocol;</li><li>To prohibit import of HCFC-based equipment by 1 January 2026;</li></ol></li><li>To deduct 2.48 ODP tonnes of HCFCs from the remaining HCFC consumption eligible for funding;</li><li>To request the Government of Jamaica and UNDP to provide, at the 87th meeting, an update on the status of implementation of the measures for strengthening the licensing and quota system and monitoring and reporting of HCFC consumption recommended in the verification report submitted at', 'answer_metadata': {'Decision ID': 4541.0, 'URL': 'https://multilateralfund.org/node/4541', 'Language': 'en', 'Title': 'Decision 86/72', 'Decision Number': 'Decision 86/72', 'Meeting': '86th Meeting of the Executive Committee', 'Issues': 'Projects approved / deferred / transferred', 'Countries': 'Jamaica', 'Agencies': 'UNDP', 'Projects': 'HCFC phaseout stage 2', 'chunk_id': 0.0, 'total_chunks': 2.0, 'chunk_length': 275.0, 'document_type': 'decision', 'meeting_id': '86'}}]
|
| 13 |
+
|
| 14 |
+
query = 'hcfc phase out plan ?'
|
| 15 |
+
chatui_format = True
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
async def generate_test(system_prompt: str, query: str, context) -> AsyncGenerator[str, None]:
|
| 19 |
+
"""
|
| 20 |
+
Asynchronous generator that calls the streaming LLM function.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
messages = _build_messages(system_prompt, query, context)
|
| 24 |
+
# accumulated_response = ""
|
| 25 |
+
# Yield raw chunks directly
|
| 26 |
+
async for chunk in _call_llm_streaming(messages):
|
| 27 |
+
# accumulated_response += chunk
|
| 28 |
+
# if chatui_format:
|
| 29 |
+
# yield {"event": "data", "data": chunk}
|
| 30 |
+
# else:
|
| 31 |
+
# yield chunk
|
| 32 |
+
yield chunk
|
| 33 |
+
|
| 34 |
+
# --- 3. Execution Option A: Print to Log (Console) ---
|
| 35 |
+
|
| 36 |
+
async def print_answer_to_log(context, system_prompt, query):
|
| 37 |
+
"""Executes the generator and prints the full stream to the console/log."""
|
| 38 |
+
formatted_context, processed_results = _process_context(context)
|
| 39 |
+
async_gen = generate_test(system_prompt, query, formatted_context)
|
| 40 |
+
final_response = ""
|
| 41 |
+
|
| 42 |
+
print("\n" + "="*50)
|
| 43 |
+
print("--- 1. STANDALONE EXECUTION: STREAMING TO CONSOLE LOG ---")
|
| 44 |
+
print("="*50)
|
| 45 |
+
|
| 46 |
+
# Print stream to console
|
| 47 |
+
async for chunk in async_gen:
|
| 48 |
+
print(chunk, end="", flush=True)
|
| 49 |
+
final_response += chunk
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
print("\n" + "="*50)
|
| 54 |
+
print("LOG STREAM FINISHED. Final length:", len(final_response))
|
| 55 |
+
print("="*50 + "\n")
|
| 56 |
+
cleaned_response = clean_citations(final_response)
|
| 57 |
+
if chatui_format and processed_results:
|
| 58 |
+
cited_numbers = _parse_citations(cleaned_response)
|
| 59 |
+
cited_sources = _extract_sources(processed_results, cited_numbers)
|
| 60 |
+
sources = _create_sources_list(cited_sources)
|
| 61 |
+
|
| 62 |
+
print(cited_numbers, cited_sources)
|
| 63 |
+
print(sources)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
with gr.Blocks() as ui:
|
| 67 |
+
gr.Markdown("# ChatFed Retrieval/Reranker Module")
|
| 68 |
+
gr.Markdown("Retrieves semantically similar documents from vector database and reranks. Intended for use in RAG pipelines as an MCP server with other ChatFed modules.")
|
| 69 |
+
|
| 70 |
+
# answer = generate()
|
| 71 |
+
# final_response = ""
|
| 72 |
+
|
| 73 |
+
# # Iterate through the chunks, print each one immediately, and accumulate the full text
|
| 74 |
+
# async for chunk in answer:
|
| 75 |
+
# # Print the chunk to the log immediately without a newline
|
| 76 |
+
# print(chunk, end="", flush=True)
|
| 77 |
+
# final_response += chunk
|
| 78 |
+
# print(final_response)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# Launch with MCP server enabled
|
| 83 |
+
if __name__ == "__main__":
|
| 84 |
+
asyncio.run(print_answer_to_log(context, system_prompt, query))
|
| 85 |
+
|
| 86 |
+
ui.launch(
|
| 87 |
+
server_name="0.0.0.0",
|
| 88 |
+
server_port=7860,
|
| 89 |
+
#mcp_server=True,
|
| 90 |
+
show_error=True
|
| 91 |
+
)
|
| 92 |
+
# # Configure logging
|
| 93 |
+
# logging.basicConfig(
|
| 94 |
+
# level=logging.INFO,
|
| 95 |
+
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 96 |
+
# handlers=[
|
| 97 |
+
# logging.StreamHandler(),
|
| 98 |
+
# logging.FileHandler('app.log')
|
| 99 |
+
# ]
|
| 100 |
+
# )
|
| 101 |
+
# logger = logging.getLogger(__name__)
|
| 102 |
+
|
| 103 |
+
# # ---------------------------------------------------------------------
|
| 104 |
+
# # FastAPI app for ChatUI endpoints
|
| 105 |
+
# # ---------------------------------------------------------------------
|
| 106 |
+
# app = FastAPI(title="ChatFed Generator", version="1.0.0")
|
| 107 |
+
|
| 108 |
+
# @app.post("/generate")
|
| 109 |
+
# async def generate_endpoint(request: Request):
|
| 110 |
+
# """
|
| 111 |
+
# Non-streaming generation endpoint for ChatUI format.
|
| 112 |
+
|
| 113 |
+
# Expected request body:
|
| 114 |
+
# {
|
| 115 |
+
# "query": "user question",
|
| 116 |
+
# "context": [...] // list of retrieval results
|
| 117 |
+
# }
|
| 118 |
+
|
| 119 |
+
# Returns ChatUI format:
|
| 120 |
+
# {
|
| 121 |
+
# "answer": "response with citations [1][2]",
|
| 122 |
+
# "sources": [{"link": "doc://...", "title": "..."}]
|
| 123 |
+
# }
|
| 124 |
+
# """
|
| 125 |
+
# try:
|
| 126 |
+
# body = await request.json()
|
| 127 |
+
# query = body.get("query", "")
|
| 128 |
+
# context = body.get("context", [])
|
| 129 |
+
|
| 130 |
+
# result = await generate(query, context, chatui_format=True)
|
| 131 |
+
# return result
|
| 132 |
+
|
| 133 |
+
# except Exception as e:
|
| 134 |
+
# logger.exception("Generation endpoint failed")
|
| 135 |
+
# return {"error": str(e)}
|
| 136 |
+
|
| 137 |
+
# @app.post("/generate/stream")
|
| 138 |
+
# async def generate_stream_endpoint(request: Request):
|
| 139 |
+
# """
|
| 140 |
+
# Streaming generation endpoint for ChatUI format.
|
| 141 |
+
|
| 142 |
+
# Expected request body:
|
| 143 |
+
# {
|
| 144 |
+
# "query": "user question",
|
| 145 |
+
# "context": [...] // list of retrieval results
|
| 146 |
+
# }
|
| 147 |
+
|
| 148 |
+
# Returns Server-Sent Events in ChatUI format:
|
| 149 |
+
# event: data
|
| 150 |
+
# data: "response chunk"
|
| 151 |
+
|
| 152 |
+
# event: sources
|
| 153 |
+
# data: {"sources": [...]}
|
| 154 |
+
|
| 155 |
+
# event: end
|
| 156 |
+
# """
|
| 157 |
+
# try:
|
| 158 |
+
# body = await request.json()
|
| 159 |
+
# query = body.get("query", "")
|
| 160 |
+
# context = body.get("context", [])
|
| 161 |
+
|
| 162 |
+
# async def event_stream():
|
| 163 |
+
# async for event in generate_streaming(query, context, chatui_format=True):
|
| 164 |
+
# event_type = event["event"]
|
| 165 |
+
# event_data = event["data"]
|
| 166 |
+
|
| 167 |
+
# if event_type == "data":
|
| 168 |
+
# yield f"event: data\ndata: {json.dumps(event_data)}\n\n"
|
| 169 |
+
# elif event_type == "sources":
|
| 170 |
+
# yield f"event: sources\ndata: {json.dumps(event_data)}\n\n"
|
| 171 |
+
# elif event_type == "end":
|
| 172 |
+
# yield f"event: end\ndata: {{}}\n\n"
|
| 173 |
+
# elif event_type == "error":
|
| 174 |
+
# yield f"event: error\ndata: {json.dumps(event_data)}\n\n"
|
| 175 |
+
|
| 176 |
+
# return StreamingResponse(
|
| 177 |
+
# event_stream(),
|
| 178 |
+
# media_type="text/event-stream",
|
| 179 |
+
# headers={
|
| 180 |
+
# "Cache-Control": "no-cache",
|
| 181 |
+
# "Connection": "keep-alive",
|
| 182 |
+
# "Access-Control-Allow-Origin": "*",
|
| 183 |
+
# "Access-Control-Allow-Headers": "*",
|
| 184 |
+
# }
|
| 185 |
+
# )
|
| 186 |
+
|
| 187 |
+
# except Exception as e:
|
| 188 |
+
# logger.exception("Streaming endpoint failed")
|
| 189 |
+
# async def error_stream():
|
| 190 |
+
# yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n"
|
| 191 |
+
|
| 192 |
+
# return StreamingResponse(
|
| 193 |
+
# error_stream(),
|
| 194 |
+
# media_type="text/event-stream"
|
| 195 |
+
# )
|
| 196 |
+
|
| 197 |
+
# # ---------------------------------------------------------------------
|
| 198 |
+
# # Wrapper function to handle async streaming for Gradio
|
| 199 |
+
# # ---------------------------------------------------------------------
|
| 200 |
+
# def generate_streaming_wrapper(query: str, context: str):
|
| 201 |
+
# """Wrapper to convert async generator to sync generator for Gradio"""
|
| 202 |
+
# logger.info(f"Starting generation request - Query length: {len(query)}, Context length: {len(context)}")
|
| 203 |
+
|
| 204 |
+
# async def _async_generator():
|
| 205 |
+
# async for chunk in generate_streaming(query, context, chatui_format=False):
|
| 206 |
+
# yield chunk
|
| 207 |
+
|
| 208 |
+
# # Create a new event loop for this thread
|
| 209 |
+
# try:
|
| 210 |
+
# loop = asyncio.get_event_loop()
|
| 211 |
+
# logger.debug("Using existing event loop")
|
| 212 |
+
# except RuntimeError:
|
| 213 |
+
# loop = asyncio.new_event_loop()
|
| 214 |
+
# asyncio.set_event_loop(loop)
|
| 215 |
+
# logger.debug("Created new event loop")
|
| 216 |
+
|
| 217 |
+
# # Convert async generator to sync generator
|
| 218 |
+
# async_gen = _async_generator()
|
| 219 |
+
|
| 220 |
+
# # Accumulate chunks for Gradio streaming
|
| 221 |
+
# accumulated_text = ""
|
| 222 |
+
# chunk_count = 0
|
| 223 |
+
|
| 224 |
+
# while True:
|
| 225 |
+
# try:
|
| 226 |
+
# chunk = loop.run_until_complete(async_gen.__anext__())
|
| 227 |
+
# accumulated_text += chunk
|
| 228 |
+
# chunk_count += 1
|
| 229 |
+
# yield accumulated_text # Yield the accumulated text, not just the chunk
|
| 230 |
+
# except StopAsyncIteration:
|
| 231 |
+
# logger.info(f"Generation completed - Total chunks: {chunk_count}, Final text length: {len(accumulated_text)}")
|
| 232 |
+
# break
|
| 233 |
+
|
| 234 |
+
# # ---------------------------------------------------------------------
|
| 235 |
+
# # Gradio Interface with MCP support and streaming
|
| 236 |
+
# # ---------------------------------------------------------------------
|
| 237 |
+
# logger.info("Initializing Gradio interface")
|
| 238 |
+
# ui = gr.Interface(
|
| 239 |
+
# fn=generate_streaming_wrapper, # Use streaming wrapper function
|
| 240 |
+
# inputs=[
|
| 241 |
+
# gr.Textbox(
|
| 242 |
+
# label="Query",
|
| 243 |
+
# lines=2,
|
| 244 |
+
# placeholder="Enter query here",
|
| 245 |
+
# info="The query to search for in the vector database"
|
| 246 |
+
# ),
|
| 247 |
+
# gr.Textbox(
|
| 248 |
+
# label="Context",
|
| 249 |
+
# lines=8,
|
| 250 |
+
# placeholder="Paste relevant context here",
|
| 251 |
+
# info="Provide the context/documents to use for answering. The API expects a list of dictionaries, but the UI should except anything"
|
| 252 |
+
# ),
|
| 253 |
+
# ],
|
| 254 |
+
# outputs=gr.Textbox(
|
| 255 |
+
# label="Generated Answer",
|
| 256 |
+
# lines=6,
|
| 257 |
+
# show_copy_button=True
|
| 258 |
+
# ),
|
| 259 |
+
# title="ChatFed Generation Module",
|
| 260 |
+
# description="Ask questions based on provided context. Intended for use in RAG pipelines as an MCP server with other ChatFed modules (i.e. context supplied by semantic retriever service).",
|
| 261 |
+
# api_name="generate"
|
| 262 |
+
# )
|
| 263 |
+
|
| 264 |
+
# # Mount Gradio app to FastAPI
|
| 265 |
+
# app = gr.mount_gradio_app(app, ui, path="/gradio")
|
| 266 |
+
|
| 267 |
+
# # Launch with MCP server enabled
|
| 268 |
+
# if __name__ == "__main__":
|
| 269 |
+
# import uvicorn
|
| 270 |
+
# logger.info("Starting ChatFed Generation Module server")
|
| 271 |
+
# logger.info("FastAPI server will be available at http://0.0.0.0:7860")
|
| 272 |
+
# logger.info("Gradio UI will be available at http://0.0.0.0:7860/gradio")
|
| 273 |
+
# logger.info("ChatUI endpoints: /generate (non-streaming), /generate/stream (streaming)")
|
| 274 |
+
|
| 275 |
+
# uvicorn.run(app, host="0.0.0.0", port=7860)
|
utils/sources.py
CHANGED
|
@@ -160,6 +160,8 @@ def _process_context(context: Union[str, List[Dict[str, Any]]]) -> tuple[str, Li
|
|
| 160 |
|
| 161 |
processed_results.append(doc_info)
|
| 162 |
|
|
|
|
|
|
|
| 163 |
# Format context string - SIMPLIFIED TO ONLY USE [1], [2], [3]
|
| 164 |
context_parts = []
|
| 165 |
for i, result in enumerate(processed_results, 1):
|
|
@@ -190,7 +192,7 @@ def _create_sources_list(cited_sources: List[Dict[str, Any]]) -> List[Dict[str,
|
|
| 190 |
url = result.get('url', 'Unknown')
|
| 191 |
meeting_id = result.get('meeting_id', 'Unknown')
|
| 192 |
type = result.get('type', 'Unknown')
|
| 193 |
-
decision_number = result.get('
|
| 194 |
|
| 195 |
|
| 196 |
|
|
|
|
| 160 |
|
| 161 |
processed_results.append(doc_info)
|
| 162 |
|
| 163 |
+
# print(processed_results)
|
| 164 |
+
|
| 165 |
# Format context string - SIMPLIFIED TO ONLY USE [1], [2], [3]
|
| 166 |
context_parts = []
|
| 167 |
for i, result in enumerate(processed_results, 1):
|
|
|
|
| 192 |
url = result.get('url', 'Unknown')
|
| 193 |
meeting_id = result.get('meeting_id', 'Unknown')
|
| 194 |
type = result.get('type', 'Unknown')
|
| 195 |
+
decision_number = result.get('decision_number', 'Unknown')
|
| 196 |
|
| 197 |
|
| 198 |
|