import openai import gradio as gr import os import time # Load your OpenAI API key from the environment variable api_key = os.getenv("OPENAI_API_KEY") # Ensure the API key doesn't have any leading/trailing whitespace or newline characters openai.api_key = api_key.strip() # Function to interact with the GPT-4o-mini model via the OpenAI API def subsurface_sentinel(user_input): prompt = f"User: {user_input}" # Retry mechanism in case of connection errors for _ in range(3): # Try up to 3 times try: response = openai.chat.completions.create( model="gpt-4o-mini", # Use the gpt-4o-mini model messages=[ {"role": "system", "content": "You are Subsurface Sentinel, a virtual assistant for professionals in the oil and gas industry, focusing on field development planning."}, {"role": "user", "content": prompt} ], max_tokens=150, temperature=0.7, ) # Extract the response text and remove any leading/trailing whitespace return response.choices[0].message.content.strip() except openai.error.APIConnectionError as e: print(f"Connection error: {e}. Retrying...") time.sleep(2) # Wait for 2 seconds before retrying except openai.InvalidRequestError as e: return f"Invalid request: {e}" except openai.AuthenticationError as e: return f"Authentication failed: {e}" except openai.RateLimitError as e: return f"Rate limit exceeded: {e}" except Exception as e: return f"An unexpected error occurred: {e}" return "Failed to connect to OpenAI API after several attempts." # Create the Gradio interface iface = gr.Interface( fn=subsurface_sentinel, # The function to be called for generating responses inputs=gr.Textbox(label="Enter your question here"), # User input outputs="text", # Output type for the bot's response title="Subsurface Sentinel", description=( "A virtual assistant for professionals in the oil and gas industry focusing on field development planning.\n\n" "You can ask questions related to field development, subsurface risks, reservoir management, and more." ), examples=[ ["Analyze the provided Field Development Plan for insights."], ["What are the potential risks in subsurface operations?"], ["How can machine learning be applied to improve reservoir management?"], ["Summarize the key details from the latest geological survey report."], ["Evaluate the proposed drilling strategy in terms of cost-effectiveness."] ] ) # Launch the Gradio interface iface.launch()