Spaces:
Sleeping
Sleeping
File size: 6,644 Bytes
0fb6b90 17bba8c 0fb6b90 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | # import azure.functions as func
import logging
import json
import os
import re
from openai import AzureOpenAI
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from typing import List, Optional
# Create a function app
# app = func.FunctionApp()
class FollowupQuestions(BaseModel):
clarity : bool = Field(
description="Whether the query is clear enough for effective semantic search"
)
follow_up_questions : List[str] = Field(
default_factory=list,
description="List of follow-up questions to clarify the query (up to 3)"
)
# Load environment variables
load_dotenv()
deployment_name = "gpt-4o-mini"
# Initialize OpenAI client
client = AzureOpenAI(
api_key=os.environ.get('AZURE_OPENAI_API_KEY_IN'),
api_version="2024-12-01-preview",
azure_endpoint=os.environ.get('AZURE_OPENAI_ENDPOINT_IN')
)
def classify_query(query):
system_prompt = """# Legal Query Assessment System
## Role and Purpose
You are a highly trained legal assistant specialized in Indian law. Your task is to assess and optimize user-submitted legal queries for effective semantic search against a vector database of Indian legal judgment summaries.
## Assessment Process
1. Evaluate whether the query is clear, specific, and context-rich enough for effective semantic search.
2. Identify missing critical details that would improve search results.
3. Ask up to three **iterative follow-up questions**, where each round can include **multiple sub-questions** if the information required is concise.
4. Use responses from earlier rounds to inform and refine later follow-up questions.
## Required Query Components
For optimal search results, ensure the final query includes:
- **Jurisdiction** (e.g., Supreme Court, Delhi High Court, NCLAT)
- **Parties involved** (e.g., RP, creditor, company, petitioner/respondent)
- **Area of law** (e.g., insolvency, constitutional, labor, criminal)
- **Specific legal issue** (e.g., applicability of a provision, interpretation, procedural compliance)
## Important Guidelines
- Ask no more than **three follow-up rounds**; within each round, you may ask **multiple concise sub-questions** if appropriate.
- Combine related clarifications into a single prompt when possible to reduce back-and-forth.
- Do not ask about timeframes, as they are not relevant for the search.
- Focus strictly on substantive legal elements that would enhance semantic matching.
## Output Format
Provide your assessment and response in JSON format with the following structure:
```json
{
"clarity": true/false,
"follow_up_questions": [
"First follow-up (possibly multi-part)",
"Second follow-up (building on previous response)",
"Third follow-up (final refinement if needed)"
]
}
```
- If the query is already clear, set "clarity" to true and include an empty list for follow-up questions
- Only include the optimized_query field once the query is considered clear, whether initially or after follow-ups."""
user_prompt = f"Query: \"{query}\"\n\n"
response = client.beta.chat.completions.parse(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=0.1,
response_format=FollowupQuestions
)
classification = response.choices[0].message.content.strip()
return classification
def parse_classification_output(text):
clarity_match = re.search(r"Clarity:\s*(YES|NO)", text, re.IGNORECASE)
clarity = clarity_match.group(1).upper() if clarity_match else "NO"
questions = re.findall(r"\d+\.\s*(.+)", text)
return clarity == "NO", questions
def reformulate_query(original_query, clarification_answers, clarification_queries):
if not clarification_answers:
return original_query
prompt = f"""# Legal Research Query Reformulation System
## Role and Purpose
You are an expert legal research assistant specialized in transforming user inquiries into precise search queries optimized for retrieving relevant case law, statutes, and legal opinions from legal databases and search engines.
## Context
Legal research requires specific terminology, jurisdictional context, and precise identification of legal issues to yield optimal results. Your task is to analyze the user's initial query and any clarifications to craft a comprehensive search query that will help locate the most relevant judgments.
## Input Information
### Original Query
{original_query}
### Queries asked for clarification
{clarification_queries}
### Additional Clarifications
{clarification_answers}
## Output Instructions
1. Return ONLY the enhanced search query without explanatory text.
2. Structure your query using these elements when applicable:
- Legal issue/doctrine (e.g., "negligence," "strict liability")
- Relevant jurisdiction (e.g., "Supreme Court of India," "California")
- Timeframe if specified (e.g., "post-2015," "before Miranda v. Arizona")
- Key facts or scenario elements (e.g., "workplace injury," "contractual breach")
- Applicable statutes or codes (e.g., "Section 302 IPC," "Fair Use Doctrine")
- Related case citations if mentioned
- Procedural context (e.g., "summary judgment," "appeal")
- Relief sought (e.g., "damages," "specific performance")
## Query Formatting Guidelines
- Use Boolean operators effectively (AND, OR, NOT)
- Incorporate quotation marks for exact phrases
- Include synonyms or alternative legal terminology with OR operators
- Order terms by importance
- Use parentheses to group related concepts
- Include relevant legal citations in standard format
- Add jurisdictional limiters as prefixes when appropriate
- Incorporate recognized legal abbreviations where helpful
"""
response = client.chat.completions.create(
model=deployment_name,
messages=[
{"role": "system", "content": "You help refine legal search queries."},
{"role": "user", "content": prompt}
],
temperature=0.1
)
return response.choices[0].message.content.strip() |