Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
Empty file.
32 changes: 32 additions & 0 deletions src/examples/crewai_example/simple_agent/agents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from crewai import Agent
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_cohere import ChatCohere
from langchain_ollama import ChatOllama


class PoetryAgents:
def __init__(self):
self.open_ai = ChatOpenAI(
model_name="gpt-4", temperature=0.7, stream_usage=True
)
self.anthropic = ChatAnthropic(
model_name="claude-3-5-sonnet-20240620", temperature=0.7
)

self.cohere = ChatCohere(model="command-r", temperature=0.7)
self.ollama = ChatOllama(model="llama3", temperature=0.7)

def create_poet_agent(self):
return Agent(
role="Expert Poetry Writer",
backstory="""
I am an Expert in poetry writing and creative expression.
I have been writing poetry for over 10 years and have published several collections.
I have a deep understanding of various poetic forms, styles, and themes. I am here to help you create beautiful and meaningful poetry that resonates with your emotions and experiences.
""",
goal="""Create a poem that captures the essence of a given theme or emotion""",
allow_delegation=False,
verbose=True,
llm=self.ollama,
)
48 changes: 48 additions & 0 deletions src/examples/crewai_example/simple_agent/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from crewai import Crew
from textwrap import dedent
from .agents import PoetryAgents
from .tasks import PoetryTasks
from langtrace_python_sdk import langtrace
from dotenv import load_dotenv
import agentops

load_dotenv()
agentops.init()
langtrace.init(write_spans_to_console=False, batch=False)


class PoetryCrew:
def __init__(self, topic) -> None:
self.topic = topic

def run(self):
agents = PoetryAgents()
tasks = PoetryTasks()

poetry_agent = agents.create_poet_agent()

create_poem = tasks.create_poem(poetry_agent, self.topic)

crew = Crew(agents=[poetry_agent], tasks=[create_poem], verbose=True)
res = crew.kickoff()
return res


# This is the main function that you will use to run your custom crew.
if __name__ == "__main__":
print("## Welcome to Poetry Crew")
print("-------------------------------")
topic = input(
dedent(
"""
What topic do you want to write a poem on?
"""
)
)

poetry_crew = PoetryCrew(topic=topic)
result = poetry_crew.run()
print("\n\n########################")
print("## Here is you poem")
print("########################\n")
print(result)
21 changes: 21 additions & 0 deletions src/examples/crewai_example/simple_agent/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from crewai import Task
from textwrap import dedent


class PoetryTasks:
def create_poem(self, agent, topic):
return Task(
description=dedent(
f"""
**Task**: Create a Poem on {topic}
**Description**: Write a poem on the given topic that captures the essence of the theme or emotion.
The poem should be creative, expressive, and resonate with the reader's emotions and experiences.
Your poem should be well-structured, engaging, and evoke a sense of beauty and meaning.

**Parameters**:
- Topic: {topic}
"""
),
expected_output="A creative and expressive poem that captures the essence of the given topic.",
agent=agent,
)
Empty file.
54 changes: 54 additions & 0 deletions src/examples/crewai_example/trip_planner/agents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from crewai import Agent
from langchain_openai import ChatOpenAI
from langchain_ollama import ChatOllama
from langchain_cohere import ChatCohere
from langchain_anthropic import ChatAnthropic
from dotenv import load_dotenv

load_dotenv()


class TravelAgents:
def __init__(self):
self.OpenAIGPT35 = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.7)
self.OpenAIGPT4 = ChatOpenAI(model_name="gpt-4", temperature=0.7)
self.Ollama = ChatOllama(model="openhermes")
self.Cohere = ChatCohere(model="command-r")
self.Anthropic = ChatAnthropic(model="claude-3-5-sonnet")

