Samee-ur commited on
Commit
ae6181a
Β·
verified Β·
1 Parent(s): 9bdbdde

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -0
app.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import random
6
+ from typing import List
7
+ from rcwa import Material, Layer, LayerStack, Source, Solver
8
+ from smolagents import tool, CodeAgent, InferenceClientModel, stream_to_gradio
9
+
10
+ # --- Constants ---
11
+ start_wl = 0.32
12
+ stop_wl = 0.80
13
+ step_wl = 0.01
14
+ wavelengths = np.arange(start_wl, stop_wl + step_wl, step_wl)
15
+ materials = ['Si', 'Si3N4', 'SiO2', 'AlN']
16
+
17
+ @tool
18
+ def simulate_spectrum_100nm(layer_order: List[str]) -> List[float]:
19
+ """
20
+ Simulates the optical transmission spectrum for a given sequence of material layers at 100nm thickness.
21
+
22
+ Args:
23
+ layer_order (List[str]): A list of material names (e.g., ["Si", "SiO2", "AlN"]) representing the order of layers in the optical stack.
24
+
25
+ Returns:
26
+ List[float]: The transmission spectrum across a predefined wavelength range.
27
+ """
28
+ source = Source(wavelength=start_wl)
29
+ reflection_layer = Layer(n=1.0)
30
+ transmission_layer = Layer(material=Material("Si"))
31
+ try:
32
+ layers = [Layer(material=Material(m), thickness=0.1) for m in layer_order]
33
+ stack = LayerStack(*layers, incident_layer=reflection_layer, transmission_layer=transmission_layer)
34
+ solver = Solver(stack, source, (1, 1))
35
+ result = solver.solve(wavelength=wavelengths)
36
+ return np.array(result['TTot']).tolist()
37
+ except Exception as e:
38
+ return []
39
+
40
+ @tool
41
+ def cosine_similarity(vec1: List[float], vec2: List[float]) -> float:
42
+ """
43
+ Computes the cosine similarity between two vectors.
44
+
45
+ Args:
46
+ vec1 (List[float]): The first vector.
47
+ vec2 (List[float]): The second vector.
48
+
49
+ Returns:
50
+ float: A similarity score between -1 and 1.
51
+ """
52
+ a, b = np.array(vec1), np.array(vec2)
53
+ return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
54
+
55
+
56
+ # --- Target Spectrum Generator ---
57
+ def get_target_spectrum(layer_order, thickness=0.1):
58
+ source = Source(wavelength=start_wl)
59
+ reflection_layer = Layer(n=1.0)
60
+ transmission_layer = Layer(material=Material("Si"))
61
+ try:
62
+ layers = [Layer(material=Material(m), thickness=thickness) for m in layer_order]
63
+ stack = LayerStack(*layers, incident_layer=reflection_layer, transmission_layer=transmission_layer)
64
+ solver = Solver(stack, source, (1, 1))
65
+ result = solver.solve(wavelength=wavelengths)
66
+ return np.array(result['TTot']).tolist()
67
+ except Exception:
68
+ return None
69
+
70
+ # --- Model Setup ---
71
+ from smolagents import LiteLLMModel
72
+ openai_key = os.getenv("OPENAI_API_KEY")
73
+ model = LiteLLMModel(model_id="openai/gpt-4.1-mini", temperature=0, api_key=openai_key)
74
+
75
+ # --- Agent Setup ---
76
+ agent_10nm_simulator = CodeAgent(
77
+ tools=[simulate_spectrum_10nm],
78
+ model=model,
79
+ stream_outputs=True,
80
+ name="agent_10nm_simulator",
81
+ description="You are an AI agent that uses tools to simulate optical spectra for materials with thickness 10nm. You must provide the simulated response back. Do not provide any other information. "
82
+ )
83
+
84
+ agent_10nm_simulator.prompt_templates['managed_agent'] = {
85
+ "task": """You're an assistant agent named '{{name}}'.
86
+ You have been given this task:
87
+ ---
88
+ {{task}}
89
+ ---
90
+ Just return the result of your tool call. Do not add explanations or formatting.
91
+ Call a tool immediately and use `final_answer(...)` to return the result.
92
+ """,
93
+ "report": """{{final_answer}}""" # Minimal required key
94
+ }
95
+
96
+
97
+
98
+ agent_100nm_simulator = CodeAgent(
99
+ tools=[simulate_spectrum_100nm],
100
+ model=model,
101
+ stream_outputs=True,
102
+ name="agent_100nm_simulator",
103
+ description="You are an AI agent that uses tools to simulate optical spectra for materials with thickness 100nm. You must provide the simulated response back. Do not provide any other information."
104
+ )
105
+
106
+
107
+ agent_100nm_simulator.prompt_templates['managed_agent'] = {
108
+ "task": """You're an assistant agent named '{{name}}'.
109
+ You have been given this task:
110
+ ---
111
+ {{task}}
112
+ ---
113
+ Just return the result of your tool call. Do not add explanations or formatting.
114
+ Call a tool immediately and use `final_answer(...)` to return the result.
115
+ """,
116
+ "report": """{{final_answer}}""" # Minimal required key
117
+ }
118
+
119
+
120
+ coordinator = CodeAgent(
121
+ tools=[cosine_similarity],
122
+ managed_agents=[agent_10nm_simulator, agent_100nm_simulator],
123
+ model=model,
124
+ stream_outputs=True,
125
+ additional_authorized_imports = ["numpy"]
126
+ )
127
+
128
+ # --- Gradio UI ---
129
+ with gr.Blocks() as demo:
130
+ gr.Markdown("""
131
+ # 🧠 Multi-Agent Thin Film Stack Optimizer
132
+ This demo simulates an AI agent coordinating spectrum simulations at 10nm and 100nm thickness to match a target.
133
+ """)
134
+ gr.Markdown("""
135
+ CodeAgent | openai/gpt-4.1-mini
136
+ β”œβ”€β”€ βœ… Authorized imports: ['numpy']
137
+ β”œβ”€β”€ πŸ› οΈ Tools:
138
+ β”‚ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
139
+ β”‚ ┃ Name ┃ Description ┃ Arguments ┃
140
+ β”‚ ┑━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
141
+ β”‚ β”‚ cosine_similarity β”‚ Computes the cosine similarity between two β”‚ vec1 (`array`): The first vector. β”‚
142
+ β”‚ β”‚ β”‚ vectors. β”‚ vec2 (`array`): The second vector. β”‚
143
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
144
+ └── πŸ€– Managed agents:
145
+ β”œβ”€β”€ agent_10nm_simulator | CodeAgent | openai/gpt-4.1-mini
146
+ β”‚ β”œβ”€β”€ βœ… Authorized imports: []
147
+ β”‚ β”œβ”€β”€ πŸ“ Description: Simulates optical spectra for 10nm thickness.
148
+ β”‚ └── πŸ› οΈ Tools:
149
+ β”‚ ┏━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
150
+ β”‚ ┃ Name ┃ Description ┃ Arguments ┃
151
+ β”‚ ┑━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
152
+ β”‚ β”‚ simulate_spectrum_10nm β”‚ Simulates spectrum for 10nm layers. β”‚ layer_order (`array`): List of materials β”‚
153
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
154
+ └── agent_100nm_simulator | CodeAgent | openai/gpt-4.1-mini
155
+ β”œβ”€β”€ βœ… Authorized imports: []
156
+ β”œβ”€β”€ πŸ“ Description: Simulates optical spectra for 100nm thickness.
157
+ └── πŸ› οΈ Tools:
158
+ ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
159
+ ┃ Name ┃ Description ┃ Arguments ┃
160
+ ┑━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
161
+ β”‚ simulate_spectrum_100nm β”‚ Simulates spectrum for 100nm layers.β”‚ layer_order (`array`): List of materials β”‚
162
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
163
+ """)
164
+ run_btn = gr.Button("πŸ” Run Agent on Random Stack")
165
+ true_order = gr.Textbox(label="True Material Order")
166
+ prompt_box = gr.Textbox(label="Agent Prompt")
167
+ chatbot = gr.Chatbot(label="Agent Reasoning Stream")
168
+
169
+ def run_agent_streaming():
170
+ true_order_val = random.sample(materials, 4)
171
+ target_val = get_target_spectrum(true_order_val)
172
+ true_order_display = ", ".join(true_order_val)
173
+
174
+ if target_val is None:
175
+ yield gr.update(value="Simulation failed"), gr.update(), gr.update()
176
+ return
177
+
178
+ prompt = f"""
179
+ You are the Coordinator Agent. Your objective is to identify a 4-layer material stack **order** and **thickness** that reproduces a given target optical transmission spectrum.
180
+
181
+ Constraints:
182
+ - Materials: [Si, Si3N4, SiO2, AlN] (use each exactly once)
183
+ - Two fixed thickness options for all layers: 10nm and 100nm
184
+
185
+ You have access to the following:
186
+ - agent_10nm_simulator: An agent that simulates a spectrum for a given material order with **10nm** layer thickness
187
+ - agent_100nm_simulator: An agent that simulates a spectrum for a given material order with **100nm** layer thickness
188
+ - cosine_similarity: Compares a predicted spectrum to the target spectrum
189
+
190
+ Your task:
191
+ 1. Choose candidate layer orders and thickness options
192
+ 2. Call the appropriate agent to simulate the spectrum
193
+ 3. Use cosine_similarity to compare with the target
194
+ 4. Stop when similarity exceeds 0.999
195
+ 5. Report the matching order, thickness, and number of attempts
196
+
197
+ Begin.
198
+
199
+ Target spectrum: {target_val}
200
+ """
201
+ chat_history = []
202
+ yield gr.update(value=true_order_display), gr.update(value=prompt), gr.update(value=[])
203
+
204
+ for msg in stream_to_gradio(coordinator, task=prompt):
205
+ if isinstance(msg, gr.ChatMessage):
206
+ chat_history.append(("", msg.content))
207
+ elif isinstance(msg, str):
208
+ if chat_history:
209
+ chat_history[-1] = ("", msg)
210
+ else:
211
+ chat_history.append(("", msg))
212
+ yield gr.update(), gr.update(), gr.update(value=chat_history)
213
+
214
+ run_btn.click(fn=run_agent_streaming, inputs=[], outputs=[true_order, prompt_box, chatbot])
215
+
216
+ demo.launch(debug=True)