Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added browserbase flights example #114

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,17 @@ By [@joaomdmoura](https://x.com/joaomdmoura).
## Examples

### Basic Examples
- [Create Job Posting](https://github.com/joaomdmoura/crewAI-examples/tree/main/job-posting)
- [Trip Planner](https://github.com/joaomdmoura/crewAI-examples/tree/main/trip_planner)
- [Create Instagram Post](https://github.com/joaomdmoura/crewAI-examples/tree/main/instagram_post)
- [Markdown Validator](https://github.com/joaomdmoura/crewAI-examples/tree/main/markdown_validator)
- [Game Generator](https://github.com/joaomdmoura/crewAI-examples/tree/main/game-builder-crew)
- [Using Azure OpenAI API](https://github.com/joaomdmoura/crewAI-examples/tree/main/azure_model)
- [Create Job Posting](./job-posting)
- [Trip Planner](./trip_planner)
- [Create Instagram Post](./instagram_post)
- [Markdown Validator](./markdown_validator)
- [Game Generator](./game-builder-crew)
- [Using Azure OpenAI API](./azure_model)

Starting your own example
- [Starter Template](https://github.com/joaomdmoura/crewAI-examples/tree/main//starter_template)
- [Starter Template](.//starter_template)
### Advanced Examples
- [Stock Analysis](https://github.com/joaomdmoura/crewAI-examples/tree/main/stock_analysis)
- [Landing Page Generator](https://github.com/joaomdmoura/crewAI-examples/tree/main/landing_page_generator)
- [CrewAI + LangGraph](https://github.com/joaomdmoura/crewAI-examples/tree/main/CrewAI-LangGraph)
- [Stock Analysis](./stock_analysis)
- [Landing Page Generator](./landing_page_generator)
- [CrewAI + LangGraph](./CrewAI-LangGraph)
- [Browserbase](./browserbase_flights)
mishushakov marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 2 additions & 0 deletions browserbase_flights/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
OPENAI_API_KEY=
BROWSERBASE_API_KEY=
164 changes: 164 additions & 0 deletions browserbase_flights/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

.ruff_cache
28 changes: 28 additions & 0 deletions browserbase_flights/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# crewAI + Browserbase flight search

The following is a multi-task, multi-agent, multi-tool example for AI-based flight search using Skyscanner and Browserbase.

## Installation

```
pip install crewai 'crewai[tools]' html2text playwright
```

Set the required environment variables:

```
export OPENAI_API_KEY=
export BROWSERBASE_API_KEY=
```

Optionally, set a different model in CrewAI:

```
export OPENAI_MODEL_NAME=gpt-4-turbo
```

## Demo

```
python3 demo.py "Sofia to Berlin one-way on 26th May"
```
26 changes: 26 additions & 0 deletions browserbase_flights/bb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
from crewai_tools import tool
from playwright.sync_api import sync_playwright
from html2text import html2text
from time import sleep


@tool("Browserbase tool")
def browserbase(url: str):
"""
Loads a URL using a headless webbrowser
"""
with sync_playwright() as playwright:
browser = playwright.chromium.connect_over_cdp(
"wss://connect.browserbase.com?apiKey=" + os.environ["BROWSERBASE_API_KEY"]
)
context = browser.contexts[0]
page = context.pages[0]
page.goto(url)

sleep(5)

page.screenshot(path="screenshot.png")
content = html2text(page.content())
browser.close()
return content
71 changes: 71 additions & 0 deletions browserbase_flights/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import sys
from crewai import Crew, Process, Task, Agent
from bb import browserbase
from skyscanner import skyscanner

output_search_example = """
Here are our top 5 flights from Sofia to Berlin on 24th May 2024:

1. Bulgaria Air: Departure: 14:45, Arrival: 15:55, Duration: 2 hours 10 minutes, Layovers: Munich, 2 hours layover, Price: £123, Flight page: https://www.skyscanner.net/transport/flights/sof/ber/240524/240526/config/16440-2405241445--32474-0-9828-2405241555|9828-2405262255--32474-0-16440-2405270205
"""

output_result_example = """
Here are our top 5 flight options from Sofia to Berlin on 24th May 2024:

1. Bulgaria Air:
- Departure: 14:45
- Arrival: 15:55
- Duration: 2 hours 10 minutes
- Layovers: Munich, 2 hours layover
- Price: £123
- Booking options:
1. [MyTrip](https://www.skyscanner.net/transport_deeplink/4.0/UK/en-GB/GBP/ctuk/1/16440.9828.2024-05-26/air/trava/flights?itinerary=flight|-32474|319|16440|2024-05-26T21:05|9828|2024-05-26T22:15|130|-|-|-&carriers=-32474&operators=-32474&passengers=1&channel=website&cabin_class=economy&fps_session_id=20287887-26ad-45dc-b225-28fb4b9d8357&ticket_price=126.90&is_npt=false&is_multipart=false&client_id=skyscanner_website&request_id=4b423165-9b7b-4281-9596-cfcd6b0bb4e0&q_ids=H4sIAAAAAAAA_-NS52JJLinNFmLh2NHAKMXM8cRHoeH7yU1sRkwKjEWsqXm67k5VzO5OAQASECl8KQAAAA|8257781087420252411|2&q_sources=JACQUARD&commercial_filters=false&q_datetime_utc=2024-05-22T13:45:58&pqid=true&booking_panel_option_guid=dfb1f593-22dc-4565-8540-5f4f70979b9b&index=0&isbp=1&posidx=0&qid=16440-2405262105--32474-0-9828-2405262215&sort=BEST&stops=0&tabs=CombinedDayView&pre_redirect_id=7cdb112a-3842-4a51-b228-1cbcbc4c8094&redirect_id=a8541976-84a8-4161-849c-c7a6343125ae&is_acorn_referral=true)
"""

flights = Agent(
role="Flights",
goal="Search flights",
backstory="I am an agent that can search for flights.",
verbose=True,
tools=[skyscanner, browserbase],
allow_delegation=False,
)

summarize_agent = Agent(
role="Summarize",
goal="Summarize content",
backstory="I am an agent that can summarize text.",
verbose=True,
allow_delegation=False,
)

search_task = Task(
description=(
"Search flights according to criteria {request}. Current year: {current_year}"
),
expected_output=output_search_example,
agent=flights,
human_input=False, # Optional
)

search_providers = Task(
description="Load every flight individually and find available booking providers",
expected_output=output_result_example,
agent=flights,
human_input=False,
)

crew = Crew(
agents=[flights, summarize_agent],
tasks=[search_task, search_providers],
process=Process.sequential,
memory=False, # Do i need this?
cache=True,
max_rpm=100,
)

result = crew.kickoff(
inputs={"request": sys.argv[1], "current_year": 2024}
)

print(result)
19 changes: 19 additions & 0 deletions browserbase_flights/skyscanner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# https://www.skyscanner.net/transport/flights/sof/ber/240521

from crewai_tools import tool
from typing import Optional


@tool("SkyScanner tool")
def skyscanner(
departure: str, destination: str, date: int, return_date: Optional[int] = 0
) -> str:
"""
Generates a SkyScanner URL for flights between departure and destination on the specified date.

:param departure: The IATA code for the departure airport (e.g., 'sof' for Sofia)
:param destination: The IATA code for the destination airport (e.g., 'ber' for Berlin)
:param date: The date of the flight in the format 'yymmdd'
:return_date: Only for two-way tickets. The date of return flight in the format 'yymmdd'
"""
return f"https://www.skyscanner.net/transport/flights/{departure}/{destination}/{date}/{return_date}"