File size: 2,331 Bytes
1bf38da
 
 
 
 
 
 
 
0e46ae7
 
 
 
 
 
 
 
 
 
f4b21ec
 
0e46ae7
 
 
1bf38da
2616683
 
0e46ae7
1bf38da
0e46ae7
1bf38da
 
25c8d3c
1bf38da
 
2a32308
 
0e46ae7
1bf38da
 
 
156d641
 
1bf38da
156d641
25c8d3c
9587196
 
 
156d641
 
 
 
1bf38da
 
 
 
156d641
1bf38da
 
2a32308
1bf38da
 
 
 
 
 
 
 
2a32308
1bf38da
 
 
 
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
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"])

# Define the system instruction (pre_prompt)
pre_prompt = """
You are a chemistry expert. Break down the given chemical reaction mechanism into simple steps. 
The output should be in JSON format with the following structure:

{
    "step 1": {
        "reactants": ["reactant 1", "reactant 2"],
        "products": ["product 1", "product 2"],
        "reason": "Describe the reason or logic behind this step",
        "reagent": "Optional reagent or conditions for this step",
        "conditions": "Environmental conditions like temperature and pressure for this step"
    },
    "step 2": { ... }
    ...
}

DO NOT USE CODEBLOCK or any markdown. Simply write the JSON only.
"""

# Define the model with the system instruction (pre_prompt)
model = genai.GenerativeModel(
    model_name="gemini-1.5-flash",
    system_instruction=pre_prompt
)

# Function to generate steps for A -> D flow
def generate_reaction_steps(reactants, products):
    prompt = f"Given reactants: {reactants} and products: {products}, break down the reaction mechanism into simple steps in JSON format."
    
    chat_session = model.start_chat(history=[])
    response = chat_session.send_message(prompt)
    
    # Extract the JSON content from the response
    try:
        # Parsing the raw response to extract the JSON text
        content = response.text
        print(response)
        print("\n\n\n")
        print(content)
        
        # Loading the JSON string to a Python dictionary
        steps = json.loads(content)
    except (json.JSONDecodeError, KeyError):
        steps = {"error": "Failed to decode JSON from Gemini response."}
    
    return steps


# Gradio interface
def process_reaction(reactants, products):
    steps = generate_reaction_steps(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 simple steps."
)

if __name__ == "__main__":
    iface.launch()