def expert_travel_agent(self):
return Agent(
role="Expert Travel Agent",
backstory="""
I am an Expert in travel planning and itinerary creation.
I have been in the travel industry for over 10 years and have helped thousands of clients plan their dream vacations.
I have extensive knowledge of popular travel destinations, local attractions, and travel logistics. I am here to help you create a personalized travel itinerary that suits your preferences and budget.
""",
goal="""Create a 7 day travel itinerary with detailed per-day plans, include budget, packing suggestions, and local/safety tips.""",
# tools=[tool_1, tool_2],
allow_delegation=False,
verbose=True,
llm=self.OpenAIGPT4,
)

def city_selection_expert(self):
return Agent(
role="City Selection Expert",
backstory="""Expert at analyzing and selecting the best cities for travel based on data""",
goal="""Select the best cities based on weather, season, prices and traveler preferences""",
# tools=[tool_1, tool_2],
allow_delegation=False,
verbose=True,
llm=self.OpenAIGPT4,
)

def local_tour_guide(self):
return Agent(
role="Local Expert at this city",
goal="Provide the BEST insights about the selected city",
backstory="""A knowledgeable local guide with extensive information about the city, it's attractions and customs""",
# tools=[tool_1, tool_2],
allow_delegation=False,
verbose=True,
llm=self.OpenAIGPT4,
)
96 changes: 96 additions & 0 deletions src/examples/crewai_example/trip_planner/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from crewai import Crew
from textwrap import dedent
from .agents import TravelAgents
from .tasks import TravelTasks
from langtrace_python_sdk import langtrace
from dotenv import load_dotenv

load_dotenv()

langtrace.init()


class TripCrew:
def __init__(self, origin, cities, date_range, interests):
self.origin = origin
self.cities = cities
self.date_range = date_range
self.interests = interests

def run(self):
# Define your custom agents and tasks in agents.py and tasks.py
agents = TravelAgents()
tasks = TravelTasks()

# Define your custom agents and tasks here
expert_travel_agent = agents.expert_travel_agent()
city_selection_expert = agents.city_selection_expert()
local_tour_guide = agents.local_tour_guide()

# Custom tasks include agent name and variables as input
plan_itinerary = tasks.plan_itinerary(
expert_travel_agent, self.cities, self.date_range, self.interests
)

identify_city = tasks.identify_city(
city_selection_expert,
self.origin,
self.cities,
self.interests,
self.date_range,
)

gather_city_info = tasks.gather_city_info(
local_tour_guide, self.cities, self.date_range, self.interests
)

# Define your custom crew here
crew = Crew(
agents=[expert_travel_agent, city_selection_expert, local_tour_guide],
tasks=[plan_itinerary, identify_city, gather_city_info],
verbose=True,
)

result = crew.kickoff()
return result


# This is the main function that you will use to run your custom crew.
if __name__ == "__main__":
print("## Welcome to Trip Planner Crew")
print("-------------------------------")
origin = input(
dedent(
"""
From where will you be traveling from?
"""
)
)
cities = input(
dedent(
"""
What are the cities options you are interested in visiting?
"""
)
)
date_range = input(
dedent(
"""
What is the date range you are interested in traveling?
"""
)
)
interests = input(
dedent(
"""
What are some of your high level interests and hobbies?
"""
)
)

trip_crew = TripCrew(origin, cities, date_range, interests)
result = trip_crew.run()
print("\n\n########################")
print("## Here is you Trip Plan")
print("########################\n")
print(result)
120 changes: 120 additions & 0 deletions src/examples/crewai_example/trip_planner/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
from crewai import Task
from textwrap import dedent

