Spaces:
Running
Running
Commit ·
7de3e97
1
Parent(s): eee15b3
Implement chunk metadata persistence in chunk_doc; enhance query response refinement in API and update HTML for global chunk loading
Browse files- infrastructure/chunker.py +12 -1
- routes/api.py +5 -2
- services/gpt_service.py +74 -0
- static/chunks.html +2 -2
infrastructure/chunker.py
CHANGED
|
@@ -5,7 +5,18 @@ Currently provides a single public helper `chunk_doc` that:
|
|
| 5 |
1. Reads a cleaned `.txt` file (already extracted & normalized elsewhere).
|
| 6 |
2. Splits it into pages (form-feed ``\f`` boundaries) and paragraphs.
|
| 7 |
3. Aggregates paragraphs into size‑bounded chunks with optional character overlap.
|
| 8 |
-
4. Persists each chunk using `infrastructure.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
Design notes:
|
| 11 |
* Chunk sizing is character based (not tokens) to avoid extra deps.
|
|
|
|
| 5 |
1. Reads a cleaned `.txt` file (already extracted & normalized elsewhere).
|
| 6 |
2. Splits it into pages (form-feed ``\f`` boundaries) and paragraphs.
|
| 7 |
3. Aggregates paragraphs into size‑bounded chunks with optional character overlap.
|
| 8 |
+
4. Persists each chunk using `infrastructure.datab path = os.path.join(CHUNKS_DIR, "chunks.jsonl")
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 12 |
+
for record in chunk_metadata_records:
|
| 13 |
+
f.write(json.dumps(record, ensure_ascii=False) + '\n')
|
| 14 |
+
logger.info(f"Appended {len(chunk_metadata_records)} chunk records to existing chunks file {path}")
|
| 15 |
+
except FileNotFoundError:
|
| 16 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 17 |
+
for record in chunk_metadata_records:
|
| 18 |
+
f.write(json.dumps(record, ensure_ascii=False) + '\n')
|
| 19 |
+
logger.info(f"Wrote {len(chunk_metadata_records)} chunk records to new chunks file {path}")_chunk`.
|
| 20 |
|
| 21 |
Design notes:
|
| 22 |
* Chunk sizing is character based (not tokens) to avoid extra deps.
|
routes/api.py
CHANGED
|
@@ -30,6 +30,7 @@ from infrastructure.document_processor import (
|
|
| 30 |
)
|
| 31 |
from infrastructure.chunker import chunk_doc
|
| 32 |
from infrastructure.vector_search import find_nearest_neighbors
|
|
|
|
| 33 |
|
| 34 |
api_bp = Blueprint("api", __name__, url_prefix="/api")
|
| 35 |
CORS(api_bp)
|
|
@@ -375,8 +376,10 @@ def query():
|
|
| 375 |
"distance": distance,
|
| 376 |
"document": doc_info
|
| 377 |
})
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
| 380 |
except Exception as e:
|
| 381 |
logger.exception("Query failed: %s", e)
|
| 382 |
return jsonify({"error": "Failed to execute query"}), 500
|
|
|
|
| 30 |
)
|
| 31 |
from infrastructure.chunker import chunk_doc
|
| 32 |
from infrastructure.vector_search import find_nearest_neighbors
|
| 33 |
+
from services.gpt_service import refine_query_response
|
| 34 |
|
| 35 |
api_bp = Blueprint("api", __name__, url_prefix="/api")
|
| 36 |
CORS(api_bp)
|
|
|
|
| 376 |
"distance": distance,
|
| 377 |
"document": doc_info
|
| 378 |
})
|
| 379 |
+
|
| 380 |
+
answer = refine_query_response(question, results)
|
| 381 |
+
|
| 382 |
+
return jsonify({"results": results, "answer": answer}), 200
|
| 383 |
except Exception as e:
|
| 384 |
logger.exception("Query failed: %s", e)
|
| 385 |
return jsonify({"error": "Failed to execute query"}), 500
|
services/gpt_service.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import openai
|
| 2 |
+
import os
|
| 3 |
+
from typing import Dict, List
|
| 4 |
+
import json
|
| 5 |
+
from infrastructure.logger import get_logger
|
| 6 |
+
|
| 7 |
+
CHAT_MODEL = os.getenv("CHAT_MODEL", "gpt-5")
|
| 8 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 9 |
+
TOP_K = 5
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
SYSTEM_PROMPT = f"""
|
| 14 |
+
You are an expert legal research assistant specializing in technology transactions, contracts, and other legal agreements. You are especially skilled at understanding complex legal queries and providing concise, accurate, and relevant responses based on the context provided. You excel at synthesizing information from multiple sources to deliver clear and actionable insights. Your task is to examine and understand a user's query, and then articulate and refine a response that is both precise and contextually appropriate. Always ensure that your responses are well-structured, easy to understand, and directly address the user's query. You will be provided with {TOP_K} relevant document chunks from which you should draw information to formulate your response. These document chunks have been retrieved based on their relevance to the user's query. Examine the text and metadata of each chunk to identify the relevant information that you should include to answer the user's query effectively. Your response should be clear, concise, and directly address the user's query using the provided context. You should try to contain your response to a maximum of 10 sentences, although you may exceed that number if necessary. Arrange your response logically. Format your response for readability (e.g., use complete sentences, insert paragraph breaks where appropriate). If the provided context does not contain sufficient information to answer the query, respond with "Insufficient information to provide an answer." Do not fabricate or assume any information beyond what is provided in the context. Always prioritize accuracy and relevance in your responses. You should return your response in the following JSON format:
|
| 15 |
+
{{
|
| 16 |
+
"response": "<Your concise and relevant answer to the user's query here>",
|
| 17 |
+
"sources": ["<List[Dict] of source document IDs, and the chunk IDs, section numbers, and section titles from those source documents, used to formulate the response>"]
|
| 18 |
+
}}
|
| 19 |
+
You should not include any other text outside of the JSON format. Here is an example of a well-structured response:
|
| 20 |
+
{{
|
| 21 |
+
"response": "The key considerations for drafting a technology transaction agreement include clearly defining the scope of services, outlining payment terms, specifying intellectual property rights, and including confidentiality clauses. It is also important to address liability limitations and dispute resolution mechanisms to protect both parties involved in the agreement.",
|
| 22 |
+
"sources": [
|
| 23 |
+
{{"doc_id": "12345",
|
| 24 |
+
"doc_type": "IP Agreement",
|
| 25 |
+
"chunks": [
|
| 26 |
+
{{"chunk_id": "567",
|
| 27 |
+
"section_number": "1.2",
|
| 28 |
+
"section_title": "Scope of Services"}},
|
| 29 |
+
{{"chunk_id": "568",
|
| 30 |
+
"section_number": "3.1",
|
| 31 |
+
"section_title": "Payment Terms"}}
|
| 32 |
+
]}},
|
| 33 |
+
{{"doc_id": "67890",
|
| 34 |
+
"doc_type": "IP Agreement",
|
| 35 |
+
"chunks": [
|
| 36 |
+
{{"chunk_id": "890",
|
| 37 |
+
"section_number": "3",
|
| 38 |
+
"section_title": "Key Clauses"}}
|
| 39 |
+
]}}
|
| 40 |
+
]
|
| 41 |
+
}}
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def refine_query_response(query: str, context: List[Dict]) -> Dict:
|
| 45 |
+
"""Uses OpenAI's chat model to refine a query based on provided context."""
|
| 46 |
+
if not OPENAI_API_KEY:
|
| 47 |
+
raise ValueError("OPENAI_API_KEY environment variable is not set.")
|
| 48 |
+
|
| 49 |
+
client = openai.OpenAI(api_key=OPENAI_API_KEY)
|
| 50 |
+
|
| 51 |
+
client_prompt = f"""
|
| 52 |
+
Given the following user query and context from relevant documents, provide a concise and accurate answer in JSON format as specified.\n\n
|
| 53 |
+
---User Query Start---\n {query}\n---
|
| 54 |
+
---User Query End---\n\n
|
| 55 |
+
---Context Start---\n
|
| 56 |
+
{json.dumps(context)}\n
|
| 57 |
+
---Context End---
|
| 58 |
+
"""
|
| 59 |
+
messages = [
|
| 60 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 61 |
+
{"role": "user", "content": client_prompt}
|
| 62 |
+
]
|
| 63 |
+
try:
|
| 64 |
+
response = client.chat.completions.create(
|
| 65 |
+
model=CHAT_MODEL,
|
| 66 |
+
messages=messages, # type: ignore
|
| 67 |
+
)
|
| 68 |
+
answer = response.choices[0].message.content
|
| 69 |
+
if answer is None:
|
| 70 |
+
raise ValueError("Received empty response from OpenAI.")
|
| 71 |
+
return json.loads(answer)
|
| 72 |
+
except Exception as e:
|
| 73 |
+
logger.error(f"Error during OpenAI chat completion: {e}")
|
| 74 |
+
return {"response": "Insufficient information to provide an answer.", "sources": []}
|
static/chunks.html
CHANGED
|
@@ -203,12 +203,12 @@
|
|
| 203 |
setStatus('');
|
| 204 |
summaryEl.innerHTML = '';
|
| 205 |
spinner();
|
| 206 |
-
const limit =
|
| 207 |
fetch(`/api/chunks/all?limit=${limit}`)
|
| 208 |
.then(r => r.json())
|
| 209 |
.then(data => {
|
| 210 |
rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
|
| 211 |
-
setStatus(rawChunks.length ? `Loaded ${rawChunks.length} chunk(s) (global
|
| 212 |
currentPage = 1;
|
| 213 |
render();
|
| 214 |
resultsPanel.style.display = 'block';
|
|
|
|
| 203 |
setStatus('');
|
| 204 |
summaryEl.innerHTML = '';
|
| 205 |
spinner();
|
| 206 |
+
const limit = 0; // No limit
|
| 207 |
fetch(`/api/chunks/all?limit=${limit}`)
|
| 208 |
.then(r => r.json())
|
| 209 |
.then(data => {
|
| 210 |
rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
|
| 211 |
+
setStatus(rawChunks.length ? `Loaded ${rawChunks.length} chunk(s) (global).` : 'No chunks.');
|
| 212 |
currentPage = 1;
|
| 213 |
render();
|
| 214 |
resultsPanel.style.display = 'block';
|