Spaces:
Running
Running
File size: 14,696 Bytes
821e9b3 3f8b483 5521e44 821e9b3 9ed8b92 5521e44 9ed8b92 5521e44 821e9b3 3f8b483 821e9b3 3f8b483 821e9b3 3f8b483 c1cd0b6 3f8b483 5521e44 821e9b3 5521e44 821e9b3 5521e44 9ed8b92 821e9b3 9ed8b92 821e9b3 9ed8b92 821e9b3 5521e44 821e9b3 9ed8b92 821e9b3 9ed8b92 821e9b3 9ed8b92 821e9b3 9ed8b92 3f8b483 821e9b3 9ed8b92 821e9b3 9ed8b92 821e9b3 9ed8b92 5521e44 821e9b3 9ed8b92 821e9b3 c1cd0b6 1feb2ff c1cd0b6 a1bc507 77ba485 fe3703e c1cd0b6 fe3703e 357fcb5 fe3703e a1bc507 fe3703e a1bc507 fe3703e a1bc507 fe3703e a1bc507 fe3703e a1bc507 fe3703e a1bc507 fe3703e a1bc507 357fcb5 fe3703e c1cd0b6 9ed8b92 c1cd0b6 9ed8b92 821e9b3 9ed8b92 821e9b3 9ed8b92 821e9b3 9ed8b92 821e9b3 9ed8b92 821e9b3 9ed8b92 821e9b3 5521e44 821e9b3 |
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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 |
import os
import re
import json
import gradio as gr
from openai import OpenAI
# Initialize the OpenAI client with the API key from environment variables.
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# In-memory storage to track submitted emails (not persistent; resets on app restart).
submitted_emails = set()
def get_evaluation_questions():
"""
Loads evaluation questions and expected answers from environment variables.
Expected environment variable names are:
- TEST_QUESTION_1: a JSON array of user query strings.
- TEST_EXPECTED: a JSON array of JSON-like strings representing the expected outputs.
Both lists must be of equal length.
"""
questions_str = os.environ.get("TEST_QUESTION_1")
expected_str = os.environ.get("TEST_EXPECTED_1")
if not questions_str or not expected_str:
return []
try:
questions_list = json.loads(questions_str)
expected_list = json.loads(expected_str)
except Exception as e:
print(f"Error parsing evaluation questions: {str(e)}")
return []
if len(questions_list) != len(expected_list):
print("Mismatch in length: questions list and expected answers list must have the same length.")
return []
return [{"question": q, "expected": e} for q, e in zip(questions_list, expected_list)]
# Load the evaluation questions once at startup.
EVALUATION_QUESTIONS = get_evaluation_questions()
def sanitize_input(text):
"""
Sanitizes input to prevent harmful content and limits its length.
"""
# Allow alphanumerics and some punctuation, then truncate to 500 characters.
clean_text = re.sub(r"[^a-zA-Z0-9\s.,!?@:\-]", "", text)
return clean_text.strip()[:500]
def validate_email(email):
"""
Validates that the provided email is in a valid format.
Returns True if valid, False otherwise.
"""
email_regex = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
return re.match(email_regex, email) is not None
def submit_prompt(email, name, system_prompt):
"""
Handles user submission:
- Validates email format.
- Checks if the email has already been used for submission.
- Evaluates the system prompt against predefined test questions.
- Prevents multiple submissions from the same email.
Returns the evaluation results or an error message if the submission is invalid.
"""
# Validate email format.
if not validate_email(email):
return "Invalid email address. Please enter a valid email."
# Check if this email has already been used for submission.
if email in submitted_emails:
return f"Submission already received for {email}. You can only submit once."
# Sanitize inputs.
email = sanitize_input(email)
name = sanitize_input(name)
system_prompt = sanitize_input(system_prompt)
score = 0
responses = []
for item in EVALUATION_QUESTIONS:
question = item["question"]
expected = item["expected"]
try:
# Use the new client-based API for chat completions.
response = client.chat.completions.create(
model="gpt-4o-mini", # Ensure this identifier matches the deployed model.
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": question}
]
)
# Extract the answer from the response object.
answer = response.choices[0].message.content.strip()
except Exception as e:
answer = f"Error during OpenAI API call: {str(e)}"
# Simple evaluation: check if the expected output is a substring of the answer (case-insensitive).
if expected.lower() in answer.lower():
score += 1
verdict = "Correct"
else:
verdict = "Incorrect"
responses.append(
f"Question: {question}\n"
f"Answer: {answer}\n"
f"Expected: {expected}\n"
f"Result: {verdict}\n"
)
result_details = "\n".join(responses)
# Record this email as having submitted their prompt.
submitted_emails.add(email)
return (
f"Thank you for your submission, {name}!\n\n"
f"Your evaluation score is {score} out of {len(EVALUATION_QUESTIONS)}.\n\nDetails:\n{result_details}"
)
def build_interface():
"""
Constructs the Gradio interface with a submission button and single-submission mechanism.
"""
with gr.Blocks() as demo:
gr.Markdown("# GPT-4o Mini System Prompt Submission")
# General description
gr.Markdown("""Classification Task: Document and Clause Level Identification
Participants must create a system prompt for a language model that classifies user queries about legal documents into two specific categories:
1. **Document Level**: Determines whether the query refers to a single document or multiple documents.
2. **Clause Level**: Identifies whether the query is focused on:
- A single clause,
- Multiple clauses, or
- General information not constrained to any specific clause.
The model must return a valid JSON object with the following structure:
```
{
"document_level": "single/multiple",
"clause_level": "single/multiple/general"
}
```
The goal is to ensure that the model's output is concise, structured, and accurate. This task is designed to evaluate the robustness of the system prompt in handling classification tasks with short, precise outputs.
""")
# Example Inputs and Outputs in an Accordion
with gr.Accordion("Example Inputs and Expected Outputs", open=False):
gr.Markdown("""
1. **User Message Example 1:**
- *"Please provide the contract for the lease agreement."*
- **Expected Output:**
```
{"document_level": "single", "clause_level": "general"}
```
2. **User Message Example 2:**
- *"I need all clauses related to termination in the employment contract."*
- **Expected Output:**
```
{"document_level": "single", "clause_level": "multiple"}
```
3. **User Message Example 3:**
- *"Can you send me the financial reports and the partnership agreement?"*
- **Expected Output:**
```
{"document_level": "multiple", "clause_level": "general"}
```
4. **User Message Example 4:**
- *"What are the key clauses in the NDA?"*
- **Expected Output:**
```
{"document_level": "single", "clause_level": "multiple"}
```
5. **User Message Example 5:**
- *"Tell me about the company’s financials."*
- **Expected Output:**
```
{"document_level": "single", "clause_level": "general"}
```
6. **User Message Example 6:**
- *"Provide all contracts and their confidentiality clauses."*
- **Expected Output:**
```
{"document_level": "multiple", "clause_level": "multiple"}
```
7. **User Message Example 7:**
- *"Extract the arbitration clause from this service agreement."*
- **Expected Output:**
```
{"document_level": "single", "clause_level": "single"}
```
""")
# Challenge instructions in another Accordion
with gr.Accordion("Challenge Instructions", open=False):
gr.Markdown("""
- Design a system prompt that ensures the AI generates outputs like those above when given similar user messages.
The system prompt should:
1. Specify formatting requirements (e.g., *"Output must be a valid JSON object"*). Note that we are not using constrained decoding or any sort of JSON mode; if not correctly prompted, the LLM will output plain text.
2. Emphasize strict adherence to classification definitions:
- *Single Document:* Refers to one document.
- *Multiple Documents:* Refers to more than one document.
- *Single Clause:* Refers to one specific clause.
- *Multiple Clauses:* Refers to more than one specific clause.
- *General Information:* Refers to general content not tied to specific clauses.
You can only submit once, so test your system prompt thoroughly before submission!
""")
gr.Markdown("""Classification Task: Document and Clause Level Identification
Challenge Description
Participants must create a system prompt for a language model that classifies user queries about legal documents into two specific categories:"
1. Document Level: Determines whether the query refers to a single document or multiple documents.
2. Clause Level: Identifies whether the query is focused on:
- A single clause,
- Multiple clauses, or
- General information not constrained to any specific clause.
The model must return a valid JSON object with the following structure:
```json
{"document_level": "single/multiple","clause_level": "single/multiple/general"}
```
The goal is to ensure that the model's output is concise, structured, and accurate. This task is designed to evaluate the robustness of the system prompt in handling classification tasks with short, precise outputs.
<details>
<summary>Click to see example inputs and outputs.</summary>
**Example Inputs and Expected Outputs**
1. **User Message Example 1:**
- *"Please provide the contract for the lease agreement."*
- **Expected Output:**
```json
{"document_level": "single", "clause_level": "general"}
```
2. **User Message Example 2:**
- *"I need all clauses related to termination in the employment contract."*
- **Expected Output:**
```json
{"document_level": "single", "clause_level": "multiple"}
```
3. **User Message Example 3:**
- *"Can you send me the financial reports and the partnership agreement?"*
- **Expected Output:**
```json
{"document_level": "multiple", "clause_level": "general"}
```
4. **User Message Example 4:**
- *"What are the key clauses in the NDA?"*
- **Expected Output:**
```json
{"document_level": "single", "clause_level": "multiple"}
```
5. **User Message Example 5:**
- *"Tell me about the company’s financials."*
- **Expected Output:**
```json
{"document_level": "single", "clause_level": "general"}
```
6. **User Message Example 6:**
- *"Provide all contracts and their confidentiality clauses."*
- **Expected Output:**
```json
{"document_level": "multiple", "clause_level": "multiple"}
```
7. **User Message Example 7:**
- *"Extract the arbitration clause from this service agreement."*
- **Expected Output:**
```json
{"document_level": "single", "clause_level": "single"}
```
</details>
**Challenge Instructions**
- Design a system prompt that ensures the AI generates outputs like those above when given similar user messages.
- The system prompt should:
1. Specify formatting requirements (e.g., "Output must be a valid JSON object"), not that we are not using constrained decoding or any sort of JSON mode, if not correctly prompted the llm will output plain text.
2. Emphasize strict adherence to classification definitions:
- *Single Document:* Refers to one document.
- *Multiple Documents:* Refers to more than one document.
- *Single Clause:* Refers to one specific clause.
- *Multiple Clauses:* Refers to more than one specific clause.
- *General Information:* Refers to general content not tied to specific clauses.
""")
gr.Markdown(
"Please enter your details and submit your system prompt below. "
"You can only submit once, I suggest trying to test and build out the system prompt using the same LM being used here elsewhere before submitting."
)
email_input = gr.Textbox(label="Email", placeholder="[email protected]")
name_input = gr.Textbox(label="Name", placeholder="Your name")
system_prompt_input = gr.Textbox(
label="System Prompt",
placeholder="Enter your system prompt here...",
lines=6,
)
submit_button = gr.Button("Submit")
output_text = gr.Textbox(label="Results", lines=15)
submit_button.click(
fn=submit_prompt,
inputs=[email_input, name_input, system_prompt_input],
outputs=output_text,
)
return demo
if __name__ == "__main__":
interface = build_interface()
# Launch the app on 0.0.0.0 so it is accessible externally (e.g., in a container).
interface.launch(server_name="0.0.0.0", server_port=7860)
|