Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506import torchfrom typing import Annotated, TypedDict, Literalfrom langchain_community.tools import DuckDuckGoSearchRunfrom langchain_core.tools import toolfrom langgraph.prebuilt import ToolNode, tools_conditionfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.graph.message import add_messagesfrom langchain_core.messages import SystemMessage, trim_messages, AIMessage, HumanMessage, ToolCallfrom langchain_huggingface.llms import HuggingFacePipelinefrom langchain_huggingface import ChatHuggingFacefrom langchain_core.prompts import PromptTemplate, ChatPromptTemplatefrom langchain_core.runnables import chainfrom uuid import uuid4import reimport matplotlib.pyplot as pltimport PIL.Image as Imageimport gradio as grimport spacesfrom rdkit import Chemfrom rdkit.Chem import AllChem, QEDfrom rdkit.Chem import Drawfrom rdkit import rdBasefrom rdkit.Chem import rdMolAlignimport osfrom rdkit import RDConfigfrom rdkit.Chem.Features.ShowFeats import _featColors as featColorsfrom rdkit.Chem.FeatMaps import FeatMapsfdef = AllChem.BuildFeatureFactory(os.path.join(RDConfig.RDDataDir,'BaseFeatures.fdef'))fmParams = {}for k in fdef.GetFeatureFamilies():fparams = FeatMaps.FeatMapParams()fmParams[k] = fparamsdevice = "cuda" if torch.cuda.is_available() else "cpu"hf = HuggingFacePipeline.from_model_id(#model_id= "swiss-ai/Apertus-8B-Instruct-2509",model_id= "microsoft/Phi-4-mini-instruct",task="text-generation",pipeline_kwargs = {"max_new_tokens": 500, "temperature": 0.4})chat_model = ChatHuggingFace(llm=hf)class State(TypedDict):'''The state of the agent.'''messages: Annotated[list, add_messages]query_smiles: strquery_task: strquery_path: strquery_reference: strtool_choice: tuplewhich_tool: intprops_string: str#(Literal["lipinski_tool", "substitution_tool", "pharm_feature_tool"],# Literal["lipinski_tool", "substitution_tool", "pharm_feature_tool"])def substitution_node(state: State) -> State:'''A simple substitution routine that looks for a substituent on a phenyl ring andsubstitutes different fragments in that location. Returns a list of novel molecules and theirQED score (1 is most drug-like, 0 is least drug-like).Args:smiles: the input smiles stringReturns:new_smiles_string: a string of novel molecules and their QED scores.'''print("substitution tool")print('===================================================')smiles = state["query_smiles"]current_props_string = state["props_string"]new_fragments = ["c(Cl)c", "c(F)c", "c(O)c", "c(C)c", "c(OC)c", "c([NH3+])c","c(Br)c", "c(C(F)(F)(F))c"]new_smiles = []for fragment in new_fragments:m = re.findall(r"c(\D\D*)c", smiles)if len(m) != 0:for group in m:#print(group)if fragment not in group:new_smile = smiles.replace(group[1:], fragment)new_smiles.append(new_smile)qeds = []for new_smile in new_smiles:qeds.append(get_qed(new_smile))original_qed = get_qed(smiles)new_smiles_string = "Substitution or Analogue creation tool results: \n"new_smiles_string += f"The original molecule SMILES was {smiles} with QED {original_qed}.\n"new_smiles_string += "Novel Molecules or Analogues and QED values: \n"for i in range(len(new_smiles)):new_smiles_string += f"SMILES: {new_smiles[i]}, QED: {qeds[i]:.3f}\n"if len(new_smiles) > 0:img = Draw.MolsToGridImage(new_smiles, molsPerRow=3, subImgSize=(200,200), legends=[f"QED: {qeds[i]:.3f}" for i in range(len(new_smiles))])img.save('Substitution_image.png')else:new_smiles_string += "No valid substitutions were found.\n"print(new_smiles_string)current_props_string += new_smiles_stringstate["props_string"] = current_props_stringstate["which_tool"] += 1return statedef get_qed(smiles):'''Helper function to compute QED for a given molecule.Args:smiles: the input smiles stringReturns:qed: the QED score of the molecule.'''mol = Chem.MolFromSmiles(smiles)qed = Chem.QED.default(mol)return qeddef lipinski_node(state: State) -> State:'''A tool to calculate QED and other lipinski properties of a molecule.Args:smiles: the input smiles stringReturns:props_string: a string of the QED and other lipinski properties of the molecule,including Molecular Weight, LogP, HBA, HBD, Polar Surface Area,Rotatable Bonds, Aromatic Rings and Undesireable Moieties.'''print("lipinski tool")print('===================================================')smiles = state["query_smiles"]current_props_string = state["props_string"]mol = Chem.MolFromSmiles(smiles)qed = Chem.QED.default(mol)p = Chem.QED.properties(mol)mw = p[0]logP = p[1]hba = p[2]hbd = p[3]psa = p[4]rb = p[5]ar = p[6]um = p[7]props_string = "Lipinski tool results: \n"props_string += f'''QED and other lipinski properties of the molecule:SMILES: {smiles},QED: {qed:.3f},Molecular Weight: {mw:.3f},LogP: {logP:.3f},Hydrogen bond acceptors: {hba},Hydrogen bond donors: {hbd},Polar Surface Area: {psa:.3f},Rotatable Bonds: {rb},Aromatic Rings: {ar},Undesireable moieties: {um}'''current_props_string += props_stringstate["props_string"] = current_props_stringstate["which_tool"] += 1return statedef pharmfeature_node(state: State) -> State:'''A tool to compare the pharmacophore features of a query molecule againsta those of a reference molecule and report the pharmacophore features of both and the featurescore of the query molecule.Args:known_smiles: the reference smiles stringtest_smiles: the query smiles stringReturns:props_string: a string of the pharmacophore features of both molecules and the featurescore of the query molecule.'''print("pharmfeature tool")print('===================================================')test_smiles = state["query_smiles"]known_smiles = state["query_reference"]current_props_string = state["props_string"]smiles = [known_smiles, test_smiles]mols = [Chem.MolFromSmiles(x) for x in smiles]mols = [Chem.AddHs(m) for m in mols]ps = AllChem.ETKDGv3()for m in mols:AllChem.EmbedMolecule(m,ps)o3d = rdMolAlign.GetO3A(mols[1],mols[0])o3d.Align()keep = ('Donor', 'Acceptor', 'NegIonizable', 'PosIonizable', 'ZnBinder', 'Aromatic', 'LumpedHydrophobe')feat_hash = {'Donor': 'Hydrogen bond donors', 'Acceptor': 'Hydrogen bond acceptors','NegIonizable': 'Negatively ionizable groups', 'PosIonizable': 'Positively ionizable groups','ZnBinder': 'Zinc Binders', 'Aromatic': 'Aromatic rings', 'LumpedHydrophobe': 'Hydrophobic/non-polar groups' }feat_vectors = []for m in mols:rawFeats = fdef.GetFeaturesForMol(m)feat_vectors.append([f for f in rawFeats if f.GetFamily() in keep])feat_maps = [FeatMaps.FeatMap(feats = x,weights=[1]*len(x),params=fmParams) for x in feat_vectors]test_score = feat_maps[0].ScoreFeats(feat_maps[1].GetFeatures())/(feat_maps[0].GetNumFeatures())feats_known = {}feats_test = {}for feat in feat_vectors[0]:if feat.GetFamily() not in feats_known.keys():feats_known[feat.GetFamily()] = 1else:feats_known[feat.GetFamily()] += 1for feat in feat_vectors[1]:if feat.GetFamily() not in feats_test.keys():feats_test[feat.GetFamily()] = 1else:feats_test[feat.GetFamily()] += 1props_string = "PharmFeature tool results: \n"props_string += f"The Pharmacophore Feature Overlap Score of the test molecule \versus the reference molecule is {test_score:.3f}. \n\n"for feat in feats_known.keys():props_string += f"There are {feats_known[feat]} {feat_hash[feat]} in the reference molecule. \n"for feat in feats_test.keys():props_string += f"There are {feats_test[feat]} {feat_hash[feat]} in the test molecule. \n"current_props_string += props_stringstate["props_string"] = current_props_stringstate["which_tool"] += 1return statedef first_node(state: State) -> State:'''The first node of the agent. This node receives the input and asks the LLMto determine which is the best tool to use to answer the QUERY TASK.Input: the initial prompt from the user. should contain only one of more of the following:smiles: the smiles string, task: the query task, path: the path to the file,reference: the reference smilesthe value should be separated from the name by a ':' and each field shouldbe separated from the previous one by a ','.All of these values are saved to the stateOutput: the tool choice'''query_smiles = Nonestate["query_smiles"] = query_smilesquery_task = Nonestate["query_task"] = query_taskquery_path = Nonestate["query_path"] = query_pathquery_reference = Nonestate["query_reference"] = query_referenceprops_string = ""state["props_string"] = props_stringraw_input = state["messages"][-1].contentparts = raw_input.split(',')for part in parts:if 'smiles' in part:query_smiles = part.split(':')[1]if query_smiles.lower() == 'none':query_smiles = Nonestate["query_smiles"] = query_smilesif 'task' in part:query_task = part.split(':')[1]state["query_task"] = query_taskif 'path' in part:query_path = part.split(':')[1]if query_path.lower() == 'none':query_path = Nonestate["query_path"] = query_pathif 'reference' in part:query_reference = part.split(':')[1]if query_reference.lower() == 'none':query_reference = Nonestate["query_reference"] = query_referenceprompt = f'For the QUERY_TASK given below, determine if one or two of the tools descibed below \can complete the task. If so, reply with only the tool names followed by "#". If two tools \are required, reply with both tool names separated by a comma and followed by "#". \If the tools cannot complete the task, reply with "None #".\n \QUERY_TASK: {query_task}.\n \Tools: \n \lipinski_tool: this tool can calculate the following properties: Quantitative \Estimate of Drug-likeness (QED), Molecular weight, LogP (measures lipophilicity, higher is more lipophilic), \HBA, HBD, Polar Surface Area, Rotatable Bonds, Aromatic Rings and Undesireable Moieties. \n \substitution_tool: this tool can generate analogues of the molecule by substituting \different chemical groups on the original molecule. Returns a list of novel molecules and their \QED score (1 is most drug-like, 0 is least drug-like). \n \pharm_feature_tool: this tool can compare the pharmacophore features of a query molecule against \a those of a reference molecule and report the pharmacophore features of both and the feature \score of the query molecule. This score tells how the common features score against each other, but \does not inform about features unique to each molecule.'res = chat_model.invoke(prompt)tool_choices = str(res).split('<|assistant|>')[1].split('#')[0].strip()tool_choices = tool_choices.split(',')if len(tool_choices) == 1:if tool_choices[0].strip().lower() == 'none':tool_choice = (None, None)else:tool_choice = (tool_choices[0].strip().lower(), None)elif len(tool_choices) == 2:if tool_choices[0].strip().lower() == 'none':tool_choice = (None, tool_choices[1].strip().lower())elif tool_choices[1].strip().lower() == 'none':tool_choice = (tool_choices[0].strip().lower(), None)else:tool_choice = (tool_choices[0].strip().lower(), tool_choices[1].strip().lower())else:tool_choice = (None, None)state["tool_choice"] = tool_choicestate["which_tool"] = 0print(f"The chosen tools are: {tool_choice}")return statedef loop_node(state: State) -> State:'''This node accepts the tool returns and decides if it needs to call anothertool or go on to the parser node.Input: the tool returns.Output: the next node to call.'''return statedef parser_node(state: State) -> State:'''This is the third node in the agent. It receives the output from the tool,puts it into a prompt as CONTEXT, and asks the LLM to answer the originalquery.Input: the output from the tool.Output: the answer to the original query.'''props_string = state["props_string"]query_task = state["query_task"]prompt = f'Using the CONTEXT below, answer the original query, which \was to answer the QUERY_TASK. End your answer with a "#" \QUERY_TASK: {query_task}.\n \CONTEXT: {props_string}.\n 'res = chat_model.invoke(prompt)return {"messages": res}def reflect_node(state: State) -> State:'''This is the fourth node of the agent. It recieves the LLMs previous answer andtries to improve it.Input: the LLMs last answer.Output: the improved answer.'''previous_answer = state["messages"][-1].contentprops_string = state["props_string"]prompt = f'Look at the PREVIOUS ANSWER below which you provided and the \TOOL RESULTS. Write an improved answer based on the PREVIOUS ANSWER and the \TOOL RESULTS by adding additional clarifying and enriching information. End \your new answer with a "#" \PREVIOUS ANSWER: {previous_answer}.\n \TOOL RESULTS: {props_string}. 'res = chat_model.invoke(prompt)return {"messages": res}def get_chemtool(state):''''''which_tool = state["which_tool"]tool_choice = state["tool_choice"]if tool_choice is None or tool_choice == (None, None):return Noneif which_tool == 0 or which_tool == 1:current_tool = tool_choice[which_tool]if current_tool is None:return Noneelif which_tool > 1:current_tool = Nonereturn current_tooldef pretty_print(answer):final = str(answer['messages'][-1]).split('<|assistant|>')[-1].split('#')[0].strip("n").strip('\\').strip('n').strip('\\')for i in range(0,len(final),100):print(final[i:i+100])def print_short(answer):for i in range(0,len(answer),100):print(answer[i:i+100])builder = StateGraph(State)builder.add_node("first_node", first_node)builder.add_node("substitution_node", substitution_node)builder.add_node("lipinski_node", lipinski_node)builder.add_node("pharmfeature_node", pharmfeature_node)builder.add_node("loop_node", loop_node)builder.add_node("parser_node", parser_node)builder.add_node("reflect_node", reflect_node)builder.add_edge(START, "first_node")builder.add_conditional_edges("first_node", get_chemtool, {"substitution_tool": "substitution_node","lipinski_tool": "lipinski_node","pharm_feature_tool": "pharmfeature_node",None: "parser_node"})builder.add_edge("lipinski_node", "loop_node")builder.add_edge("substitution_node", "loop_node")builder.add_edge("pharmfeature_node", "loop_node")builder.add_conditional_edges("loop_node", get_chemtool, {"substitution_tool": "substitution_node","lipinski_tool": "lipinski_node","pharm_feature_tool": "pharmfeature_node",None: "parser_node"})builder.add_edge("parser_node", "reflect_node")builder.add_edge("reflect_node", END)graph = builder.compile()@spaces.GPUdef PropAgent(smiles, reference, task):#if Substitution_image.png exists, remove itif os.path.exists('Substitution_image.png'):os.remove('Substitution_image.png')input = {"messages": [HumanMessage(f'query_smiles: {smiles}, query_task: {task}, query_reference: {reference}')]}#print(input)replies = []for c in graph.stream(input): #, stream_mode='updates'):m = re.findall(r'[a-z]+\_node', str(c))if len(m) != 0:reply = c[str(m[0])]['messages']if 'assistant' in str(reply):reply = str(reply).split("<|assistant|>")[-1].split('#')[0].strip()replies.append(reply)#check if image existsif os.path.exists('Substitution_image.png'):img_loc = 'Substitution_image.png'img = Image.open(img_loc)#else create a dummy blank imageelse:img = Image.new('RGB', (250, 250), color = (255, 255, 255))return replies[-1], imgwith gr.Blocks(fill_height=True) as forest:gr.Markdown('''# Properties Agent- uses RDKit to calculate lipinski properties- finds pharmacophore similarity between two molecules- generated analogues of a molecule''')name, smiles = None, Nonewith gr.Row():with gr.Column():smiles = gr.Textbox(label="Molecule SMILES of interest (optional): ", placeholder='none')ref = gr.Textbox(label="Reference molecule SMILES of interest (optional): ", placeholder='none')task = gr.Textbox(label="Task for Agent: ")calc_btn = gr.Button(value = "Submit to Agent")with gr.Column():props = gr.Textbox(label="Agent results: ", lines=20 )pic = gr.Image(label="Molecule")calc_btn.click(PropAgent, inputs = [smiles, ref, task], outputs = [props, pic])forest.launch(debug=False, mcp_server=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506import torchfrom typing import Annotated, TypedDict, Literalfrom langchain_community.tools import DuckDuckGoSearchRunfrom langchain_core.tools import toolfrom langgraph.prebuilt import ToolNode, tools_conditionfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.graph.message import add_messagesfrom langchain_core.messages import SystemMessage, trim_messages, AIMessage, HumanMessage, ToolCallfrom langchain_huggingface.llms import HuggingFacePipelinefrom langchain_huggingface import ChatHuggingFacefrom langchain_core.prompts import PromptTemplate, ChatPromptTemplatefrom langchain_core.runnables import chainfrom uuid import uuid4import reimport matplotlib.pyplot as pltimport PIL.Image as Imageimport gradio as grimport spacesfrom rdkit import Chemfrom rdkit.Chem import AllChem, QEDfrom rdkit.Chem import Drawfrom rdkit import rdBasefrom rdkit.Chem import rdMolAlignimport osfrom rdkit import RDConfigfrom rdkit.Chem.Features.ShowFeats import _featColors as featColorsfrom rdkit.Chem.FeatMaps import FeatMapsfdef = AllChem.BuildFeatureFactory(os.path.join(RDConfig.RDDataDir,'BaseFeatures.fdef'))fmParams = {}for k in fdef.GetFeatureFamilies():fparams = FeatMaps.FeatMapParams()fmParams[k] = fparamsdevice = "cuda" if torch.cuda.is_available() else "cpu"hf = HuggingFacePipeline.from_model_id(#model_id= "swiss-ai/Apertus-8B-Instruct-2509",model_id= "microsoft/Phi-4-mini-instruct",task="text-generation",pipeline_kwargs = {"max_new_tokens": 400, "temperature": 0.4})chat_model = ChatHuggingFace(llm=hf)class State(TypedDict):'''The state of the agent.'''messages: Annotated[list, add_messages]query_smiles: strquery_task: strquery_path: strquery_reference: strtool_choice: tuplewhich_tool: intprops_string: str#(Literal["lipinski_tool", "substitution_tool", "pharm_feature_tool"],# Literal["lipinski_tool", "substitution_tool", "pharm_feature_tool"])def substitution_node(state: State) -> State:'''A simple substitution routine that looks for a substituent on a phenyl ring andsubstitutes different fragments in that location. Returns a list of novel molecules and theirQED score (1 is most drug-like, 0 is least drug-like).Args:smiles: the input smiles stringReturns:new_smiles_string: a string of novel molecules and their QED scores.'''print("substitution tool")print('===================================================')smiles = state["query_smiles"]current_props_string = state["props_string"]new_fragments = ["c(Cl)c", "c(F)c", "c(O)c", "c(C)c", "c(OC)c", "c([NH3+])c","c(Br)c", "c(C(F)(F)(F))c"]new_smiles = []for fragment in new_fragments:m = re.findall(r"c(\D\D*)c", smiles)if len(m) != 0:for group in m:#print(group)if fragment not in group:new_smile = smiles.replace(group[1:], fragment)new_smiles.append(new_smile)qeds = []for new_smile in new_smiles:qeds.append(get_qed(new_smile))original_qed = get_qed(smiles)new_smiles_string = "Substitution or Analogue creation tool results: \n"new_smiles_string += f"The original molecule SMILES was {smiles} with QED {original_qed}.\n"new_smiles_string += "Novel Molecules or Analogues and QED values: \n"for i in range(len(new_smiles)):new_smiles_string += f"SMILES: {new_smiles[i]}, QED: {qeds[i]:.3f}\n"if len(new_smiles) > 0:img = Draw.MolsToGridImage(new_smiles, molsPerRow=3, subImgSize=(200,200), legends=[f"QED: {qeds[i]:.3f}" for i in range(len(new_smiles))])img.save('Substitution_image.png')else:new_smiles_string += "No valid substitutions were found.\n"print(new_smiles_string)current_props_string += new_smiles_stringstate["props_string"] = current_props_stringstate["which_tool"] += 1return statedef get_qed(smiles):'''Helper function to compute QED for a given molecule.Args:smiles: the input smiles stringReturns:qed: the QED score of the molecule.'''mol = Chem.MolFromSmiles(smiles)qed = Chem.QED.default(mol)return qeddef lipinski_node(state: State) -> State:'''A tool to calculate QED and other lipinski properties of a molecule.Args:smiles: the input smiles stringReturns:props_string: a string of the QED and other lipinski properties of the molecule,including Molecular Weight, LogP, HBA, HBD, Polar Surface Area,Rotatable Bonds, Aromatic Rings and Undesireable Moieties.'''print("lipinski tool")print('===================================================')smiles = state["query_smiles"]current_props_string = state["props_string"]mol = Chem.MolFromSmiles(smiles)qed = Chem.QED.default(mol)p = Chem.QED.properties(mol)mw = p[0]logP = p[1]hba = p[2]hbd = p[3]psa = p[4]rb = p[5]ar = p[6]um = p[7]props_string = "Lipinski tool results: \n"props_string += f'''QED and other lipinski properties of the molecule:SMILES: {smiles},QED: {qed:.3f},Molecular Weight: {mw:.3f},LogP: {logP:.3f},Hydrogen bond acceptors: {hba},Hydrogen bond donors: {hbd},Polar Surface Area: {psa:.3f},Rotatable Bonds: {rb},Aromatic Rings: {ar},Undesireable moieties: {um}'''current_props_string += props_stringstate["props_string"] = current_props_stringstate["which_tool"] += 1return statedef pharmfeature_node(state: State) -> State:'''A tool to compare the pharmacophore features of a query molecule againsta those of a reference molecule and report the pharmacophore features of both and the featurescore of the query molecule.Args:known_smiles: the reference smiles stringtest_smiles: the query smiles stringReturns:props_string: a string of the pharmacophore features of both molecules and the featurescore of the query molecule.'''print("pharmfeature tool")print('===================================================')test_smiles = state["query_smiles"]known_smiles = state["query_reference"]current_props_string = state["props_string"]smiles = [known_smiles, test_smiles]mols = [Chem.MolFromSmiles(x) for x in smiles]mols = [Chem.AddHs(m) for m in mols]ps = AllChem.ETKDGv3()for m in mols:AllChem.EmbedMolecule(m,ps)o3d = rdMolAlign.GetO3A(mols[1],mols[0])o3d.Align()keep = ('Donor', 'Acceptor', 'NegIonizable', 'PosIonizable', 'ZnBinder', 'Aromatic', 'LumpedHydrophobe')feat_hash = {'Donor': 'Hydrogen bond donors', 'Acceptor': 'Hydrogen bond acceptors','NegIonizable': 'Negatively ionizable groups', 'PosIonizable': 'Positively ionizable groups','ZnBinder': 'Zinc Binders', 'Aromatic': 'Aromatic rings', 'LumpedHydrophobe': 'Hydrophobic/non-polar groups' }feat_vectors = []for m in mols:rawFeats = fdef.GetFeaturesForMol(m)feat_vectors.append([f for f in rawFeats if f.GetFamily() in keep])feat_maps = [FeatMaps.FeatMap(feats = x,weights=[1]*len(x),params=fmParams) for x in feat_vectors]test_score = feat_maps[0].ScoreFeats(feat_maps[1].GetFeatures())/(feat_maps[0].GetNumFeatures())feats_known = {}feats_test = {}for feat in feat_vectors[0]:if feat.GetFamily() not in feats_known.keys():feats_known[feat.GetFamily()] = 1else:feats_known[feat.GetFamily()] += 1for feat in feat_vectors[1]:if feat.GetFamily() not in feats_test.keys():feats_test[feat.GetFamily()] = 1else:feats_test[feat.GetFamily()] += 1props_string = "PharmFeature tool results: \n"props_string += f"The Pharmacophore Feature Overlap Score of the test molecule \versus the reference molecule is {test_score:.3f}. \n\n"for feat in feats_known.keys():props_string += f"There are {feats_known[feat]} {feat_hash[feat]} in the reference molecule. \n"for feat in feats_test.keys():props_string += f"There are {feats_test[feat]} {feat_hash[feat]} in the test molecule. \n"current_props_string += props_stringstate["props_string"] = current_props_stringstate["which_tool"] += 1return statedef first_node(state: State) -> State:'''The first node of the agent. This node receives the input and asks the LLMto determine which is the best tool to use to answer the QUERY TASK.Input: the initial prompt from the user. should contain only one of more of the following:smiles: the smiles string, task: the query task, path: the path to the file,reference: the reference smilesthe value should be separated from the name by a ':' and each field shouldbe separated from the previous one by a ','.All of these values are saved to the stateOutput: the tool choice'''query_smiles = Nonestate["query_smiles"] = query_smilesquery_task = Nonestate["query_task"] = query_taskquery_path = Nonestate["query_path"] = query_pathquery_reference = Nonestate["query_reference"] = query_referenceprops_string = ""state["props_string"] = props_stringraw_input = state["messages"][-1].contentparts = raw_input.split(',')for part in parts:if 'smiles' in part:query_smiles = part.split(':')[1]if query_smiles.lower() == 'none':query_smiles = Nonestate["query_smiles"] = query_smilesif 'task' in part:query_task = part.split(':')[1]state["query_task"] = query_taskif 'path' in part:query_path = part.split(':')[1]if query_path.lower() == 'none':query_path = Nonestate["query_path"] = query_pathif 'reference' in part:query_reference = part.split(':')[1]if query_reference.lower() == 'none':query_reference = Nonestate["query_reference"] = query_referenceprompt = f'For the QUERY_TASK given below, determine if one or two of the tools descibed below \can complete the task. If so, reply with only the tool names followed by "#". If two tools \are required, reply with both tool names separated by a comma and followed by "#". \If the tools cannot complete the task, reply with "None #".\n \QUERY_TASK: {query_task}.\n \Tools: \n \lipinski_tool: this tool can calculate the following properties: Quantitative \Estimate of Drug-likeness (QED), Molecular weight, LogP (measures lipophilicity, higher is more lipophilic), \HBA, HBD, Polar Surface Area, Rotatable Bonds, Aromatic Rings and Undesireable Moieties. \n \substitution_tool: this tool can generate analogues of the molecule by substituting \different chemical groups on the original molecule. Returns a list of novel molecules and their \QED score (1 is most drug-like, 0 is least drug-like). \n \pharm_feature_tool: this tool can compare the pharmacophore features of a query molecule against \a those of a reference molecule and report the pharmacophore features of both and the feature \score of the query molecule. This score tells how the common features score against each other, but \does not inform about features unique to each molecule.'res = chat_model.invoke(prompt)tool_choices = str(res).split('<|assistant|>')[1].split('#')[0].strip()tool_choices = tool_choices.split(',')if len(tool_choices) == 1:if tool_choices[0].strip().lower() == 'none':tool_choice = (None, None)else:tool_choice = (tool_choices[0].strip().lower(), None)elif len(tool_choices) == 2:if tool_choices[0].strip().lower() == 'none':tool_choice = (None, tool_choices[1].strip().lower())elif tool_choices[1].strip().lower() == 'none':tool_choice = (tool_choices[0].strip().lower(), None)else:tool_choice = (tool_choices[0].strip().lower(), tool_choices[1].strip().lower())else:tool_choice = (None, None)state["tool_choice"] = tool_choicestate["which_tool"] = 0print(f"The chosen tools are: {tool_choice}")return statedef loop_node(state: State) -> State:'''This node accepts the tool returns and decides if it needs to call anothertool or go on to the parser node.Input: the tool returns.Output: the next node to call.'''return statedef parser_node(state: State) -> State:'''This is the third node in the agent. It receives the output from the tool,puts it into a prompt as CONTEXT, and asks the LLM to answer the originalquery.Input: the output from the tool.Output: the answer to the original query.'''props_string = state["props_string"]query_task = state["query_task"]prompt = f'Using the CONTEXT below, answer the original query, which \was to answer the QUERY_TASK. End your answer with a "#" \QUERY_TASK: {query_task}.\n \CONTEXT: {props_string}.\n 'res = chat_model.invoke(prompt)return {"messages": res}def reflect_node(state: State) -> State:'''This is the fourth node of the agent. It recieves the LLMs previous answer andtries to improve it.Input: the LLMs last answer.Output: the improved answer.'''previous_answer = state["messages"][-1].contentprops_string = state["props_string"]prompt = f'Look at the PREVIOUS ANSWER below which you provided and the \TOOL RESULTS. Write an improved answer based on the PREVIOUS ANSWER and the \TOOL RESULTS by adding additional clarifying and enriching information. End \your new answer with a "#" \PREVIOUS ANSWER: {previous_answer}.\n \TOOL RESULTS: {props_string}. 'res = chat_model.invoke(prompt)return {"messages": res}def get_chemtool(state):''''''which_tool = state["which_tool"]tool_choice = state["tool_choice"]if tool_choice is None or tool_choice == (None, None):return Noneif which_tool == 0 or which_tool == 1:current_tool = tool_choice[which_tool]if current_tool is None:return Noneelif which_tool > 1:current_tool = Nonereturn current_tooldef pretty_print(answer):final = str(answer['messages'][-1]).split('<|assistant|>')[-1].split('#')[0].strip("n").strip('\\').strip('n').strip('\\')for i in range(0,len(final),100):print(final[i:i+100])def print_short(answer):for i in range(0,len(answer),100):print(answer[i:i+100])builder = StateGraph(State)builder.add_node("first_node", first_node)builder.add_node("substitution_node", substitution_node)builder.add_node("lipinski_node", lipinski_node)builder.add_node("pharmfeature_node", pharmfeature_node)builder.add_node("loop_node", loop_node)builder.add_node("parser_node", parser_node)builder.add_node("reflect_node", reflect_node)builder.add_edge(START, "first_node")builder.add_conditional_edges("first_node", get_chemtool, {"substitution_tool": "substitution_node","lipinski_tool": "lipinski_node","pharm_feature_tool": "pharmfeature_node",None: "parser_node"})builder.add_edge("lipinski_node", "loop_node")builder.add_edge("substitution_node", "loop_node")builder.add_edge("pharmfeature_node", "loop_node")builder.add_conditional_edges("loop_node", get_chemtool, {"substitution_tool": "substitution_node","lipinski_tool": "lipinski_node","pharm_feature_tool": "pharmfeature_node",None: "parser_node"})builder.add_edge("parser_node", "reflect_node")builder.add_edge("reflect_node", END)graph = builder.compile()@spaces.GPUdef PropAgent(smiles, reference, task):#if Substitution_image.png exists, remove itif os.path.exists('Substitution_image.png'):os.remove('Substitution_image.png')input = {"messages": [HumanMessage(f'query_smiles: {smiles}, query_task: {task}, query_reference: {reference}')]}#print(input)replies = []for c in graph.stream(input): #, stream_mode='updates'):m = re.findall(r'[a-z]+\_node', str(c))if len(m) != 0:reply = c[str(m[0])]['messages']if 'assistant' in str(reply):reply = str(reply).split("<|assistant|>")[-1].split('#')[0].strip()replies.append(reply)#check if image existsif os.path.exists('Substitution_image.png'):img_loc = 'Substitution_image.png'img = Image.open(img_loc)#else create a dummy blank imageelse:img = Image.new('RGB', (250, 250), color = (255, 255, 255))return replies[-1], imgwith gr.Blocks(fill_height=True) as forest:gr.Markdown('''# Properties Agent- uses RDKit to calculate lipinski properties- finds pharmacophore similarity between two molecules- generated analogues of a molecule''')name, smiles = None, Nonewith gr.Row():with gr.Column():smiles = gr.Textbox(label="Molecule SMILES of interest (optional): ", placeholder='none')ref = gr.Textbox(label="Reference molecule SMILES of interest (optional): ", placeholder='none')task = gr.Textbox(label="Task for Agent: ")calc_btn = gr.Button(value = "Submit to Agent")with gr.Column():props = gr.Textbox(label="Agent results: ", lines=20 )pic = gr.Image(label="Molecule")calc_btn.click(PropAgent, inputs = [smiles, ref, task], outputs = [props, pic])forest.launch(debug=False, mcp_server=True)
app.py+505-505