To integrate the ChemCrow agent into your CrewAI agents system, you can create a new agent within your CrewAI framework that utilizes ChemCrow's functionalities. Below is the modified code that combines the ChemCrow agent with your existing CrewAI agents.
1. Install ChemCrow
First, ensure that you have installed ChemCrow and its dependencies:
pip install chemcrow
2. Import ChemCrow into Your Agents
Update your agents.py to include the ChemCrow agent.
# agents.py
from crewai import Agent
from chemcrow.agents import ChemCrow # Import ChemCrow
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY') # Ensure API key is set
# Previous imports remain the same
from tools.text_to_molecule_tool import TextToMoleculeTool
from tools.molecule_to_text_tool import MoleculeToTextTool
from tools.valid_molecule_tool import ValidMoleculeTool
from tools.molecule_optimizer_tool import MoleculeOptimizerTool
from tools.visualization_tool import VisualizationTool
from tools.rdkit_tools import (
CalculateLogPTool,
CalculateMolWtTool,
LipinskiRuleOfFiveTool,
SimilarityMapTool,
)
def create_agents(verbose=False):
# Agent 1: Chemistry Expert with RDKit tools
chemistry_expert = Agent(
role="Chemistry Expert",
goal="Provide chemistry knowledge and visualize molecules",
backstory="""You are an experienced chemist with expertise in chemical analysis and visualization.""",
tools=[
ValidMoleculeTool(),
VisualizationTool(),
CalculateLogPTool(),
CalculateMolWtTool(),
LipinskiRuleOfFiveTool(),
SimilarityMapTool(),
],
allow_delegation=True,
verbose=verbose,
)
# Agent 2: Molecule Generator and Descriptor
molecule_generator = Agent(
role="Molecule Generator",
goal="Generate molecules from descriptions and describe molecules",
backstory="""You specialize in converting text descriptions to molecules and vice versa.""",
tools=[TextToMoleculeTool(), MoleculeToTextTool()],
allow_delegation=True,
verbose=verbose,
)
# Agent 3: Molecule Editor
molecule_editor = Agent(
role="Molecule Editor",
goal="Suggest molecule edits and alternatives",
backstory="""You are skilled in suggesting modifications to molecular structures.""",
tools=[MoleculeOptimizerTool()],
allow_delegation=True,
verbose=verbose,
)
# Agent 4: ChemCrow Agent
# Initialize ChemCrow agent
chemcrow_agent_executor = ChemCrow(
model='gpt-4-0613',
tools_model='gpt-4-turbo-preview',
temp=0.1,
openai_api_key=os.getenv('OPENAI_API_KEY'),
).agent_executor
# Wrap ChemCrow agent in CrewAI Agent
chemcrow_agent = Agent(
role="ChemCrow Agent",
goal="Perform advanced chemistry tasks using ChemCrow",
backstory="""You utilize ChemCrow's capabilities to perform complex chemistry tasks.""",
tools=[],
allow_delegation=True,
verbose=verbose,
)
# Attach the ChemCrow agent executor to the agent
chemcrow_agent.external_agent = chemcrow_agent_executor
return [chemistry_expert, molecule_generator, molecule_editor, chemcrow_agent]
3. Modify Your Agent Class to Support External Agents
You may need to modify your Agent class to support interaction with external agents like ChemCrow.
# In your Agent class (agent.py in CrewAI)
class Agent:
# Existing code...
def __init__(self, role, goal, backstory, tools, allow_delegation, verbose):
# Existing initialization code...
self.external_agent = None # Add this line
# Existing methods...
def run(self, prompt):
if self.external_agent is not None:
# Use the external agent
return self.external_agent.run(prompt)
else:
# Process with internal tools
# Existing logic...
pass
4. Use the Agents in Your Application
Now, when you run your agents, you can use the ChemCrow agent as part of your CrewAI agents.
# main.py
from agents import create_agents
def main():
agents = create_agents(verbose=True)
# Use the ChemCrow agent
chemcrow_agent = next(agent for agent in agents if agent.role == "ChemCrow Agent")
prompt = 'How can I synthesize safinamide?'
response = chemcrow_agent.run(prompt)
print(f"Agent Response: {response}")
if __name__ == "__main__":
main()
5. Ensure OpenAI API Keys are Set
Make sure your OpenAI API key is properly set in your environment variables or within the code (ensure to handle secrets securely).
# .env file
OPENAI_API_KEY=your-openai-api-key
6. Handle Dependencies and Compatibility
Ensure that the versions of the packages used in ChemCrow and CrewAI are compatible. You may need to adjust versions or refactor some code to resolve any compatibility issues.
7. Testing
Test the integrated system thoroughly to ensure that the ChemCrow agent works as expected within your CrewAI agents framework.
Full Modified Code
Here's the complete modified code integrating ChemCrow with your CrewAI agents.
agents.py
from crewai import Agent
from chemcrow.agents import ChemCrow # Import ChemCrow
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY') # Ensure API key is set
# Previous imports remain the same
from tools.text_to_molecule_tool import TextToMoleculeTool
from tools.molecule_to_text_tool import MoleculeToTextTool
from tools.valid_molecule_tool import ValidMoleculeTool
from tools.molecule_optimizer_tool import MoleculeOptimizerTool
from tools.visualization_tool import VisualizationTool
from tools.rdkit_tools import (
CalculateLogPTool,
CalculateMolWtTool,
LipinskiRuleOfFiveTool,
SimilarityMapTool,
)
def create_agents(verbose=False):
# Agent 1: Chemistry Expert with RDKit tools
chemistry_expert = Agent(
role="Chemistry Expert",
goal="Provide chemistry knowledge and visualize molecules",
backstory="""You are an experienced chemist with expertise in chemical analysis and visualization.""",
tools=[
ValidMoleculeTool(),
VisualizationTool(),
CalculateLogPTool(),
CalculateMolWtTool(),
LipinskiRuleOfFiveTool(),
SimilarityMapTool(),
],
allow_delegation=True,
verbose=verbose,
)
# Agent 2: Molecule Generator and Descriptor
molecule_generator = Agent(
role="Molecule Generator",
goal="Generate molecules from descriptions and describe molecules",
backstory="""You specialize in converting text descriptions to molecules and vice versa.""",
tools=[TextToMoleculeTool(), MoleculeToTextTool()],
allow_delegation=True,
verbose=verbose,
)
# Agent 3: Molecule Editor
molecule_editor = Agent(
role="Molecule Editor",
goal="Suggest molecule edits and alternatives",
backstory="""You are skilled in suggesting modifications to molecular structures.""",
tools=[MoleculeOptimizerTool()],
allow_delegation=True,
verbose=verbose,
)
# Agent 4: ChemCrow Agent
# Initialize ChemCrow agent
chemcrow_agent_executor = ChemCrow(
model='gpt-4-0613',
tools_model='gpt-4-turbo-preview',
temp=0.1,
openai_api_key=os.getenv('OPENAI_API_KEY'),
).agent_executor
# Wrap ChemCrow agent in CrewAI Agent
chemcrow_agent = Agent(
role="ChemCrow Agent",
goal="Perform advanced chemistry tasks using ChemCrow",
backstory="""You utilize ChemCrow's capabilities to perform complex chemistry tasks.""",
tools=[], # ChemCrow uses its own tools internally
allow_delegation=True,
verbose=verbose,
)
# Attach the ChemCrow agent executor to the agent
chemcrow_agent.external_agent = chemcrow_agent_executor
return [chemistry_expert, molecule_generator, molecule_editor, chemcrow_agent]
Modifications to Agent Class (agent.py)
# agent.py in CrewAI
class Agent:
def __init__(self, role, goal, backstory, tools, allow_delegation, verbose):
self.role = role
self.goal = goal
self.backstory = backstory
self.tools = tools
self.allow_delegation = allow_delegation
self.verbose = verbose
self.external_agent = None # Added to support external agents like ChemCrow
def run(self, prompt):
if self.external_agent is not None:
# Use the external agent
if self.verbose:
print(f"{self.role} is processing the prompt using an external agent.")
return self.external_agent.run(prompt)
else:
# Existing logic for handling the prompt
if self.verbose:
print(f"{self.role} is processing the prompt internally.")
# Implement internal processing using tools
response = self.process_prompt_with_tools(prompt)
return response
def process_prompt_with_tools(self, prompt):
# Implement the logic to process the prompt using the agent's tools
# For example, you can parse the prompt and decide which tool to use
pass
main.py
# main.py
from agents import create_agents
def run_prompt(agent, prompt):
print(f"User Prompt: {prompt}")
try:
response = agent.run(prompt)
print(f"Agent Response: {response}")
except Exception as e:
print(f"Error: {e}")
def main():
agents = create_agents(verbose=True)
# Use the ChemCrow agent
chemcrow_agent = next(agent for agent in agents if agent.role == "ChemCrow Agent")
prompt = 'How can I synthesize safinamide?'
run_prompt(chemcrow_agent, prompt)
if __name__ == "__main__":
main()
tools/rdkit_tools.py
No changes are needed in your rdkit_tools.py, but ensure that all tools are properly imported and used within your agents.
Notes
- Environment Variables: Ensure your
.env file contains the OPENAI_API_KEY and any other necessary environment variables.
- Dependencies: Make sure all dependencies are installed, including
chemcrow, crewai, rdkit, and streamlit.
- Error Handling: Add appropriate error handling where necessary to catch and debug any issues during execution.
- Verbose Logging: With
verbose=True, the agents will print detailed logs, which can help with debugging.
Conclusion
By creating a new agent in your CrewAI system that wraps the ChemCrow agent, you can integrate ChemCrow's advanced chemistry capabilities into your existing framework. This approach allows you to maintain the modularity and flexibility of your agents while expanding their functionality.
Let me know if you have any questions or need further assistance!