|
|
import gradio as gr |
|
|
import openai |
|
|
import os |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SYSTEM_PROMPT = "You are a highly accurate math solver. Provide the final numerical answer to the user's problem. Use the required units (e.g., '40 cm^2') and round to two decimal places if needed. Do not show your work, steps, or formulas." |
|
|
|
|
|
|
|
|
try: |
|
|
|
|
|
client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) |
|
|
except Exception as e: |
|
|
print(f"Error initializing OpenAI client: {e}") |
|
|
|
|
|
client = None |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def call_external_api(prompt): |
|
|
""" |
|
|
Calls the external OpenAI API to get the model's response. |
|
|
""" |
|
|
if not client: |
|
|
return "Error: API Key not configured. Please set OPENAI_API_KEY environment variable." |
|
|
|
|
|
try: |
|
|
|
|
|
response = client.chat.completions.create( |
|
|
model="gpt-3.5-turbo", |
|
|
messages=[ |
|
|
{"role": "system", "content": SYSTEM_PROMPT}, |
|
|
{"role": "user", "content": prompt} |
|
|
], |
|
|
temperature=0.0 |
|
|
) |
|
|
|
|
|
|
|
|
return response.choices[0].message.content.strip() |
|
|
|
|
|
except Exception as e: |
|
|
return f"API Call Error: Could not get a response from the external model. Details: {e}" |
|
|
|
|
|
|
|
|
|
|
|
def generate_response(message, history): |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
response = call_external_api(message) |
|
|
|
|
|
|
|
|
return response |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
demo = gr.ChatInterface( |
|
|
fn=generate_response, |
|
|
title=f"Reliable Math LLM (Powered by External API)", |
|
|
description="Ask a math problem! This uses a reliable external service for answers.", |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch() |