crewAIInc / crewAI-examples

2.54k stars 933 forks source link

Automated Agents and Tasks Generation #44

Open mbahmujono opened 7 months ago

mbahmujono commented 7 months ago

I've made some feature using langchain to automate the process of creating agents and tasks.

I'm using AWS Bedrock as my LLM

Basically it will list agents and tasks needed to achieve the goal

from crewai import Agent, Task, Crew, Process
from langchain_community.llms.bedrock import Bedrock
from langchain.prompts import PromptTemplate
from langchain.output_parsers import ResponseSchema, StructuredOutputParser

llm = Bedrock(model_id='anthropic.claude-instant-v1', model_kwargs={'max_tokens_to_sample': 3000, 'temperature': 0.1, 'top_p': 0.9}, streaming=True)

Agent_schema = ResponseSchema(
    name='Agents',
    description='list of dictionaries which have keys: role, goal, backstory',
    type='array',
    required=True,
    example='{\'role\': \'CEO\',\'goal\': \'Oversee medical operations and ensure AI solutions are clinically validated and improve diagnostic accuracy\', \'backstory\': \'A creative soul who translates complex tech jargon into engaging narratives for the people, you write using simple words in a friendly and inviting tone that does not sounds like AI.\'}'
)

Task_schema = ResponseSchema(
    name='Tasks',
    description='list of dictionaries of the task that needed to work by the agents which have keys: description, agent(this is a list of agent\'s role that needed to work on this task)',
    type='array',
    required=True
)

response_schema = [Agent_schema, Task_schema]

output_parsers = StructuredOutputParser.from_response_schemas(response_schema)

format_instructions = output_parsers.get_format_instructions()

prompt = PromptTemplate(
    template="Human: answer the users question as best as possible.\n {format_instructions} in JSON format \n\n {question} Assistant:",
    input_variables=["question"],
    partial_variables={"format_instructions": format_instructions},
)

chain = prompt | llm | output_parsers

class Agents():
    def goal(self, goal):
        # define agent needed to achieve goal
        agent = chain.invoke({"question": f'Analyze this goal \'{goal}\' and identify the list of agents and step by step tasks needed to achieve it in json format.'})
        return agent

    def create_agent(self, goal):
        results = self.goal(goal)
        agent_list = []
        agents = {}
        for agent in results["Agents"]:
            agento = Agent(
                role = agent["role"],
                goal = agent["goal"],
                backstory = agent["backstory"],
                verbose=True,
                llm=llm
            )
            # ic(agento)
            agents[agent.get("role")] = agento
            agent_list.append(agento)

        tasks = []
        for task in results["Tasks"]:
            ic(task)
            role = task["agents"]

            agents_list = []
            for rolo in role:
                agents_list.append(agents[rolo])

            tasko = Task(
                description = task["description"],
                agent = agents_list[0]
            )
            tasks.append(tasko)

        return agent_list, tasks

if __name__ == '__main__':
    agents, tasks = Agents().create_agent("Create a Centralized AI with chat function for all the business operations and data analytics in Medical Diagnostic Center Business")

    crew = Crew(
        agents=agents,
        tasks=tasks,
        verbose=2, # You can set it to 1 or 2 to different logging levels
    )

    # # Get your crew to work!
    result = crew.kickoff()

    print("######################")
    print(result)
slavakurilyak commented 6 months ago

@mbahmujono this does not list agents and tasks needed to achieve the goal but rather creates agents and their associated tasks

I tried RESPOND ONLY with a list recommended agents and tasks BUT DO NOT execute these agents or tasks with your script but I was not able to make it work

Anyway to enforce this list using a user prompt?

mbahmujono commented 1 month ago

from langchain_community.llms.bedrock import Bedrock from langchain.prompts import PromptTemplate from langchain.output_parsers import ResponseSchema, StructuredOutputParser

llm = Bedrock(model_id='anthropic.claude-instant-v1', model_kwargs={'max_tokens_to_sample': 3000, 'temperature': 0.1, 'top_p': 0.9}, streaming=True)

Agent_schema = ResponseSchema( name='Agents', description='list of dictionaries which have keys: role, goal, backstory', type='array', required=True, example='{\'role\': \'CEO\',\'goal\': \'Oversee medical operations and ensure AI solutions are clinically validated and improve diagnostic accuracy\', \'backstory\': \'A creative soul who translates complex tech jargon into engaging narratives for the people, you write using simple words in a friendly and inviting tone that does not sounds like AI.\'}' )

Task_schema = ResponseSchema( name='Tasks', description='list of dictionaries of the task that needed to work by the agents which have keys: description, agent(this is a list of agent\'s role that needed to work on this task)', type='array', required=True )

response_schema = [Agent_schema, Task_schema] output_parsers = StructuredOutputParser.from_response_schemas(response_schema) format_instructions = output_parsers.get_format_instructions()

prompt = PromptTemplate( template="Human: RESPOND ONLY with a list of recommended agents and tasks to achieve the following goal. DO NOT execute these agents or tasks. Provide the response in JSON format as specified.\n {format_instructions} \n\n Goal: {question}\n\nAssistant:", input_variables=["question"], partial_variables={"format_instructions": format_instructions}, )

chain = prompt | llm | output_parsers

class Agents(): def recommend(self, goal):

Get recommendations for agents and tasks

    recommendations = chain.invoke({"question": goal})
    return recommendations

if name == 'main': goal = "Create a Centralized AI with chat function for all the business operations and data analytics in Medical Diagnostic Center Business"

agents = Agents()
recommendations = agents.recommend(goal)

print("Recommended Agents:")
for agent in recommendations["Agents"]:
    print(f"- Role: {agent['role']}")
    print(f"  Goal: {agent['goal']}")
    print(f"  Backstory: {agent['backstory']}")
    print()

print("Recommended Tasks:")
for task in recommendations["Tasks"]:
    print(f"- Description: {task['description']}")
    print(f"  Assigned to: {', '.join(task['agent'])}")
    print()