-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
237 lines (204 loc) · 9.53 KB
/
agent.py
File metadata and controls
237 lines (204 loc) · 9.53 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import streamlit as st
import anthropic
import requests
import os
import sys
from pathlib import Path
# Import run_vmd_script directly from main.py (no HTTP overhead)
sys.path.insert(0, str(Path(__file__).parent))
from main import run_vmd_script
# ---------------------------------------------------------------------------
# Anthropic client
# ---------------------------------------------------------------------------
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
MODEL = "claude-sonnet-4-6"
# ---------------------------------------------------------------------------
# Tool definition (Anthropic format)
# ---------------------------------------------------------------------------
tools = [
{
"name": "execute_vmd",
"description": (
"Execute a VMD Tcl script on the loaded protein structure and return a rendered image."
),
"input_schema": {
"type": "object",
"properties": {
"tcl_script": {
"type": "string",
"description": (
"Complete VMD Tcl script. Assume the structure is already loaded as "
"molecule 0 (top). Always start by removing all existing representations."
),
}
},
"required": ["tcl_script"],
},
}
]
SYSTEM_PROMPT = """You are an expert in VMD (Visual Molecular Dynamics) Tcl scripting and protein structure visualization.
A protein structure has been loaded. When the user asks you to visualize something, use the execute_vmd tool to render it.
VMD Tcl conventions:
- Always start scripts with a loop to remove all existing representations:
set nreps [molinfo top get numreps]
for {set i 0} {$i < $nreps} {incr i} { mol delrep 0 top }
- Background: color Display Background white
- Turn off axes: axes location off
- Turn off depth cueing: display depthcue off
- Color codes: 0=blue, 1=red, 2=gray, 3=orange, 4=yellow, 5=tan, 6=silver, 7=green, 8=white, 9=pink, 10=cyan
- Default drawing method: VDW (unless user asks for ribbon, cartoon, surface, licorice, etc.)
- To add a representation:
mol addrep top
mol modstyle 0 top <DrawMethod>
mol modcolor 0 top ColorID <n>
mol modselect 0 top "<selection>"
- if representation is said Ribbon it means NewRibbons representation with thickness 3.0 showing alpha helices and beta sheets; not vdw or cpk
- Multiple representations: increment the rep index (0, 1, 2, ...) for each mol modstyle/modcolor/modselect call
After each render, briefly describe what is shown. Remember context from previous messages to maintain continuity."""
# ---------------------------------------------------------------------------
# Helper: serialize Anthropic content blocks to plain dicts for session state
# ---------------------------------------------------------------------------
def serialize_content(content):
result = []
for block in content:
if block.type == "text":
result.append({"type": "text", "text": block.text})
elif block.type == "tool_use":
result.append({"type": "tool_use", "id": block.id, "name": block.name, "input": block.input})
return result
# ---------------------------------------------------------------------------
# Page config
# ---------------------------------------------------------------------------
st.set_page_config(page_title="VMD Agent", layout="centered")
st.title("VMD Visualization Agent")
# ---------------------------------------------------------------------------
# Session state init
# ---------------------------------------------------------------------------
if "messages" not in st.session_state:
st.session_state.messages = []
if "chat_display" not in st.session_state:
st.session_state.chat_display = []
# ---------------------------------------------------------------------------
# Sidebar: PDB loading
# ---------------------------------------------------------------------------
with st.sidebar:
st.header("Load Protein Structure")
pdb_id_input = st.text_input("PDB ID (e.g. 1CRN)")
if st.button("Fetch from RCSB") and pdb_id_input:
pdb_id = pdb_id_input.strip().upper()
url = f"https://files.rcsb.org/download/{pdb_id}.pdb"
with st.spinner(f"Fetching {pdb_id}..."):
resp = requests.get(url, timeout=15)
if resp.status_code == 200:
pdb_path = f"/tmp/{pdb_id}.pdb"
with open(pdb_path, "wb") as f:
f.write(resp.content)
st.session_state.pdb_path = pdb_path
st.session_state.messages = []
st.session_state.chat_display = []
st.success(f"Loaded {pdb_id}")
else:
st.error(f"Could not fetch {pdb_id} (HTTP {resp.status_code})")
st.markdown("---")
uploaded = st.file_uploader("Or upload a .pdb file", type=["pdb"])
if uploaded is not None:
pdb_path = f"/tmp/{uploaded.name}"
with open(pdb_path, "wb") as f:
f.write(uploaded.getbuffer())
if st.session_state.get("pdb_path") != pdb_path:
st.session_state.pdb_path = pdb_path
st.session_state.messages = []
st.session_state.chat_display = []
st.success(f"Loaded {uploaded.name}")
if "pdb_path" in st.session_state:
st.info(f"Active structure: **{Path(st.session_state.pdb_path).name}**")
else:
st.warning("No structure loaded. Fetch a PDB ID or upload a file.")
# ---------------------------------------------------------------------------
# Render existing chat history
# ---------------------------------------------------------------------------
for entry in st.session_state.chat_display:
with st.chat_message(entry["role"]):
if entry.get("text"):
st.markdown(entry["text"])
if entry.get("image"):
st.image(entry["image"], use_container_width=True)
with open(entry["image"], "rb") as f:
st.download_button("Download image", f, file_name=Path(entry["image"]).name, mime="image/png", key=entry["image"])
# ---------------------------------------------------------------------------
# Chat input
# ---------------------------------------------------------------------------
user_input = st.chat_input(
"Describe the visualization...",
disabled="pdb_path" not in st.session_state,
)
if user_input:
if "pdb_path" not in st.session_state:
st.warning("Please load a PDB structure first.")
st.stop()
# Show user message immediately
st.session_state.chat_display.append({"role": "user", "text": user_input, "image": None})
with st.chat_message("user"):
st.markdown(user_input)
# Append to message history
st.session_state.messages.append({"role": "user", "content": user_input})
# ------------------------------------------------------------------
# Agent loop
# ------------------------------------------------------------------
image_path = None
final_text = ""
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
response = client.messages.create(
model=MODEL,
max_tokens=4096,
system=SYSTEM_PROMPT,
tools=tools,
messages=st.session_state.messages,
)
# Keep going while Claude wants to call tools
while response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use" and block.name == "execute_vmd":
tcl_script = block.input["tcl_script"]
# Run VMD; returns "http://localhost:8000/static/vmd_<uuid>.png"
result_url = run_vmd_script(tcl_script, st.session_state.pdb_path)
local_path = result_url.replace("http://localhost:8000/", "")
image_path = local_path
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": "Image rendered successfully.",
})
# Append assistant turn and tool results (serialize to plain dicts)
st.session_state.messages.append(
{"role": "assistant", "content": serialize_content(response.content)}
)
st.session_state.messages.append(
{"role": "user", "content": tool_results}
)
response = client.messages.create(
model=MODEL,
max_tokens=4096,
system=SYSTEM_PROMPT,
tools=tools,
messages=st.session_state.messages,
)
# Extract final text
for block in response.content:
if hasattr(block, "text"):
final_text += block.text
# Persist final assistant message
st.session_state.messages.append(
{"role": "assistant", "content": serialize_content(response.content)}
)
if final_text:
st.markdown(final_text)
if image_path:
st.image(image_path, use_container_width=True)
with open(image_path, "rb") as f:
st.download_button("Download image", f, file_name=Path(image_path).name, mime="image/png")
st.session_state.chat_display.append(
{"role": "assistant", "text": final_text, "image": image_path}
)