NihalGazi's picture
Create app.py
1bf38da verified
raw
history blame
2 kB
import os
import json
import google.generativeai as genai
import gradio as gr
# Configure the Gemini API
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
# Generation configuration
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
"response_mime_type": "text/plain",
}
# Define the model
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config=generation_config,
)
# Function to generate substeps recursively
def generate_substeps(reactants, products):
prompt = f"Given reactants: {reactants} and products: {products}, break down the reaction mechanism into simple steps and provide in JSON format."
chat_session = model.start_chat(history=[])
response = chat_session.send_message(prompt)
# Extract the JSON output
try:
steps = json.loads(response.text)
except json.JSONDecodeError:
steps = {"error": "Failed to decode JSON from Gemini response."}
# Recursively break down each step if possible
for step in steps:
step_reactants = steps[step][0] # reactants in this step
step_products = steps[step][1] # products in this step
reason = steps[step][2] # reason in this step
if reason != "found through experiment":
substeps = generate_substeps(step_reactants, step_products)
steps[step].append({"substeps": substeps})
return steps
# Gradio interface
def process_reaction(reactants, products):
steps = generate_substeps(reactants, products)
return json.dumps(steps, indent=4)
# Create the Gradio interface
iface = gr.Interface(
fn=process_reaction,
inputs=[gr.Textbox(label="Reactants (comma-separated)"), gr.Textbox(label="Products (comma-separated)")],
outputs="json",
title="Chemistry Rationalizer",
description="Break down a reaction mechanism into recursive steps."
)
if __name__ == "__main__":
iface.launch()