"""
Creating Tasks Cheat Sheet:
- Begin with the end in mind. Identify the specific outcome your tasks are aiming to achieve.
- Break down the outcome into actionable tasks, assigning each task to the appropriate agent.
- Ensure tasks are descriptive, providing clear instructions and expected deliverables.

Goal:
- Develop a detailed itinerary, including city selection, attractions, and practical travel advice.

Key Steps for Task Creation:
1. Identify the Desired Outcome: Define what success looks like for your project.
- A detailed 7 day travel itenerary.

2. Task Breakdown: Divide the goal into smaller, manageable tasks that agents can execute.
- Itenerary Planning: develop a detailed plan for each day of the trip.
- City Selection: Analayze and pick the best cities to visit.
- Local Tour Guide: Find a local expert to provide insights and recommendations.

3. Assign Tasks to Agents: Match tasks with agents based on their roles and expertise.

4. Task Description Template:
- Use this template as a guide to define each task in your CrewAI application.
- This template helps ensure that each task is clearly defined, actionable, and aligned with the specific goals of your project.

Template:
---------
def [task_name](self, agent, [parameters]):
return Task(description=dedent(f'''
**Task**: [Provide a concise name or summary of the task.]
**Description**: [Detailed description of what the agent is expected to do, including actionable steps and expected outcomes. This should be clear and direct, outlining the specific actions required to complete the task.]

**Parameters**:
- [Parameter 1]: [Description]
- [Parameter 2]: [Description]
... [Add more parameters as needed.]

**Note**: [Optional section for incentives or encouragement for high-quality work. This can include tips, additional context, or motivations to encourage agents to deliver their best work.]

'''), agent=agent)

"""


class TravelTasks:
def __tip_section(self):
return "If you do your BEST WORK, I'll give you a $10,000 commission!"

def plan_itinerary(self, agent, city, travel_dates, interests):
return Task(
description=dedent(
f"""
**Task**: Develop a 7-Day Travel Itinerary
**Description**: Expand the city guide into a full 7-day travel itinerary with detailed
per-day plans, including weather forecasts, places to eat, packing suggestions,
and a budget breakdown. You MUST suggest actual places to visit, actual hotels to stay,
and actual restaurants to go to. This itinerary should cover all aspects of the trip,
from arrival to departure, integrating the city guide information with practical travel logistics.

**Parameters**:
- City: {city}
- Trip Date: {travel_dates}
- Traveler Interests: {interests}

**Note**: {self.__tip_section()}
"""
),
expected_output="A detailed 7-day travel itinerary with per-day plans, budget breakdown, and practical travel advice.",
agent=agent,
)

def identify_city(self, agent, origin, cities, interests, travel_dates):
return Task(
description=dedent(
f"""
**Task**: Identify the Best City for the Trip
**Description**: Analyze and select the best city for the trip based on specific
criteria such as weather patterns, seasonal events, and travel costs.
This task involves comparing multiple cities, considering factors like current weather
conditions, upcoming cultural or seasonal events, and overall travel expenses.
Your final answer must be a detailed report on the chosen city,
including actual flight costs, weather forecast, and attractions.


**Parameters**:
- Origin: {origin}
- Cities: {cities}
- Interests: {interests}
- Travel Date: {travel_dates}

**Note**: {self.__tip_section()}
"""
),
agent=agent,
expected_output="A detailed report on the best city for the trip, including flight costs, weather forecast, and attractions.",
)

def gather_city_info(self, agent, city, travel_dates, interests):
return Task(
description=dedent(
f"""
**Task**: Gather In-depth City Guide Information
**Description**: Compile an in-depth guide for the selected city, gathering information about
key attractions, local customs, special events, and daily activity recommendations.
This guide should provide a thorough overview of what the city has to offer, including
hidden gems, cultural hotspots, must-visit landmarks, weather forecasts, and high-level costs.

**Parameters**:
- Cities: {city}
- Interests: {interests}
- Travel Date: {travel_dates}

**Note**: {self.__tip_section()}
"""
),
expected_output="An in-depth city guide with detailed information on attractions, local customs, events, and daily activity recommendations.",
agent=agent,
)
16 changes: 16 additions & 0 deletions src/examples/crewai_example/trip_planner/tools/calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from langchain.tools import tool


class CalculatorTools:

@tool("Make a calculation")
def calculate(self, operation):
"""Useful to perform any mathematical calculations,
like sum, minus, multiplication, division, etc.
The input to this tool should be a mathematical
expression, a couple examples are `200*7` or `5000/2*10`
"""
try:
return eval(operation)
except SyntaxError:
return "Error: Invalid syntax in mathematical expression"
Loading