From 359b9dd037f402d4e7c8aec3a1650514b3c24b66 Mon Sep 17 00:00:00 2001 From: HamadaSalhab Date: Thu, 21 Nov 2024 17:50:57 +0300 Subject: [PATCH] Update cookbooks --- .../01-Website_Crawler_using_Spider.ipynb | 492 -------- cookbooks/01-website-crawler.ipynb | 522 +++++++++ ..._using_Spider.py => 01-website-crawler.py} | 0 ...02-Sarcastic_News_Headline_Generator.ipynb | 357 ------ ...02-sarcastic-news-headline-generator.ipynb | 541 +++++++++ ...> 02-sarcastic-news-headline-generator.py} | 0 .../03-SmartResearcher_With_WebSearch.ipynb | 395 ------- .../03-SmartResearcher_With_WebSearch.py | 110 -- cookbooks/03-trip-planning-assistant.ipynb | 1044 +++++++++++++++++ ...iInfo.py => 03-trip-planning-assistant.py} | 0 ...ripPlanner_With_Weather_And_WikiInfo.ipynb | 418 ------- ...=> 04-hook-generator-trending-reels.ipynb} | 2 +- ...py => 04-hook-generator-trending-reels.py} | 0 ...05-Basic_Agent_Creation_and_Interaction.py | 70 -- ...deo-processing-with-natural-language.ipynb | 545 +++++++++ cookbooks/06-Designing_Multi-Step_Tasks.py | 139 --- .../07-Integrating_External_Tools_and_APIs.py | 128 -- cookbooks/08-Managing_Persistent_Sessions.py | 146 --- .../09-User_Management_and_Personalization.py | 196 ---- .../10-Document_Management_and_Search.py | 184 --- cookbooks/11-Advanced_Chat_Interactions.py | 177 --- cookbooks/12-Monitoring_Task_Executions.py | 162 --- cookbooks/13-Error_Handling_and_Recovery.py | 165 --- ...utomated_Webinar_Scheduling_Workflow.ipynb | 306 ----- ...4-Automated_Webinar_Scheduling_Workflow.py | 244 ---- cookbooks/15-Personal_Finance_Tracker.ipynb | 208 ---- cookbooks/15-Personal_Finance_Tracker.py | 164 --- ...E_commerce_Order_Processing_Workflow.ipynb | 381 ------ ...16-E_commerce_Order_Processing_Workflow.py | 238 ---- 29 files changed, 2653 insertions(+), 4681 deletions(-) delete mode 100644 cookbooks/01-Website_Crawler_using_Spider.ipynb create mode 100644 cookbooks/01-website-crawler.ipynb rename cookbooks/{01-Website_Crawler_using_Spider.py => 01-website-crawler.py} (100%) delete mode 100644 cookbooks/02-Sarcastic_News_Headline_Generator.ipynb create mode 100644 cookbooks/02-sarcastic-news-headline-generator.ipynb rename cookbooks/{02-Sarcastic_News_Headline_Generator.py => 02-sarcastic-news-headline-generator.py} (100%) delete mode 100644 cookbooks/03-SmartResearcher_With_WebSearch.ipynb delete mode 100644 cookbooks/03-SmartResearcher_With_WebSearch.py create mode 100644 cookbooks/03-trip-planning-assistant.ipynb rename cookbooks/{04-TripPlanner_With_Weather_And_WikiInfo.py => 03-trip-planning-assistant.py} (100%) delete mode 100644 cookbooks/04-TripPlanner_With_Weather_And_WikiInfo.ipynb rename cookbooks/{17-Hook-Generator-Trending-Reels.ipynb => 04-hook-generator-trending-reels.ipynb} (99%) rename cookbooks/{17-Hook-Generator-Trending-Reels.py => 04-hook-generator-trending-reels.py} (100%) delete mode 100644 cookbooks/05-Basic_Agent_Creation_and_Interaction.py create mode 100644 cookbooks/05-video-processing-with-natural-language.ipynb delete mode 100644 cookbooks/06-Designing_Multi-Step_Tasks.py delete mode 100644 cookbooks/07-Integrating_External_Tools_and_APIs.py delete mode 100644 cookbooks/08-Managing_Persistent_Sessions.py delete mode 100644 cookbooks/09-User_Management_and_Personalization.py delete mode 100644 cookbooks/10-Document_Management_and_Search.py delete mode 100644 cookbooks/11-Advanced_Chat_Interactions.py delete mode 100644 cookbooks/12-Monitoring_Task_Executions.py delete mode 100644 cookbooks/13-Error_Handling_and_Recovery.py delete mode 100644 cookbooks/14-Automated_Webinar_Scheduling_Workflow.ipynb delete mode 100644 cookbooks/14-Automated_Webinar_Scheduling_Workflow.py delete mode 100644 cookbooks/15-Personal_Finance_Tracker.ipynb delete mode 100644 cookbooks/15-Personal_Finance_Tracker.py delete mode 100644 cookbooks/16-E_commerce_Order_Processing_Workflow.ipynb delete mode 100644 cookbooks/16-E_commerce_Order_Processing_Workflow.py diff --git a/cookbooks/01-Website_Crawler_using_Spider.ipynb b/cookbooks/01-Website_Crawler_using_Spider.ipynb deleted file mode 100644 index e813be743..000000000 --- a/cookbooks/01-Website_Crawler_using_Spider.ipynb +++ /dev/null @@ -1,492 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"julep\"\n", - "
\n", - "\n", - "## Task Definition: Spider Crawler Integration\n", - "\n", - "### Overview\n", - "\n", - "This task is a simple task that leverages the spider `integration` tool, and combines it with a prompt step to crawl a website for a given URL, and then create a summary of the results.\n", - "\n", - "### Task Tools:\n", - "\n", - "**Spider Crawler**: An `integration` type tool that can crawl the web and extract data from a given URL.\n", - "\n", - "### Task Input:\n", - "\n", - "**url**: The URL of the website to crawl.\n", - "\n", - "### Task Output:\n", - "\n", - "**output**: A dictionary that contains a `documents` key which contains the extracted data from the given URL. Check the output below for a detailed output schema.\n", - "\n", - "### Task Flow\n", - "\n", - "1. **Input**: The user provides a URL to crawl.\n", - "\n", - "2. **Spider Tool Integration**: The `spider_crawler` tool is called to crawl the web and extract data from the given URL.\n", - "\n", - "3. **Prompt Step**: The prompt step is used to create a summary of the results from the spider tool.\n", - "\n", - "4. **Output**: The final output is the summary of the results from the spider tool." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Implementation\n", - "\n", - "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", - "\n", - "\n", - " \"Open\n", - "\n", - "\n", - "### Additional Information\n", - "\n", - "For more details about the task or if you have any questions, please don't hesitate to contact the author:\n", - "\n", - "**Author:** Julep AI \n", - "**Contact:** [hey@julep.ai](mailto:hey@julep.ai) or Discord" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Installing the Julep Client" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "!pip install julep -U --quiet" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import uuid\n", - "\n", - "# NOTE: these UUIDs are used in order not to use the `create_or_update` methods instead of\n", - "# the `create` methods for the sake of not creating new resources every time a cell is run.\n", - "AGENT_UUID = uuid.uuid4()\n", - "TASK_UUID = uuid.uuid4() " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Creating Julep Client with the API Key" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "from julep import Client\n", - "import os\n", - "\n", - "api_key = os.getenv(\"JULEP_API_KEY\")\n", - "\n", - "# Create a Julep client\n", - "client = Client(api_key=api_key, environment=\"dev\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating an \"agent\"\n", - "\n", - "Agent is the object to which LLM settings, like model, temperature along with tools are scoped to.\n", - "\n", - "To learn more about the agent, please refer to the [documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#agent)." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [], - "source": [ - "# Create agent\n", - "agent = client.agents.create_or_update(\n", - " agent_id=AGENT_UUID,\n", - " name=\"Spiderman\",\n", - " about=\"AI that can crawl the web and extract data\",\n", - " model=\"gpt-4o\",\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Defining a Task\n", - "\n", - "Tasks in Julep are Github-Actions-style workflows that define long-running, multi-step actions.\n", - "\n", - "You can use them to conduct complex actions by defining them step-by-step.\n", - "\n", - "To learn more about tasks, please refer to the `Tasks` section in [Julep Concepts](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#tasks)." - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "metadata": {}, - "outputs": [], - "source": [ - "import yaml\n", - "\n", - "spider_api_key = os.getenv(\"SPIDER_API_KEY\")\n", - "\n", - "# Define the task\n", - "task_def = yaml.safe_load(f\"\"\"\n", - "name: Crawling Task\n", - "\n", - "# Define the tools that the agent will use in this workflow\n", - "tools:\n", - "- name: spider_crawler\n", - " type: integration\n", - " integration:\n", - " provider: spider\n", - " setup:\n", - " spider_api_key: \"{spider_api_key}\"\n", - "\n", - "# Define the steps of the workflow\n", - "main:\n", - "# Define a tool call step that calls the spider_crawler tool with the url input\n", - "- tool: spider_crawler\n", - " arguments:\n", - " url: \"_['url']\" # You can also use 'inputs[0]['url']'\n", - " \n", - " \n", - "- prompt: |\n", - " You are {{{{agent.about}}}}\n", - " I have given you this url: {{{{inputs[0]['url']}}}}\n", - " And you have crawled that website. Here are the results you found:\n", - " {{{{_['documents']}}}}\n", - " I want you to create a short summary (no longer than 100 words) of the results you found while crawling that website.\n", - "\n", - " unwrap: True\n", - "\"\"\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Notes:\n", - "- The reason for using the quadruple curly braces `{{{{}}}}` for the jinja template is to avoid conflicts with the curly braces when using the `f` formatted strings in python. [More information here](https://stackoverflow.com/questions/64493332/jinja-templating-in-airflow-along-with-formatted-text)\n", - "- The `unwrap: True` in the prompt step is used to unwrap the output of the prompt step (to unwrap the `choices[0].message.content` from the output of the model).\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating/Updating a task" - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "metadata": {}, - "outputs": [], - "source": [ - "# creating the task object\n", - "task = client.tasks.create_or_update(\n", - " task_id=TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **task_def\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating an Execution\n", - "\n", - "An execution is a single run of a task. It is a way to run a task with a specific set of inputs." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creates a execution worklow for the Task defined in the yaml file." - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "metadata": {}, - "outputs": [], - "source": [ - "# creating an execution object\n", - "execution = client.executions.create(\n", - " task_id=TASK_UUID,\n", - " input={\n", - " \"url\": \"https://spider.cloud\"\n", - " }\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "There are multiple ways to get the execution details and the output:\n", - "\n", - "1. **Get Execution Details**: This method retrieves the details of the execution, including the output of the last transition that took place.\n", - "\n", - "2. **List Transitions**: This method lists all the task steps that have been executed up to this point in time, so the output of a successful execution will be the output of the last transition (first in the transition list as it is in reverse chronological order), which should have a type of `finish`.\n", - "\n", - "\n", - "Note: You need to wait for a few seconds for the execution to complete before you can get the final output, so feel free to run the following cells multiple times until you get the final output.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 53, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Spider.cloud is a cutting-edge web crawling service designed for AI applications, offering high-speed and cost-effective data collection. Built with a robust Rust engine, Spider supports seamless integration with AI tools and provides various response formats, including LLM-ready markdown. It features concurrent streaming, caching, smart mode with headless Chrome, and auto proxy rotations. Ideal for large-scale projects, Spider ensures compliance with robots.txt and offers a free trial. Trusted by tech leaders, it enables efficient data curation and transformation, with capabilities to handle extreme workloads and dynamic content rendering.\n" - ] - } - ], - "source": [ - "# Get execution details\n", - "execution = client.executions.get(execution.id)\n", - "# Print the output\n", - "print(execution.output)" - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Transition type: init\n", - "Transition output: {'url': 'https://spider.cloud'}\n", - "--------------------------------------------------\n", - "Transition type: step\n", - "Transition output: {'documents': [{'id': None, 'metadata': {'description': 'Experience cutting-edge web crawling with unparalleled speeds, perfect for LLMs, Machine Learning, and Artificial Intelligence. The fastest and most efficient web scraper tailored for AI applications.', 'domain': 'spider.cloud', 'extracted_data': None, 'file_size': 9112, 'keywords': ['AI agent stack', 'AI 🕷️ Spider', 'AWS infrastructure reduced', 'Auto Proxy rotations', 'Comprehensive Data Curation', 'Concurrent Streaming Save time', 'Data Collecting Projects Today Jumpstart web crawling', 'FAQ Frequently asked questions', 'Fastest Web Crawler', 'Multiple response formats', 'Open Source Spider engine', 'Performance Tuned Spider', 'Seamless Integrations Seamlessly integrate Spider', 'Smart Mode Spider dynamically switches', 'Spider accurately crawls', 'Spider convert web data', 'Spider outputs HTML', 'Toggle Theme Sign InRegister', 'Transform Convert raw HTML', 'WilliamEspegren Web crawler built', 'achieve crawling thousands', 'affordable web scraping', 'and`XML`for API responses', 'caching repeated web page crawls', 'cost step caching', 'crazy resource management Aaaaaaand', 'custom browser scripting', 'data = json', 'data formats including LLM-ready markdown', 'ensure continuous maintenance', 'ensuring data curation perfectly aligned', 'finest data collecting solution', 'full elastic scaling concurrency', 'handle extreme workloads', 'iammerrick Rust based crawler Spider', 'insightful data solutions', 'json headers =', 'large scraping projects', 'large-scale data collection', 'latest AI models', 'leading tech businesses worldwide', 'leading web crawling tool designed', 'real-time web data', 'request Python JSONL Copy ``` import requests', 'requires JavaScript rendering', 'response = requests', 'robust Rust engine scales effortlessly', 'scrapes significantly faster', 'search engine results', 'traditional scraping services Spider API Request Modes', 'training AI models'], 'pathname': '/', 'resource_type': '.md', 'title': 'Spider: The Web Crawler for AI', 'url': '8475428e-4e0c-44de-967f-c14fb73cf490/spider.cloud/_cloud/12638123428881205758.md', 'user_id': '8475428e-4e0c-44de-967f-c14fb73cf490'}, 'page_content': 'Spider: The Web Crawler for AI\\n[Spider](https://spider.cloud/)\\n[Github1k](https://github.com/spider-rs/spider)\\n[API](https://spider.cloud/docs/api)\\n[Docs](https://spider.cloud/docs/overview)\\n[Pricing](https://spider.cloud/credits/new)\\nToggle Theme\\nSign InRegister\\nTo help you get started with Spider, we’ll give you $200 in credits when you spend $100.[Terms apply](https://spider.cloud/promotion-spider-credits)\\n# The Web Crawler for AI Agents and LLMs\\nSpider offers the finest data collecting solution. Engineered for speed and scalability, it allows you to elevate your AI projects.\\n[Get Started](https://spider.cloud/credits/new)View Preview\\n* Basic\\n* Streaming\\nExample request\\nPython\\nJSONL\\nCopy\\n```\\nimport requests, os, json\\nheaders = {\\n \\'Authorization\\': os.getenv(\"SPIDER_API_KEY\"),\\n \\'Content-Type\\': \\'application/jsonl\\',\\n}\\njson_data = {\"limit\":50,\"metadata\":True,\"url\":\"https://spider.cloud\"}\\nresponse = requests.post(\\'https://api.spider.cloud/crawl\\', \\n headers=headers, json=json_data, stream=True)\\nwith response as r:\\n r.raise_for_status()\\nfor chunk in r.iter_lines(\\n chunk_size=None, \\n decode_unicode=True\\n ):\\n data = json.loads(chunk)\\n print(data)\\n```\\n[Free Trial](https://spider.cloud/credits/new?free-trial=1)\\nExample Response\\n## Built with the need for**Speed**\\nExperience the power of**Spider**, built fully in**Rust**for next-generation scalability.\\n### 2.4secs\\nTo crawl over 20,000 pages\\n### 500-1000x\\nFaster than alternatives\\n### 500x\\nCheaper than traditional scraping services\\nSpider API Request Modes · Benchmarked tailwindcss.com ·06/16/2024\\n[See framework benchmarks](https://github.com/spider-rs/spider/blob/main/benches/BENCHMARKS.md)\\n### Seamless Integrations\\nSeamlessly integrate Spider with a wide range of platforms, ensuring data curation perfectly aligned with your requirements. Compatible with all major AI tools.\\n[LangChain integration](https://python.langchain.com/docs/integrations/document_loaders/spider)[LlamaIndex integration](https://docs.llamaindex.ai/en/stable/examples/data_connectors/WebPageDemo/#using-spider-reader)[CrewAI integration](https://docs.crewai.com/tools/SpiderTool/)[FlowWiseAI integration](https://docs.flowiseai.com/integrations/langchain/document-loaders/spider-web-scraper-crawler)[Composio integration](https://docs.composio.dev/introduction/foundations/components/list_local_tools#spider-crawler)[PhiData integration](https://docs.phidata.com/tools/spider)\\n### Concurrent Streaming\\nSave time and money without having to worry about bandwidth concerns by effectively streaming all the results concurrently. The latency cost that is saved becomes drastic as you crawl more websites.\\n### Warp Speed\\nPowered by the cutting-edge[Spider](https://github.com/spider-rs/spider)open-source project, our robust Rust engine scales effortlessly to handle extreme workloads. We ensure continuous maintenance and improvement for top-tier performance.\\n## Kickstart Your Data Collecting Projects Today\\nJumpstart web crawling with full elastic scaling concurrency, optimal formats, and AI scraping.\\n### Performance Tuned\\nSpider is written in Rust and runs in full concurrency to achieve crawling thousands of pages in secs.\\n### Multiple response formats\\nGet clean and formatted markdown, HTML, or text content for fine-tuning or training AI models.\\n### Caching\\nFurther boost speed by caching repeated web page crawls to minimize expenses while building.\\n### Smart Mode\\nSpider dynamically switches to Headless Chrome when it needs to quick.\\nBeta\\n### Scrape with AI\\nDo custom browser scripting and data extraction using the latest AI models with no cost step caching.\\n### The crawler for LLMs\\nDon\\'t let crawling and scraping be the highest latency in your LLM & AI agent stack.\\n### Scrape with no headaches\\n* Auto Proxy rotations\\n* Agent headers\\n* Anti-bot detections\\n* Headless chrome\\n* Markdown responses\\n### The Fastest Web Crawler\\n* Powered by[spider-rs](https://github.com/spider-rs/spider)\\n* 20,000 pages/seconds\\n* Unlimited concurrency\\n* Simple API\\n* 50,000 RPM\\n### Do more with AI\\n* Browser scripting\\n* Advanced extraction\\n* Data pipelines\\n* Ideal for LLMs and AI Agents\\n* Accurate labeling\\n## Achieve more with these new API features\\nOur API is set to stream so you can act in realtime.\\n### Search\\nGet access to search engine results from anywhere and easily crawl and transform pages to LLM-ready markdown.\\n[Explore Search](https://spider.cloud/docs/api#search)\\n### Transform\\nConvert raw HTML into markdown easily by using this API. Transform thousands of html pages in seconds.\\n[Explore Transform](https://spider.cloud/docs/api#transform)\\n## Join the community\\nBacked by a network of early advocates, contributors, and supporters.\\n[GitHub discussions\\n](https://github.com/orgs/spider-rs/discussions)\\n[Discord\\n](https://discord.spider.cloud)\\n[\\n@iammerrick\\nRust based crawler Spider is next level for crawling & scraping sites. So fast. Their cloud offering is also so easy to use. Good stuff. https://github.com/spider-rs/spider\\n](https://twitter.com/iammerrick/status/1787873425446572462)\\n[\\n@WilliamEspegren\\nWeb crawler built in rust, currently the nr1 performance in the world with crazy resource management Aaaaaaand they have a cloud offer, that’s wayyyy cheaper than any competitor Name a reason for me to use anything else? github.com/spider-rs/spid…\\n](https://twitter.com/WilliamEspegren/status/1789419820821184764)\\n[\\n@gasa\\n@gasathenaper is the best crawling tool i have used. I had a complicated project where i needed to paste url and get the website whole website data. Spider cloud does it in an instant\\n](https://x.com/gasathenaper/status/1810612492596383948)\\n[\\n@Ashpreet Bedi\\n@ashpreetbedi is THE best crawler out there, give it a try\\n](https://x.com/ashpreetbedi/status/1815512219003572315?s=46&t=37F5QP_8oKqOsNpHSo6VVw)\\n[\\n@Troyusrex\\nI found a new tool, Spider-rs, which scrapes significantly faster and handles more scenarios than the basic scraper I built did. Our use of Spider-rs and AWS infrastructure reduced the scraping time from four months to under a week.\\n](https://medium.com/@troyusrex/inside-my-virtual-college-advisor-a-deep-dive-into-rag-ai-and-agent-technology-84731b2928f7#1326)\\n[\\n@Dify.AI\\n🕷️ Spider @spider\\\\_rust can be used as a built-in tool in #Dify Workflow or as an LLM-callable tool in Agent. It allows fast and affordable web scraping and crawling when your AI applications need real-time web data for context.\\n](https://x.com/dify_ai/status/1818226971056243089)\\n## FAQ\\nFrequently asked questions about Spider.\\n### What is Spider?\\nSpider is a leading web crawling tool designed for speed and cost-effectiveness, supporting various data formats including LLM-ready markdown.\\n### Why is my website not crawling?\\nYour crawl may fail if it requires JavaScript rendering. Try setting your request to \\'chrome\\' to solve this issue.\\n### Can you crawl all pages?\\nYes, Spider accurately crawls all necessary content without needing a sitemap.\\n### What formats can Spider convert web data into?\\nSpider outputs HTML, raw, text, and various markdown formats. It supports`JSON`,`JSONL`,`CSV`, and`XML`for API responses.\\n### Is Spider suitable for large scraping projects?\\nAbsolutely, Spider is ideal for large-scale data collection and offers a cost-effective dashboard for data management.\\n### How can I try Spider?\\nPurchase credits for our cloud system or test the Open Source Spider engine to explore its capabilities.\\n### Does it respect robots.txt?\\nYes, compliance with robots.txt is default, but you can disable this if necessary.\\n### Unable to get dynamic content?\\nIf you are having trouble getting dynamic pages, try setting the request parameter to \"chrome\" or \"smart.\" You may also need to set `disable\\\\_intercept` to allow third-party or external scripts to run.\\n### Why is my crawl going slow?\\nIf you are experiencing a slow crawl, it is most likely due to the robots.txt file for the website. The robots.txt file may have a crawl delay set, and we respect the delay up to 60 seconds.\\n### Do you offer a Free Trial?\\nYes, you can try out the service before being charged for free at[checkout](https://spider.cloud/credits/new?free-trial=1).\\n## Comprehensive Data Curation for Everyone\\nTrusted by leading tech businesses worldwide to deliver accurate and insightful data solutions.\\n[](https://zapier.com/apps/spider/integrations)\\n### Next generation data for AI, scale to millions\\n[Start now](https://spider.cloud/credits/new)\\n### Company\\n* [About](https://spider.cloud/about)\\n* [Privacy](https://spider.cloud/privacy)\\n* [Terms](https://spider.cloud/eula)\\n* [FAQ](https://spider.cloud/faq)\\n### Resources\\n* [API](https://spider.cloud/docs/api)\\n* [Docs](https://spider.cloud/docs/overview)\\n* [Guides](https://spider.cloud/guides)\\n* [Spider.rs Docs](https://docs.rs/spider/latest/spider/)\\n### Services\\n* [Pricing](https://spider.cloud/credits/new)\\n* [Web Crawling and Scraping](https://spider.cloud/web-crawling-and-scraping)\\n[All systems normal.](https://spidercloud.statuspage.io/)\\n[GitHub](https://github.com/spider-rs/spider)\\n[Discord](https://discord.spider.cloud)\\n[Twitter](https://twitter.com/spider_rust)\\n', 'type': 'Document'}]}\n", - "--------------------------------------------------\n", - "Transition type: finish\n", - "Transition output: Spider.cloud is a cutting-edge web crawling service designed for AI applications, offering high-speed and cost-effective data collection. Built with a robust Rust engine, Spider supports seamless integration with AI tools and provides various response formats, including LLM-ready markdown. It features concurrent streaming, caching, smart mode with headless Chrome, and auto proxy rotations. Ideal for large-scale projects, Spider ensures compliance with robots.txt and offers a free trial. Trusted by tech leaders, it enables efficient data curation and transformation, with capabilities to handle extreme workloads and dynamic content rendering.\n", - "--------------------------------------------------\n" - ] - } - ], - "source": [ - "# Lists all the task steps that have been executed up to this point in time\n", - "transitions = client.executions.transitions.list(execution_id=execution.id).items\n", - "\n", - "# Transitions are retreived in reverse chronological order\n", - "for transition in reversed(transitions):\n", - " print(\"Transition type: \", transition.type)\n", - " print(\"Transition output: \", transition.output)\n", - " print(\"-\"*50)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Running the same task with a different URL" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We will use the same code to run the same task, but with a different URL" - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "metadata": {}, - "outputs": [], - "source": [ - "execution = client.executions.create(\n", - " task_id=TASK_UUID,\n", - " input={\n", - " \"url\": \"https://www.harvard.edu/\"\n", - " }\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": 66, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Harvard University's website highlights its commitment to excellence in teaching, research, and leadership development globally\n", - "It offers diverse academic programs, including undergraduate, graduate, and professional learning\n", - "The site features information about Harvard's various schools, libraries, museums, and research initiatives\n", - "It emphasizes Harvard's global impact, historical achievements, and contributions to fields like climate change, medicine, and biodiversity\n", - "The site also provides resources for campus visits, events, and news updates, showcasing Harvard's vibrant community and its role in advancing knowledge and societal well-being.\n" - ] - } - ], - "source": [ - "execution = client.executions.get(execution.id)\n", - "print(\"\\n\".join(execution.output.split(\". \")))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note: you can get the output of the crawling step by accessing the corresponding transition's output from the transitions list.\n", - "\n", - "Example:" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'documents': [{'id': None,\n", - " 'metadata': {'description': 'Harvard University is devoted to excellence in teaching, learning, and research, and to developing leaders who make a difference globally.',\n", - " 'domain': 'www.harvard.edu',\n", - " 'extracted_data': None,\n", - " 'file_size': 19620,\n", - " 'keywords': ['Amazon rainforest immersion',\n", - " 'Ants Army ants',\n", - " 'Arnold Arboretum Horticultural Library',\n", - " 'Cabot Science Library',\n", - " 'Dumbarton Oaks Research Library',\n", - " 'Ernst Mayr Library',\n", - " 'Fine Arts Library',\n", - " 'Frances Loeb Library',\n", - " 'Griffin Graduate School',\n", - " 'Harvard Amazon Rainforest Immersion program',\n", - " 'Harvard Art Museums',\n", - " 'Harvard Business School',\n", - " 'Harvard Divinity School',\n", - " 'Harvard Divinity School Library',\n", - " 'Harvard Film Archive',\n", - " 'Harvard Forest research project explored naturalist Frank Morton Jones',\n", - " 'Harvard Graduate School',\n", - " 'Harvard Kennedy School',\n", - " 'Harvard Law School',\n", - " 'Harvard Law School Library',\n", - " 'Harvard Map Collection',\n", - " 'Harvard Medical School',\n", - " 'Harvard Radcliffe Institute',\n", - " 'Harvard Schools Academics Visit',\n", - " 'Harvard University Archives',\n", - " 'Harvard University Herbaria',\n", - " 'Harvard scientist Gary Ruvkun awarded medicine prize',\n", - " 'Historical Scientific Instruments',\n", - " 'Howler monkeys Monkeys don',\n", - " 'Loeb Music Library',\n", - " 'Meet Professor Gary Ruvkun',\n", - " 'Moose Harvard Forest',\n", - " 'Recent topics include',\n", - " 'Report Copyright Infringement',\n", - " 'Report Security Issue',\n", - " 'Trending News Stories News',\n", - " 'Warren Anatomical Museum',\n", - " 'Woodberry Poetry Room',\n", - " 'Worms Invasive worms',\n", - " 'altering soil composition',\n", - " 'boost mental health',\n", - " 'climate change mitigation',\n", - " 'collective foraging behavior',\n", - " 'die-hard Harvard buffs',\n", - " 'eastern North America',\n", - " 'eliminating ground cover',\n", - " 'endangered Chinese tree',\n", - " 'forest fires impact',\n", - " 'forests Climate change',\n", - " 'growing global population continue',\n", - " 'long-term ecological research site located',\n", - " 'mycorrhizae plays important roles',\n", - " 'offset carbon emissions',\n", - " 'people experience long COVID symptoms',\n", - " 'pitcher plant research',\n", - " 'rainforests promote biodiversity',\n", - " 'temperate woody plants',\n", - " 'woods Research shows'],\n", - " 'pathname': '/',\n", - " 'resource_type': '.md',\n", - " 'title': 'Harvard University',\n", - " 'url': '8475428e-4e0c-44de-967f-c14fb73cf490/www.harvard.edu/www_edu/12638123428881205758.md',\n", - " 'user_id': '8475428e-4e0c-44de-967f-c14fb73cf490'},\n", - " 'page_content': \"Harvard University\\n[Skip to main content](#main-content)\\n[Harvard University](https://www.harvard.edu/)\\nSearch\\n**SearchQuick Links**\\n1. [A to Z index](https://www.harvard.edu/a-to-z/)\\nMenu\\n1. Academics\\n\\nAcademics\\n**[Academics](https://www.harvard.edu/academics/)**Learning at Harvard can happen for every type of learner, at any phase of life.\\n\\n1. Degree programs\\n\\nAcademics\\n**Degree programs**Browse all of our undergraduate concentrations and graduate degrees.\\n\\n1. [**Undergraduate Degrees**](https://www.harvard.edu//programs/?degree_levels=undergraduate)\\n 2. [**Graduate Degrees**](https://www.harvard.edu//programs/?degree_levels=graduate)\\n 3. [**Other**](https://www.harvard.edu/academics/professional-and-lifelong-learning/)\\n\\n2. [Professional and Lifelong Learning](https://www.harvard.edu/academics/professional-and-lifelong-learning/)\\n 3. [Harvard Online](https://www.harvardonline.harvard.edu/)\\n 4. Harvard Schools\\n\\nAcademics\\nVisit each School for information on admissions and financial aid.[Explore more](/schools/)\\n\\n1. [**Harvard College**](https://college.harvard.edu/)\\n 2. [**Harvard Business School**](http://www.hbs.edu)\\n 3. [**Harvard Division of Continuing Education**](https://www.dce.harvard.edu/)\\n 4. [**Harvard Divinity School**](https://hds.harvard.edu/)\\n 5. [**Harvard Faculty of Arts and Sciences**](https://www.fas.harvard.edu/)\\n 6. [**Harvard Kenneth C. Griffin Graduate School of Arts and Sciences**](https://gsas.harvard.edu/)\\n 7. [**Harvard Graduate School of Design**](https://www.gsd.harvard.edu/)\\n 8. [**Harvard Graduate School of Education**](https://gse.harvard.edu/)\\n 9. [**Harvard John A. Paulson School of Engineering and Applied Sciences**](https://www.seas.harvard.edu/)\\n 10. [**Harvard Kennedy School**](https://www.hks.harvard.edu/)\\n 11. [**Harvard Law School**](https://hls.harvard.edu/)\\n 12. [**Harvard Medical School**](https://hms.harvard.edu/)\\n 13. [**Harvard Radcliffe Institute**](https://www.radcliffe.harvard.edu/)\\n 14. [**Harvard School of Dental Medicine**](https://hsdm.harvard.edu/)\\n 15. [**Harvard T.H. Chan School of Public Health**](https://www.hsph.harvard.edu/)\\n\\n2. Campus\\n\\nCampus\\n**[Harvard's Campus](https://www.harvard.edu/campus/)**Get tickets to our next game, hours and locations for our libraries and museums, and information about your next career move.\\n\\n1. Libraries\\n\\nCampus\\n[Explore our libraries](https://www.harvard.edu/campus/libraries/)\\n\\n1. [**Arnold Arboretum Horticultural Library**](https://arboretum.harvard.edu/research/library/)\\n 2. [**Baker Library and Special Collections**](https://www.library.hbs.edu/)\\n 3. [**Biblioteca Berenson**](http://itatti.harvard.edu/berenson-library)\\n 4. [**Botany Libraries**](https://huh.harvard.edu/libraries)\\n 5. [**Cabot Science Library**](https://library.harvard.edu/libraries/cabot)\\n 6. [**Countway Library**](https://countway.harvard.edu/)\\n 7. [**Dumbarton Oaks Research Library**](https://www.doaks.org/research/library-archives)\\n 8. [**Ernst Mayr Library**](https://library.mcz.harvard.edu/)\\n 9. [**Fine Arts Library**](https://library.harvard.edu/libraries/fine-arts)\\n 10. [**Frances Loeb Library**](https://www.gsd.harvard.edu/frances-loeb-library/)\\n 11. [**Fung Library**](https://library.harvard.edu/libraries/fung)\\n 12. [**Gutman Library**](https://gse.harvard.edu/community/library)\\n 13. [**Harvard Divinity School Library**](https://library.hds.harvard.edu/)\\n 14. [**Harvard Film Archive**](https://harvardfilmarchive.org/)\\n 15. [**Harvard Law School Library**](https://hls.harvard.edu/library/)\\n 16. [**Harvard Map Collection**](https://library.harvard.edu/libraries/harvard-map-collection)\\n 17. [**Harvard University Archives**](https://library.harvard.edu/libraries/harvard-university-archives)\\n 18. [**Harvard-Yenching Library**](https://library.harvard.edu/libraries/yenching)\\n 19. [**HKS Library and Knowledge Services**](https://www.hks.harvard.edu/research-insights/library-knowledge-services)\\n 20. [**Houghton Library**](https://library.harvard.edu/libraries/houghton)\\n 21. [**Lamont Library**](https://library.harvard.edu/libraries/lamont)\\n 22. [**Loeb Music Library**](https://library.harvard.edu/libraries/loeb-music)\\n 23. [**Robbins Library of Philosophy**](https://library.harvard.edu/libraries/robbins-philosophy)\\n 24. [**Schlesinger Library on the History of Women in America**](https://www.radcliffe.harvard.edu/schlesinger-library)\\n 25. [**Tozzer Library**](https://library.harvard.edu/libraries/tozzer)\\n 26. [**Widener Library**](https://library.harvard.edu/libraries/widener)\\n 27. [**Woodberry Poetry Room**](https://library.harvard.edu/libraries/poetryroom)\\n\\n2. Museums\\n\\nCampus\\n[Explore our museums](https://www.harvard.edu/campus/museums/)\\n\\n1. [**The Arnold Arboretum**](http://www.arboretum.harvard.edu/)\\n 2. [**Carpenter Center for the Visual Arts**](http://ccva.fas.harvard.edu/)\\n 3. [**Collection of Historical Scientific Instruments**](http://chsi.harvard.edu/)\\n 4. [**Graduate School of Design Exhibitions**](http://www.gsd.harvard.edu/exhibitions/)\\n 5. [**Harvard Art Museums**](http://www.harvardartmuseums.org/)\\n 6. [**Harvard Forest**](https://harvardforest.fas.harvard.edu/)\\n 7. [**Harvard Museum of Natural History**](http://www.hmnh.harvard.edu/)\\n 8. [**The Harvard Museum of the Ancient Near East**](https://hmane.harvard.edu/)\\n 9. [**Harvard Museums of Science and Culture**](http://hmsc.harvard.edu/)\\n 10. [**Harvard University Herbaria**](http://www.huh.harvard.edu/)\\n 11. [**Mineralogical and Geological Museum**](http://mgmh.fas.harvard.edu/)\\n 12. [**Museum of Comparative Zoology**](http://www.mcz.harvard.edu/)\\n 13. [**The Peabody Museum of Archaeology and Ethnology**](http://www.peabody.harvard.edu/)\\n 14. [**Warren Anatomical Museum**](https://countway.harvard.edu/center-history-medicine/collections-research-access/warren-anatomical-museum-collection)\\n\\n3. [Athletics](https://www.harvard.edu/campus/athletics/)\\n 4. [Work at Harvard](https://www.harvard.edu/campus/work-at-harvard/)\\n 5. [Events](https://news.harvard.edu/gazette/harvard-events/)\\n 6. [Commencement](http://commencement.harvard.edu/)\\n\\n3. In Focus\\n\\nIn Focus\\n**Explore and understand the world with Harvard**In Focus is a curated examination of Harvard's research, scholarly work, and community. Recent topics include:\\n\\n1. Forests\\n\\nIn Focus\\n**Forests**From sprawling jungles to city parks, forests are complex ecosystems that support the livelihoods of flora, fauna, humans, and the planet.[Take a hike](https://www.harvard.edu/in-focus/forests/)\\n\\n1. **What's inside?**\\n 1. [\\n **Urban forests can help cool cities**](https://www.gsd.harvard.edu/2023/10/the-forest-for-the-trees-and-the-birds-and-the-people-and-the-planet/)\\n 2. [\\n **Forests can help offset carbon emissions**](https://news.harvard.edu/gazette/story/2022/11/new-report-shows-forests-have-big-role-to-play-in-climate-change-fight/)\\n\\n2. Harvard in the World\\n\\nIn Focus\\n**Harvard in the World**Harvard faculty, students, and alumni compose a global network that is exploring\\xa0health, law, government, education, business, and more around the world.[Explore the globe](https://www.harvard.edu/in-focus/harvard-in-the-world/)\\n\\n1. **What's inside**\\n 1. [\\n **Journey to the Amazon**](https://news.harvard.edu/gazette/story/2024/10/journey-to-a-key-front-in-climate-change-fight/)\\n 2. [\\n **Learn about Worldwide Week at Harvard**](https://worldwide.harvard.edu/worldwide-week-harvard-2024)\\n\\n3. Nobels at Harvard\\n\\nIn Focus\\n**Nobels at Harvard**Explore Harvard's history with the Nobel Prize and learn about winners past and present.[View the feature](https://www.harvard.edu/in-focus/nobels-at-harvard/)\\n\\n1. **What's inside**\\n 1. [\\n **Meet Professor Gary Ruvkun, a 2024 winner**](https://news.harvard.edu/gazette/story/2024/10/harvard-scientist-awarded-nobel/)\\n 2. [\\n **Meet Harvard's Nobel Laureates**](https://www.harvard.edu/about/history/nobel-laureates/)\\n\\n4. [\\n Explore the In Focus archives](https://www.harvard.edu/in-focus/)\\n\\n4. Visit\\n\\nVisit\\n**[Visit Harvard](https://www.harvard.edu/visit/)**Ideas and assistance for your trip to our campus.\\n\\n1. [Tours](https://www.harvard.edu/visit/tours/)\\n 2. [Maps and directions](https://www.harvard.edu/visit/maps-directions/)\\n 3. [Tour Providers](https://www.harvard.edu/visit/tour-providers/)\\n\\n5. About\\n\\nAbout\\n**[About Harvard](https://www.harvard.edu/about/)**Learn how Harvard is structured, explore our long history, and discover our extended community.\\n\\n1. History of Harvard\\n\\nAbout\\n**History of Harvard**Harvard is perhaps best-known because of its enduring history of innovation in education. But even die-hard Harvard buffs are not likely to know all of these Harvard firsts and historical snippets.[Learn more](https://www.harvard.edu/about/history/)\\n\\n1. [**History timeline**](https://www.harvard.edu/about/history/timeline/)\\n 2. [**Nobel Laureates**](https://www.harvard.edu/about/history/nobel-laureates/)\\n 3. [**Honorary Degrees**](https://www.harvard.edu/about/history/honorary-degrees/)\\n 4. [**Harvard shields**](https://www.harvard.edu/about/history/shields/)\\n\\n2. Leadership and governance\\n\\nAbout\\n[Learn about our Leadership](https://www.harvard.edu/about/leadership-and-governance/)\\n\\n1. [**President**](https://www.harvard.edu//president/)\\n 2. [**Officers and Deans**](https://www.harvard.edu/about/leadership-and-governance/officers-and-deans/)\\n 3. [**Harvard Corporation**](https://www.harvard.edu/about/leadership-and-governance/harvard-corporation/)\\n 4. [**Board of Overseers**](https://www.harvard.edu/about/leadership-and-governance/board-of-overseers/)\\n\\n3. [University Professorships](https://www.harvard.edu/about/university-professorships/)\\n 4. [Diversity and Inclusion](https://www.harvard.edu/about/diversity-and-inclusion/)\\n 5. [Endowment](https://www.harvard.edu/about/endowment/)\\n 6. [Harvard in the Community](https://www.harvard.edu/about/harvard-in-the-community/)\\n 7. [Harvard in the World](https://www.harvard.edu/about/harvard-in-the-world/)\\n\\n6. News\\n\\nNews\\n**[The Harvard Gazette](https://news.harvard.edu/gazette/)**Official news from Harvard University about science, medicine, art, campus life, University issues, and broader national and global concerns.\\n\\n1. Trending News Stories\\n\\nNews\\n[Read more news](http://news.harvard.edu)\\n\\n1. [**Unearthed papyrus contains lost scenes from Euripides’ plays**Alums help identify, decipher ‘one of the most significant new finds in Greek literature in this century’\\n ](https://news.harvard.edu/gazette/story/2024/10/unearthed-papyrus-contains-lost-scenes-from-euripides-plays/)\\n2. [**What’s next after a Nobel? It’s a surprise.**Harvard scientist Gary Ruvkun awarded medicine prize for microRNA insights. ‘My ignorance is bliss,’ he says.\\n ](https://news.harvard.edu/gazette/story/2024/10/harvard-scientist-awarded-nobel/)\\n3. [**Getting to the bottom of long COVID**A reservoir of virus in the body may explain why some people experience long COVID symptoms\\n ](https://news.harvard.edu/gazette/story/2024/10/getting-to-the-bottom-of-long-covid/)\\n\\n2. [Sign up for the Daily Gazette](https://www.pages01.net/harvard/gazette?email=)\\n\\n**NavigationQuick Links**\\n1. [A to Z index](https://www.harvard.edu/a-to-z/)\\n2. [Find a person](https://connections.harvard.edu/)\\n3. [Events](https://news.harvard.edu/gazette/harvard-events/)\\n4. [Media Relations](/media-relations)\\n5. [Alumni](https://alumni.harvard.edu/)\\n6. [Give Now](https://alumni.harvard.edu/giving/givenow)\\n7. [Emergency](https://www.harvard.edu/emergency/)\\n[Harvard University](https://www.harvard.edu/)\\nClose\\n# Harvard University\\n## Forests\\nFrom sprawling jungles to city parks, forests are complex ecosystems that support the livelihoods of flora, fauna, humans, and the planet.\\n## Our forests\\nHarvard maintains and stewards two forests where we house a living collection of plants and expand our forest knowledge through research.\\n### Harvard Forest\\nA 4000-acre laboratory, classroom, and long-term ecological research site located in central Massachusetts.\\nLearn more about Harvard Forest\\n[Learn more about Harvard Forest](https://harvardforest.fas.harvard.edu/)\\n### Arnold Arboretum\\nA 281-acre preserve of temperate woody plants from eastern North America and eastern Asia, located in the Boston neighborhood of Jamaica Plain.\\nLearn more about the Arboretum\\n[Learn more about the Arboretum](https://arboretum.harvard.edu/)\\n## How forests help us\\nForest play a major role in[the planet’s overall wellbeing](https://repository.gheli.harvard.edu/repository/12580/), from sequestering carbon and creating oxygen to fostering a diversity of life.\\n### [Forests help offset carbon emissions](https://news.harvard.edu/gazette/story/2022/11/new-report-shows-forests-have-big-role-to-play-in-climate-change-fight/)\\n[Learn more about forests’ role in climate change mitigation](https://news.harvard.edu/gazette/story/2020/08/new-englands-trees-capturing-more-carbon-says-25-year-study/)\\n### [Rainforests are an engine of diverse life](https://news.harvard.edu/gazette/story/2018/07/study-says-rainforests-gave-birth-to-worlds-most-varied-tropical-region/)\\n[Learn more about how rainforests promote biodiversity](https://arboretum.harvard.edu/stories/resolving-the-enigma-of-rainforest-biodiversity/)\\n### [Urban forests can help cool cities](https://www.hsph.harvard.edu/news/features/linear-urban-forest-project-aims-to-mitigate-heat-improve-health-in-cities/)\\n[Learn more about the benefits of urban forests](https://www.gsd.harvard.edu/2023/10/the-forest-for-the-trees-and-the-birds-and-the-people-and-the-planet/)\\n## Forest flora\\n[Explore more plant life](https://arboretum.harvard.edu/plants/)\\n### Paperbark Maple\\nThe Arboretum has been active in the conservation of this endangered Chinese tree for more than a century.\\nLearn more about the tree\\n[Learn more about the tree](https://arboretum.harvard.edu/plant-bios/paperbark-maple/)\\n### Pitcher plants\\nA Harvard Forest research project explored naturalist Frank Morton Jones’ pitcher plant research.\\nLearn more about carnivorous plants\\n[Learn more about carnivorous plants](https://harvardforest.fas.harvard.edu/ellison/current-research/Frank-Morton-Jones)\\n### Sapria himalayana\\nThese unusual plants have no roots, stems, or leaves of their own, living only as a collection of cells until they produce some of the largest flowers in the world.\\nLearn more about this strange, stinky flower\\n[Learn more about this strange, stinky flower](https://news.harvard.edu/gazette/story/2021/01/harvard-researchers-sequence-sapria-genome/)\\nInside Harvard’s Amazon rainforest immersion\\n[Click to Play Video](https://youtu.be/yTOEaON95DA)\\n## Forests around the world\\nHarvard researchers are exploring and supporting forests all over the world, including plant expeditions in[Japan](https://arboretum.harvard.edu/stories/science-and-spirit-in-the-forests-of-central-honshu/)and the[Pacific Northwest](https://arboretum.harvard.edu/expeditions/oregon-and-washington-expedition-owe/), Amazon conservation in[Brazil](https://hir.harvard.edu/the-waiapi-tribe-the-protectors-of-the-amazon-rainforest/)and[Peru](https://revista.drclas.harvard.edu/saving-latin-america-forests/), and a deep dive into the forests right in our[New England](https://hmnh.harvard.edu/new-england-forests)backyard.\\n[Learn about the Harvard Amazon Rainforest Immersion program](https://news.harvard.edu/gazette/story/2024/10/journey-to-a-key-front-in-climate-change-fight/)\\n## How we can help forests\\nClimate change and a growing global population continue to be detrimental to the world’s forests, but researchers are working to understand and mitigate those threats.\\n### Invasion\\n[How global shipping may bring pests that threaten our forests](https://harvardforest.fas.harvard.edu/news/old-growth-forests-elders-under-threat)\\n### Preservation\\n[How deforestation can affect the surviving forests](https://environment.harvard.edu/news/deforestation-damages-even-rainforests-survive-it)\\n### Conflagration\\n[How forest fires impact the world](https://news.harvard.edu/gazette/story/2023/06/in-the-thick-of-canadian-wildfires/)\\n## Forest fauna\\n[Explore more wildlife](https://arboretum.harvard.edu/visit/wildlife-at-the-arboretum/)\\n### Mink\\nA member of the weasel family, minks have been seen at the Arboretum for several years, typically near wetlands.\\nLearn more about the Arboretum’s newest residents\\n[Learn more about the Arboretum’s newest residents](https://arboretum.harvard.edu/stories/fishers-weasels-are-latest-residents-of-bostons-arboretum/)\\n### Howler monkeys\\nMonkeys don’t just consume fruits, but also make forest by dispersing the seeds of trees they consume.\\nLearn more about monkeys’ relationship to the forests they inhabit\\n[Learn more about monkeys’ relationship to the forests they inhabit](https://revista.drclas.harvard.edu/how-monkeys-create-tropical-rainforests/)\\n### Moose\\nHarvard Forest’s wildlife cameras have spotted moose and deer using their trees.\\nExplore more animals from Harvard Forest\\n[Explore more animals from Harvard Forest](https://harvardforest.fas.harvard.edu/browsing-wildlife-photos)\\n## []()\\n### Walking in the woods\\nResearch shows that hiking and “forest baths” have physical and mental benefits.\\n[Learn how the woods can help boost mental health](https://magazine.hms.harvard.edu/articles/walk-woods-may-boost-mental-health)\\n[Learn more about “forest bathing”](https://arboretum.harvard.edu/stories/walk-into-a-forest-breathe-deeply-repeat-as-needed/)\\n## Underground dwellers\\n### Mycorrhizae\\nA connection produced between a plant and fungi that live in the plant’s roots, mycorrhizae plays important roles in plant nutrition and soil biology and chemistry.\\nLearn more about this symbiotic relationship\\n[Learn more about this symbiotic relationship](https://arboretum.harvard.edu/stories/food-poison-and-espionage-mycorrhizal-networks-in-action/)\\n### Worms\\nInvasive worms are eliminating ground cover and altering soil composition, threatening some plant communities in New England.\\nLearn more about worms\\n[Learn more about worms](https://arboretum.harvard.edu/stories/native-plants-and-the-crazy-snake-worm/)\\n### Ants\\nArmy ants’ mass raids are considered the pinnacle of collective foraging behavior in the animal kingdom, but scientists are only just learning how they evolved to create them.\\nLearn how ant raids have evolved\\n[Learn how ant raids have evolved](https://oeb.harvard.edu/news/how-army-ants-iconic-mass-raids-evolved)\\nYou may also like\\n## Related In Focus topics\\n* [Arboretum Anniversary](https://www.harvard.edu/in-focus/arboretum-anniversary/)\\n* [Animal Magnetism](https://www.harvard.edu/in-focus/animal-magnetism/)\\n* [Earth Science](https://www.harvard.edu/in-focus/earth-science/)\\n## Security & Brand\\n1. [Report Copyright Infringement](https://www.harvard.edu/copyright-issue/)\\n2. [Report Security Issue](https://www.harvard.edu/security-issue/)\\n3. [Trademark Notice](https://trademark.harvard.edu/pages/trademark-notice)\\n## Website\\n1. [Accessibility](https://accessibility.harvard.edu/)\\n2. [Digital Accessibility](https://accessibility.huit.harvard.edu/digital-accessibility-policy)\\n3. [Privacy statement](https://www.harvard.edu/privacy-statement/)\\n## Get In Touch\\n1. [Contact Harvard](/contact-harvard)\\n2. [Maps & Directions](/maps-directions)\\n3. [Jobs](http://hr.harvard.edu/jobs)\\nCopyright © 2024 The President and Fellows of Harvard College\\n[](https://www.harvard.edu/)\\n* [Instagram](https://www.instagram.com/harvard/)\\n* [TikTok](https://www.tiktok.com/@harvard)\\n* [LinkedIn](https://www.linkedin.com/school/harvard-university)\\n* [Facebook](https://www.facebook.com/Harvard/)\\n* [YouTube](https://www.youtube.com/harvard)\\n\",\n", - " 'type': 'Document'}]}" - ] - }, - "execution_count": 67, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "transitions = client.executions.transitions.list(execution_id=execution.id).items\n", - "\n", - "transitions[1].output" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "ai", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.3" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/cookbooks/01-website-crawler.ipynb b/cookbooks/01-website-crawler.ipynb new file mode 100644 index 000000000..184ae951b --- /dev/null +++ b/cookbooks/01-website-crawler.ipynb @@ -0,0 +1,522 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + " \"julep\"\n", + "
\n", + "\n", + "## Task Definition: Spider Crawler Integration\n", + "\n", + "### Overview\n", + "\n", + "This task is a simple task that leverages the spider `integration` tool, and combines it with a prompt step to crawl a website for a given URL, and then create a summary of the results.\n", + "\n", + "### Task Tools:\n", + "\n", + "**Spider Crawler**: An `integration` type tool that can crawl the web and extract data from a given URL.\n", + "\n", + "### Task Input:\n", + "\n", + "**url**: The URL of the website to crawl.\n", + "\n", + "### Task Output:\n", + "\n", + "**output**: A dictionary that contains a `documents` key which contains the extracted data from the given URL. Check the output below for a detailed output schema.\n", + "\n", + "### Task Flow\n", + "\n", + "1. **Input**: The user provides a URL to crawl.\n", + "\n", + "2. **Spider Tool Integration**: The `spider_crawler` tool is called to crawl the web and extract data from the given URL.\n", + "\n", + "3. **Prompt Step**: The prompt step is used to create a summary of the results from the spider tool.\n", + "\n", + "4. **Output**: The final output is the summary of the results from the spider tool." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Implementation\n", + "\n", + "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", + "\n", + "\n", + " \"Open\n", + "\n", + "\n", + "### Additional Information\n", + "\n", + "For more details about the task or if you have any questions, please don't hesitate to contact the author:\n", + "\n", + "**Author:** Julep AI \n", + "**Contact:** [hey@julep.ai](mailto:hey@julep.ai) or Discord" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Installing the Julep Client" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "!pip install --upgrade julep --quiet" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "import uuid\n", + "\n", + "# NOTE: these UUIDs are used in order not to use the `create_or_update` methods instead of\n", + "# the `create` methods for the sake of not creating new resources every time a cell is run.\n", + "AGENT_UUID = uuid.uuid4()\n", + "TASK_UUID = uuid.uuid4()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Creating Julep Client with the API Key" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "from julep import Client\n", + "import os\n", + "\n", + "api_key = os.getenv(\"JULEP_API_KEY\")\n", + "\n", + "# Create a Julep client\n", + "client = Client(api_key=api_key, environment=\"dev\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an \"agent\"\n", + "\n", + "Agent is the object to which LLM settings, like model, temperature along with tools are scoped to.\n", + "\n", + "To learn more about the agent, please refer to the [documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#agent)." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# Create agent\n", + "agent = client.agents.create_or_update(\n", + " agent_id=AGENT_UUID,\n", + " name=\"Spiderman\",\n", + " about=\"AI that can crawl the web and extract data\",\n", + " model=\"gpt-4o\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining a Task\n", + "\n", + "Tasks in Julep are Github-Actions-style workflows that define long-running, multi-step actions.\n", + "\n", + "You can use them to conduct complex actions by defining them step-by-step.\n", + "\n", + "To learn more about tasks, please refer to the `Tasks` section in [Julep Concepts](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#tasks)." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "import yaml\n", + "\n", + "spider_api_key = os.getenv(\"SPIDER_API_KEY\")\n", + "\n", + "# Define the task\n", + "task_def = yaml.safe_load(f\"\"\"\n", + "name: Crawling Task\n", + "\n", + "# Define the tools that the agent will use in this workflow\n", + "tools:\n", + "- name: spider_crawler\n", + " type: integration\n", + " integration:\n", + " provider: spider\n", + " setup:\n", + " spider_api_key: \"{spider_api_key}\"\n", + "\n", + "# Define the steps of the workflow\n", + "main:\n", + "# Define a tool call step that calls the spider_crawler tool with the url input\n", + "- tool: spider_crawler\n", + " arguments:\n", + " url: \"_['url']\" # You can also use 'inputs[0]['url']'\n", + " \n", + " \n", + "- prompt: |\n", + " You are {{{{agent.about}}}}\n", + " I have given you this url: {{{{inputs[0]['url']}}}}\n", + " And you have crawled that website. Here are the results you found:\n", + " {{{{_['documents']}}}}\n", + " I want you to create a short summary (no longer than 100 words) of the results you found while crawling that website.\n", + "\n", + " unwrap: True\n", + "\"\"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notes:\n", + "- The reason for using the quadruple curly braces `{{{{}}}}` for the jinja template is to avoid conflicts with the curly braces when using the `f` formatted strings in python. [More information here](https://stackoverflow.com/questions/64493332/jinja-templating-in-airflow-along-with-formatted-text)\n", + "- The `unwrap: True` in the prompt step is used to unwrap the output of the prompt step (to unwrap the `choices[0].message.content` from the output of the model).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating/Updating a task" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "# creating the task object\n", + "task = client.tasks.create_or_update(\n", + " task_id=TASK_UUID,\n", + " agent_id=AGENT_UUID,\n", + " **task_def\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an Execution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "An execution is a single run of a task. It is a way to run a task with a specific set of inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "# creating an execution object\n", + "execution = client.executions.create(\n", + " task_id=TASK_UUID,\n", + " input={\n", + " \"url\": \"https://spider.cloud\"\n", + " }\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Checking execution details and output" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are multiple ways to get the execution details and the output:\n", + "\n", + "1. **Get Execution Details**: This method retrieves the details of the execution, including the output of the last transition that took place.\n", + "\n", + "2. **List Transitions**: This method lists all the task steps that have been executed up to this point in time, so the output of a successful execution will be the output of the last transition (first in the transition list as it is in reverse chronological order), which should have a type of `finish`.\n", + "\n", + "\n", + "Note: You need to wait for a few seconds for the execution to complete before you can get the final output, so feel free to run the following cells multiple times until you get the final output.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Spider.cloud is a leading web crawling tool designed for AI applications, offering high-speed, scalable, and cost-effective data collection solutions. Built in Rust, it can crawl over 20,000 pages in seconds, making it significantly faster and cheaper than traditional scrapers. Spider supports various data formats, including LLM-ready markdown, and integrates seamlessly with major AI tools. It offers features like auto proxy rotations, custom browser scripting, and caching to enhance performance. Users can start with $200 in credits and explore features through a free trial. Spider is trusted by tech businesses worldwide for insightful data solutions.\n" + ] + } + ], + "source": [ + "# Get execution details\n", + "execution = client.executions.get(execution.id)\n", + "# Print the output\n", + "print(execution.output)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Transition type: init\n", + "Transition output: {'url': 'https://spider.cloud'}\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: {'documents': [{'id': None, 'metadata': {'description': 'Experience cutting-edge web crawling with unparalleled speeds, perfect for LLMs, Machine Learning, and Artificial Intelligence. The fastest and most efficient web scraper tailored for AI applications.', 'domain': 'spider.cloud', 'extracted_data': None, 'file_size': 10031, 'keywords': ['AI agent stack', 'AWS infrastructure reduced', 'Auto Proxy rotations', 'Comprehensive Data Curation', 'Concurrent Streaming Save time', 'Data Collecting Projects Today Jumpstart web crawling', 'FAQ Frequently asked questions', 'Fastest Web Crawler', 'Latest sports news', 'Multiple response formats', 'Open Source Spider engine', 'Performance Tuned Spider', 'Seamless Integrations Seamlessly integrate Spider', 'Smart Mode Spider dynamically switches', 'Spider accurately crawls', 'Spider convert web data', 'Spider outputs HTML', 'Transform Convert raw HTML', 'WilliamEspegren Web crawler built', 'achieve crawling thousands', 'affordable web scraping', 'and`XML`for API responses', 'caching repeated web page crawls', 'cost step caching', 'crazy resource management Aaaaaaand', 'custom browser scripting', 'data = json', 'data formats including LLM-ready markdown', 'ensure continuous maintenance', 'ensuring data curation perfectly aligned', 'finest data collecting solution', 'full elastic scaling concurrency', 'handle extreme workloads', 'iammerrick Rust based crawler Spider', 'insightful data solutions', 'json headers =', 'large scraping projects', 'large-scale data collection', 'leading tech businesses worldwide', 'leading web crawling tool designed', 'real-time web data', 'request Python JSONL Copy ``` `import requests', 'requires JavaScript rendering', 'response = requests', 'robust Rust engine scales effortlessly', 'scrapes significantly faster', 'search engine results', 'traditional scraping services Spider API Request Modes', 'training AI models', 'user interface segment showing'], 'pathname': '/', 'resource_type': '.md', 'title': 'Spider: The Web Crawler for AI', 'url': '8475428e-4e0c-44de-967f-c14fb73cf490/spider.cloud/_cloud/12638123428881205758.md', 'user_id': '8475428e-4e0c-44de-967f-c14fb73cf490'}, 'page_content': \"To help you get started with Spider, we’ll give you $200 in credits when you spend $100.[Terms apply](https://spider.cloud/promotion-spider-credits)\\n# The Web Crawler for AI Agents and LLMs\\nSpider offers the finest data collecting solution. Engineered for speed and scalability, it\\nallows you to elevate your AI projects.\\n[Get Started](https://spider.cloud/credits/new)View Preview\\n* Basic\\n* Streaming\\nExample request\\nPython\\nJSONL\\nCopy\\n```\\n`import requests, os, json\\nheaders = {\\n''Authorization'': f''Bearer {os.getenv(""SPIDER\\\\_API\\\\_KEY"")}'',\\n''Content-Type'': ''application/jsonl'',\\n}\\njson\\\\_data = {""limit"":50,""metadata"":True,""url"":""https://spider.cloud""}\\nresponse = requests.post(''https://api.spider.cloud/crawl'', headers=headers, json=json\\\\_data, stream=True)\\nwith response as r:\\nr.raise\\\\_for\\\\_status()\\nfor chunk in r.iter\\\\_lines(\\nchunk\\\\_size=None, decode\\\\_unicode=True\\n):\\ndata = json.loads(chunk)\\nprint(data)`\\n```\\n[Free Trial](https://spider.cloud/credits/new?free-trial=1)\\nExample Response\\n## Built with the need for**Speed**\\nExperience the power of**Spider**, built fully in**Rust**for\\nnext-generation scalability.\\n### 2secs\\nCapable of crawling over 20k pages in batch mode\\n### 500-1000x\\nFaster than alternatives\\n### 500x\\nCheaper than traditional scraping services\\nSpider API Request Modes · Benchmarked tailwindcss.com ·06/16/2024\\n[See framework benchmarks](https://github.com/spider-rs/spider/blob/main/benches/BENCHMARKS.md)\\n### Seamless Integrations\\nSeamlessly integrate Spider with a wide range of platforms, ensuring data curation\\nperfectly aligned with your requirements. Compatible with all major AI tools.\\n[LangChain integration](https://python.langchain.com/docs/integrations/document_loaders/spider)[LlamaIndex integration](https://docs.llamaindex.ai/en/stable/examples/data_connectors/WebPageDemo/#using-spider-reader)[CrewAI integration](https://docs.crewai.com/tools/SpiderTool/)[FlowWiseAI integration](https://docs.flowiseai.com/integrations/langchain/document-loaders/spider-web-scraper-crawler)[Composio integration](https://docs.composio.dev/introduction/foundations/components/list_local_tools#spider-crawler)[PhiData integration](https://docs.phidata.com/tools/spider)\\n### Concurrent Streaming\\nSave time and money without having to worry about bandwidth concerns by effectively\\nstreaming all the results concurrently. The latency cost that is saved becomes drastic as\\nyou crawl more websites.\\n### Warp Speed\\nPowered by the cutting-edge[Spider](https://github.com/spider-rs/spider)open-source project, our robust Rust engine scales effortlessly to handle extreme\\nworkloads. We ensure continuous maintenance and improvement for top-tier performance.\\n## Kickstart Your Data Collecting Projects Today\\nJumpstart web crawling with full elastic scaling concurrency, optimal formats, and AI scraping.\\n### Performance Tuned\\nSpider is written in Rust and runs in full concurrency to achieve crawling thousands of\\npages in secs.\\n### Multiple response formats\\nGet clean and formatted markdown, HTML, or text content for fine-tuning or training AI\\nmodels.\\n### Caching\\nFurther boost speed by caching repeated web page crawls to minimize expenses while\\nbuilding.\\n### Smart Mode\\nSpider dynamically switches to Headless Chrome when it needs to quick.\\nBeta\\n### Scrape with AI\\nDo custom browser scripting and data extraction using the latest AI models with no cost\\nstep caching.\\n### The crawler for LLMs\\nDon't let crawling and scraping be the highest latency in your LLM & AI agent stack.\\n### Scrape with no headaches\\n* Auto Proxy rotations\\n* Agent headers\\n* Anti-bot detections\\n* Headless chrome\\n* Markdown responses\\n### The Fastest Web Crawler\\n* Powered by[spider-rs](https://github.com/spider-rs/spider)\\n* 100,000 pages/seconds\\n* Unlimited concurrency\\n* Simple API\\n* 50,000 RPM\\n### Do more with AI\\n* Browser scripting\\n* Advanced extraction\\n* Data pipelines\\n* Ideal for LLMs and AI Agents\\n* Accurate labeling\\n## Achieve more with these new API features\\nOur API is set to stream so you can act in realtime.\\n![A user interface with a search bar containing the text "Latest sports news," a green "Submit" button, and two icon buttons to display searching and extracting with the service.](https://spider.cloud/img/search_feature.webp)\\n### Search\\nGet access to search engine results from anywhere and easily crawl and transform pages to\\nLLM-ready markdown.\\n[Explore Search](https://spider.cloud/docs/api#search)\\n![A user interface segment showing three icons representing different stages of data transformation.](https://spider.cloud/img/transform_feature_example.webp)\\n### Transform\\nConvert raw HTML into markdown easily by using this API. Transform thousands of html pages\\nin seconds.\\n[Explore Transform](https://spider.cloud/docs/api#transform)\\n## Join the community\\nBacked by a network of early advocates, contributors, and supporters.\\n[GitHub discussions\\n](https://github.com/orgs/spider-rs/discussions)[Discord\\n](https://discord.spider.cloud)\\n[\\n![iammerrick's avatar](https://spider.cloud/img/external/iammerrick_twitter.webp)\\n@iammerrick\\nRust based crawler Spider is next level for crawling & scraping sites. So fast.\\nTheir cloud offering is also so easy to use. Good stuff. https://github.com/spider-rs/spider\\n](https://twitter.com/iammerrick/status/1787873425446572462)\\n[\\n![WilliamEspegren's avatar](https://spider.cloud/img/external/william_twitter.webp)\\n@WilliamEspegren\\nWeb crawler built in rust, currently the nr1 performance in the world with crazy resource management Aaaaaaand they have a cloud offer, that’s wayyyy cheaper than any competitor\\nName a reason for me to use anything else?\\ngithub.com/spider-rs/spid…\\n](https://twitter.com/WilliamEspegren/status/1789419820821184764)\\n[\\n![gasa's avatar](https://spider.cloud/img/external/gaza_twitter.webp)\\n@gasa\\n@gasathenaper\\nis the best crawling tool i have used. I had a complicated project where i needed to paste url and get the website whole website data. Spider does it in an instant\\n](https://x.com/gasathenaper/status/1810612492596383948)\\n[\\n![Ashpreet Bedi's avatar](https://spider.cloud/img/external/ashpreet_bedi.webp)\\n@Ashpreet Bedi\\n@ashpreetbedi\\nis THE best crawler out there, give it a try\\n](https://x.com/ashpreetbedi/status/1815512219003572315?s=46&t=37F5QP_8oKqOsNpHSo6VVw)\\n[\\n![Troyusrex's avatar](https://spider.cloud/img/external/troy_twitter.webp)\\n@Troyusrex\\nI found a new tool, Spider-rs, which scrapes significantly faster and handles more scenarios than the basic scraper I built did. Our use of Spider-rs and AWS infrastructure reduced the scraping time from four months to under a week.\\n](https://medium.com/@troyusrex/inside-my-virtual-college-advisor-a-deep-dive-into-rag-ai-and-agent-technology-84731b2928f7#1326)\\n[\\n![Dify.AI's avatar](https://spider.cloud/img/external/difyai.webp)\\n@Dify.AI\\n🕷️Spider @spider\\\\_rust\\ncan be used as a built-in tool in #Dify Workflow or as an LLM-callable tool in Agent. It allows fast and affordable web scraping and crawling when your AI applications need real-time web data for context.\\n](https://x.com/dify_ai/status/1818226971056243089)\\n## FAQ\\nFrequently asked questions about Spider.\\n### What is Spider?\\nSpider is a leading web crawling tool designed for speed and cost-effectiveness, supporting various data formats including LLM-ready markdown.\\n### Why is my website not crawling?\\nYour crawl may fail if it requires JavaScript rendering. Try setting your request to 'chrome' to solve this issue.\\n### Can you crawl all pages?\\nYes, Spider accurately crawls all necessary content without needing a sitemap.\\n### What formats can Spider convert web data into?\\nSpider outputs HTML, raw, text, and various markdown formats. It supports`JSON`,`JSONL`,`CSV`, and`XML`for API responses.\\n### Is Spider suitable for large scraping projects?\\nAbsolutely, Spider is ideal for large-scale data collection and offers a cost-effective dashboard for data management.\\n### How can I try Spider?\\nPurchase credits for our cloud system or test the Open Source Spider engine to explore its capabilities.\\n### Does it respect robots.txt?\\nYes, compliance with robots.txt is default, but you can disable this if necessary.\\n### Unable to get dynamic content?\\nIf you are having trouble getting dynamic pages, try setting the request parameter to ""chrome"" or ""smart."" You may also need to set `disable\\\\_intercept` to allow third-party or external scripts to run.\\n### Why is my crawl going slow?\\nIf you are experiencing a slow crawl, it is most likely due to the robots.txt file for the website. The robots.txt file may have a crawl delay set, and we respect the delay up to 60 seconds.\\n### Do you offer a Free Trial?\\nYes, you can try out the service before being charged for free at[checkout](https://spider.cloud/credits/new?free-trial=1).\\n## Comprehensive Data Curation for Everyone\\nTrusted by leading tech businesses worldwide to deliver accurate and insightful data solutions.\\n[Zapier](https://zapier.com/apps/spider/integrations)\\n### Next generation data for AI, scale to millions\\n[Start now](https://spider.cloud/credits/new)\\n### Company\\n* [About](https://spider.cloud/about)\\n* [Privacy](https://spider.cloud/privacy)\\n* [Terms](https://spider.cloud/eula)\\n* [FAQ](https://spider.cloud/faq)\\n### Resources\\n* [API](https://spider.cloud/docs/api)\\n* [Docs](https://spider.cloud/docs/overview)\\n* [Guides](https://spider.cloud/guides)\\n* [Spider.rs Docs](https://docs.rs/spider/latest/spider/)\\n### Services\\n* [Pricing](https://spider.cloud/credits/new)\\n* [Web Crawling and Scraping](https://spider.cloud/web-crawling-and-scraping)\\n[All systems normal.](https://spidercloud.statuspage.io/)\\n[\\nGitHub\\n](https://github.com/spider-rs/spider)[\\nDiscord\\n](https://discord.spider.cloud)[\\nTwitter\\n](https://twitter.com/spider_rust)\", 'type': 'Document'}]}\n", + "--------------------------------------------------\n", + "Transition type: finish\n", + "Transition output: Spider.cloud is a leading web crawling tool designed for AI applications, offering high-speed, scalable, and cost-effective data collection solutions. Built in Rust, it can crawl over 20,000 pages in seconds, making it significantly faster and cheaper than traditional scrapers. Spider supports various data formats, including LLM-ready markdown, and integrates seamlessly with major AI tools. It offers features like auto proxy rotations, custom browser scripting, and caching to enhance performance. Users can start with $200 in credits and explore features through a free trial. Spider is trusted by tech businesses worldwide for insightful data solutions.\n", + "--------------------------------------------------\n" + ] + } + ], + "source": [ + "# Lists all the task steps that have been executed up to this point in time\n", + "transitions = client.executions.transitions.list(execution_id=execution.id).items\n", + "\n", + "# Transitions are retreived in reverse chronological order\n", + "for transition in reversed(transitions):\n", + " print(\"Transition type: \", transition.type)\n", + " print(\"Transition output: \", transition.output)\n", + " print(\"-\"*50)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Running the same task with a different URL" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will use the same code to run the same task, but with a different URL" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "execution = client.executions.create(\n", + " task_id=TASK_UUID,\n", + " input={\n", + " \"url\": \"https://www.harvard.edu/\"\n", + " }\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Harvard University's website emphasizes its commitment to excellence in teaching, learning, and research\n", + "It highlights initiatives related to food, including nutrition, sustainability, and healthful eating\n", + "The site features experts like Christina Warinner and Leah Penniman, and initiatives like the Harvard Food Systems Initiative and Food Literacy Project\n", + "It explores topics such as junk food cravings, vegan diets, and the impact of avocados on heart disease\n", + "The site also showcases Harvard's efforts in sustainable food practices, food donation programs, and educational resources like free online cooking courses\n", + "Additionally, it highlights the contributions of chefs within the Harvard community.\n" + ] + } + ], + "source": [ + "execution = client.executions.get(execution.id)\n", + "print(\"\\n\".join(execution.output.split(\". \")))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note: you can get the output of the crawling step by accessing the corresponding transition's output from the transitions list.\n", + "\n", + "Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'documents': [{'id': None,\n", + " 'metadata': {'description': 'Harvard University is devoted to excellence in teaching, learning, and research, and to developing leaders who make a difference globally.',\n", + " 'domain': 'www.harvard.edu',\n", + " 'extracted_data': None,\n", + " 'file_size': 15310,\n", + " 'keywords': ['Business School podcast',\n", + " 'Christina Warinner Christina co-authored',\n", + " 'Dental Medicine shares advice',\n", + " 'Dining Services Learnings Report Learn',\n", + " 'Dining Services team',\n", + " 'Education alum started Bite Sized Education',\n", + " 'Expand Image Joanne Chang Stephanie Mitchell',\n", + " 'Expand Image Julia Child Paul Child Julia Child',\n", + " 'Expand Image Ludger Wessels Chef Wessels',\n", + " 'Expand Image Nick DiGiovanni Kris Snibbe',\n", + " 'Expand Image Nisha Vora Photo',\n", + " 'Flour Bakery owner Joanne Chang',\n", + " 'Food Donation Program',\n", + " 'Food Food nourishes',\n", + " 'Food Law',\n", + " 'Food Literacy Project',\n", + " 'Food Literacy Project hosts',\n", + " 'Free cooking courses Learn',\n", + " 'Graduate School',\n", + " 'Harvard Chan School',\n", + " 'Harvard Chan School found',\n", + " 'Harvard College first-year student explains',\n", + " 'Harvard College student',\n", + " 'Harvard College student stories',\n", + " 'Harvard College student story',\n", + " 'Harvard Divinity School explores',\n", + " 'Harvard Food Systems Initiative',\n", + " 'Harvard Food Systems Initiative Led',\n", + " 'Harvard Square food scene',\n", + " 'Harvard Staff Photographer',\n", + " 'Harvard University Dining Services',\n", + " 'Harvard University Dining Services launched',\n", + " 'Harvard alum',\n", + " 'Harvard alum Marcos Barrozo worked',\n", + " 'Healthful Food Standards',\n", + " 'Healthy Eating Plate',\n", + " 'Historian Joyce Chaplin explored',\n", + " 'Ingestible insights Harvard researchers',\n", + " 'James Beard Leadership Award winner',\n", + " 'Joanne Chang wears',\n", + " 'Julia Child pours hot syrup',\n", + " 'Leah Gose worked',\n", + " 'Leah Penniman Leah',\n", + " 'Luke MacQueen spent years creating',\n", + " 'Michael Marquand Law School grad Nisha Vora left',\n", + " 'Prevention Research Center',\n", + " 'Sustainable Food Harvard',\n", + " 'Sustainable Food Systems Graduate Certificate',\n", + " 'Teaching science concepts',\n", + " 'accelerating food shortages',\n", + " 'ancient humans adapted',\n", + " 'biggest problems facing farmers',\n", + " 'chef Ludger Wessels',\n", + " 'co-founded Soul Fire Farm',\n", + " 'converting food waste',\n", + " 'crave junk food',\n", + " 'crave junk food Harvard Medical School',\n", + " 'cultivate healthier eating habits',\n", + " 'engage secondary students',\n", + " 'exploring medical technology',\n", + " 'food Graduate School alum John Ahrens cultivated',\n", + " 'food Research shows',\n", + " 'food connoisseur shares',\n", + " 'food insecurity solutions',\n", + " 'free online courses',\n", + " 'gas fermentation-derived chocolate',\n", + " 'heart disease risk',\n", + " 'inspire elevated thinking',\n", + " 'lab-grown fish fillets',\n", + " 'leading authority providing science-based guidance',\n", + " 'local nonprofit Food',\n", + " 'peach industry fight brown rot',\n", + " 'postmenopausal weight loss',\n", + " 'reduce food waste',\n", + " 'reduce greenhouse gas emissions',\n", + " 'regenerative farming practices',\n", + " 'seasonal rainfall patterns',\n", + " 'selling meat-free meals',\n", + " 'shape future food systems leaders',\n", + " 'six-time American Culinary Federation competition award winner',\n", + " 'specialties include regional German',\n", + " 'vegetarian restaurant Clover'],\n", + " 'pathname': '/',\n", + " 'resource_type': '.md',\n", + " 'title': 'Harvard University',\n", + " 'url': '8475428e-4e0c-44de-967f-c14fb73cf490/www.harvard.edu/www_edu/12638123428881205758.md',\n", + " 'user_id': '8475428e-4e0c-44de-967f-c14fb73cf490'},\n", + " 'page_content': '[Skip to main content](#main-content)\\n[Harvard University](https://www.harvard.edu/)\\nSearch\\nMenu\\n[Harvard University](https://www.harvard.edu/)\\nClose\\n# Harvard University\\n## Food\\nFood nourishes us, inspires us, and brings us together. The Harvard community is exploring nutrition, sustainability, and the science behind the things we eat.\\n## [Tips for your teeth](https://hsdm.harvard.edu/news/maintaining-your-oral-health-during-holiday-season)\\nThe Harvard School of Dental Medicine shares advice for keeping your teeth healthy between holiday meals.\\n![]()\\n## Experts in the edible\\n### Christina Warinner\\nChristina co-authored a study showing that ancient humans adapted to eating starch-rich foods as far back as 100,000 years ago. These foods likely helped pave the way for the expansion of the human brain.\\nLearn more about the study\\n[Learn more about the study](https://news.harvard.edu/gazette/story/2021/05/study-explains-early-humans-ate-starch-and-why-it-matters/)\\n### Ayr Muir\\nAs the founder of the vegetarian restaurant Clover, Ayr is selling meat-free meals and reducing our impact on climate change one sandwich at a time.\\nExplore the Business School podcast\\n[Explore the Business School podcast](https://www.alumni.hbs.edu/stories/Pages/story-bulletin.aspx?num=7302)\\n### Leah Penniman\\nLeah, a James Beard Leadership Award winner, co-founded Soul Fire Farm to train people in regenerative farming practices that are now the go-to methods of sustainable and organic agriculture.\\nLearn more about her farm\\n[Learn more about her farm](https://hds.harvard.edu/news/2019/09/18/leah-penniman-fight-food-justice)\\n![](https://www.harvard.edu/wp-content/themes/core/assets/img/theme/shims/16x9.png)\\nTeaching science concepts through cooking\\n[Click to Play Video](https://www.youtube.com/watch?v=cOJYELbyYGg)\\n### Kate Strangfeld\\nThe Graduate School of Education alum started Bite Sized Education to engage secondary students in science. Her goal is to empower students to “think like a scientist” through food and cooking.\\n## Ingestible insights\\nHarvard researchers are exploring the effects that certain foods and types of eating have on our health.\\n[Learn more about what you should eat](https://nutritionsource.hsph.harvard.edu/what-should-you-eat/)\\n![Two cartoon heads, one with a soda inside it and one with a broccoli](https://www.harvard.edu/wp-content/uploads/2024/11/this_or_that-junk-food-craving-wondering2.png?w=736&h=491&crop=1)### Why we crave junk food\\nHarvard Medical School’s Uma Naidoo, the author of the books “This Is Your Brain on Food” and “Calm Your Mind with Food,” explains why we crave junk food and how to cultivate healthier eating habits.\\n[Why we crave junk food](https://news.harvard.edu/gazette/story/2024/09/why-do-we-crave-junk-food-diet-psychology/)\\n### Chocolate\\nand its effect on postmenopausal weight loss\\n![A bar of chocolate](https://www.harvard.edu/wp-content/uploads/2024/11/chocolate-1277002_1280.jpg?w=375&h=281&crop=1)[Chocolate](https://news.harvard.edu/gazette/story/2021/06/starting-the-day-off-with-chocolate-may-have-unexpected-benefits/)\\n### Ultra-processed food\\nand its influence on obesity and disease\\n![Nuggets and fries](https://www.harvard.edu/wp-content/uploads/2024/11/chicken-nuggets-246180_1280.jpg?w=375&h=281&crop=1)[Ultra-processed food](https://news.harvard.edu/gazette/story/2023/12/why-are-americans-so-sick-researchers-point-to-middle-grocery-aisles/)\\n### Vegan diet\\nand Alzheimer’s improvements\\n![A colorful salad](https://www.harvard.edu/wp-content/uploads/2024/11/food-1075228_1280.jpg?w=375&h=281&crop=1)[Vegan diet](https://news.harvard.edu/gazette/story/2024/07/alzheimers-study-finds-diet-lifestyle-changes-yield-improvements/)\\n### Avocados\\nand their effect on heart disease risk\\n![avocados](https://www.harvard.edu/wp-content/uploads/2024/11/avocado-8498520_1280.jpg?w=375&h=281&crop=1)[Avocados](https://news.harvard.edu/gazette/story/2022/04/an-avocado-a-week-may-lower-heart-disease-risk/)\\n### Late-night eating\\nand its role in depression and mood\\n![A person looking into a fridge at night](https://www.harvard.edu/wp-content/uploads/2024/11/AdobeStock_254026165.jpeg?w=375&h=281&crop=1)[Late-night eating](https://hms.harvard.edu/news/daytime-eating-mental-health)\\nHome cooking\\n## Chefs in our community\\n[Explore some of the amazing dishes from chefs all over Harvard](https://www.harvard.edu/in-focus/food/recipes/)\\nMeet the chefs\\n![Joanne Chang wears an apron in a kitchen](https://www.harvard.edu/wp-content/uploads/2024/11/020320_Chang_Joanne_09b.jpg?w=731)\\nExpand Image\\nJoanne Chang\\nStephanie Mitchell/Harvard Staff Photographer\\n"Pastry Love," a cookbook by Harvard alum and Flour Bakery owner Joanne Chang, honors some of her decadent and delicious favorites.\\n[Explore one of Joanne's recipes](https://www.harvard.edu/in-focus/food/recipes#joanne)\\n![A student wearing an apron stands in a kitchen with a cutting board of purple cabbage in front of him](https://www.harvard.edu/wp-content/uploads/2022/10/062629_Chef_006-e1675280860455.jpg?w=1200)\\nExpand Image\\nNick DiGiovanni\\nKris Snibbe/Harvard Staff Photographer\\nWhile at Harvard College, Nick DiGiovanni, who competed on MasterChef, created his own concentration in food and climate.\\n[Explore one of Nick's recipe](https://www.harvard.edu/in-focus/food/recipes#nick)\\n![Julia Child pours hot syrup over a Croquembouche in a kitchen](https://www.harvard.edu/wp-content/uploads/2022/10/Screen-Shot-2022-10-25-at-8.49.09-AM.png?w=634)\\nExpand Image\\nJulia Child\\nPaul Child\\nJulia Child’s television series “The French Chef,” which first aired in 1963, launched a revolution in cooking and eating in the United States. Her papers are part of the collection at the Schlesinger Library.\\n[Explore one of Julia's recipes](https://www.harvard.edu/in-focus/food/recipes#julia)\\n![A woman stands in a kitchen](https://www.harvard.edu/wp-content/uploads/2022/10/Nisha_Portrait_2500-copy-e1675280779442.jpg?w=1500)\\nExpand Image\\nNisha Vora\\nPhoto by Michael Marquand\\nLaw School grad Nisha Vora left the legal life for vegan cooking.\\n[Explore one of Nisha's recipes](https://www.harvard.edu/in-focus/food/recipes#nisha)\\n![Headshot of chef Ludger Wessels against a brick wall](https://www.harvard.edu/wp-content/uploads/2022/10/LudgerWessels-e1675281023551.jpg?w=1600)\\nExpand Image\\nLudger Wessels\\nChef Wessels, a six-time American Culinary Federation competition award winner, is executive chef at Harvard University Dining Services. His specialties include regional German and French cuisine.\\n[Explore one of Ludger's recipes](https://www.harvard.edu/in-focus/food/recipes#ludger)\\n## Further into food\\n### The Nutrition Source\\nA leading authority providing science-based guidance on food and nutrition. Explore articles, recipes, and tools.\\nExplore the resources\\n[Explore the resources](https://nutritionsource.hsph.harvard.edu/)\\n### Free cooking courses\\nLearn about fermentation or explore the chemistry and physics of cooking in these free online courses.\\nSign up for a free cooking course\\n[Sign up for a free cooking course](https://pll.harvard.edu/catalog?keywords=cooking)\\n### The sacredness of food\\nThe Harvard Divinity School explores the many ways that food overlaps with religions around the world.\\nLearn more from the Divinity School\\n[Learn more from the Divinity School](https://news-archive.hds.harvard.edu/news/2016/11/22/sacredness-food)\\n## Sustenance solutions\\nThe Harvard community is exploring solutions for the biggest problems facing farmers, consumers, and the planet.\\n### The need for food\\nReserachers at Harvard Chan School found an[increase in food insufficiency](https://www.hsph.harvard.edu/news/press-releases/)following the decrease in SNAP benefits; Graduate School of Design[students looked at food insecurity solutions in Mississippi](https://news.harvard.edu/gazette/story/newsplus/designing-food-security-in-rural-mississippi/), ranked as America’s hungriest state; Harvard alum[Leah Gose worked to improve how communities respond to hunger](https://gsas.harvard.edu/news/hungry-change), starting with her hometown of Atlanta; and Historian Joyce Chaplin explored[the long history of who gets to eat](https://hmsc.harvard.edu/2020/07/01/food-and-status-a-discussion-with-historian-joyce-chaplin/).\\n### The risks for food\\nResearch shows that changes to seasonal rainfall patterns are[accelerating food shortages](https://salatainstitute.harvard.edu/interview-unpredictable-rains-erode-food-security-gains/)across the globe; Harvard alum Marcos Barrozo worked to[lower emissions from Brazil’s cattle industry](https://gsas.harvard.edu/news/beef-climate-change); the Wyss Institute is exploring medical technology to[help the peach industry fight brown rot](https://wyss.harvard.edu/media-post/arbor-armor-could-fcmbl-save-the-peach-industry/?q=arbor); and the Schools of Engineering and Public Health are teaming up to[reduce food waste and foodborne illness](https://seas.harvard.edu/news/2022/06/food-packaging-system-reduces-health-risks-and-saves-food)in a novel way.\\n### The future of food\\nGraduate School alum John Ahrens cultivated[lab-grown fish fillets](https://gsas.harvard.edu/news/reel-hope-ocean-conservation)to address the global demand for seafood; Wyss Institute’s Luke MacQueen spent years creating[an animal-free meat that tastes and feels like the real thing](https://wyss.harvard.edu/news/from-montreal-to-a-menu-near-you/); the founders of Circe created the[world’s first gas fermentation-derived chocolate](https://otd.harvard.edu/news/circe-bioscience-licenses-technology-to-decarbonize-industry-with-microbes-developed-at-wyss-institute-at-harvard-university/)in response to the worldwide shortage of cocoa; and David Weitz’s lab is exploring[converting food waste into sugar alternatives](https://salatainstitute.harvard.edu/salata-institute-funds-five-new-climate-research-projects/).\\n## Food at Harvard\\n![](https://www.harvard.edu/wp-content/uploads/2024/10/082922_Global_158-1-1168x934-1.jpg?w=500&h=500&crop=1)\\n### Healthful and Sustainable Food\\nHarvard's Office for Sustainability pledges to reduce greenhouse gas emissions from food by 25% by 2030 as part of the Coolfood Pledge.\\n[Learn more about Harvard's sustainable and healthful food](https://sustainable.harvard.edu/our-plan/how-we-operate/food/)\\n![](https://www.harvard.edu/wp-content/uploads/2024/10/Family-Meals-before-and-after-768x639b.jpg?w=500&h=500&crop=1)\\n### Food Donation Program\\nIn 2014, Harvard University Dining Services launched an effort to address chronic hunger among its neighbors in Cambridge and Boston by partnering with the local nonprofit Food for Free to donate nearly 2,000 nutritious meals each week to families in need.\\n[Learn more about the program](https://dining.harvard.edu/about-huds/sustainability/food-donation-program)\\n![](https://www.harvard.edu/wp-content/uploads/2024/10/Annenberg_0.jpeg?w=500&h=500&crop=1)\\n### Finding home through food\\nA Harvard College first-year student explains what the food is like at Harvard, and how to cure food-homesickness.\\n[Learn more from Harvard College student stories](https://college.harvard.edu/student-life/student-stories/finding-home-through-food)\\n![](https://www.harvard.edu/wp-content/uploads/2024/10/MG_5399-1-1024x683-1.jpg?w=500&h=500&crop=1)\\n### Harvard Food Systems Initiative\\nLed by Harvard University Dining Services in collaboration with Harvard Faculty and practitioners in the field, Harvard Food Systems Initiative is an educational program to inspire elevated thinking and change to shape future food systems leaders for a more sustainable future.\\n[Learn more about the initiative](https://hfsi.harvard.edu/)\\n![](https://www.harvard.edu/wp-content/uploads/2024/10/img-2670_1-1.jpg?w=500&h=500&crop=1)\\n### The Harvard Square food scene\\nA Harvard College student and food connoisseur shares the best places to grab a bite in the square.\\n[Learn more from this Harvard College student story](https://college.harvard.edu/student-life/student-stories/harvard-square-food-scene)\\n![](https://www.harvard.edu/wp-content/uploads/2024/10/061824_Farmers_Market_Opening_052.jpg?w=500&h=500&crop=1)\\n### Food Literacy Project\\nThe Food Literacy Project hosts a fellowship program for students to help cultivate an understanding of food from the ground up. Education focuses on sustainability, nutrition, food preparation and community.\\n[Learn more about the program](https://dining.harvard.edu/food-literacy-project)\\n![](https://www.harvard.edu/wp-content/uploads/2024/11/LEARNINGS-REPORT-PRINT-AUG30LR_24_25.jpg?w=624&h=624&crop=1)\\n### Dining Services Learnings Report\\nLearn how Harvard's Dining Services team has created places and experiences that are formative to how Harvard lives on in the memories of our students.\\n[Explore the report](https://dining.harvard.edu/about-huds/learnings-reports)\\nExplore the food and nutrition organizations, exhibits, and collections at Harvard.\\n[Food Law and Policy Clinic](https://hls.harvard.edu/clinics/in-house-clinics/food-law-and-policy-clinic/)\\n[The Nutrition Source](https://www.hsph.harvard.edu/nutritionsource/)\\n[Harvard University Dining Services](https://dining.harvard.edu/)\\n[Harvard Food Systems Initiative (HFSI)](https://hfsi.harvard.edu/)\\n[Healthy Eating Plate](https://www.hsph.harvard.edu/nutritionsource/healthy-eating-plate/)\\n[Historic Cookbooks at Schlesinger Library\\n](https://guides.library.harvard.edu/schlesinger/historic_cookbooks)\\n[Food Literacy Project](https://dining.harvard.edu/food-literacy-project/flp-programs-events)\\n[Harvard Farmers’ Market](https://dining.harvard.edu/farmers-market)\\n[Sustainable Food Systems Graduate Certificate](https://extension.harvard.edu/academics/programs/sustainable-food-systems-graduate-certificate/)\\n[Prevention Research Center on Nutrition and Physical Activity at the Harvard Chan School (HPRC)](https://www.hsph.harvard.edu/prc/)\\n[Sustainable and Healthful Food Standards](https://green.harvard.edu/topics/food)\\nYOU MAY ALSO LIKE\\n## Related In Focus topics\\n* [Sleep](https://www.harvard.edu/in-focus/sleep/)\\n* [Healthy living](https://www.harvard.edu/in-focus/healthy-living/)\\n* [Mindfulness & Meditation](https://www.harvard.edu/in-focus/mindfulness-meditation/)\\n## Security & Brand\\n## Website\\n## Get In Touch\\nCopyright Š2024 The President and Fellows of Harvard College\\n[![Harvard University](https://www.harvard.edu/wp-content/themes/core/assets/img/theme/branding-assets/footer-logo.svg)](https://www.harvard.edu/)\\n* [Instagram![Instagram](https://www.harvard.edu/wp-content/uploads/2023/11/Instagram-1.png)](https://www.instagram.com/harvard/)\\n* [TikTok![TikTok](https://www.harvard.edu/wp-content/uploads/2023/11/tiktok-1.png)](https://www.tiktok.com/@harvard)\\n* [LinkedIn![LinkedIn](https://www.harvard.edu/wp-content/uploads/2023/11/Linkedin-1.png)](https://www.linkedin.com/school/harvard-university)\\n* [Facebook![Facebook](https://www.harvard.edu/wp-content/uploads/2023/11/FB3.png)](https://www.facebook.com/Harvard/)\\n* [YouTube![YouTube](https://www.harvard.edu/wp-content/uploads/2023/11/youtube-1.png)](https://www.youtube.com/harvard)',\n", + " 'type': 'Document'}]}" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "transitions = client.executions.transitions.list(execution_id=execution.id).items\n", + "\n", + "transitions[1].output" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "ai", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/cookbooks/01-Website_Crawler_using_Spider.py b/cookbooks/01-website-crawler.py similarity index 100% rename from cookbooks/01-Website_Crawler_using_Spider.py rename to cookbooks/01-website-crawler.py diff --git a/cookbooks/02-Sarcastic_News_Headline_Generator.ipynb b/cookbooks/02-Sarcastic_News_Headline_Generator.ipynb deleted file mode 100644 index fb7957a5f..000000000 --- a/cookbooks/02-Sarcastic_News_Headline_Generator.ipynb +++ /dev/null @@ -1,357 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"julep\"\n", - "
\n", - "\n", - "## Task Definition: Sarcastic News Headline Generator using Brave Search Integration\n", - "\n", - "### Overview\n", - "\n", - "This task generates a sarcastic news headline on a user-provided topic. It utilizes web search to gather context and information about the topic, then uses this data to create a headline with a sarcastic tone. \n", - "\n", - "### Task Flow\n", - "\n", - "1. **Input**: \n", - " - User provides a topic for the sarcastic news headline (e.g., \"technology\" or \"politics\").\n", - "\n", - "2. **Web Search using Bravesearch Integration**: \n", - " - Conducts a search to find information about the topic, focusing on humorous or quirky content.\n", - " - Gathers relevant context and amusing details for headline generation.\n", - "\n", - "3. **Headline Creation**: \n", - " - Generates a sarcastic news headline based on the topic and gathered information.\n", - " - Combines factual or common perceptions with humor and sarcasm.\n", - " \n", - "4. **Output**: \n", - " - Produces a sarcastic, witty headline on the given topic.\n", - " - Can be used for entertainment or as a creative writing prompt.\n", - "\n", - "### Key Features\n", - "\n", - "- Leverages web search to enhance contextual relevance of sarcastic content.\n", - "- Combines real-world information with humorous twists for engaging headlines.\n", - "- Adaptable to various topics, allowing for diverse and creative outputs.\n", - "\n", - "```plaintext\n", - "+----------+ +------------+ +------------+ +-----------+\n", - "| User | | Brave | | Agent | | Sarcastic |\n", - "| Input | --> | Search | --> | Processing | --> | Headline |\n", - "| (Topic) | | | | | | Output |\n", - "+----------+ +------------+ +------------+ +-----------+\n", - " | | | |\n", - " | | | |\n", - " v v v v\n", - " \"politics\" Find funny Generate witty \"Area Man Still\n", - " content headline Believes in Democracy\"\n", - "\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Implementation\n", - "\n", - "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", - "\n", - "\n", - " \"Open\n", - "\n", - "\n", - "### Additional Information\n", - "\n", - "For more details about the task or if you have any questions, please don't hesitate to contact the author:\n", - "\n", - "**Author:** Julep AI \n", - "**Contact:** [hey@julep.ai](mailto:hey@julep.ai) or Discord" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Installing the Julep Client" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "!pip install julep -U --quiet" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### NOTE:\n", - "\n", - "- UUIDs are generated for both the agent and task to uniquely identify them within the system.\n", - "- Once created, these UUIDs should remain unchanged for simplicity.\n", - "- Altering a UUID will result in the system treating it as a new agent or task.\n", - "- If a UUID is changed, the original agent or task will continue to exist in the system alongside the new one." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "# Global UUID is generated for agent and task\n", - "import uuid\n", - "\n", - "AGENT_UUID = uuid.uuid4()\n", - "TASK_UUID = uuid.uuid4() " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Creating Julep Client with the API Key" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "from julep import Client\n", - "\n", - "api_key = \"\" # Your API key here\n", - "\n", - "# Create a client\n", - "client = Client(api_key=api_key, environment=\"dev\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating an \"agent\"\n", - "\n", - "\n", - "Agent is the object to which LLM settings, like model, temperature along with tools are scoped to.\n", - "\n", - "To learn more about the agent, please refer to the [documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#agent)." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [], - "source": [ - "# Defining the agent\n", - "name = \"Jarvis\"\n", - "about = \"The original AI conscious the Iron Man.\"\n", - "default_settings = {\n", - " \"temperature\": 0.7,\n", - " \"top_p\": 1,\n", - " \"min_p\": 0.01,\n", - " \"presence_penalty\": 0,\n", - " \"frequency_penalty\": 0,\n", - " \"length_penalty\": 1.0,\n", - " \"max_tokens\": 150,\n", - "}\n", - "\n", - "\n", - "# Create the agent\n", - "agent = client.agents.create_or_update(\n", - " agent_id=AGENT_UUID,\n", - " name=name,\n", - " about=about,\n", - " model=\"gpt-4o\",\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Defining a Task\n", - "\n", - "Tasks in Julep are Github Actions style workflows that define long-running, multi-step actions. \n", - "You can use them to conduct complex actions by defining them step-by-step. They have access to all Julep integrations.\n", - "\n", - "To learn more about tasks, visit [Julep documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#task)." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [], - "source": [ - "import yaml" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "More on how to define a task can be found [here](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md)." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [], - "source": [ - "# defining the task definition\n", - "task_def = yaml.safe_load(\"\"\"\n", - "name: Sarcasm Headline Generator\n", - "\n", - "tools:\n", - "- name: brave_search\n", - " type: integration\n", - " integration:\n", - " provider: brave\n", - " setup:\n", - " api_key: \"YOU_API_KEY\"\n", - "\n", - "main:\n", - "- tool: brave_search\n", - " arguments:\n", - " query: \"_.topic + ' funny'\"\n", - "\n", - "- prompt:\n", - " - role: system\n", - " content: >-\n", - " write a sarcastic news headline on the topic of {{inputs[0].topic}}.\n", - " Here's some more info on this: {{_}}\n", - " unwrap: true\n", - "\n", - "\"\"\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creating/Updating a task." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": {}, - "outputs": [], - "source": [ - "# creating the task object\n", - "task = client.tasks.create_or_update(\n", - " task_id=TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **task_def\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating an Execution\n", - "\n", - "An execution is a single run of a task. It is a way to run a task with a specific set of inputs." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creates a execution worklow for the Task defined in the yaml file." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": {}, - "outputs": [], - "source": [ - "# creating an execution object\n", - "execution = client.executions.create(\n", - " task_id=TASK_UUID,\n", - " input={\n", - " \"topic\": \"elon musk\"\n", - " }\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# getting the execution details\n", - "execution = client.executions.get(execution.id)\n", - "#printing the output\n", - "execution.output" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Retrieves and lists all the steps of a defined task that have been executed up to that point in time. Unlike streaming, this function does not continuously monitor the execution; it only provides a snapshot of the steps completed so far without displaying real-time updates as the task progresses." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "client.executions.transitions.list(execution_id=execution.id).items" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Continuously monitor and stream the steps of a defined task. It retrieves and displays the transitions or execution steps of the task identified by execution.id in real-time, showing each step sequentially until the task is either completed or an error causes it to terminate." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "client.executions.transitions.stream(execution_id=execution.id)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "ai", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.11.5" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/cookbooks/02-sarcastic-news-headline-generator.ipynb b/cookbooks/02-sarcastic-news-headline-generator.ipynb new file mode 100644 index 000000000..1bd689087 --- /dev/null +++ b/cookbooks/02-sarcastic-news-headline-generator.ipynb @@ -0,0 +1,541 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + " \"julep\"\n", + "
\n", + "\n", + "## Task Definition: Sarcastic News Headline Generator using Brave Search Integration\n", + "\n", + "### Overview\n", + "\n", + "This task generates a sarcastic news headline on a user-provided topic. It utilizes web search to gather context and information about the topic, then uses this data to create a headline with a sarcastic tone. \n", + "\n", + "### Task Flow\n", + "\n", + "1. **Input**: \n", + " - User provides a topic for the sarcastic news headline (e.g., \"technology\" or \"politics\").\n", + "\n", + "2. **Web Search using Bravesearch Integration**: \n", + " - Conducts a search to find information about the topic, focusing on humorous or quirky content.\n", + " - Gathers relevant context and amusing details for headline generation.\n", + "\n", + "3. **Headline Creation**: \n", + " - Generates a sarcastic news headline based on the topic and gathered information.\n", + " - Combines factual or common perceptions with humor and sarcasm.\n", + " \n", + "4. **Output**: \n", + " - Produces a sarcastic, witty headline on the given topic.\n", + " - Can be used for entertainment or as a creative writing prompt.\n", + "\n", + "### Key Features\n", + "\n", + "- Leverages web search to enhance contextual relevance of sarcastic content.\n", + "- Combines real-world information with humorous twists for engaging headlines.\n", + "- Adaptable to various topics, allowing for diverse and creative outputs.\n", + "\n", + "```plaintext\n", + "+----------+ +------------+ +------------+ +-----------+\n", + "| User | | Brave | | Agent | | Sarcastic |\n", + "| Input | --> | Search | --> | Processing | --> | Headline |\n", + "| (Topic) | | | | | | Output |\n", + "+----------+ +------------+ +------------+ +-----------+\n", + " | | | |\n", + " | | | |\n", + " v v v v\n", + " \"politics\" Find funny Generate witty \"Area Man Still\n", + " content headline Believes in Democracy\"\n", + "\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Implementation\n", + "\n", + "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", + "\n", + "\n", + " \"Open\n", + "\n", + "\n", + "### Additional Information\n", + "\n", + "For more details about the task or if you have any questions, please don't hesitate to contact the author:\n", + "\n", + "**Author:** Julep AI \n", + "**Contact:** [hey@julep.ai](mailto:hey@julep.ai) or Discord" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Installing the Julep Client" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "!pip install --upgrade julep --quiet" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### NOTE:\n", + "\n", + "- UUIDs are generated for both the agent and task to uniquely identify them within the system.\n", + "- Once created, these UUIDs should remain unchanged for simplicity.\n", + "- Altering a UUID will result in the system treating it as a new agent or task.\n", + "- If a UUID is changed, the original agent or task will continue to exist in the system alongside the new one." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "# Global UUID is generated for agent and task\n", + "import uuid\n", + "\n", + "AGENT_UUID = uuid.uuid4()\n", + "TASK_UUID = uuid.uuid4() " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Creating Julep Client with the API Key" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "from julep import Client\n", + "import os\n", + "\n", + "api_key = os.getenv(\"JULEP_API_KEY\")\n", + "\n", + "# Create a client\n", + "client = Client(api_key=api_key, environment=\"dev\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an \"agent\"\n", + "\n", + "\n", + "Agent is the object to which LLM settings, like model, temperature along with tools are scoped to.\n", + "\n", + "To learn more about the agent, please refer to the [documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#agent)." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "# Defining the agent\n", + "name = \"Chad\"\n", + "about = \"Sarcastic news headline reporter.\"\n", + "default_settings = {\n", + " \"temperature\": 0.7,\n", + " \"top_p\": 1,\n", + " \"min_p\": 0.01,\n", + " \"presence_penalty\": 0,\n", + " \"frequency_penalty\": 0,\n", + " \"length_penalty\": 1.0,\n", + " \"max_tokens\": 150,\n", + "}\n", + "\n", + "\n", + "# Create the agent\n", + "agent = client.agents.create_or_update(\n", + " agent_id=AGENT_UUID,\n", + " name=name,\n", + " about=about,\n", + " model=\"claude-3.5-sonnet\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining a Task\n", + "\n", + "Tasks in Julep are Github Actions style workflows that define long-running, multi-step actions.\n", + "\n", + "You can use them to conduct complex actions by defining them step-by-step.\n", + "\n", + "To learn more about tasks, please refer to the `Tasks` section in [Julep Concepts](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#tasks)." + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": {}, + "outputs": [], + "source": [ + "import yaml\n", + "\n", + "brave_api_key = os.getenv(\"BRAVE_API_KEY\")\n", + "\n", + "# Define the task\n", + "task_def = yaml.safe_load(f\"\"\"\n", + "name: Sarcasm Headline Generator\n", + "\n", + "tools:\n", + "- name: brave_search\n", + " type: integration\n", + " integration:\n", + " provider: brave\n", + " setup:\n", + " api_key: \"{brave_api_key}\"\n", + "\n", + "main:\n", + "- tool: brave_search\n", + " arguments:\n", + " query: \"_.topic + ' funny news'\"\n", + "\n", + "- evaluate:\n", + " search_results: |-\n", + " [\n", + " {{\n", + " 'snippet': r['snippet'],\n", + " 'title': r['title']\n", + " }}\n", + " for r in _['result']\n", + " ]\n", + " \n", + "- prompt:\n", + " - role: system\n", + " content: >-\n", + " You are {{{{agent.about}}}}.\n", + " The user will send you a topic and search results for that topic.\n", + " Your goal is to write a sarcastic news headlines based on that topic and search results.\n", + " - role: user\n", + " content: >-\n", + " My topic is: {{{{inputs[0].topic}}}}.\n", + " Here are the search results: {{{{_}}}}\n", + " unwrap: true\n", + "\n", + "\"\"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notes:\n", + "- The reason for using the quadruple curly braces `{{{{}}}}` for the jinja template is to avoid conflicts with the curly braces when using the `f` formatted strings in python. [More information here](https://stackoverflow.com/questions/64493332/jinja-templating-in-airflow-along-with-formatted-text)\n", + "- The `unwrap: True` in the prompt step is used to unwrap the output of the prompt step (to unwrap the `choices[0].message.content` from the output of the model).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating/Updating a task." + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": {}, + "outputs": [], + "source": [ + "# creating the task object\n", + "task = client.tasks.create_or_update(\n", + " task_id=TASK_UUID,\n", + " agent_id=AGENT_UUID,\n", + " **task_def\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an Execution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "An execution is a single run of a task. It is a way to run a task with a specific set of inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": {}, + "outputs": [], + "source": [ + "# creating an execution object\n", + "execution = client.executions.create(\n", + " task_id=TASK_UUID,\n", + " input={\n", + " \"topic\": \"Elon Musk\"\n", + " }\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Checking execution details and output" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are multiple ways to get the execution details and the output:\n", + "\n", + "1. **Get Execution Details**: This method retrieves the details of the execution, including the output of the last transition that took place.\n", + "\n", + "2. **List Transitions**: This method lists all the task steps that have been executed up to this point in time, so the output of a successful execution will be the output of the last transition (first in the transition list as it is in reverse chronological order), which should have a type of `finish`.\n", + "\n", + "\n", + "Note: You need to wait for a few seconds for the execution to complete before you can get the final output, so feel free to run the following cells multiple times until you get the final output.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Based on these search results about Elon Musk's attempts at humor, I'll write some sarcastic headlines:\n", + "\n", + "1. \"Breaking: World's Richest Man Still Can't Buy a Sense of Humor, Studies Show\"\n", + "\n", + "2. \"Shocking: Billionaire's Joke Algorithm Malfunctions, Produces Only Cringe\"\n", + "\n", + "3. \"Tech Titan Discovers Comedy Is Harder Than Rocket Science; Mars Mission Suddenly Looks Easier\"\n", + "\n", + "4. \"EXCLUSIVE: Musk's Twitter Bio Updated to 'Chief Unfunny Officer' After Latest Failed Attempt at Humor\"\n", + "\n", + "5. \"Report: Man Worth $230 Billion Still Can't Afford Professional Comedy Writer\"\n", + "\n", + "6. \"Scientists Confirm: Musk's Jokes Have Lower Success Rate Than Tesla Cybertruck Windows\"\n", + "\n", + "7. \"Breaking: Social Media Platform Owner Becomes First Person to Ratio Himself With His Own Bad Jokes\"\n", + "\n", + "8. \"UPDATE: AI Refuses to Generate Fake Laughs for Billionaire's Twitter Jokes, Cites Ethical Concerns\"\n", + "\n", + "These headlines are crafted to playfully mock the recent news about Musk's attempts at humor and social media posts, particularly focusing on the apparent consensus that his jokes aren't landing as well as his rockets!\n" + ] + } + ], + "source": [ + "# Get execution details\n", + "execution = client.executions.get(execution.id)\n", + "# Print the output\n", + "print(execution.output)" + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Transition type: init\n", + "Transition output: {'topic': 'Elon Musk'}\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: {'result': [{'link': 'https://www.rollingstone.com/culture/culture-lists/elon-musks-unfunniest-jokes-2023-1234929823/', 'snippet': 'Somehow, it didn’t get funnier the more he used it. If Zuck my 👅 really wants a lesson in why there are weight categories in fighting so badly, I could just head over to his house next week and teach him a lesson he won’t soon forget— Elon Musk (@elonmusk) August 11, 2023https://p...', 'title': 'Elon Musk’s 9 Unfunniest Jokes of 2023'}, {'link': 'https://www.beaumontenterprise.com/culture/article/elon-musk-funny-19742906.php', 'snippet': 'Your Beaumont local news source plus the latest in entertainment, sports and Jefferson County Texas news.', 'title': \"Elon Musk's unfunny acronyms are getting exhausting\"}, {'link': 'https://www.youtube.com/watch?v=EbxBv6mjRvY', 'snippet': 'A genius in business, technology and humor!Sometimes Elon Musk will go the extra mile to get a laugh. Here’s a collection of his funniest moments.', 'title': 'Elon Musk Funniest Moments - YouTube'}]}\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: {'search_results': [{'snippet': 'Somehow, it didn’t get funnier the more he used it. If Zuck my 👅 really wants a lesson in why there are weight categories in fighting so badly, I could just head over to his house next week and teach him a lesson he won’t soon forget— Elon Musk (@elonmusk) August 11, 2023https://p...', 'title': 'Elon Musk’s 9 Unfunniest Jokes of 2023'}, {'snippet': 'Your Beaumont local news source plus the latest in entertainment, sports and Jefferson County Texas news.', 'title': \"Elon Musk's unfunny acronyms are getting exhausting\"}, {'snippet': 'A genius in business, technology and humor!Sometimes Elon Musk will go the extra mile to get a laugh. Here’s a collection of his funniest moments.', 'title': 'Elon Musk Funniest Moments - YouTube'}]}\n", + "--------------------------------------------------\n", + "Transition type: finish\n", + "Transition output: Based on these search results about Elon Musk's attempts at humor, I'll write some sarcastic headlines:\n", + "\n", + "1. \"Breaking: World's Richest Man Still Can't Buy a Sense of Humor, Studies Show\"\n", + "\n", + "2. \"Shocking: Billionaire's Joke Algorithm Malfunctions, Produces Only Cringe\"\n", + "\n", + "3. \"Tech Titan Discovers Comedy Is Harder Than Rocket Science; Mars Mission Suddenly Looks Easier\"\n", + "\n", + "4. \"EXCLUSIVE: Musk's Twitter Bio Updated to 'Chief Unfunny Officer' After Latest Failed Attempt at Humor\"\n", + "\n", + "5. \"Report: Man Worth $230 Billion Still Can't Afford Professional Comedy Writer\"\n", + "\n", + "6. \"Scientists Confirm: Musk's Jokes Have Lower Success Rate Than Tesla Cybertruck Windows\"\n", + "\n", + "7. \"Breaking: Social Media Platform Owner Becomes First Person to Ratio Himself With His Own Bad Jokes\"\n", + "\n", + "8. \"UPDATE: AI Refuses to Generate Fake Laughs for Billionaire's Twitter Jokes, Cites Ethical Concerns\"\n", + "\n", + "These headlines are crafted to playfully mock the recent news about Musk's attempts at humor and social media posts, particularly focusing on the apparent consensus that his jokes aren't landing as well as his rockets!\n", + "--------------------------------------------------\n" + ] + } + ], + "source": [ + "# Lists all the task steps that have been executed up to this point in time\n", + "transitions = client.executions.transitions.list(execution_id=execution.id).items\n", + "\n", + "# Transitions are retreived in reverse chronological order\n", + "for transition in reversed(transitions):\n", + " print(\"Transition type: \", transition.type)\n", + " print(\"Transition output: \", transition.output)\n", + " print(\"-\"*50)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Running the same task with a different topic" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will use the same code to run the same task, but with a different topic" + ] + }, + { + "cell_type": "code", + "execution_count": 74, + "metadata": {}, + "outputs": [], + "source": [ + "execution = client.executions.create(\n", + " task_id=TASK_UUID,\n", + " input={\n", + " \"topic\": \"Tottenham Hotspur\"\n", + " }\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 80, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Based on the search results about Tottenham Hotspur, here are some sarcastic headlines:\n", + "\n", + "1. \"BREAKING: Tottenham Somehow Manages to Draw a Match They Haven't Even Played Yet\"\n", + "\n", + "2. \"SHOCKING: Spurs Fan Found Who Still Has Hope for This Season, Doctors Baffled\"\n", + "\n", + "3. \"EXCLUSIVE: Tottenham's Trophy Cabinet Files Complaint for Workplace Neglect, Cites 'Years of Emptiness'\"\n", + "\n", + "4. \"REPORT: Tottenham Players Perfect the Art of 'Almost Winning' - Declare It Their New Club Strategy\"\n", + "\n", + "5. \"URGENT: Scientists Confirm Supporting Tottenham May Be Leading Cause of Premature Gray Hair\"\n", + "\n", + "6. \"DEVELOPMENT: Spurs Consider Renaming Stadium to 'The Almost Champions Arena' to Better Reflect Club's Legacy\"\n", + "\n", + "7. \"INVESTIGATION: Local Man Claims He's Seen Tottenham Win Trophy - Experts Say It Was Just a Mirage\"\n", + "\n", + "8. \"STUDY: Tottenham Fans Develop Superhuman Ability to Handle Disappointment, Medical Community Amazed\"\n", + "\n", + "9. \"REVEALED: Club's 'To Do' List Found - 'Win Something' Written 362 Times in Increasingly Desperate Handwriting\"\n", + "\n", + "10. \"WEATHER ALERT: Forecast Predicts Flying Pigs Before Tottenham's Next Trophy\"\n", + "\n", + "These headlines playfully poke fun at Tottenham's notorious reputation for coming close but not quite achieving major trophies, while drawing from their current status as a prominent Premier League club with a dedicated fanbase.\n" + ] + } + ], + "source": [ + "execution = client.executions.get(execution.id)\n", + "print(execution.output)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note: you can get the output of the search step by accessing the corresponding transition's output from the transitions list.\n", + "\n", + "Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 82, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'search_results': [{'snippet': 'The latest Tottenham news, transfers, fixtures and more. Including Live blogs, pictures, video, podcasts, polls and indepth analysis from our dedicated Spurs writers.',\n", + " 'title': 'Tottenham Hotspur FC - latest news, pictures, video comment - Football.london'},\n", + " {'snippet': 'Latest Spurs news, transfer rumours, team news, fixtures and more from the Tottenham Hotspur Stadium. Breaking Tottenham rumours & news now, 24/7.',\n", + " 'title': 'Spurs News | Tottenham Transfer News - NewsNow'},\n", + " {'snippet': 'Latest official news and video from Tottenham Hotspur',\n", + " 'title': 'News | Tottenham Hotspur'}]}" + ] + }, + "execution_count": 82, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "transitions = client.executions.transitions.list(execution_id=execution.id).items\n", + "\n", + "transitions[1].output" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "ai", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/cookbooks/02-Sarcastic_News_Headline_Generator.py b/cookbooks/02-sarcastic-news-headline-generator.py similarity index 100% rename from cookbooks/02-Sarcastic_News_Headline_Generator.py rename to cookbooks/02-sarcastic-news-headline-generator.py diff --git a/cookbooks/03-SmartResearcher_With_WebSearch.ipynb b/cookbooks/03-SmartResearcher_With_WebSearch.ipynb deleted file mode 100644 index 9bb6436c4..000000000 --- a/cookbooks/03-SmartResearcher_With_WebSearch.ipynb +++ /dev/null @@ -1,395 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"julep\"\n", - "
\n", - "\n", - "## Task: Research Assistant with Web Search Integration\n", - "\n", - "### Overview\n", - "\n", - "This task is designed to conduct comprehensive research on multiple user-provided topics. It leverages web search capabilities to gather up-to-date information and generates relevant keywords for each topic, streamlining the research process through efficient tool integration and parallel processing.\n", - "\n", - "### Task Flow\n", - "\n", - "1. **User Input**\n", - " - User provides a list of research topics\n", - " - Each topic is processed individually\n", - "\n", - "2. **Web Search and Information Gathering**\n", - " - Utilizes BraveWeb to conduct searches for each topic\n", - " - Retrieves latest news and relevant information\n", - "\n", - "3. **Intelligent Analysis**\n", - " - System analyzes search results (HTML snippets)\n", - " - Generates Wikipedia keywords related to each topic\n", - " - AI assistant identifies most relevant keywords based on search content\n", - "\n", - "4. **Parallel Processing**\n", - " - Implements concurrent topic processing\n", - " - Enhances efficiency and reduces overall research time\n", - "\n", - "### Key Features\n", - "\n", - "- **Multi-topic Research**: Handles multiple research topics simultaneously\n", - "- **Up-to-date Information**: Utilizes web search to access current data\n", - "- **Keyword Generation**: Provides relevant Wikipedia keywords for each topic\n", - "- **AI-assisted Analysis**: Employs AI to identify and prioritize key information\n", - "- **Efficient Processing**: Leverages parallel processing for faster results\n", - "\n", - "### Output\n", - "\n", - "- Comprehensive list of relevant Wikipedia keywords for each input topic\n", - "- Curated, up-to-date information gathered from web searches\n", - "\n", - "This workflow provides a robust, efficient approach to in-depth topic exploration, combining the power of web search, AI analysis, and parallel processing.\n", - "\n", - "```plaintext\n", - "\n", - "+----------------+ +--------------------------+ +-----------------+ +------------------------+ +-------------------------+\n", - "| User Input | | Web Search & Information | | Intelligent | | Parallel Processing | | Output Stage |\n", - "|(List of Topics)| --> | Gathering (BraveWeb) | --> | Analysis | --> | (Concurrent Execution) | --> | Summarized Research |\n", - "| | | | | | | | | (Final Report) |\n", - "+----------------+ +--------------------------+ +-----------------+ +------------------------+ +-------------------------+\n", - " | | | | |\n", - " | | | | |\n", - " v v v v v\n", - " Topic 1, Topic 2, ... Retrieve HTML snippets Extract Wikipedia Process multiple Compile summary and \n", - " Each topic processed from search results keywords from HTML topics concurrently present most relevant \n", - " individually. for each topic. snippets, analyze for faster results. findings per topic.\n", - " relevance.\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Implementation\n", - "\n", - "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", - "\n", - "\n", - " \"Open\n", - "\n", - "\n", - "### Additional Information\n", - "\n", - "For more details about the task or if you have any questions, please don't hesitate to contact the author:\n", - "\n", - "**Author:** Julep AI \n", - "**Contact:** [hey@julep.ai](mailto:hey@julep.ai) or Discord" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Installing the Julep Client" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "!pip install julep -U --quiet" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### NOTE:\n", - "\n", - "- UUIDs are generated for both the agent and task to uniquely identify them within the system.\n", - "- Once created, these UUIDs should remain unchanged for simplicity.\n", - "- Altering a UUID will result in the system treating it as a new agent or task.\n", - "- If a UUID is changed, the original agent or task will continue to exist in the system alongside the new one." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "# Global UUID is generated for agent and task\n", - "import uuid\n", - "\n", - "AGENT_UUID = uuid.uuid4()\n", - "TASK_UUID = uuid.uuid4()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Creating Julep Client with the API Key" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "from julep import Client\n", - "\n", - "api_key = \"\" # Your API key here\n", - "\n", - "# Create a client\n", - "client = Client(api_key=api_key, environment=\"dev\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating an \"agent\"\n", - "\n", - "\n", - "Agent is the object to which LLM settings, like model, temperature along with tools are scoped to.\n", - "\n", - "To learn more about the agent, please refer to the [documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#agent)." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "# Defining the agent\n", - "name = \"Jarvis\"\n", - "about = \"The original AI conscious the Iron Man.\"\n", - "default_settings = {\n", - " \"temperature\": 0.7,\n", - " \"top_p\": 1,\n", - " \"min_p\": 0.01,\n", - " \"presence_penalty\": 0,\n", - " \"frequency_penalty\": 0,\n", - " \"length_penalty\": 1.0,\n", - " \"max_tokens\": 150,\n", - "}\n", - "\n", - "\n", - "# Create the agent\n", - "agent = client.agents.create_or_update(\n", - " agent_id=AGENT_UUID,\n", - " name=name,\n", - " about=about,\n", - " model=\"gpt-4o\",\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Defining a Task\n", - "\n", - "Tasks in Julep are Github Actions style workflows that define long-running, multi-step actions. \n", - "You can use them to conduct complex actions by defining them step-by-step. They have access to all Julep integrations.\n", - "\n", - "To learn more about tasks, visit [Julep documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#task)." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "import yaml" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "More on how to define a task can be found [here](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md)." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "task_def= yaml.safe_load(\"\"\"\n", - "name: Research Assistant to find Wikipedia Keywords\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " topics:\n", - " type: array\n", - " items:\n", - " type: string\n", - " description: The topics to search for.\n", - "\n", - "tools:\n", - "- name: brave_search\n", - " type: integration\n", - " integration:\n", - " provider: brave\n", - " setup:\n", - " api_key: \"YOUR_API_KEY\"\n", - "\n", - "main:\n", - "- over: _.topics\n", - " map:\n", - " tool: brave_search\n", - " arguments:\n", - " query: \"'the latest news about ' + _\"\n", - "\n", - "- over: _\n", - " parallelism: 2\n", - " map:\n", - " prompt:\n", - " - role: system\n", - " content: >-\n", - " You are a research assistant.\n", - " I need you to do in-depth research on topics trending in the news currently.\n", - " Based on the following latest html news snippet, come up with a list of wikipedia keywords to search:\n", - " \"{{_}}\"\n", - " Your response should be a list of keywords, separated by commas. Do not add any other text.\n", - " Example: `KEYWORDS: keyword1, keyword2, keyword3`\n", - "\n", - " unwrap: true\n", - "\"\"\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creating/Updating a task." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [], - "source": [ - "# creating the task object\n", - "task = client.tasks.create_or_update(\n", - " task_id=TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **task_def\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating an Execution\n", - "\n", - "An execution is a single run of a task. It is a way to run a task with a specific set of inputs." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creates a execution worklow for the Task defined in the yaml file." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [], - "source": [ - "execution= client.executions.create(\n", - " task_id=task.id,\n", - " input={\n", - " \"topics\": [\"Burger King Cup on the Ground Behind a Wendy’s\",\"Forbidden Chemical X\",\"Finger Bracelets\",\"Amusing Notions\"]\n", - " }\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "execution.id" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": {}, - "outputs": [], - "source": [ - "# getting the execution details\n", - "execution = client.executions.get(execution.id)\n", - "#printing the outpu\n", - "execution.output" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Retrieves and lists all the steps of a defined task that have been executed up to that point in time. Unlike streaming, this function does not continuously monitor the execution; it only provides a snapshot of the steps completed so far without displaying real-time updates as the task progresses." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "client.executions.transitions.list(execution_id=execution.id).items" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Continuously monitor and stream the steps of a defined task. It retrieves and displays the transitions or execution steps of the task identified by execution.id in real-time, showing each step sequentially until the task is either completed or an error causes it to terminate." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "client.executions.transitions.stream(execution_id=execution.id)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "ai", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.4" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/cookbooks/03-SmartResearcher_With_WebSearch.py b/cookbooks/03-SmartResearcher_With_WebSearch.py deleted file mode 100644 index 6b0b210fb..000000000 --- a/cookbooks/03-SmartResearcher_With_WebSearch.py +++ /dev/null @@ -1,110 +0,0 @@ -import uuid -from julep import Client -import yaml, time - -# Global UUID is generated for agent and task -AGENT_UUID = uuid.uuid4() -TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an "agent" -name = "Jarvis" -about = "The original AI conscious the Iron Man." -default_settings = { - "temperature": 0.7, - "top_p": 1, - "min_p": 0.01, - "presence_penalty": 0, - "frequency_penalty": 0, - "length_penalty": 1.0, - "max_tokens": 150, -} - -# Create the agent -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name=name, - about=about, - model="gpt-4o", -) - -# Defining a Task -task_def = yaml.safe_load(""" -name: Research Assistant to find Wikipedia Keywords - -input_schema: - type: object - properties: - topics: - type: array - items: - type: string - description: The topics to search for. - -tools: -- name: brave_search - type: integration - integration: - provider: brave - setup: - api_key: "YOUR_API_KEY" - -main: -- over: _.topics - map: - tool: brave_search - arguments: - query: "'the latest news about ' + _" - -- over: _ - parallelism: 2 - map: - prompt: - - role: system - content: >- - You are a research assistant. - I need you to do in-depth research on topics trending in the news currently. - Based on the following latest html news snippet, come up with a list of wikipedia keywords to search: - "{{_}}" - Your response should be a list of keywords, separated by commas. Do not add any other text. - Example: `KEYWORDS: keyword1, keyword2, keyword3` - - unwrap: true -""") - -# Creating/Updating a task -task = client.tasks.create_or_update( - task_id=TASK_UUID, - agent_id=AGENT_UUID, - **task_def -) - -# Creating an Execution -execution = client.executions.create( - task_id=task.id, - input={ - "topics": ["Burger King Cup on the Ground Behind a Wendy's", "Forbidden Chemical X", "Finger Bracelets", "Amusing Notions"] - } -) - -print(execution.id) - -# Wait for the execution to complete -time.sleep(10) - -# Getting the execution details -execution = client.executions.get(execution.id) -print(execution.output) - -# Listing all the steps of a defined task -transitions = client.executions.transitions.list(execution_id=execution.id).items -print("Execution Steps:") -for transition in transitions: - print(transition) - -# Stream the steps of the defined task -print("Streaming execution transitions:") -print(client.executions.transitions.stream(execution_id=execution.id)) \ No newline at end of file diff --git a/cookbooks/03-trip-planning-assistant.ipynb b/cookbooks/03-trip-planning-assistant.ipynb new file mode 100644 index 000000000..380822ae2 --- /dev/null +++ b/cookbooks/03-trip-planning-assistant.ipynb @@ -0,0 +1,1044 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + " \"julep\"\n", + "
\n", + "\n", + "## Task: Travel Itinerary Assistant\n", + "\n", + "### Overview\n", + "\n", + "The Travel Itinerary Assistant helps users plan a travel itinerary that takes into account **current weather conditions** and **local tourist attractions**. By integrating data from Wikipedia for tourist attractions and using a weather API for real-time weather updates, the system provides a comprehensive travel plan tailored to each location. The generated itinerary suggests appropriate activities based on the weather, enhancing the overall travel experience.\n", + "\n", + "### Task Flow\n", + "\n", + "1. **User Input**\n", + " - User provides a list of desired travel locations.\n", + " - Each location is processed individually to gather the required data.\n", + "\n", + "2. **Weather Data Retrieval**\n", + " - Fetch current weather data for each location using a weather API.\n", + " - Extract relevant weather details, such as temperature, weather condition, and recommendations.\n", + "\n", + "3. **Tourist Attractions Lookup**\n", + " - Use Wikipedia to search for the top tourist attractions for each location.\n", + " - The query format used is: `\" tourist attractions\"`.\n", + " - Retrieve and compile a list of popular tourist spots and landmarks.\n", + "\n", + "4. **Data Evaluation and Integration**\n", + " - Combine weather data and tourist attractions into a unified list for each location.\n", + " - Format the data into a structured tuple: `(location, weather, attractions)`.\n", + "\n", + "5. **Itinerary Generation**\n", + " - Create a detailed travel itinerary based on:\n", + " - Current weather conditions (e.g., sunny, rainy, cloudy).\n", + " - Top tourist attractions for each location.\n", + " - Suggested activities categorized as indoor or outdoor based on weather.\n", + "\n", + "### Key Features\n", + "\n", + "- **Multi-location Travel Planning**: Handles multiple destinations simultaneously, offering a consolidated travel plan.\n", + "- **Real-time Weather Data**: Leverages weather APIs to provide up-to-date weather conditions.\n", + "- **Tourist Attraction Discovery**: Integrates Wikipedia to find and recommend popular attractions.\n", + "- **Intelligent Itinerary Suggestions**: Suggests indoor or outdoor activities based on the weather.\n", + "- **Comprehensive Itinerary Output**: Combines weather and tourist data into a user-friendly travel plan.\n", + "\n", + "### Output\n", + "\n", + "- A detailed travel itinerary for each location\n", + "- Curated, up-to-date information gathered from weather searches and Wikipedia\n", + "\n", + "```plaintext\n", + "\n", + "+----------------+ +--------------------------+ +--------------------------+ +------------------------------+ +-------------------------+\n", + "| User Input | | Weather Data Retrieval | | Tourist Attractions | | Data Evaluation & Integration| | Itinerary Generation |\n", + "| (List of | --> | (Weather API) | --> | Lookup (Wikipedia) | --> | (Combine Weather & | --> | (Generate Suggested |\n", + "| Locations) | | | | | | Attractions Data) | | Activities/Plan) |\n", + "+----------------+ +--------------------------+ +--------------------------+ +------------------------------+ +-------------------------+\n", + " | | | | |\n", + " | | | | |\n", + " v v v v v\n", + "Location 1, Location 2, ... Fetch weather for each Search Wikipedia for Combine weather data and Create itinerary with\n", + "Each location processed location individually, \" tourist tourist attractions into suggested activities\n", + "individually for extracting temp., attractions\", retrieve a structured tuple: based on weather and\n", + "weather data. conditions, & top spots. (location, weather, attractions.\n", + " recommendations. attractions).\n", + "```\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Implementation\n", + "\n", + "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", + "\n", + "\n", + " \"Open\n", + "\n", + "\n", + "### Additional Information\n", + "\n", + "For more details about the task or if you have any questions, please don't hesitate to contact the author:\n", + "\n", + "**Author:** Julep AI \n", + "**Contact:** [hey@julep.ai](mailto:hey@julep.ai) or Discord" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Installing the Julep Client" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "!pip install julep -U --quiet" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### NOTE:\n", + "\n", + "- UUIDs are generated for both the agent and task to uniquely identify them within the system.\n", + "- Once created, these UUIDs should remain unchanged for simplicity.\n", + "- Altering a UUID will result in the system treating it as a new agent or task.\n", + "- If a UUID is changed, the original agent or task will continue to exist in the system alongside the new one." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# Global UUID is generated for agent and task\n", + "import uuid\n", + "\n", + "AGENT_UUID = uuid.uuid4()\n", + "TASK_UUID = uuid.uuid4() " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Creating Julep Client with the API Key" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "from julep import Client\n", + "import os\n", + "\n", + "api_key = os.getenv(\"JULEP_API_KEY\")\n", + "\n", + "# Create a Julep client\n", + "client = Client(api_key=api_key, environment=\"dev\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an \"agent\"\n", + "\n", + "\n", + "Agent is the object to which LLM settings, like model, temperature along with tools are scoped to.\n", + "\n", + "To learn more about the agent, please refer to the [documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#agent)." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# Defining the agent\n", + "name = \"Jacob\"\n", + "about = \"a travel assistant that helps plan the perfect trip.\"\n", + "default_settings = {\n", + " \"temperature\": 0.7,\n", + " \"top_p\": 1,\n", + " \"min_p\": 0.01,\n", + " \"presence_penalty\": 0,\n", + " \"frequency_penalty\": 0,\n", + " \"length_penalty\": 1.0,\n", + " \"max_tokens\": 150,\n", + "}\n", + "\n", + "# Create the agent\n", + "agent = client.agents.create_or_update(\n", + " agent_id=AGENT_UUID,\n", + " name=name,\n", + " about=about,\n", + " model=\"gpt-4o\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining a Task\n", + "\n", + "Tasks in Julep are Github-Actions-style workflows that define long-running, multi-step actions.\n", + "\n", + "You can use them to conduct complex actions by defining them step-by-step.\n", + "\n", + "To learn more about tasks, please refer to the `Tasks` section in [Julep Concepts](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#tasks)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "import yaml\n", + "\n", + "openweathermap_api_key = os.getenv(\"OPENWEATHERMAP_API_KEY\")\n", + "brave_api_key = os.getenv(\"BRAVE_API_KEY\")\n", + "\n", + "# Defining the task\n", + "task_def = yaml.safe_load(f\"\"\"\n", + "name: Tourist Plan With Weather And Attractions\n", + "\n", + "input_schema:\n", + " type: object\n", + " properties:\n", + " locations:\n", + " type: array\n", + " items:\n", + " type: string\n", + " description: The locations to search for.\n", + "\n", + "tools:\n", + "- name: wikipedia\n", + " type: integration\n", + " integration:\n", + " provider: wikipedia\n", + "\n", + "- name: weather\n", + " type: integration\n", + " integration:\n", + " provider: weather\n", + " setup:\n", + " openweathermap_api_key: {openweathermap_api_key}\n", + "\n", + "- name: internet_search\n", + " type: integration\n", + " integration:\n", + " provider: brave\n", + " setup:\n", + " api_key: {brave_api_key}\n", + "\n", + "main:\n", + "- over: inputs[0].locations\n", + " map:\n", + " tool: weather\n", + " arguments:\n", + " location: _\n", + "\n", + "- over: inputs[0].locations\n", + " map:\n", + " tool: internet_search\n", + " arguments:\n", + " query: \"'tourist attractions in ' + _\"\n", + "\n", + "# Zip locations, weather, and attractions into a list of tuples [(location, weather, attractions)]\n", + "- evaluate:\n", + " zipped: |-\n", + " list(\n", + " zip(\n", + " inputs[0].locations,\n", + " [output['result'] for output in outputs[0]],\n", + " outputs[1]\n", + " )\n", + " )\n", + "\n", + "\n", + "- over: _['zipped']\n", + " parallelism: 3\n", + " # Inside the map step, each `_` represents the current element in the list\n", + " # which is a tuple of (location, weather, attractions)\n", + " map:\n", + " prompt:\n", + " - role: system\n", + " content: >-\n", + " You are {{{{agent.name}}}}. Your task is to create a detailed itinerary\n", + " for visiting tourist attractions in some locations.\n", + " The user will give you the following information for each location:\n", + "\n", + " - The location\n", + " - The current weather condition\n", + " - The top tourist attractions\n", + " - role: user\n", + " content: >-\n", + " Location: \"{{{{_[0]}}}}\"\n", + " Weather: \"{{{{_[1]}}}}\"\n", + " Attractions: \"{{{{_[2]}}}}\"\n", + " unwrap: true\n", + "\n", + "- evaluate:\n", + " final_plan: |-\n", + " '\\\\n---------------\\\\n'.join(activity for activity in _)\n", + "\"\"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notes:\n", + "- The reason for using the quadruple curly braces `{{{{}}}}` for the jinja template is to avoid conflicts with the curly braces when using the `f` formatted strings in python. [More information here](https://stackoverflow.com/questions/64493332/jinja-templating-in-airflow-along-with-formatted-text)\n", + "- The `unwrap: True` in the prompt step is used to unwrap the output of the prompt step (to unwrap the `choices[0].message.content` from the output of the model).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating/Updating a task" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "# creating the task object\n", + "task = client.tasks.create_or_update(\n", + " task_id=TASK_UUID,\n", + " agent_id=AGENT_UUID,\n", + " **task_def\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an Execution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "An execution is a single run of a task. It is a way to run a task with a specific set of inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Started an execution. Execution ID: 240c3e5e-a1a5-4d2c-aa24-ee86e876139e\n" + ] + } + ], + "source": [ + "execution = client.executions.create(\n", + " task_id=task.id,\n", + " input={\n", + " \"locations\": [\"New York\", \"London\", \"Paris\", \"Tokyo\", \"Sydney\"]\n", + " }\n", + ")\n", + "\n", + "print(\"Started an execution. Execution ID:\", execution.id)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Checking execution details and output" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are multiple ways to get the execution details and the output:\n", + "\n", + "1. **Get Execution Details**: This method retrieves the details of the execution, including the output of the last transition that took place.\n", + "\n", + "2. **List Transitions**: This method lists all the task steps that have been executed up to this point in time, so the output of a successful execution will be the output of the last transition (first in the transition list as it is in reverse chronological order), which should have a type of `finish`.\n", + "\n", + "\n", + "Note: You need to wait for a few seconds for the execution to complete before you can get the final output, so feel free to run the following cells multiple times until you get the final output.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'final_plan': \"Here's a detailed itinerary for visiting top tourist attractions in New York, considering the current weather conditions. \\n\\n### Day 1: Iconic Landmarks and Observation Decks\\n- **Morning:**\\n - **Top of the Rock Observation Deck:** Start your day with a visit to the Top of the Rock Observation Deck at Rockefeller Plaza. The panoramic 360-degree views from the 70th floor are a must-see. Dress warmly as it feels like 5.2°C outside, and it’s quite windy.\\n - **Link for more info:** [Tripadvisor - Top of the Rock](https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html)\\n\\n- **Afternoon:**\\n - **St. Patrick’s Cathedral:** Just a short walk from Rockefeller Plaza, explore the stunning architecture of St. Patrick’s Cathedral. The overcast skies will provide a dramatic backdrop for photos.\\n - **Fifth Avenue:** Enjoy a leisurely stroll along Fifth Avenue, visiting iconic stores and landmarks.\\n\\n- **Evening:**\\n - **Times Square:** Experience the vibrant lights and energy of Times Square. The overcast clouds might enhance the brightness of the neon lights.\\n\\n### Day 2: Culture and History\\n- **Morning:**\\n - **The Museum of Modern Art (MoMA):** Spend your morning exploring MoMA’s vast collection of modern and contemporary art. This indoor activity is perfect for a cloudy day.\\n\\n- **Afternoon:**\\n - **Central Park:** Head to Central Park for a refreshing walk. With 100% cloud cover, it's a great day to explore the park without the harsh sun. Consider visiting the Central Park Zoo or taking a guided tour.\\n\\n- **Evening:**\\n - **Broadway Show:** End your day with a Broadway show. It’s an ideal indoor activity to avoid the chilly weather outside. Book tickets in advance for popular shows.\\n\\n### Day 3: Historical and Educational\\n- **Morning:**\\n - **Statue of Liberty and Ellis Island:** Take a ferry to visit these iconic sites. Dress warmly for the ferry ride. The cloud cover will provide a unique perspective for photos.\\n\\n- **Afternoon:**\\n - **9/11 Memorial and Museum:** Spend your afternoon reflecting at the 9/11 Memorial and exploring the museum exhibits.\\n\\n- **Evening:**\\n - **Brooklyn Bridge:** Walk across the Brooklyn Bridge and enjoy the city skyline. With the wind speed at 5.81 m/s, be prepared for breezy conditions.\\n\\n### Additional Tips:\\n- **Clothing:** Wear layers to keep warm, as the temperature feels colder than it actually is.\\n- **Dining:** New York offers a plethora of dining options. Consider trying some local favorites like a classic New York bagel or pizza.\\n- **Transportation:** Utilize the subway for efficient travel across the city. Taxis and ride-sharing services are also readily available.\\n\\nFor more details on attractions and guided tours, you can visit [USA Guided Tours](https://usaguidedtours.com/nyc/attraction/) and [I Love NY](https://www.iloveny.com/places-to-go/new-york-city/attractions/). \\n\\nEnjoy your trip to New York City!\\n---------------\\n**Day 1: Exploring Iconic London Landmarks**\\n\\n**Morning:**\\n1. **Buckingham Palace**\\n - Start your day early with a visit to Buckingham Palace. Arrive by 9:30 AM to catch the Changing of the Guard ceremony, which typically starts at 11:00 AM. Enjoy the majestic architecture and the surrounding gardens.\\n - Weather Tip: With the overcast clouds, it might feel chilly, so dress warmly and bring an umbrella just in case.\\n\\n**Midday:**\\n2. **Westminster Abbey**\\n - Head towards Westminster Abbey, a short walk from Buckingham Palace. This historic church has been the site of many significant events, including royal weddings and coronations. Spend about 1.5 hours exploring.\\n\\n3. **Lunch at Borough Market**\\n - Take a tube or walk to Borough Market for a variety of food options. It's a great place to warm up with some hot street food and explore the diverse culinary offerings.\\n\\n**Afternoon:**\\n4. **London Eye**\\n - After lunch, head to the London Eye. The overcast sky might not offer the clearest views, but the experience is still worthwhile. Pre-book your tickets to avoid long lines and enjoy a 30-minute ride on this iconic Ferris wheel.\\n\\n**Evening:**\\n5. **The Globe Theatre**\\n - As the day winds down, visit Shakespeare's Globe Theatre. If there's a performance, consider attending or simply take a guided tour to learn about the history of this famous theater.\\n\\n**Day 2: Museums and Cultural Exploration**\\n\\n**Morning:**\\n1. **The British Museum**\\n - Start your second day at the British Museum. Spend a few hours exploring the vast collection of art and antiquities. Highlights include the Rosetta Stone and the Elgin Marbles.\\n\\n**Midday:**\\n2. **Lunch near Covent Garden**\\n - Head to Covent Garden for lunch. This area is bustling with restaurants and cafes, perfect for a cozy indoor meal.\\n\\n**Afternoon:**\\n3. **The Tower of London**\\n - After lunch, make your way to the Tower of London. Delve into England's rich history and see the Crown Jewels. Allocate about 2-3 hours for this visit.\\n\\n**Evening:**\\n4. **Tower Bridge**\\n - Conclude your day with a walk across Tower Bridge. The views of the Thames River and the cityscape are beautiful, even on a cloudy evening.\\n\\n**Day 3: Leisure and Local Experiences**\\n\\n**Morning:**\\n1. **Natural History Museum**\\n - Begin your last day at the Natural History Museum. It's a family-friendly museum with fascinating exhibits, including dinosaur skeletons and a model of a blue whale.\\n\\n**Midday:**\\n2. **Lunch at South Kensington**\\n - Enjoy a relaxed lunch in South Kensington. There are plenty of options, from casual cafes to high-end dining.\\n\\n**Afternoon:**\\n3. **Hyde Park**\\n - Spend your afternoon strolling through Hyde Park. Visit the Serpentine Galleries if you're interested in contemporary art. The park's natural beauty is a peaceful retreat amidst the city hustle.\\n\\n**Evening:**\\n4. **Dinner and a Show in the West End**\\n - End your London adventure with a memorable dinner followed by a theater show in the West End. Book your tickets in advance for popular shows.\\n\\n**Additional Tips:**\\n- Always check the attraction websites for any specific COVID-19 guidelines or changes in operating hours.\\n- London’s public transport system is efficient; consider getting an Oyster card for convenient travel.\\n- Don't forget to dress in layers to adapt to the chilly weather, and always have your camera ready to capture memories.\\n---------------\\nHere’s a detailed itinerary for your visit to Paris, considering the current snowy weather conditions and top attractions:\\n\\n### Day 1: Embrace the Iconic Landmarks\\n\\n**Morning: Eiffel Tower**\\n- **Time:** 9:00 AM\\n- **Details:** Begin your day with a visit to the Eiffel Tower. Even in the snow, the tower offers stunning views of Paris. Dress warmly and enjoy hot chocolate from nearby cafes.\\n- **Link for more info:** [Tripadvisor - Things to Do in Paris](https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html)\\n\\n**Afternoon: Louvre Museum**\\n- **Time:** 1:00 PM\\n- **Details:** Spend your afternoon indoors at the Louvre Museum. With its vast collection of art and history, it's a perfect way to escape the cold. Consider taking a guided tour to make the most of your visit.\\n- **Link for more info:** [U.S. News Travel - Things To Do](https://travel.usnews.com/Paris_France/Things_To_Do/)\\n\\n**Evening: Seine River Cruise**\\n- **Time:** 6:00 PM\\n- **Details:** End your day with a magical Seine River cruise. The snow adds a picturesque touch to the illuminated landmarks. Ensure to book a heated cruise for comfort.\\n\\n### Day 2: Explore Cultural and Historical Treasures\\n\\n**Morning: Notre-Dame Cathedral**\\n- **Time:** 9:30 AM\\n- **Details:** Visit the iconic Notre-Dame Cathedral. Although some areas may be under restoration, its architecture and history are worth experiencing. Warm clothing is essential as the interior can be chilly.\\n\\n**Afternoon: Musée d'Orsay**\\n- **Time:** 1:30 PM\\n- **Details:** Head to the Musée d'Orsay, renowned for its Impressionist masterpieces. This indoor activity is ideal for escaping the cold and enjoying world-class art.\\n\\n**Evening: Montmartre and Sacré-Cœur**\\n- **Time:** 5:00 PM\\n- **Details:** Wander through the charming streets of Montmartre and visit the Sacré-Cœur Basilica. The view of Paris in the snow is breathtaking. Enjoy a cozy dinner at a local bistro in Montmartre.\\n\\n### Day 3: Discover Hidden Gems and Local Flavors\\n\\n**Morning: Le Marais District**\\n- **Time:** 10:00 AM\\n- **Details:** Explore Le Marais, known for its vibrant street art, boutiques, and cafes. Enjoy a leisurely breakfast and shop for unique souvenirs.\\n\\n**Afternoon: Palais Garnier (Opera House)**\\n- **Time:** 2:00 PM\\n- **Details:** Tour the opulent Palais Garnier. Its stunning interiors are a must-see, especially when it's snowy outside.\\n\\n**Evening: Moulin Rouge Show**\\n- **Time:** 8:00 PM\\n- **Details:** Conclude your trip with a classic Parisian experience at the Moulin Rouge. Book in advance to secure a good seat and enjoy the legendary cabaret performance.\\n\\n### Additional Tips:\\n- **Weather Preparation:** Wear layers, waterproof boots, and carry an umbrella. The snow and cold wind can be intense.\\n- **Dining:** Indulge in warm, hearty French cuisine at local cafes and restaurants. Try dishes like French onion soup, coq au vin, and tarte Tatin.\\n- **Transport:** Use public transportation to avoid the snowy streets, and consider purchasing a Paris Visite pass for unlimited travel.\\n\\nEnjoy your snowy adventure in Paris!\\n---------------\\n**Tokyo Itinerary**\\n\\n**Day 1: Arrival and Exploration of Historical and Cultural Sites**\\n\\n- **Morning:**\\n - **Asakusa District**: Begin your day with a visit to the historic Asakusa district. Explore the iconic Senso-ji Temple, Tokyo's oldest temple. Enjoy the traditional market streets like Nakamise Street for some shopping and snacks.\\n\\n- **Afternoon:**\\n - **Tokyo National Museum**: Head to Ueno Park and visit the Tokyo National Museum. Discover Japan’s extensive collection of art and antiquities. This is a great spot to dive into Japanese history and culture.\\n\\n- **Evening:**\\n - **Dinner in Ueno**: Explore the local dining options around Ueno and enjoy a traditional Japanese dinner.\\n\\n**Day 2: Modern Tokyo and Unique Experiences**\\n\\n- **Morning:**\\n - **Ghibli Museum**: Start your day with a magical visit to the Ghibli Museum in Mitaka. Perfect for fans of Studio Ghibli's animated films, this museum offers a whimsical look into the creative world of Hayao Miyazaki.\\n\\n- **Afternoon:**\\n - **Shibuya and Harajuku**: Head towards the bustling areas of Shibuya and Harajuku. Witness the famous Shibuya Crossing and explore the trendy shops of Harajuku, especially Takeshita Street.\\n\\n- **Evening:**\\n - **Golden Gai**: Conclude your day in the vibrant Golden Gai district. This area is renowned for its narrow alleys filled with small bars and eateries. Experience the unique nightlife of Tokyo here.\\n\\n**Day 3: Relax and Explore Green Spaces**\\n\\n- **Morning:**\\n - **Shinjuku Gyoen National Garden**: Spend a peaceful morning strolling through the beautiful Shinjuku Gyoen, one of Tokyo's largest and most beautiful parks. It's a perfect spot for relaxation and enjoying nature.\\n\\n- **Afternoon:**\\n - **Meiji Shrine**: Visit the Meiji Shrine, located in a forested area near Harajuku and Shibuya. It's a serene place to learn about Shinto traditions and enjoy the tranquil setting.\\n\\n- **Evening:**\\n - **Tokyo Tower or Skytree**: End your trip with a visit to either Tokyo Tower or Tokyo Skytree for a panoramic view of the city. It's an unforgettable way to see Tokyo illuminated at night.\\n\\n**Weather Considerations:**\\n- With the current weather of few clouds and a mild temperature around 10.32°C, it is advisable to wear layers and carry a light jacket for comfort during outdoor activities.\\n- Humidity is high (92%), so be prepared for a slightly damp feeling and consider moisture-wicking clothing.\\n\\n**Additional Tips:**\\n- Always check the opening hours of attractions and book tickets in advance where necessary.\\n- Use Tokyo’s efficient public transport to move around easily.\\n- Consider visiting the websites linked in the attraction descriptions for more detailed information and current updates.\\n---------------\\nHere's a detailed itinerary for exploring some of Sydney's top tourist attractions with the current weather conditions in mind. With clear skies and pleasant temperatures, it's a perfect day to explore the outdoors and enjoy what Sydney has to offer.\\n\\n### Morning\\n\\n**9:00 AM - Sydney Opera House**\\n- Begin your day with a visit to the iconic Sydney Opera House. Take a guided tour to learn about its history and architecture. Tours are available in multiple languages.\\n- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\\n\\n**11:00 AM - Royal Botanic Garden Sydney**\\n- Just a short walk from the Opera House, enjoy a leisurely stroll through the Royal Botanic Garden. The clear skies will offer beautiful views of the diverse plant life and the Sydney Harbour.\\n\\n### Afternoon\\n\\n**12:30 PM - Lunch at Opera Bar**\\n- Head back to Opera Bar for lunch. Enjoy a refreshing cocktail with stunning views of the Sydney Harbour Bridge and the waterfront.\\n- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\\n\\n**2:00 PM - Sydney Harbour Bridge**\\n- After lunch, take a scenic walk across the Sydney Harbour Bridge. If you're up for it, consider the BridgeClimb for breathtaking panoramic views of the city.\\n\\n**4:00 PM - The Rocks**\\n- Explore The Rocks, one of Sydney's most historic areas. Wander through the cobbled streets, visit the local markets, and perhaps enjoy a cup of coffee at a nearby café.\\n\\n### Evening\\n\\n**6:00 PM - Darling Harbour**\\n- Make your way to Darling Harbour for the evening. Here you can visit attractions such as the SEA LIFE Sydney Aquarium or simply enjoy the lively atmosphere by the waterfront.\\n\\n**8:00 PM - Dinner at a Local Restaurant**\\n- Conclude your day with dinner at one of Darling Harbour's many restaurants. Choose from a variety of cuisines while enjoying the vibrant night scene.\\n\\n### Additional Suggestions\\n\\n- If you're interested in more unique experiences, consider visiting some of the attractions listed on [Time Out Sydney](https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck), which includes thrilling adventures and scenic tours.\\n\\nWith clear skies and mild temperatures, this itinerary offers a balanced mix of cultural, historical, and scenic experiences. Enjoy your visit to Sydney!\"}\n", + "--------------------------------------------------\n", + "Here's a detailed itinerary for visiting top tourist attractions in New York, considering the current weather conditions. \n", + "\n", + "### Day 1: Iconic Landmarks and Observation Decks\n", + "- **Morning:**\n", + " - **Top of the Rock Observation Deck:** Start your day with a visit to the Top of the Rock Observation Deck at Rockefeller Plaza. The panoramic 360-degree views from the 70th floor are a must-see. Dress warmly as it feels like 5.2°C outside, and it’s quite windy.\n", + " - **Link for more info:** [Tripadvisor - Top of the Rock](https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html)\n", + "\n", + "- **Afternoon:**\n", + " - **St. Patrick’s Cathedral:** Just a short walk from Rockefeller Plaza, explore the stunning architecture of St. Patrick’s Cathedral. The overcast skies will provide a dramatic backdrop for photos.\n", + " - **Fifth Avenue:** Enjoy a leisurely stroll along Fifth Avenue, visiting iconic stores and landmarks.\n", + "\n", + "- **Evening:**\n", + " - **Times Square:** Experience the vibrant lights and energy of Times Square. The overcast clouds might enhance the brightness of the neon lights.\n", + "\n", + "### Day 2: Culture and History\n", + "- **Morning:**\n", + " - **The Museum of Modern Art (MoMA):** Spend your morning exploring MoMA’s vast collection of modern and contemporary art. This indoor activity is perfect for a cloudy day.\n", + "\n", + "- **Afternoon:**\n", + " - **Central Park:** Head to Central Park for a refreshing walk. With 100% cloud cover, it's a great day to explore the park without the harsh sun. Consider visiting the Central Park Zoo or taking a guided tour.\n", + "\n", + "- **Evening:**\n", + " - **Broadway Show:** End your day with a Broadway show. It’s an ideal indoor activity to avoid the chilly weather outside. Book tickets in advance for popular shows.\n", + "\n", + "### Day 3: Historical and Educational\n", + "- **Morning:**\n", + " - **Statue of Liberty and Ellis Island:** Take a ferry to visit these iconic sites. Dress warmly for the ferry ride. The cloud cover will provide a unique perspective for photos.\n", + "\n", + "- **Afternoon:**\n", + " - **9/11 Memorial and Museum:** Spend your afternoon reflecting at the 9/11 Memorial and exploring the museum exhibits.\n", + "\n", + "- **Evening:**\n", + " - **Brooklyn Bridge:** Walk across the Brooklyn Bridge and enjoy the city skyline. With the wind speed at 5.81 m/s, be prepared for breezy conditions.\n", + "\n", + "### Additional Tips:\n", + "- **Clothing:** Wear layers to keep warm, as the temperature feels colder than it actually is.\n", + "- **Dining:** New York offers a plethora of dining options. Consider trying some local favorites like a classic New York bagel or pizza.\n", + "- **Transportation:** Utilize the subway for efficient travel across the city. Taxis and ride-sharing services are also readily available.\n", + "\n", + "For more details on attractions and guided tours, you can visit [USA Guided Tours](https://usaguidedtours.com/nyc/attraction/) and [I Love NY](https://www.iloveny.com/places-to-go/new-york-city/attractions/). \n", + "\n", + "Enjoy your trip to New York City!\n", + "---------------\n", + "**Day 1: Exploring Iconic London Landmarks**\n", + "\n", + "**Morning:**\n", + "1. **Buckingham Palace**\n", + " - Start your day early with a visit to Buckingham Palace. Arrive by 9:30 AM to catch the Changing of the Guard ceremony, which typically starts at 11:00 AM. Enjoy the majestic architecture and the surrounding gardens.\n", + " - Weather Tip: With the overcast clouds, it might feel chilly, so dress warmly and bring an umbrella just in case.\n", + "\n", + "**Midday:**\n", + "2. **Westminster Abbey**\n", + " - Head towards Westminster Abbey, a short walk from Buckingham Palace. This historic church has been the site of many significant events, including royal weddings and coronations. Spend about 1.5 hours exploring.\n", + "\n", + "3. **Lunch at Borough Market**\n", + " - Take a tube or walk to Borough Market for a variety of food options. It's a great place to warm up with some hot street food and explore the diverse culinary offerings.\n", + "\n", + "**Afternoon:**\n", + "4. **London Eye**\n", + " - After lunch, head to the London Eye. The overcast sky might not offer the clearest views, but the experience is still worthwhile. Pre-book your tickets to avoid long lines and enjoy a 30-minute ride on this iconic Ferris wheel.\n", + "\n", + "**Evening:**\n", + "5. **The Globe Theatre**\n", + " - As the day winds down, visit Shakespeare's Globe Theatre. If there's a performance, consider attending or simply take a guided tour to learn about the history of this famous theater.\n", + "\n", + "**Day 2: Museums and Cultural Exploration**\n", + "\n", + "**Morning:**\n", + "1. **The British Museum**\n", + " - Start your second day at the British Museum. Spend a few hours exploring the vast collection of art and antiquities. Highlights include the Rosetta Stone and the Elgin Marbles.\n", + "\n", + "**Midday:**\n", + "2. **Lunch near Covent Garden**\n", + " - Head to Covent Garden for lunch. This area is bustling with restaurants and cafes, perfect for a cozy indoor meal.\n", + "\n", + "**Afternoon:**\n", + "3. **The Tower of London**\n", + " - After lunch, make your way to the Tower of London. Delve into England's rich history and see the Crown Jewels. Allocate about 2-3 hours for this visit.\n", + "\n", + "**Evening:**\n", + "4. **Tower Bridge**\n", + " - Conclude your day with a walk across Tower Bridge. The views of the Thames River and the cityscape are beautiful, even on a cloudy evening.\n", + "\n", + "**Day 3: Leisure and Local Experiences**\n", + "\n", + "**Morning:**\n", + "1. **Natural History Museum**\n", + " - Begin your last day at the Natural History Museum. It's a family-friendly museum with fascinating exhibits, including dinosaur skeletons and a model of a blue whale.\n", + "\n", + "**Midday:**\n", + "2. **Lunch at South Kensington**\n", + " - Enjoy a relaxed lunch in South Kensington. There are plenty of options, from casual cafes to high-end dining.\n", + "\n", + "**Afternoon:**\n", + "3. **Hyde Park**\n", + " - Spend your afternoon strolling through Hyde Park. Visit the Serpentine Galleries if you're interested in contemporary art. The park's natural beauty is a peaceful retreat amidst the city hustle.\n", + "\n", + "**Evening:**\n", + "4. **Dinner and a Show in the West End**\n", + " - End your London adventure with a memorable dinner followed by a theater show in the West End. Book your tickets in advance for popular shows.\n", + "\n", + "**Additional Tips:**\n", + "- Always check the attraction websites for any specific COVID-19 guidelines or changes in operating hours.\n", + "- London’s public transport system is efficient; consider getting an Oyster card for convenient travel.\n", + "- Don't forget to dress in layers to adapt to the chilly weather, and always have your camera ready to capture memories.\n", + "---------------\n", + "Here’s a detailed itinerary for your visit to Paris, considering the current snowy weather conditions and top attractions:\n", + "\n", + "### Day 1: Embrace the Iconic Landmarks\n", + "\n", + "**Morning: Eiffel Tower**\n", + "- **Time:** 9:00 AM\n", + "- **Details:** Begin your day with a visit to the Eiffel Tower. Even in the snow, the tower offers stunning views of Paris. Dress warmly and enjoy hot chocolate from nearby cafes.\n", + "- **Link for more info:** [Tripadvisor - Things to Do in Paris](https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html)\n", + "\n", + "**Afternoon: Louvre Museum**\n", + "- **Time:** 1:00 PM\n", + "- **Details:** Spend your afternoon indoors at the Louvre Museum. With its vast collection of art and history, it's a perfect way to escape the cold. Consider taking a guided tour to make the most of your visit.\n", + "- **Link for more info:** [U.S. News Travel - Things To Do](https://travel.usnews.com/Paris_France/Things_To_Do/)\n", + "\n", + "**Evening: Seine River Cruise**\n", + "- **Time:** 6:00 PM\n", + "- **Details:** End your day with a magical Seine River cruise. The snow adds a picturesque touch to the illuminated landmarks. Ensure to book a heated cruise for comfort.\n", + "\n", + "### Day 2: Explore Cultural and Historical Treasures\n", + "\n", + "**Morning: Notre-Dame Cathedral**\n", + "- **Time:** 9:30 AM\n", + "- **Details:** Visit the iconic Notre-Dame Cathedral. Although some areas may be under restoration, its architecture and history are worth experiencing. Warm clothing is essential as the interior can be chilly.\n", + "\n", + "**Afternoon: Musée d'Orsay**\n", + "- **Time:** 1:30 PM\n", + "- **Details:** Head to the Musée d'Orsay, renowned for its Impressionist masterpieces. This indoor activity is ideal for escaping the cold and enjoying world-class art.\n", + "\n", + "**Evening: Montmartre and Sacré-Cœur**\n", + "- **Time:** 5:00 PM\n", + "- **Details:** Wander through the charming streets of Montmartre and visit the Sacré-Cœur Basilica. The view of Paris in the snow is breathtaking. Enjoy a cozy dinner at a local bistro in Montmartre.\n", + "\n", + "### Day 3: Discover Hidden Gems and Local Flavors\n", + "\n", + "**Morning: Le Marais District**\n", + "- **Time:** 10:00 AM\n", + "- **Details:** Explore Le Marais, known for its vibrant street art, boutiques, and cafes. Enjoy a leisurely breakfast and shop for unique souvenirs.\n", + "\n", + "**Afternoon: Palais Garnier (Opera House)**\n", + "- **Time:** 2:00 PM\n", + "- **Details:** Tour the opulent Palais Garnier. Its stunning interiors are a must-see, especially when it's snowy outside.\n", + "\n", + "**Evening: Moulin Rouge Show**\n", + "- **Time:** 8:00 PM\n", + "- **Details:** Conclude your trip with a classic Parisian experience at the Moulin Rouge. Book in advance to secure a good seat and enjoy the legendary cabaret performance.\n", + "\n", + "### Additional Tips:\n", + "- **Weather Preparation:** Wear layers, waterproof boots, and carry an umbrella. The snow and cold wind can be intense.\n", + "- **Dining:** Indulge in warm, hearty French cuisine at local cafes and restaurants. Try dishes like French onion soup, coq au vin, and tarte Tatin.\n", + "- **Transport:** Use public transportation to avoid the snowy streets, and consider purchasing a Paris Visite pass for unlimited travel.\n", + "\n", + "Enjoy your snowy adventure in Paris!\n", + "---------------\n", + "**Tokyo Itinerary**\n", + "\n", + "**Day 1: Arrival and Exploration of Historical and Cultural Sites**\n", + "\n", + "- **Morning:**\n", + " - **Asakusa District**: Begin your day with a visit to the historic Asakusa district. Explore the iconic Senso-ji Temple, Tokyo's oldest temple. Enjoy the traditional market streets like Nakamise Street for some shopping and snacks.\n", + "\n", + "- **Afternoon:**\n", + " - **Tokyo National Museum**: Head to Ueno Park and visit the Tokyo National Museum. Discover Japan’s extensive collection of art and antiquities. This is a great spot to dive into Japanese history and culture.\n", + "\n", + "- **Evening:**\n", + " - **Dinner in Ueno**: Explore the local dining options around Ueno and enjoy a traditional Japanese dinner.\n", + "\n", + "**Day 2: Modern Tokyo and Unique Experiences**\n", + "\n", + "- **Morning:**\n", + " - **Ghibli Museum**: Start your day with a magical visit to the Ghibli Museum in Mitaka. Perfect for fans of Studio Ghibli's animated films, this museum offers a whimsical look into the creative world of Hayao Miyazaki.\n", + "\n", + "- **Afternoon:**\n", + " - **Shibuya and Harajuku**: Head towards the bustling areas of Shibuya and Harajuku. Witness the famous Shibuya Crossing and explore the trendy shops of Harajuku, especially Takeshita Street.\n", + "\n", + "- **Evening:**\n", + " - **Golden Gai**: Conclude your day in the vibrant Golden Gai district. This area is renowned for its narrow alleys filled with small bars and eateries. Experience the unique nightlife of Tokyo here.\n", + "\n", + "**Day 3: Relax and Explore Green Spaces**\n", + "\n", + "- **Morning:**\n", + " - **Shinjuku Gyoen National Garden**: Spend a peaceful morning strolling through the beautiful Shinjuku Gyoen, one of Tokyo's largest and most beautiful parks. It's a perfect spot for relaxation and enjoying nature.\n", + "\n", + "- **Afternoon:**\n", + " - **Meiji Shrine**: Visit the Meiji Shrine, located in a forested area near Harajuku and Shibuya. It's a serene place to learn about Shinto traditions and enjoy the tranquil setting.\n", + "\n", + "- **Evening:**\n", + " - **Tokyo Tower or Skytree**: End your trip with a visit to either Tokyo Tower or Tokyo Skytree for a panoramic view of the city. It's an unforgettable way to see Tokyo illuminated at night.\n", + "\n", + "**Weather Considerations:**\n", + "- With the current weather of few clouds and a mild temperature around 10.32°C, it is advisable to wear layers and carry a light jacket for comfort during outdoor activities.\n", + "- Humidity is high (92%), so be prepared for a slightly damp feeling and consider moisture-wicking clothing.\n", + "\n", + "**Additional Tips:**\n", + "- Always check the opening hours of attractions and book tickets in advance where necessary.\n", + "- Use Tokyo’s efficient public transport to move around easily.\n", + "- Consider visiting the websites linked in the attraction descriptions for more detailed information and current updates.\n", + "---------------\n", + "Here's a detailed itinerary for exploring some of Sydney's top tourist attractions with the current weather conditions in mind. With clear skies and pleasant temperatures, it's a perfect day to explore the outdoors and enjoy what Sydney has to offer.\n", + "\n", + "### Morning\n", + "\n", + "**9:00 AM - Sydney Opera House**\n", + "- Begin your day with a visit to the iconic Sydney Opera House. Take a guided tour to learn about its history and architecture. Tours are available in multiple languages.\n", + "- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\n", + "\n", + "**11:00 AM - Royal Botanic Garden Sydney**\n", + "- Just a short walk from the Opera House, enjoy a leisurely stroll through the Royal Botanic Garden. The clear skies will offer beautiful views of the diverse plant life and the Sydney Harbour.\n", + "\n", + "### Afternoon\n", + "\n", + "**12:30 PM - Lunch at Opera Bar**\n", + "- Head back to Opera Bar for lunch. Enjoy a refreshing cocktail with stunning views of the Sydney Harbour Bridge and the waterfront.\n", + "- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\n", + "\n", + "**2:00 PM - Sydney Harbour Bridge**\n", + "- After lunch, take a scenic walk across the Sydney Harbour Bridge. If you're up for it, consider the BridgeClimb for breathtaking panoramic views of the city.\n", + "\n", + "**4:00 PM - The Rocks**\n", + "- Explore The Rocks, one of Sydney's most historic areas. Wander through the cobbled streets, visit the local markets, and perhaps enjoy a cup of coffee at a nearby café.\n", + "\n", + "### Evening\n", + "\n", + "**6:00 PM - Darling Harbour**\n", + "- Make your way to Darling Harbour for the evening. Here you can visit attractions such as the SEA LIFE Sydney Aquarium or simply enjoy the lively atmosphere by the waterfront.\n", + "\n", + "**8:00 PM - Dinner at a Local Restaurant**\n", + "- Conclude your day with dinner at one of Darling Harbour's many restaurants. Choose from a variety of cuisines while enjoying the vibrant night scene.\n", + "\n", + "### Additional Suggestions\n", + "\n", + "- If you're interested in more unique experiences, consider visiting some of the attractions listed on [Time Out Sydney](https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck), which includes thrilling adventures and scenic tours.\n", + "\n", + "With clear skies and mild temperatures, this itinerary offers a balanced mix of cultural, historical, and scenic experiences. Enjoy your visit to Sydney!\n" + ] + } + ], + "source": [ + "# Get execution details\n", + "execution = client.executions.get(execution.id)\n", + "# Print the output\n", + "print(execution.output)\n", + "print(\"-\"*50)\n", + "\n", + "if 'final_plan' in execution.output:\n", + " print(execution.output['final_plan'])" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Transition type: init\n", + "Transition output: {'locations': ['New York', 'London', 'Paris', 'Tokyo', 'Sydney']}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: New York\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': 'In New York, the current weather is as follows:\\nDetailed status: overcast clouds\\nWind speed: 5.81 m/s, direction: 22°\\nHumidity: 90%\\nTemperature: \\n - Current: 8.34°C\\n - High: 9.01°C\\n - Low: 7.16°C\\n - Feels like: 5.2°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%'}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: London\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': 'In London, the current weather is as follows:\\nDetailed status: overcast clouds\\nWind speed: 2.57 m/s, direction: 350°\\nHumidity: 72%\\nTemperature: \\n - Current: 3.42°C\\n - High: 3.97°C\\n - Low: 2.79°C\\n - Feels like: 0.97°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%'}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: Paris\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': 'In Paris, the current weather is as follows:\\nDetailed status: snow\\nWind speed: 9.26 m/s, direction: 70°\\nHumidity: 99%\\nTemperature: \\n - Current: 0.57°C\\n - High: 1.16°C\\n - Low: -0.35°C\\n - Feels like: -6.04°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%'}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: Tokyo\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': 'In Tokyo, the current weather is as follows:\\nDetailed status: few clouds\\nWind speed: 2.57 m/s, direction: 280°\\nHumidity: 92%\\nTemperature: \\n - Current: 10.32°C\\n - High: 10.91°C\\n - Low: 9.19°C\\n - Feels like: 9.81°C\\nRain: {}\\nHeat index: None\\nCloud cover: 20%'}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: Sydney\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': 'In Sydney, the current weather is as follows:\\nDetailed status: clear sky\\nWind speed: 2.93 m/s, direction: 348°\\nHumidity: 81%\\nTemperature: \\n - Current: 16.95°C\\n - High: 18.04°C\\n - Low: 15.42°C\\n - Feels like: 16.82°C\\nRain: {}\\nHeat index: None\\nCloud cover: 0%'}\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: [{'result': 'In New York, the current weather is as follows:\\nDetailed status: overcast clouds\\nWind speed: 5.81 m/s, direction: 22°\\nHumidity: 90%\\nTemperature: \\n - Current: 8.34°C\\n - High: 9.01°C\\n - Low: 7.16°C\\n - Feels like: 5.2°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%'}, {'result': 'In London, the current weather is as follows:\\nDetailed status: overcast clouds\\nWind speed: 2.57 m/s, direction: 350°\\nHumidity: 72%\\nTemperature: \\n - Current: 3.42°C\\n - High: 3.97°C\\n - Low: 2.79°C\\n - Feels like: 0.97°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%'}, {'result': 'In Paris, the current weather is as follows:\\nDetailed status: snow\\nWind speed: 9.26 m/s, direction: 70°\\nHumidity: 99%\\nTemperature: \\n - Current: 0.57°C\\n - High: 1.16°C\\n - Low: -0.35°C\\n - Feels like: -6.04°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%'}, {'result': 'In Tokyo, the current weather is as follows:\\nDetailed status: few clouds\\nWind speed: 2.57 m/s, direction: 280°\\nHumidity: 92%\\nTemperature: \\n - Current: 10.32°C\\n - High: 10.91°C\\n - Low: 9.19°C\\n - Feels like: 9.81°C\\nRain: {}\\nHeat index: None\\nCloud cover: 20%'}, {'result': 'In Sydney, the current weather is as follows:\\nDetailed status: clear sky\\nWind speed: 2.93 m/s, direction: 348°\\nHumidity: 81%\\nTemperature: \\n - Current: 16.95°C\\n - High: 18.04°C\\n - Low: 15.42°C\\n - Feels like: 16.82°C\\nRain: {}\\nHeat index: None\\nCloud cover: 0%'}]\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: New York\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html', 'snippet': 'Top of the Rock Observation Deck, the newly opened, 3-tiered observation deck on the 67th, 69th and 70th floors of 30 Rockefeller Plaza, is New York City's most amazing attraction! The unforgettable experience includes a panoramic 360-degree, unobstructed view from the 70th floor observatory, ...', 'title': 'THE 15 BEST Things to Do in NYC - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.iloveny.com/places-to-go/new-york-city/attractions/', 'snippet': 'Whether you're into architecture, Broadway theater, restaurants or other cultural hotspots, New York City has something for you. Plan your trip today!', 'title': 'NYC Attractions | Museums, Parks, Zoos & Landmarks'}, {'link': 'https://usaguidedtours.com/nyc/attraction/', 'snippet': 'Learn more about New York City attractions or simply book one of our award-winning guided tours and explore them up-close and personal!', 'title': 'New York Attractions - USA Guided Tours'}]}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: London\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g186338-Activities-London_England.html', 'snippet': 'Things to Do in London, England: See Tripadvisor's 7,202,262 traveler reviews and photos of London tourist attractions. Find what to do today, this weekend, or in August. We have reviews of the best places to see in London. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in London (2024) - Must-See Attractions'}, {'link': 'https://www.visitlondon.com/things-to-do/sightseeing/london-attraction', 'snippet': 'Find the best London tourist attractions, including museums, palaces and London landmarks. Pick things to see in London, attractions or take a sightseeing tour.', 'title': \"London attractions | Visit London's top tourist attractions\"}, {'link': 'https://www.timeout.com/london/attractions/top-london-attractions', 'snippet': 'Discover the best, most unmissable attractions in London, including Buckingham Palace, The Globe, the London Eye and more.', 'title': '50 Best Attractions in London for 2024 | Best Things to Do in London'}]}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: Paris\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html', 'snippet': 'Things to Do in Paris, France: See Tripadvisor's 5,011,626 traveler reviews and photos of Paris tourist attractions. Find what to do today, this weekend, or in September. We have reviews of the best places to see in Paris. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Paris (2024) - Must-See Attractions'}, {'link': 'https://www.timeout.com/paris/en/attractions/best-paris-attractions', 'snippet': 'And we’re not alone in thinking that. Paris is a major tourist destination that attracts thousands upon thousands of enthusiastic travellers with heads filled with images of Breton jumpers, tiny dogs, and decadent pastries - the kind you can dip in your hot chocolate.', 'title': '51 Best Attractions in Paris for 2024 | Best Sites to See in Paris'}, {'link': 'https://travel.usnews.com/Paris_France/Things_To_Do/', 'snippet': 'If you've been dreaming of a visit to the Eiffel Tower, Louvre Museum and Moulin Rouge, plan your trip with these expert recommendations for things to do in Paris.', 'title': '32 Best Things to Do in Paris, France | U.S. News Travel'}]}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: Tokyo\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g298184-Activities-Tokyo_Tokyo_Prefecture_Kanto.html', 'snippet': 'Things to Do in Tokyo, Japan: See Tripadvisor's 1,602,397 traveler reviews and photos of Tokyo tourist attractions. Find what to do today, this weekend, or in March. We have reviews of the best places to see in Tokyo. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Tokyo - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.lonelyplanet.com/japan/tokyo/attractions', 'snippet': 'Discover the best attractions in Tokyo including Tokyo National Museum, Ghibli Museum, and Golden Gai.', 'title': 'Must-see attractions Tokyo, Japan - Lonely Planet'}, {'link': 'https://www.japan-guide.com/e/e2164.html', 'snippet': 'The city's history can be appreciated in districts such as Asakusa and in many excellent museums, historic temples and gardens. Contrary to common perception, Tokyo also offers a number of attractive green spaces in the city center and within relatively short train rides at its outskirts.', 'title': 'Tokyo City Guide - What to do in Tokyo'}]}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: Sydney\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g255060-Activities-Sydney_New_South_Wales.html', 'snippet': 'Things to Do in Sydney, Australia: See Tripadvisor's 1,043,552 traveler reviews and photos of Sydney tourist attractions. Find what to do today, this weekend, or in March. We have reviews of the best places to see in Sydney. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Sydney - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.sydney.com/things-to-do/attractions', 'snippet': 'The UNESCO World Heritage-listed building offers daily guided tours, available in English, Mandarin, French, German, Japanese, Korean and Spanish. Meanwhile, Opera Bar has the best view in town, letting you sip cocktails as you marvel at the Sydney Harbour Bridge.', 'title': 'Top attractions in Sydney | Sydney.com'}, {'link': 'https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck', 'snippet': 'We’ve rounded up 19 infamous Sydney tourist stops that you'll actually enjoy, from thrilling adventures to scenic tours.', 'title': \"19 Amazing Tourist Attractions in Sydney That Don't Suck\"}]}\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: [{'result': [{'link': 'https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html', 'snippet': 'Top of the Rock Observation Deck, the newly opened, 3-tiered observation deck on the 67th, 69th and 70th floors of 30 Rockefeller Plaza, is New York City's most amazing attraction! The unforgettable experience includes a panoramic 360-degree, unobstructed view from the 70th floor observatory, ...', 'title': 'THE 15 BEST Things to Do in NYC - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.iloveny.com/places-to-go/new-york-city/attractions/', 'snippet': 'Whether you're into architecture, Broadway theater, restaurants or other cultural hotspots, New York City has something for you. Plan your trip today!', 'title': 'NYC Attractions | Museums, Parks, Zoos & Landmarks'}, {'link': 'https://usaguidedtours.com/nyc/attraction/', 'snippet': 'Learn more about New York City attractions or simply book one of our award-winning guided tours and explore them up-close and personal!', 'title': 'New York Attractions - USA Guided Tours'}]}, {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g186338-Activities-London_England.html', 'snippet': 'Things to Do in London, England: See Tripadvisor's 7,202,262 traveler reviews and photos of London tourist attractions. Find what to do today, this weekend, or in August. We have reviews of the best places to see in London. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in London (2024) - Must-See Attractions'}, {'link': 'https://www.visitlondon.com/things-to-do/sightseeing/london-attraction', 'snippet': 'Find the best London tourist attractions, including museums, palaces and London landmarks. Pick things to see in London, attractions or take a sightseeing tour.', 'title': \"London attractions | Visit London's top tourist attractions\"}, {'link': 'https://www.timeout.com/london/attractions/top-london-attractions', 'snippet': 'Discover the best, most unmissable attractions in London, including Buckingham Palace, The Globe, the London Eye and more.', 'title': '50 Best Attractions in London for 2024 | Best Things to Do in London'}]}, {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html', 'snippet': 'Things to Do in Paris, France: See Tripadvisor's 5,011,626 traveler reviews and photos of Paris tourist attractions. Find what to do today, this weekend, or in September. We have reviews of the best places to see in Paris. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Paris (2024) - Must-See Attractions'}, {'link': 'https://www.timeout.com/paris/en/attractions/best-paris-attractions', 'snippet': 'And we’re not alone in thinking that. Paris is a major tourist destination that attracts thousands upon thousands of enthusiastic travellers with heads filled with images of Breton jumpers, tiny dogs, and decadent pastries - the kind you can dip in your hot chocolate.', 'title': '51 Best Attractions in Paris for 2024 | Best Sites to See in Paris'}, {'link': 'https://travel.usnews.com/Paris_France/Things_To_Do/', 'snippet': 'If you've been dreaming of a visit to the Eiffel Tower, Louvre Museum and Moulin Rouge, plan your trip with these expert recommendations for things to do in Paris.', 'title': '32 Best Things to Do in Paris, France | U.S. News Travel'}]}, {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g298184-Activities-Tokyo_Tokyo_Prefecture_Kanto.html', 'snippet': 'Things to Do in Tokyo, Japan: See Tripadvisor's 1,602,397 traveler reviews and photos of Tokyo tourist attractions. Find what to do today, this weekend, or in March. We have reviews of the best places to see in Tokyo. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Tokyo - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.lonelyplanet.com/japan/tokyo/attractions', 'snippet': 'Discover the best attractions in Tokyo including Tokyo National Museum, Ghibli Museum, and Golden Gai.', 'title': 'Must-see attractions Tokyo, Japan - Lonely Planet'}, {'link': 'https://www.japan-guide.com/e/e2164.html', 'snippet': 'The city's history can be appreciated in districts such as Asakusa and in many excellent museums, historic temples and gardens. Contrary to common perception, Tokyo also offers a number of attractive green spaces in the city center and within relatively short train rides at its outskirts.', 'title': 'Tokyo City Guide - What to do in Tokyo'}]}, {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g255060-Activities-Sydney_New_South_Wales.html', 'snippet': 'Things to Do in Sydney, Australia: See Tripadvisor's 1,043,552 traveler reviews and photos of Sydney tourist attractions. Find what to do today, this weekend, or in March. We have reviews of the best places to see in Sydney. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Sydney - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.sydney.com/things-to-do/attractions', 'snippet': 'The UNESCO World Heritage-listed building offers daily guided tours, available in English, Mandarin, French, German, Japanese, Korean and Spanish. Meanwhile, Opera Bar has the best view in town, letting you sip cocktails as you marvel at the Sydney Harbour Bridge.', 'title': 'Top attractions in Sydney | Sydney.com'}, {'link': 'https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck', 'snippet': 'We’ve rounded up 19 infamous Sydney tourist stops that you'll actually enjoy, from thrilling adventures to scenic tours.', 'title': \"19 Amazing Tourist Attractions in Sydney That Don't Suck\"}]}]\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: {'zipped': [['New York', 'In New York, the current weather is as follows:\\nDetailed status: overcast clouds\\nWind speed: 5.81 m/s, direction: 22°\\nHumidity: 90%\\nTemperature: \\n - Current: 8.34°C\\n - High: 9.01°C\\n - Low: 7.16°C\\n - Feels like: 5.2°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html', 'snippet': 'Top of the Rock Observation Deck, the newly opened, 3-tiered observation deck on the 67th, 69th and 70th floors of 30 Rockefeller Plaza, is New York City's most amazing attraction! The unforgettable experience includes a panoramic 360-degree, unobstructed view from the 70th floor observatory, ...', 'title': 'THE 15 BEST Things to Do in NYC - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.iloveny.com/places-to-go/new-york-city/attractions/', 'snippet': 'Whether you're into architecture, Broadway theater, restaurants or other cultural hotspots, New York City has something for you. Plan your trip today!', 'title': 'NYC Attractions | Museums, Parks, Zoos & Landmarks'}, {'link': 'https://usaguidedtours.com/nyc/attraction/', 'snippet': 'Learn more about New York City attractions or simply book one of our award-winning guided tours and explore them up-close and personal!', 'title': 'New York Attractions - USA Guided Tours'}]}], ['London', 'In London, the current weather is as follows:\\nDetailed status: overcast clouds\\nWind speed: 2.57 m/s, direction: 350°\\nHumidity: 72%\\nTemperature: \\n - Current: 3.42°C\\n - High: 3.97°C\\n - Low: 2.79°C\\n - Feels like: 0.97°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g186338-Activities-London_England.html', 'snippet': 'Things to Do in London, England: See Tripadvisor's 7,202,262 traveler reviews and photos of London tourist attractions. Find what to do today, this weekend, or in August. We have reviews of the best places to see in London. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in London (2024) - Must-See Attractions'}, {'link': 'https://www.visitlondon.com/things-to-do/sightseeing/london-attraction', 'snippet': 'Find the best London tourist attractions, including museums, palaces and London landmarks. Pick things to see in London, attractions or take a sightseeing tour.', 'title': \"London attractions | Visit London's top tourist attractions\"}, {'link': 'https://www.timeout.com/london/attractions/top-london-attractions', 'snippet': 'Discover the best, most unmissable attractions in London, including Buckingham Palace, The Globe, the London Eye and more.', 'title': '50 Best Attractions in London for 2024 | Best Things to Do in London'}]}], ['Paris', 'In Paris, the current weather is as follows:\\nDetailed status: snow\\nWind speed: 9.26 m/s, direction: 70°\\nHumidity: 99%\\nTemperature: \\n - Current: 0.57°C\\n - High: 1.16°C\\n - Low: -0.35°C\\n - Feels like: -6.04°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html', 'snippet': 'Things to Do in Paris, France: See Tripadvisor's 5,011,626 traveler reviews and photos of Paris tourist attractions. Find what to do today, this weekend, or in September. We have reviews of the best places to see in Paris. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Paris (2024) - Must-See Attractions'}, {'link': 'https://www.timeout.com/paris/en/attractions/best-paris-attractions', 'snippet': 'And we’re not alone in thinking that. Paris is a major tourist destination that attracts thousands upon thousands of enthusiastic travellers with heads filled with images of Breton jumpers, tiny dogs, and decadent pastries - the kind you can dip in your hot chocolate.', 'title': '51 Best Attractions in Paris for 2024 | Best Sites to See in Paris'}, {'link': 'https://travel.usnews.com/Paris_France/Things_To_Do/', 'snippet': 'If you've been dreaming of a visit to the Eiffel Tower, Louvre Museum and Moulin Rouge, plan your trip with these expert recommendations for things to do in Paris.', 'title': '32 Best Things to Do in Paris, France | U.S. News Travel'}]}], ['Tokyo', 'In Tokyo, the current weather is as follows:\\nDetailed status: few clouds\\nWind speed: 2.57 m/s, direction: 280°\\nHumidity: 92%\\nTemperature: \\n - Current: 10.32°C\\n - High: 10.91°C\\n - Low: 9.19°C\\n - Feels like: 9.81°C\\nRain: {}\\nHeat index: None\\nCloud cover: 20%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g298184-Activities-Tokyo_Tokyo_Prefecture_Kanto.html', 'snippet': 'Things to Do in Tokyo, Japan: See Tripadvisor's 1,602,397 traveler reviews and photos of Tokyo tourist attractions. Find what to do today, this weekend, or in March. We have reviews of the best places to see in Tokyo. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Tokyo - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.lonelyplanet.com/japan/tokyo/attractions', 'snippet': 'Discover the best attractions in Tokyo including Tokyo National Museum, Ghibli Museum, and Golden Gai.', 'title': 'Must-see attractions Tokyo, Japan - Lonely Planet'}, {'link': 'https://www.japan-guide.com/e/e2164.html', 'snippet': 'The city's history can be appreciated in districts such as Asakusa and in many excellent museums, historic temples and gardens. Contrary to common perception, Tokyo also offers a number of attractive green spaces in the city center and within relatively short train rides at its outskirts.', 'title': 'Tokyo City Guide - What to do in Tokyo'}]}], ['Sydney', 'In Sydney, the current weather is as follows:\\nDetailed status: clear sky\\nWind speed: 2.93 m/s, direction: 348°\\nHumidity: 81%\\nTemperature: \\n - Current: 16.95°C\\n - High: 18.04°C\\n - Low: 15.42°C\\n - Feels like: 16.82°C\\nRain: {}\\nHeat index: None\\nCloud cover: 0%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g255060-Activities-Sydney_New_South_Wales.html', 'snippet': 'Things to Do in Sydney, Australia: See Tripadvisor's 1,043,552 traveler reviews and photos of Sydney tourist attractions. Find what to do today, this weekend, or in March. We have reviews of the best places to see in Sydney. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Sydney - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.sydney.com/things-to-do/attractions', 'snippet': 'The UNESCO World Heritage-listed building offers daily guided tours, available in English, Mandarin, French, German, Japanese, Korean and Spanish. Meanwhile, Opera Bar has the best view in town, letting you sip cocktails as you marvel at the Sydney Harbour Bridge.', 'title': 'Top attractions in Sydney | Sydney.com'}, {'link': 'https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck', 'snippet': 'We’ve rounded up 19 infamous Sydney tourist stops that you'll actually enjoy, from thrilling adventures to scenic tours.', 'title': \"19 Amazing Tourist Attractions in Sydney That Don't Suck\"}]}]]}\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: ['London', 'In London, the current weather is as follows:\\nDetailed status: overcast clouds\\nWind speed: 2.57 m/s, direction: 350°\\nHumidity: 72%\\nTemperature: \\n - Current: 3.42°C\\n - High: 3.97°C\\n - Low: 2.79°C\\n - Feels like: 0.97°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g186338-Activities-London_England.html', 'snippet': 'Things to Do in London, England: See Tripadvisor's 7,202,262 traveler reviews and photos of London tourist attractions. Find what to do today, this weekend, or in August. We have reviews of the best places to see in London. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in London (2024) - Must-See Attractions'}, {'link': 'https://www.visitlondon.com/things-to-do/sightseeing/london-attraction', 'snippet': 'Find the best London tourist attractions, including museums, palaces and London landmarks. Pick things to see in London, attractions or take a sightseeing tour.', 'title': \"London attractions | Visit London's top tourist attractions\"}, {'link': 'https://www.timeout.com/london/attractions/top-london-attractions', 'snippet': 'Discover the best, most unmissable attractions in London, including Buckingham Palace, The Globe, the London Eye and more.', 'title': '50 Best Attractions in London for 2024 | Best Things to Do in London'}]}]\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: ['New York', 'In New York, the current weather is as follows:\\nDetailed status: overcast clouds\\nWind speed: 5.81 m/s, direction: 22°\\nHumidity: 90%\\nTemperature: \\n - Current: 8.34°C\\n - High: 9.01°C\\n - Low: 7.16°C\\n - Feels like: 5.2°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html', 'snippet': 'Top of the Rock Observation Deck, the newly opened, 3-tiered observation deck on the 67th, 69th and 70th floors of 30 Rockefeller Plaza, is New York City's most amazing attraction! The unforgettable experience includes a panoramic 360-degree, unobstructed view from the 70th floor observatory, ...', 'title': 'THE 15 BEST Things to Do in NYC - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.iloveny.com/places-to-go/new-york-city/attractions/', 'snippet': 'Whether you're into architecture, Broadway theater, restaurants or other cultural hotspots, New York City has something for you. Plan your trip today!', 'title': 'NYC Attractions | Museums, Parks, Zoos & Landmarks'}, {'link': 'https://usaguidedtours.com/nyc/attraction/', 'snippet': 'Learn more about New York City attractions or simply book one of our award-winning guided tours and explore them up-close and personal!', 'title': 'New York Attractions - USA Guided Tours'}]}]\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: ['Paris', 'In Paris, the current weather is as follows:\\nDetailed status: snow\\nWind speed: 9.26 m/s, direction: 70°\\nHumidity: 99%\\nTemperature: \\n - Current: 0.57°C\\n - High: 1.16°C\\n - Low: -0.35°C\\n - Feels like: -6.04°C\\nRain: {}\\nHeat index: None\\nCloud cover: 100%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html', 'snippet': 'Things to Do in Paris, France: See Tripadvisor's 5,011,626 traveler reviews and photos of Paris tourist attractions. Find what to do today, this weekend, or in September. We have reviews of the best places to see in Paris. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Paris (2024) - Must-See Attractions'}, {'link': 'https://www.timeout.com/paris/en/attractions/best-paris-attractions', 'snippet': 'And we’re not alone in thinking that. Paris is a major tourist destination that attracts thousands upon thousands of enthusiastic travellers with heads filled with images of Breton jumpers, tiny dogs, and decadent pastries - the kind you can dip in your hot chocolate.', 'title': '51 Best Attractions in Paris for 2024 | Best Sites to See in Paris'}, {'link': 'https://travel.usnews.com/Paris_France/Things_To_Do/', 'snippet': 'If you've been dreaming of a visit to the Eiffel Tower, Louvre Museum and Moulin Rouge, plan your trip with these expert recommendations for things to do in Paris.', 'title': '32 Best Things to Do in Paris, France | U.S. News Travel'}]}]\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: Here’s a detailed itinerary for your visit to Paris, considering the current snowy weather conditions and top attractions:\n", + "\n", + "### Day 1: Embrace the Iconic Landmarks\n", + "\n", + "**Morning: Eiffel Tower**\n", + "- **Time:** 9:00 AM\n", + "- **Details:** Begin your day with a visit to the Eiffel Tower. Even in the snow, the tower offers stunning views of Paris. Dress warmly and enjoy hot chocolate from nearby cafes.\n", + "- **Link for more info:** [Tripadvisor - Things to Do in Paris](https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html)\n", + "\n", + "**Afternoon: Louvre Museum**\n", + "- **Time:** 1:00 PM\n", + "- **Details:** Spend your afternoon indoors at the Louvre Museum. With its vast collection of art and history, it's a perfect way to escape the cold. Consider taking a guided tour to make the most of your visit.\n", + "- **Link for more info:** [U.S. News Travel - Things To Do](https://travel.usnews.com/Paris_France/Things_To_Do/)\n", + "\n", + "**Evening: Seine River Cruise**\n", + "- **Time:** 6:00 PM\n", + "- **Details:** End your day with a magical Seine River cruise. The snow adds a picturesque touch to the illuminated landmarks. Ensure to book a heated cruise for comfort.\n", + "\n", + "### Day 2: Explore Cultural and Historical Treasures\n", + "\n", + "**Morning: Notre-Dame Cathedral**\n", + "- **Time:** 9:30 AM\n", + "- **Details:** Visit the iconic Notre-Dame Cathedral. Although some areas may be under restoration, its architecture and history are worth experiencing. Warm clothing is essential as the interior can be chilly.\n", + "\n", + "**Afternoon: Musée d'Orsay**\n", + "- **Time:** 1:30 PM\n", + "- **Details:** Head to the Musée d'Orsay, renowned for its Impressionist masterpieces. This indoor activity is ideal for escaping the cold and enjoying world-class art.\n", + "\n", + "**Evening: Montmartre and Sacré-Cœur**\n", + "- **Time:** 5:00 PM\n", + "- **Details:** Wander through the charming streets of Montmartre and visit the Sacré-Cœur Basilica. The view of Paris in the snow is breathtaking. Enjoy a cozy dinner at a local bistro in Montmartre.\n", + "\n", + "### Day 3: Discover Hidden Gems and Local Flavors\n", + "\n", + "**Morning: Le Marais District**\n", + "- **Time:** 10:00 AM\n", + "- **Details:** Explore Le Marais, known for its vibrant street art, boutiques, and cafes. Enjoy a leisurely breakfast and shop for unique souvenirs.\n", + "\n", + "**Afternoon: Palais Garnier (Opera House)**\n", + "- **Time:** 2:00 PM\n", + "- **Details:** Tour the opulent Palais Garnier. Its stunning interiors are a must-see, especially when it's snowy outside.\n", + "\n", + "**Evening: Moulin Rouge Show**\n", + "- **Time:** 8:00 PM\n", + "- **Details:** Conclude your trip with a classic Parisian experience at the Moulin Rouge. Book in advance to secure a good seat and enjoy the legendary cabaret performance.\n", + "\n", + "### Additional Tips:\n", + "- **Weather Preparation:** Wear layers, waterproof boots, and carry an umbrella. The snow and cold wind can be intense.\n", + "- **Dining:** Indulge in warm, hearty French cuisine at local cafes and restaurants. Try dishes like French onion soup, coq au vin, and tarte Tatin.\n", + "- **Transport:** Use public transportation to avoid the snowy streets, and consider purchasing a Paris Visite pass for unlimited travel.\n", + "\n", + "Enjoy your snowy adventure in Paris!\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: Here's a detailed itinerary for visiting top tourist attractions in New York, considering the current weather conditions. \n", + "\n", + "### Day 1: Iconic Landmarks and Observation Decks\n", + "- **Morning:**\n", + " - **Top of the Rock Observation Deck:** Start your day with a visit to the Top of the Rock Observation Deck at Rockefeller Plaza. The panoramic 360-degree views from the 70th floor are a must-see. Dress warmly as it feels like 5.2°C outside, and it’s quite windy.\n", + " - **Link for more info:** [Tripadvisor - Top of the Rock](https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html)\n", + "\n", + "- **Afternoon:**\n", + " - **St. Patrick’s Cathedral:** Just a short walk from Rockefeller Plaza, explore the stunning architecture of St. Patrick’s Cathedral. The overcast skies will provide a dramatic backdrop for photos.\n", + " - **Fifth Avenue:** Enjoy a leisurely stroll along Fifth Avenue, visiting iconic stores and landmarks.\n", + "\n", + "- **Evening:**\n", + " - **Times Square:** Experience the vibrant lights and energy of Times Square. The overcast clouds might enhance the brightness of the neon lights.\n", + "\n", + "### Day 2: Culture and History\n", + "- **Morning:**\n", + " - **The Museum of Modern Art (MoMA):** Spend your morning exploring MoMA’s vast collection of modern and contemporary art. This indoor activity is perfect for a cloudy day.\n", + "\n", + "- **Afternoon:**\n", + " - **Central Park:** Head to Central Park for a refreshing walk. With 100% cloud cover, it's a great day to explore the park without the harsh sun. Consider visiting the Central Park Zoo or taking a guided tour.\n", + "\n", + "- **Evening:**\n", + " - **Broadway Show:** End your day with a Broadway show. It’s an ideal indoor activity to avoid the chilly weather outside. Book tickets in advance for popular shows.\n", + "\n", + "### Day 3: Historical and Educational\n", + "- **Morning:**\n", + " - **Statue of Liberty and Ellis Island:** Take a ferry to visit these iconic sites. Dress warmly for the ferry ride. The cloud cover will provide a unique perspective for photos.\n", + "\n", + "- **Afternoon:**\n", + " - **9/11 Memorial and Museum:** Spend your afternoon reflecting at the 9/11 Memorial and exploring the museum exhibits.\n", + "\n", + "- **Evening:**\n", + " - **Brooklyn Bridge:** Walk across the Brooklyn Bridge and enjoy the city skyline. With the wind speed at 5.81 m/s, be prepared for breezy conditions.\n", + "\n", + "### Additional Tips:\n", + "- **Clothing:** Wear layers to keep warm, as the temperature feels colder than it actually is.\n", + "- **Dining:** New York offers a plethora of dining options. Consider trying some local favorites like a classic New York bagel or pizza.\n", + "- **Transportation:** Utilize the subway for efficient travel across the city. Taxis and ride-sharing services are also readily available.\n", + "\n", + "For more details on attractions and guided tours, you can visit [USA Guided Tours](https://usaguidedtours.com/nyc/attraction/) and [I Love NY](https://www.iloveny.com/places-to-go/new-york-city/attractions/). \n", + "\n", + "Enjoy your trip to New York City!\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: **Day 1: Exploring Iconic London Landmarks**\n", + "\n", + "**Morning:**\n", + "1. **Buckingham Palace**\n", + " - Start your day early with a visit to Buckingham Palace. Arrive by 9:30 AM to catch the Changing of the Guard ceremony, which typically starts at 11:00 AM. Enjoy the majestic architecture and the surrounding gardens.\n", + " - Weather Tip: With the overcast clouds, it might feel chilly, so dress warmly and bring an umbrella just in case.\n", + "\n", + "**Midday:**\n", + "2. **Westminster Abbey**\n", + " - Head towards Westminster Abbey, a short walk from Buckingham Palace. This historic church has been the site of many significant events, including royal weddings and coronations. Spend about 1.5 hours exploring.\n", + "\n", + "3. **Lunch at Borough Market**\n", + " - Take a tube or walk to Borough Market for a variety of food options. It's a great place to warm up with some hot street food and explore the diverse culinary offerings.\n", + "\n", + "**Afternoon:**\n", + "4. **London Eye**\n", + " - After lunch, head to the London Eye. The overcast sky might not offer the clearest views, but the experience is still worthwhile. Pre-book your tickets to avoid long lines and enjoy a 30-minute ride on this iconic Ferris wheel.\n", + "\n", + "**Evening:**\n", + "5. **The Globe Theatre**\n", + " - As the day winds down, visit Shakespeare's Globe Theatre. If there's a performance, consider attending or simply take a guided tour to learn about the history of this famous theater.\n", + "\n", + "**Day 2: Museums and Cultural Exploration**\n", + "\n", + "**Morning:**\n", + "1. **The British Museum**\n", + " - Start your second day at the British Museum. Spend a few hours exploring the vast collection of art and antiquities. Highlights include the Rosetta Stone and the Elgin Marbles.\n", + "\n", + "**Midday:**\n", + "2. **Lunch near Covent Garden**\n", + " - Head to Covent Garden for lunch. This area is bustling with restaurants and cafes, perfect for a cozy indoor meal.\n", + "\n", + "**Afternoon:**\n", + "3. **The Tower of London**\n", + " - After lunch, make your way to the Tower of London. Delve into England's rich history and see the Crown Jewels. Allocate about 2-3 hours for this visit.\n", + "\n", + "**Evening:**\n", + "4. **Tower Bridge**\n", + " - Conclude your day with a walk across Tower Bridge. The views of the Thames River and the cityscape are beautiful, even on a cloudy evening.\n", + "\n", + "**Day 3: Leisure and Local Experiences**\n", + "\n", + "**Morning:**\n", + "1. **Natural History Museum**\n", + " - Begin your last day at the Natural History Museum. It's a family-friendly museum with fascinating exhibits, including dinosaur skeletons and a model of a blue whale.\n", + "\n", + "**Midday:**\n", + "2. **Lunch at South Kensington**\n", + " - Enjoy a relaxed lunch in South Kensington. There are plenty of options, from casual cafes to high-end dining.\n", + "\n", + "**Afternoon:**\n", + "3. **Hyde Park**\n", + " - Spend your afternoon strolling through Hyde Park. Visit the Serpentine Galleries if you're interested in contemporary art. The park's natural beauty is a peaceful retreat amidst the city hustle.\n", + "\n", + "**Evening:**\n", + "4. **Dinner and a Show in the West End**\n", + " - End your London adventure with a memorable dinner followed by a theater show in the West End. Book your tickets in advance for popular shows.\n", + "\n", + "**Additional Tips:**\n", + "- Always check the attraction websites for any specific COVID-19 guidelines or changes in operating hours.\n", + "- London’s public transport system is efficient; consider getting an Oyster card for convenient travel.\n", + "- Don't forget to dress in layers to adapt to the chilly weather, and always have your camera ready to capture memories.\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: ['Tokyo', 'In Tokyo, the current weather is as follows:\\nDetailed status: few clouds\\nWind speed: 2.57 m/s, direction: 280°\\nHumidity: 92%\\nTemperature: \\n - Current: 10.32°C\\n - High: 10.91°C\\n - Low: 9.19°C\\n - Feels like: 9.81°C\\nRain: {}\\nHeat index: None\\nCloud cover: 20%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g298184-Activities-Tokyo_Tokyo_Prefecture_Kanto.html', 'snippet': 'Things to Do in Tokyo, Japan: See Tripadvisor's 1,602,397 traveler reviews and photos of Tokyo tourist attractions. Find what to do today, this weekend, or in March. We have reviews of the best places to see in Tokyo. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Tokyo - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.lonelyplanet.com/japan/tokyo/attractions', 'snippet': 'Discover the best attractions in Tokyo including Tokyo National Museum, Ghibli Museum, and Golden Gai.', 'title': 'Must-see attractions Tokyo, Japan - Lonely Planet'}, {'link': 'https://www.japan-guide.com/e/e2164.html', 'snippet': 'The city's history can be appreciated in districts such as Asakusa and in many excellent museums, historic temples and gardens. Contrary to common perception, Tokyo also offers a number of attractive green spaces in the city center and within relatively short train rides at its outskirts.', 'title': 'Tokyo City Guide - What to do in Tokyo'}]}]\n", + "--------------------------------------------------\n", + "Transition type: init_branch\n", + "Transition output: ['Sydney', 'In Sydney, the current weather is as follows:\\nDetailed status: clear sky\\nWind speed: 2.93 m/s, direction: 348°\\nHumidity: 81%\\nTemperature: \\n - Current: 16.95°C\\n - High: 18.04°C\\n - Low: 15.42°C\\n - Feels like: 16.82°C\\nRain: {}\\nHeat index: None\\nCloud cover: 0%', {'result': [{'link': 'https://www.tripadvisor.com/Attractions-g255060-Activities-Sydney_New_South_Wales.html', 'snippet': 'Things to Do in Sydney, Australia: See Tripadvisor's 1,043,552 traveler reviews and photos of Sydney tourist attractions. Find what to do today, this weekend, or in March. We have reviews of the best places to see in Sydney. Visit top-rated & must-see attractions.', 'title': 'THE 15 BEST Things to Do in Sydney - 2024 (with Photos) - Tripadvisor'}, {'link': 'https://www.sydney.com/things-to-do/attractions', 'snippet': 'The UNESCO World Heritage-listed building offers daily guided tours, available in English, Mandarin, French, German, Japanese, Korean and Spanish. Meanwhile, Opera Bar has the best view in town, letting you sip cocktails as you marvel at the Sydney Harbour Bridge.', 'title': 'Top attractions in Sydney | Sydney.com'}, {'link': 'https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck', 'snippet': 'We’ve rounded up 19 infamous Sydney tourist stops that you'll actually enjoy, from thrilling adventures to scenic tours.', 'title': \"19 Amazing Tourist Attractions in Sydney That Don't Suck\"}]}]\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: **Tokyo Itinerary**\n", + "\n", + "**Day 1: Arrival and Exploration of Historical and Cultural Sites**\n", + "\n", + "- **Morning:**\n", + " - **Asakusa District**: Begin your day with a visit to the historic Asakusa district. Explore the iconic Senso-ji Temple, Tokyo's oldest temple. Enjoy the traditional market streets like Nakamise Street for some shopping and snacks.\n", + "\n", + "- **Afternoon:**\n", + " - **Tokyo National Museum**: Head to Ueno Park and visit the Tokyo National Museum. Discover Japan’s extensive collection of art and antiquities. This is a great spot to dive into Japanese history and culture.\n", + "\n", + "- **Evening:**\n", + " - **Dinner in Ueno**: Explore the local dining options around Ueno and enjoy a traditional Japanese dinner.\n", + "\n", + "**Day 2: Modern Tokyo and Unique Experiences**\n", + "\n", + "- **Morning:**\n", + " - **Ghibli Museum**: Start your day with a magical visit to the Ghibli Museum in Mitaka. Perfect for fans of Studio Ghibli's animated films, this museum offers a whimsical look into the creative world of Hayao Miyazaki.\n", + "\n", + "- **Afternoon:**\n", + " - **Shibuya and Harajuku**: Head towards the bustling areas of Shibuya and Harajuku. Witness the famous Shibuya Crossing and explore the trendy shops of Harajuku, especially Takeshita Street.\n", + "\n", + "- **Evening:**\n", + " - **Golden Gai**: Conclude your day in the vibrant Golden Gai district. This area is renowned for its narrow alleys filled with small bars and eateries. Experience the unique nightlife of Tokyo here.\n", + "\n", + "**Day 3: Relax and Explore Green Spaces**\n", + "\n", + "- **Morning:**\n", + " - **Shinjuku Gyoen National Garden**: Spend a peaceful morning strolling through the beautiful Shinjuku Gyoen, one of Tokyo's largest and most beautiful parks. It's a perfect spot for relaxation and enjoying nature.\n", + "\n", + "- **Afternoon:**\n", + " - **Meiji Shrine**: Visit the Meiji Shrine, located in a forested area near Harajuku and Shibuya. It's a serene place to learn about Shinto traditions and enjoy the tranquil setting.\n", + "\n", + "- **Evening:**\n", + " - **Tokyo Tower or Skytree**: End your trip with a visit to either Tokyo Tower or Tokyo Skytree for a panoramic view of the city. It's an unforgettable way to see Tokyo illuminated at night.\n", + "\n", + "**Weather Considerations:**\n", + "- With the current weather of few clouds and a mild temperature around 10.32°C, it is advisable to wear layers and carry a light jacket for comfort during outdoor activities.\n", + "- Humidity is high (92%), so be prepared for a slightly damp feeling and consider moisture-wicking clothing.\n", + "\n", + "**Additional Tips:**\n", + "- Always check the opening hours of attractions and book tickets in advance where necessary.\n", + "- Use Tokyo’s efficient public transport to move around easily.\n", + "- Consider visiting the websites linked in the attraction descriptions for more detailed information and current updates.\n", + "--------------------------------------------------\n", + "Transition type: finish_branch\n", + "Transition output: Here's a detailed itinerary for exploring some of Sydney's top tourist attractions with the current weather conditions in mind. With clear skies and pleasant temperatures, it's a perfect day to explore the outdoors and enjoy what Sydney has to offer.\n", + "\n", + "### Morning\n", + "\n", + "**9:00 AM - Sydney Opera House**\n", + "- Begin your day with a visit to the iconic Sydney Opera House. Take a guided tour to learn about its history and architecture. Tours are available in multiple languages.\n", + "- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\n", + "\n", + "**11:00 AM - Royal Botanic Garden Sydney**\n", + "- Just a short walk from the Opera House, enjoy a leisurely stroll through the Royal Botanic Garden. The clear skies will offer beautiful views of the diverse plant life and the Sydney Harbour.\n", + "\n", + "### Afternoon\n", + "\n", + "**12:30 PM - Lunch at Opera Bar**\n", + "- Head back to Opera Bar for lunch. Enjoy a refreshing cocktail with stunning views of the Sydney Harbour Bridge and the waterfront.\n", + "- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\n", + "\n", + "**2:00 PM - Sydney Harbour Bridge**\n", + "- After lunch, take a scenic walk across the Sydney Harbour Bridge. If you're up for it, consider the BridgeClimb for breathtaking panoramic views of the city.\n", + "\n", + "**4:00 PM - The Rocks**\n", + "- Explore The Rocks, one of Sydney's most historic areas. Wander through the cobbled streets, visit the local markets, and perhaps enjoy a cup of coffee at a nearby café.\n", + "\n", + "### Evening\n", + "\n", + "**6:00 PM - Darling Harbour**\n", + "- Make your way to Darling Harbour for the evening. Here you can visit attractions such as the SEA LIFE Sydney Aquarium or simply enjoy the lively atmosphere by the waterfront.\n", + "\n", + "**8:00 PM - Dinner at a Local Restaurant**\n", + "- Conclude your day with dinner at one of Darling Harbour's many restaurants. Choose from a variety of cuisines while enjoying the vibrant night scene.\n", + "\n", + "### Additional Suggestions\n", + "\n", + "- If you're interested in more unique experiences, consider visiting some of the attractions listed on [Time Out Sydney](https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck), which includes thrilling adventures and scenic tours.\n", + "\n", + "With clear skies and mild temperatures, this itinerary offers a balanced mix of cultural, historical, and scenic experiences. Enjoy your visit to Sydney!\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: [\"Here's a detailed itinerary for visiting top tourist attractions in New York, considering the current weather conditions. \\n\\n### Day 1: Iconic Landmarks and Observation Decks\\n- **Morning:**\\n - **Top of the Rock Observation Deck:** Start your day with a visit to the Top of the Rock Observation Deck at Rockefeller Plaza. The panoramic 360-degree views from the 70th floor are a must-see. Dress warmly as it feels like 5.2°C outside, and it’s quite windy.\\n - **Link for more info:** [Tripadvisor - Top of the Rock](https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html)\\n\\n- **Afternoon:**\\n - **St. Patrick’s Cathedral:** Just a short walk from Rockefeller Plaza, explore the stunning architecture of St. Patrick’s Cathedral. The overcast skies will provide a dramatic backdrop for photos.\\n - **Fifth Avenue:** Enjoy a leisurely stroll along Fifth Avenue, visiting iconic stores and landmarks.\\n\\n- **Evening:**\\n - **Times Square:** Experience the vibrant lights and energy of Times Square. The overcast clouds might enhance the brightness of the neon lights.\\n\\n### Day 2: Culture and History\\n- **Morning:**\\n - **The Museum of Modern Art (MoMA):** Spend your morning exploring MoMA’s vast collection of modern and contemporary art. This indoor activity is perfect for a cloudy day.\\n\\n- **Afternoon:**\\n - **Central Park:** Head to Central Park for a refreshing walk. With 100% cloud cover, it's a great day to explore the park without the harsh sun. Consider visiting the Central Park Zoo or taking a guided tour.\\n\\n- **Evening:**\\n - **Broadway Show:** End your day with a Broadway show. It’s an ideal indoor activity to avoid the chilly weather outside. Book tickets in advance for popular shows.\\n\\n### Day 3: Historical and Educational\\n- **Morning:**\\n - **Statue of Liberty and Ellis Island:** Take a ferry to visit these iconic sites. Dress warmly for the ferry ride. The cloud cover will provide a unique perspective for photos.\\n\\n- **Afternoon:**\\n - **9/11 Memorial and Museum:** Spend your afternoon reflecting at the 9/11 Memorial and exploring the museum exhibits.\\n\\n- **Evening:**\\n - **Brooklyn Bridge:** Walk across the Brooklyn Bridge and enjoy the city skyline. With the wind speed at 5.81 m/s, be prepared for breezy conditions.\\n\\n### Additional Tips:\\n- **Clothing:** Wear layers to keep warm, as the temperature feels colder than it actually is.\\n- **Dining:** New York offers a plethora of dining options. Consider trying some local favorites like a classic New York bagel or pizza.\\n- **Transportation:** Utilize the subway for efficient travel across the city. Taxis and ride-sharing services are also readily available.\\n\\nFor more details on attractions and guided tours, you can visit [USA Guided Tours](https://usaguidedtours.com/nyc/attraction/) and [I Love NY](https://www.iloveny.com/places-to-go/new-york-city/attractions/). \\n\\nEnjoy your trip to New York City!\", \"**Day 1: Exploring Iconic London Landmarks**\\n\\n**Morning:**\\n1. **Buckingham Palace**\\n - Start your day early with a visit to Buckingham Palace. Arrive by 9:30 AM to catch the Changing of the Guard ceremony, which typically starts at 11:00 AM. Enjoy the majestic architecture and the surrounding gardens.\\n - Weather Tip: With the overcast clouds, it might feel chilly, so dress warmly and bring an umbrella just in case.\\n\\n**Midday:**\\n2. **Westminster Abbey**\\n - Head towards Westminster Abbey, a short walk from Buckingham Palace. This historic church has been the site of many significant events, including royal weddings and coronations. Spend about 1.5 hours exploring.\\n\\n3. **Lunch at Borough Market**\\n - Take a tube or walk to Borough Market for a variety of food options. It's a great place to warm up with some hot street food and explore the diverse culinary offerings.\\n\\n**Afternoon:**\\n4. **London Eye**\\n - After lunch, head to the London Eye. The overcast sky might not offer the clearest views, but the experience is still worthwhile. Pre-book your tickets to avoid long lines and enjoy a 30-minute ride on this iconic Ferris wheel.\\n\\n**Evening:**\\n5. **The Globe Theatre**\\n - As the day winds down, visit Shakespeare's Globe Theatre. If there's a performance, consider attending or simply take a guided tour to learn about the history of this famous theater.\\n\\n**Day 2: Museums and Cultural Exploration**\\n\\n**Morning:**\\n1. **The British Museum**\\n - Start your second day at the British Museum. Spend a few hours exploring the vast collection of art and antiquities. Highlights include the Rosetta Stone and the Elgin Marbles.\\n\\n**Midday:**\\n2. **Lunch near Covent Garden**\\n - Head to Covent Garden for lunch. This area is bustling with restaurants and cafes, perfect for a cozy indoor meal.\\n\\n**Afternoon:**\\n3. **The Tower of London**\\n - After lunch, make your way to the Tower of London. Delve into England's rich history and see the Crown Jewels. Allocate about 2-3 hours for this visit.\\n\\n**Evening:**\\n4. **Tower Bridge**\\n - Conclude your day with a walk across Tower Bridge. The views of the Thames River and the cityscape are beautiful, even on a cloudy evening.\\n\\n**Day 3: Leisure and Local Experiences**\\n\\n**Morning:**\\n1. **Natural History Museum**\\n - Begin your last day at the Natural History Museum. It's a family-friendly museum with fascinating exhibits, including dinosaur skeletons and a model of a blue whale.\\n\\n**Midday:**\\n2. **Lunch at South Kensington**\\n - Enjoy a relaxed lunch in South Kensington. There are plenty of options, from casual cafes to high-end dining.\\n\\n**Afternoon:**\\n3. **Hyde Park**\\n - Spend your afternoon strolling through Hyde Park. Visit the Serpentine Galleries if you're interested in contemporary art. The park's natural beauty is a peaceful retreat amidst the city hustle.\\n\\n**Evening:**\\n4. **Dinner and a Show in the West End**\\n - End your London adventure with a memorable dinner followed by a theater show in the West End. Book your tickets in advance for popular shows.\\n\\n**Additional Tips:**\\n- Always check the attraction websites for any specific COVID-19 guidelines or changes in operating hours.\\n- London’s public transport system is efficient; consider getting an Oyster card for convenient travel.\\n- Don't forget to dress in layers to adapt to the chilly weather, and always have your camera ready to capture memories.\", \"Here’s a detailed itinerary for your visit to Paris, considering the current snowy weather conditions and top attractions:\\n\\n### Day 1: Embrace the Iconic Landmarks\\n\\n**Morning: Eiffel Tower**\\n- **Time:** 9:00 AM\\n- **Details:** Begin your day with a visit to the Eiffel Tower. Even in the snow, the tower offers stunning views of Paris. Dress warmly and enjoy hot chocolate from nearby cafes.\\n- **Link for more info:** [Tripadvisor - Things to Do in Paris](https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html)\\n\\n**Afternoon: Louvre Museum**\\n- **Time:** 1:00 PM\\n- **Details:** Spend your afternoon indoors at the Louvre Museum. With its vast collection of art and history, it's a perfect way to escape the cold. Consider taking a guided tour to make the most of your visit.\\n- **Link for more info:** [U.S. News Travel - Things To Do](https://travel.usnews.com/Paris_France/Things_To_Do/)\\n\\n**Evening: Seine River Cruise**\\n- **Time:** 6:00 PM\\n- **Details:** End your day with a magical Seine River cruise. The snow adds a picturesque touch to the illuminated landmarks. Ensure to book a heated cruise for comfort.\\n\\n### Day 2: Explore Cultural and Historical Treasures\\n\\n**Morning: Notre-Dame Cathedral**\\n- **Time:** 9:30 AM\\n- **Details:** Visit the iconic Notre-Dame Cathedral. Although some areas may be under restoration, its architecture and history are worth experiencing. Warm clothing is essential as the interior can be chilly.\\n\\n**Afternoon: Musée d'Orsay**\\n- **Time:** 1:30 PM\\n- **Details:** Head to the Musée d'Orsay, renowned for its Impressionist masterpieces. This indoor activity is ideal for escaping the cold and enjoying world-class art.\\n\\n**Evening: Montmartre and Sacré-Cœur**\\n- **Time:** 5:00 PM\\n- **Details:** Wander through the charming streets of Montmartre and visit the Sacré-Cœur Basilica. The view of Paris in the snow is breathtaking. Enjoy a cozy dinner at a local bistro in Montmartre.\\n\\n### Day 3: Discover Hidden Gems and Local Flavors\\n\\n**Morning: Le Marais District**\\n- **Time:** 10:00 AM\\n- **Details:** Explore Le Marais, known for its vibrant street art, boutiques, and cafes. Enjoy a leisurely breakfast and shop for unique souvenirs.\\n\\n**Afternoon: Palais Garnier (Opera House)**\\n- **Time:** 2:00 PM\\n- **Details:** Tour the opulent Palais Garnier. Its stunning interiors are a must-see, especially when it's snowy outside.\\n\\n**Evening: Moulin Rouge Show**\\n- **Time:** 8:00 PM\\n- **Details:** Conclude your trip with a classic Parisian experience at the Moulin Rouge. Book in advance to secure a good seat and enjoy the legendary cabaret performance.\\n\\n### Additional Tips:\\n- **Weather Preparation:** Wear layers, waterproof boots, and carry an umbrella. The snow and cold wind can be intense.\\n- **Dining:** Indulge in warm, hearty French cuisine at local cafes and restaurants. Try dishes like French onion soup, coq au vin, and tarte Tatin.\\n- **Transport:** Use public transportation to avoid the snowy streets, and consider purchasing a Paris Visite pass for unlimited travel.\\n\\nEnjoy your snowy adventure in Paris!\", \"**Tokyo Itinerary**\\n\\n**Day 1: Arrival and Exploration of Historical and Cultural Sites**\\n\\n- **Morning:**\\n - **Asakusa District**: Begin your day with a visit to the historic Asakusa district. Explore the iconic Senso-ji Temple, Tokyo's oldest temple. Enjoy the traditional market streets like Nakamise Street for some shopping and snacks.\\n\\n- **Afternoon:**\\n - **Tokyo National Museum**: Head to Ueno Park and visit the Tokyo National Museum. Discover Japan’s extensive collection of art and antiquities. This is a great spot to dive into Japanese history and culture.\\n\\n- **Evening:**\\n - **Dinner in Ueno**: Explore the local dining options around Ueno and enjoy a traditional Japanese dinner.\\n\\n**Day 2: Modern Tokyo and Unique Experiences**\\n\\n- **Morning:**\\n - **Ghibli Museum**: Start your day with a magical visit to the Ghibli Museum in Mitaka. Perfect for fans of Studio Ghibli's animated films, this museum offers a whimsical look into the creative world of Hayao Miyazaki.\\n\\n- **Afternoon:**\\n - **Shibuya and Harajuku**: Head towards the bustling areas of Shibuya and Harajuku. Witness the famous Shibuya Crossing and explore the trendy shops of Harajuku, especially Takeshita Street.\\n\\n- **Evening:**\\n - **Golden Gai**: Conclude your day in the vibrant Golden Gai district. This area is renowned for its narrow alleys filled with small bars and eateries. Experience the unique nightlife of Tokyo here.\\n\\n**Day 3: Relax and Explore Green Spaces**\\n\\n- **Morning:**\\n - **Shinjuku Gyoen National Garden**: Spend a peaceful morning strolling through the beautiful Shinjuku Gyoen, one of Tokyo's largest and most beautiful parks. It's a perfect spot for relaxation and enjoying nature.\\n\\n- **Afternoon:**\\n - **Meiji Shrine**: Visit the Meiji Shrine, located in a forested area near Harajuku and Shibuya. It's a serene place to learn about Shinto traditions and enjoy the tranquil setting.\\n\\n- **Evening:**\\n - **Tokyo Tower or Skytree**: End your trip with a visit to either Tokyo Tower or Tokyo Skytree for a panoramic view of the city. It's an unforgettable way to see Tokyo illuminated at night.\\n\\n**Weather Considerations:**\\n- With the current weather of few clouds and a mild temperature around 10.32°C, it is advisable to wear layers and carry a light jacket for comfort during outdoor activities.\\n- Humidity is high (92%), so be prepared for a slightly damp feeling and consider moisture-wicking clothing.\\n\\n**Additional Tips:**\\n- Always check the opening hours of attractions and book tickets in advance where necessary.\\n- Use Tokyo’s efficient public transport to move around easily.\\n- Consider visiting the websites linked in the attraction descriptions for more detailed information and current updates.\", \"Here's a detailed itinerary for exploring some of Sydney's top tourist attractions with the current weather conditions in mind. With clear skies and pleasant temperatures, it's a perfect day to explore the outdoors and enjoy what Sydney has to offer.\\n\\n### Morning\\n\\n**9:00 AM - Sydney Opera House**\\n- Begin your day with a visit to the iconic Sydney Opera House. Take a guided tour to learn about its history and architecture. Tours are available in multiple languages.\\n- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\\n\\n**11:00 AM - Royal Botanic Garden Sydney**\\n- Just a short walk from the Opera House, enjoy a leisurely stroll through the Royal Botanic Garden. The clear skies will offer beautiful views of the diverse plant life and the Sydney Harbour.\\n\\n### Afternoon\\n\\n**12:30 PM - Lunch at Opera Bar**\\n- Head back to Opera Bar for lunch. Enjoy a refreshing cocktail with stunning views of the Sydney Harbour Bridge and the waterfront.\\n- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\\n\\n**2:00 PM - Sydney Harbour Bridge**\\n- After lunch, take a scenic walk across the Sydney Harbour Bridge. If you're up for it, consider the BridgeClimb for breathtaking panoramic views of the city.\\n\\n**4:00 PM - The Rocks**\\n- Explore The Rocks, one of Sydney's most historic areas. Wander through the cobbled streets, visit the local markets, and perhaps enjoy a cup of coffee at a nearby café.\\n\\n### Evening\\n\\n**6:00 PM - Darling Harbour**\\n- Make your way to Darling Harbour for the evening. Here you can visit attractions such as the SEA LIFE Sydney Aquarium or simply enjoy the lively atmosphere by the waterfront.\\n\\n**8:00 PM - Dinner at a Local Restaurant**\\n- Conclude your day with dinner at one of Darling Harbour's many restaurants. Choose from a variety of cuisines while enjoying the vibrant night scene.\\n\\n### Additional Suggestions\\n\\n- If you're interested in more unique experiences, consider visiting some of the attractions listed on [Time Out Sydney](https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck), which includes thrilling adventures and scenic tours.\\n\\nWith clear skies and mild temperatures, this itinerary offers a balanced mix of cultural, historical, and scenic experiences. Enjoy your visit to Sydney!\"]\n", + "--------------------------------------------------\n", + "Transition type: finish\n", + "Transition output: {'final_plan': \"Here's a detailed itinerary for visiting top tourist attractions in New York, considering the current weather conditions. \\n\\n### Day 1: Iconic Landmarks and Observation Decks\\n- **Morning:**\\n - **Top of the Rock Observation Deck:** Start your day with a visit to the Top of the Rock Observation Deck at Rockefeller Plaza. The panoramic 360-degree views from the 70th floor are a must-see. Dress warmly as it feels like 5.2°C outside, and it’s quite windy.\\n - **Link for more info:** [Tripadvisor - Top of the Rock](https://www.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html)\\n\\n- **Afternoon:**\\n - **St. Patrick’s Cathedral:** Just a short walk from Rockefeller Plaza, explore the stunning architecture of St. Patrick’s Cathedral. The overcast skies will provide a dramatic backdrop for photos.\\n - **Fifth Avenue:** Enjoy a leisurely stroll along Fifth Avenue, visiting iconic stores and landmarks.\\n\\n- **Evening:**\\n - **Times Square:** Experience the vibrant lights and energy of Times Square. The overcast clouds might enhance the brightness of the neon lights.\\n\\n### Day 2: Culture and History\\n- **Morning:**\\n - **The Museum of Modern Art (MoMA):** Spend your morning exploring MoMA’s vast collection of modern and contemporary art. This indoor activity is perfect for a cloudy day.\\n\\n- **Afternoon:**\\n - **Central Park:** Head to Central Park for a refreshing walk. With 100% cloud cover, it's a great day to explore the park without the harsh sun. Consider visiting the Central Park Zoo or taking a guided tour.\\n\\n- **Evening:**\\n - **Broadway Show:** End your day with a Broadway show. It’s an ideal indoor activity to avoid the chilly weather outside. Book tickets in advance for popular shows.\\n\\n### Day 3: Historical and Educational\\n- **Morning:**\\n - **Statue of Liberty and Ellis Island:** Take a ferry to visit these iconic sites. Dress warmly for the ferry ride. The cloud cover will provide a unique perspective for photos.\\n\\n- **Afternoon:**\\n - **9/11 Memorial and Museum:** Spend your afternoon reflecting at the 9/11 Memorial and exploring the museum exhibits.\\n\\n- **Evening:**\\n - **Brooklyn Bridge:** Walk across the Brooklyn Bridge and enjoy the city skyline. With the wind speed at 5.81 m/s, be prepared for breezy conditions.\\n\\n### Additional Tips:\\n- **Clothing:** Wear layers to keep warm, as the temperature feels colder than it actually is.\\n- **Dining:** New York offers a plethora of dining options. Consider trying some local favorites like a classic New York bagel or pizza.\\n- **Transportation:** Utilize the subway for efficient travel across the city. Taxis and ride-sharing services are also readily available.\\n\\nFor more details on attractions and guided tours, you can visit [USA Guided Tours](https://usaguidedtours.com/nyc/attraction/) and [I Love NY](https://www.iloveny.com/places-to-go/new-york-city/attractions/). \\n\\nEnjoy your trip to New York City!\\n---------------\\n**Day 1: Exploring Iconic London Landmarks**\\n\\n**Morning:**\\n1. **Buckingham Palace**\\n - Start your day early with a visit to Buckingham Palace. Arrive by 9:30 AM to catch the Changing of the Guard ceremony, which typically starts at 11:00 AM. Enjoy the majestic architecture and the surrounding gardens.\\n - Weather Tip: With the overcast clouds, it might feel chilly, so dress warmly and bring an umbrella just in case.\\n\\n**Midday:**\\n2. **Westminster Abbey**\\n - Head towards Westminster Abbey, a short walk from Buckingham Palace. This historic church has been the site of many significant events, including royal weddings and coronations. Spend about 1.5 hours exploring.\\n\\n3. **Lunch at Borough Market**\\n - Take a tube or walk to Borough Market for a variety of food options. It's a great place to warm up with some hot street food and explore the diverse culinary offerings.\\n\\n**Afternoon:**\\n4. **London Eye**\\n - After lunch, head to the London Eye. The overcast sky might not offer the clearest views, but the experience is still worthwhile. Pre-book your tickets to avoid long lines and enjoy a 30-minute ride on this iconic Ferris wheel.\\n\\n**Evening:**\\n5. **The Globe Theatre**\\n - As the day winds down, visit Shakespeare's Globe Theatre. If there's a performance, consider attending or simply take a guided tour to learn about the history of this famous theater.\\n\\n**Day 2: Museums and Cultural Exploration**\\n\\n**Morning:**\\n1. **The British Museum**\\n - Start your second day at the British Museum. Spend a few hours exploring the vast collection of art and antiquities. Highlights include the Rosetta Stone and the Elgin Marbles.\\n\\n**Midday:**\\n2. **Lunch near Covent Garden**\\n - Head to Covent Garden for lunch. This area is bustling with restaurants and cafes, perfect for a cozy indoor meal.\\n\\n**Afternoon:**\\n3. **The Tower of London**\\n - After lunch, make your way to the Tower of London. Delve into England's rich history and see the Crown Jewels. Allocate about 2-3 hours for this visit.\\n\\n**Evening:**\\n4. **Tower Bridge**\\n - Conclude your day with a walk across Tower Bridge. The views of the Thames River and the cityscape are beautiful, even on a cloudy evening.\\n\\n**Day 3: Leisure and Local Experiences**\\n\\n**Morning:**\\n1. **Natural History Museum**\\n - Begin your last day at the Natural History Museum. It's a family-friendly museum with fascinating exhibits, including dinosaur skeletons and a model of a blue whale.\\n\\n**Midday:**\\n2. **Lunch at South Kensington**\\n - Enjoy a relaxed lunch in South Kensington. There are plenty of options, from casual cafes to high-end dining.\\n\\n**Afternoon:**\\n3. **Hyde Park**\\n - Spend your afternoon strolling through Hyde Park. Visit the Serpentine Galleries if you're interested in contemporary art. The park's natural beauty is a peaceful retreat amidst the city hustle.\\n\\n**Evening:**\\n4. **Dinner and a Show in the West End**\\n - End your London adventure with a memorable dinner followed by a theater show in the West End. Book your tickets in advance for popular shows.\\n\\n**Additional Tips:**\\n- Always check the attraction websites for any specific COVID-19 guidelines or changes in operating hours.\\n- London’s public transport system is efficient; consider getting an Oyster card for convenient travel.\\n- Don't forget to dress in layers to adapt to the chilly weather, and always have your camera ready to capture memories.\\n---------------\\nHere’s a detailed itinerary for your visit to Paris, considering the current snowy weather conditions and top attractions:\\n\\n### Day 1: Embrace the Iconic Landmarks\\n\\n**Morning: Eiffel Tower**\\n- **Time:** 9:00 AM\\n- **Details:** Begin your day with a visit to the Eiffel Tower. Even in the snow, the tower offers stunning views of Paris. Dress warmly and enjoy hot chocolate from nearby cafes.\\n- **Link for more info:** [Tripadvisor - Things to Do in Paris](https://www.tripadvisor.com/Attractions-g187147-Activities-Paris_Ile_de_France.html)\\n\\n**Afternoon: Louvre Museum**\\n- **Time:** 1:00 PM\\n- **Details:** Spend your afternoon indoors at the Louvre Museum. With its vast collection of art and history, it's a perfect way to escape the cold. Consider taking a guided tour to make the most of your visit.\\n- **Link for more info:** [U.S. News Travel - Things To Do](https://travel.usnews.com/Paris_France/Things_To_Do/)\\n\\n**Evening: Seine River Cruise**\\n- **Time:** 6:00 PM\\n- **Details:** End your day with a magical Seine River cruise. The snow adds a picturesque touch to the illuminated landmarks. Ensure to book a heated cruise for comfort.\\n\\n### Day 2: Explore Cultural and Historical Treasures\\n\\n**Morning: Notre-Dame Cathedral**\\n- **Time:** 9:30 AM\\n- **Details:** Visit the iconic Notre-Dame Cathedral. Although some areas may be under restoration, its architecture and history are worth experiencing. Warm clothing is essential as the interior can be chilly.\\n\\n**Afternoon: Musée d'Orsay**\\n- **Time:** 1:30 PM\\n- **Details:** Head to the Musée d'Orsay, renowned for its Impressionist masterpieces. This indoor activity is ideal for escaping the cold and enjoying world-class art.\\n\\n**Evening: Montmartre and Sacré-Cœur**\\n- **Time:** 5:00 PM\\n- **Details:** Wander through the charming streets of Montmartre and visit the Sacré-Cœur Basilica. The view of Paris in the snow is breathtaking. Enjoy a cozy dinner at a local bistro in Montmartre.\\n\\n### Day 3: Discover Hidden Gems and Local Flavors\\n\\n**Morning: Le Marais District**\\n- **Time:** 10:00 AM\\n- **Details:** Explore Le Marais, known for its vibrant street art, boutiques, and cafes. Enjoy a leisurely breakfast and shop for unique souvenirs.\\n\\n**Afternoon: Palais Garnier (Opera House)**\\n- **Time:** 2:00 PM\\n- **Details:** Tour the opulent Palais Garnier. Its stunning interiors are a must-see, especially when it's snowy outside.\\n\\n**Evening: Moulin Rouge Show**\\n- **Time:** 8:00 PM\\n- **Details:** Conclude your trip with a classic Parisian experience at the Moulin Rouge. Book in advance to secure a good seat and enjoy the legendary cabaret performance.\\n\\n### Additional Tips:\\n- **Weather Preparation:** Wear layers, waterproof boots, and carry an umbrella. The snow and cold wind can be intense.\\n- **Dining:** Indulge in warm, hearty French cuisine at local cafes and restaurants. Try dishes like French onion soup, coq au vin, and tarte Tatin.\\n- **Transport:** Use public transportation to avoid the snowy streets, and consider purchasing a Paris Visite pass for unlimited travel.\\n\\nEnjoy your snowy adventure in Paris!\\n---------------\\n**Tokyo Itinerary**\\n\\n**Day 1: Arrival and Exploration of Historical and Cultural Sites**\\n\\n- **Morning:**\\n - **Asakusa District**: Begin your day with a visit to the historic Asakusa district. Explore the iconic Senso-ji Temple, Tokyo's oldest temple. Enjoy the traditional market streets like Nakamise Street for some shopping and snacks.\\n\\n- **Afternoon:**\\n - **Tokyo National Museum**: Head to Ueno Park and visit the Tokyo National Museum. Discover Japan’s extensive collection of art and antiquities. This is a great spot to dive into Japanese history and culture.\\n\\n- **Evening:**\\n - **Dinner in Ueno**: Explore the local dining options around Ueno and enjoy a traditional Japanese dinner.\\n\\n**Day 2: Modern Tokyo and Unique Experiences**\\n\\n- **Morning:**\\n - **Ghibli Museum**: Start your day with a magical visit to the Ghibli Museum in Mitaka. Perfect for fans of Studio Ghibli's animated films, this museum offers a whimsical look into the creative world of Hayao Miyazaki.\\n\\n- **Afternoon:**\\n - **Shibuya and Harajuku**: Head towards the bustling areas of Shibuya and Harajuku. Witness the famous Shibuya Crossing and explore the trendy shops of Harajuku, especially Takeshita Street.\\n\\n- **Evening:**\\n - **Golden Gai**: Conclude your day in the vibrant Golden Gai district. This area is renowned for its narrow alleys filled with small bars and eateries. Experience the unique nightlife of Tokyo here.\\n\\n**Day 3: Relax and Explore Green Spaces**\\n\\n- **Morning:**\\n - **Shinjuku Gyoen National Garden**: Spend a peaceful morning strolling through the beautiful Shinjuku Gyoen, one of Tokyo's largest and most beautiful parks. It's a perfect spot for relaxation and enjoying nature.\\n\\n- **Afternoon:**\\n - **Meiji Shrine**: Visit the Meiji Shrine, located in a forested area near Harajuku and Shibuya. It's a serene place to learn about Shinto traditions and enjoy the tranquil setting.\\n\\n- **Evening:**\\n - **Tokyo Tower or Skytree**: End your trip with a visit to either Tokyo Tower or Tokyo Skytree for a panoramic view of the city. It's an unforgettable way to see Tokyo illuminated at night.\\n\\n**Weather Considerations:**\\n- With the current weather of few clouds and a mild temperature around 10.32°C, it is advisable to wear layers and carry a light jacket for comfort during outdoor activities.\\n- Humidity is high (92%), so be prepared for a slightly damp feeling and consider moisture-wicking clothing.\\n\\n**Additional Tips:**\\n- Always check the opening hours of attractions and book tickets in advance where necessary.\\n- Use Tokyo’s efficient public transport to move around easily.\\n- Consider visiting the websites linked in the attraction descriptions for more detailed information and current updates.\\n---------------\\nHere's a detailed itinerary for exploring some of Sydney's top tourist attractions with the current weather conditions in mind. With clear skies and pleasant temperatures, it's a perfect day to explore the outdoors and enjoy what Sydney has to offer.\\n\\n### Morning\\n\\n**9:00 AM - Sydney Opera House**\\n- Begin your day with a visit to the iconic Sydney Opera House. Take a guided tour to learn about its history and architecture. Tours are available in multiple languages.\\n- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\\n\\n**11:00 AM - Royal Botanic Garden Sydney**\\n- Just a short walk from the Opera House, enjoy a leisurely stroll through the Royal Botanic Garden. The clear skies will offer beautiful views of the diverse plant life and the Sydney Harbour.\\n\\n### Afternoon\\n\\n**12:30 PM - Lunch at Opera Bar**\\n- Head back to Opera Bar for lunch. Enjoy a refreshing cocktail with stunning views of the Sydney Harbour Bridge and the waterfront.\\n- **Link:** [Top attractions in Sydney | Sydney.com](https://www.sydney.com/things-to-do/attractions)\\n\\n**2:00 PM - Sydney Harbour Bridge**\\n- After lunch, take a scenic walk across the Sydney Harbour Bridge. If you're up for it, consider the BridgeClimb for breathtaking panoramic views of the city.\\n\\n**4:00 PM - The Rocks**\\n- Explore The Rocks, one of Sydney's most historic areas. Wander through the cobbled streets, visit the local markets, and perhaps enjoy a cup of coffee at a nearby café.\\n\\n### Evening\\n\\n**6:00 PM - Darling Harbour**\\n- Make your way to Darling Harbour for the evening. Here you can visit attractions such as the SEA LIFE Sydney Aquarium or simply enjoy the lively atmosphere by the waterfront.\\n\\n**8:00 PM - Dinner at a Local Restaurant**\\n- Conclude your day with dinner at one of Darling Harbour's many restaurants. Choose from a variety of cuisines while enjoying the vibrant night scene.\\n\\n### Additional Suggestions\\n\\n- If you're interested in more unique experiences, consider visiting some of the attractions listed on [Time Out Sydney](https://www.timeout.com/sydney/attractions/tourist-attractions-that-dont-suck), which includes thrilling adventures and scenic tours.\\n\\nWith clear skies and mild temperatures, this itinerary offers a balanced mix of cultural, historical, and scenic experiences. Enjoy your visit to Sydney!\"}\n", + "--------------------------------------------------\n" + ] + } + ], + "source": [ + "# Lists all the task steps that have been executed up to this point in time\n", + "transitions = client.executions.transitions.list(execution_id=execution.id).items\n", + "\n", + "# Transitions are retreived in reverse chronological order\n", + "for transition in reversed(transitions):\n", + " print(\"Transition type: \", transition.type)\n", + " print(\"Transition output: \", transition.output)\n", + " print(\"-\"*50)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "ai", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/cookbooks/04-TripPlanner_With_Weather_And_WikiInfo.py b/cookbooks/03-trip-planning-assistant.py similarity index 100% rename from cookbooks/04-TripPlanner_With_Weather_And_WikiInfo.py rename to cookbooks/03-trip-planning-assistant.py diff --git a/cookbooks/04-TripPlanner_With_Weather_And_WikiInfo.ipynb b/cookbooks/04-TripPlanner_With_Weather_And_WikiInfo.ipynb deleted file mode 100644 index dad492f20..000000000 --- a/cookbooks/04-TripPlanner_With_Weather_And_WikiInfo.ipynb +++ /dev/null @@ -1,418 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "
\n", - " \"julep\"\n", - "
\n", - "\n", - "## Task: Travel Itinerary Assistant with Weather and Wikipedia Integrations\n", - "\n", - "### Overview\n", - "\n", - "The Travel Itinerary Assistant helps users plan a travel itinerary that takes into account current weather conditions and local tourist attractions. By integrating data from Wikipedia for tourist attractions and using a weather API for real-time weather updates, the tool provides a comprehensive travel plan tailored to each location. The generated itinerary suggests appropriate activities based on the weather, enhancing the overall travel experience.\n", - "\n", - "### Task Flow\n", - "\n", - "1. **User Input**\n", - " - User provides a list of desired travel locations.\n", - " - Each location is processed individually to gather the required data.\n", - "\n", - "2. **Weather Data Retrieval**\n", - " - Fetch current weather data for each location using a weather API.\n", - " - Extract relevant weather details, such as temperature, weather condition, and recommendations.\n", - "\n", - "3. **Tourist Attractions Lookup**\n", - " - Use Wikipedia to search for the top tourist attractions for each location.\n", - " - The query format used is: `\" tourist attractions\"`.\n", - " - Retrieve and compile a list of popular tourist spots and landmarks.\n", - "\n", - "4. **Data Evaluation and Integration**\n", - " - Combine weather data and tourist attractions into a unified list for each location.\n", - " - Format the data into a structured tuple: `(location, weather, attractions)`.\n", - "\n", - "5. **Itinerary Generation**\n", - " - Create a detailed travel itinerary based on:\n", - " - Current weather conditions (e.g., sunny, rainy, cloudy).\n", - " - Top tourist attractions for each location.\n", - " - Suggested activities categorized as indoor or outdoor based on weather.\n", - "\n", - "### Key Features\n", - "\n", - "- **Multi-location Travel Planning**: Handles multiple destinations simultaneously, offering a consolidated travel plan.\n", - "- **Real-time Weather Data**: Leverages weather APIs to provide up-to-date weather conditions.\n", - "- **Tourist Attraction Discovery**: Integrates Wikipedia to find and recommend popular attractions.\n", - "- **Intelligent Itinerary Suggestions**: Suggests indoor or outdoor activities based on the weather.\n", - "- **Comprehensive Itinerary Output**: Combines weather and tourist data into a user-friendly travel plan.\n", - "\n", - "### Output\n", - "\n", - "- A detailed travel itinerary for each location\n", - "- Curated, up-to-date information gathered from weather searches and Wikipedia\n", - "\n", - "```plaintext\n", - "\n", - "+----------------+ +--------------------------+ +--------------------------+ +------------------------------+ +-------------------------+\n", - "| User Input | | Weather Data Retrieval | | Tourist Attractions | | Data Evaluation & Integration| | Itinerary Generation |\n", - "| (List of | --> | (Weather API) | --> | Lookup (Wikipedia) | --> | (Combine Weather & | --> | (Generate Suggested |\n", - "| Locations) | | | | | | Attractions Data) | | Activities/Plan) |\n", - "+----------------+ +--------------------------+ +--------------------------+ +------------------------------+ +-------------------------+\n", - " | | | | |\n", - " | | | | |\n", - " v v v v v\n", - "Location 1, Location 2, ... Fetch weather for each Search Wikipedia for Combine weather data and Create itinerary with\n", - "Each location processed location individually, \" tourist tourist attractions into suggested activities\n", - "individually for extracting temp., attractions\", retrieve a structured tuple: based on weather and\n", - "weather data. conditions, & top spots. (location, weather, attractions.\n", - " recommendations. attractions).\n", - "```\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Implementation\n", - "\n", - "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", - "\n", - "\n", - " \"Open\n", - "\n", - "\n", - "### Additional Information\n", - "\n", - "For more details about the task or if you have any questions, please don't hesitate to contact the author:\n", - "\n", - "**Author:** Julep AI \n", - "**Contact:** [hey@julep.ai](mailto:hey@julep.ai) or Discord" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Installing the Julep Client" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [], - "source": [ - "!pip install julep -U --quiet" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### NOTE:\n", - "\n", - "- UUIDs are generated for both the agent and task to uniquely identify them within the system.\n", - "- Once created, these UUIDs should remain unchanged for simplicity.\n", - "- Altering a UUID will result in the system treating it as a new agent or task.\n", - "- If a UUID is changed, the original agent or task will continue to exist in the system alongside the new one." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "metadata": {}, - "outputs": [], - "source": [ - "# Global UUID is generated for agent and task\n", - "import uuid\n", - "\n", - "AGENT_UUID = uuid.uuid4()\n", - "TASK_UUID = uuid.uuid4() " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Creating Julep Client with the API Key" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": {}, - "outputs": [], - "source": [ - "from julep import Client\n", - "\n", - "api_key = \"\" # Your API key here\n", - "\n", - "# Create a client\n", - "client = Client(api_key=api_key, environment=\"dev\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating an \"agent\"\n", - "\n", - "\n", - "Agent is the object to which LLM settings, like model, temperature along with tools are scoped to.\n", - "\n", - "To learn more about the agent, please refer to the [documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#agent)." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": {}, - "outputs": [], - "source": [ - "# Defining the agent\n", - "name = \"Jarvis\"\n", - "about = \"The original AI conscious the Iron Man.\"\n", - "default_settings = {\n", - " \"temperature\": 0.7,\n", - " \"top_p\": 1,\n", - " \"min_p\": 0.01,\n", - " \"presence_penalty\": 0,\n", - " \"frequency_penalty\": 0,\n", - " \"length_penalty\": 1.0,\n", - " \"max_tokens\": 150,\n", - "}\n", - "\n", - "# Create the agent\n", - "agent = client.agents.create_or_update(\n", - " agent_id=AGENT_UUID,\n", - " name=name,\n", - " about=about,\n", - " model=\"gpt-4o\",\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Defining a Task\n", - "\n", - "Tasks in Julep are Github Actions style workflows that define long-running, multi-step actions. \n", - "You can use them to conduct complex actions by defining them step-by-step. They have access to all Julep integrations.\n", - "\n", - "To learn more about tasks, visit [Julep documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#task)." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": {}, - "outputs": [], - "source": [ - "import yaml" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "More on how to define a task can be found [here](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md)." - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "metadata": {}, - "outputs": [], - "source": [ - "task_def = yaml.safe_load(\"\"\"\n", - "name: Tourist Plan With Weather And Attractions\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " locations:\n", - " type: array\n", - " items:\n", - " type: string\n", - " description: The locations to search for.\n", - "\n", - "tools:\n", - "- name: wikipedia\n", - " type: integration\n", - " integration:\n", - " provider: wikipedia\n", - "\n", - "- name: weather\n", - " type: integration\n", - " integration:\n", - " provider: weather\n", - " setup:\n", - " openweathermap_api_key: \"YOUR_API_KEY\"\n", - "\n", - "main:\n", - "- over: inputs[0].locations\n", - " map:\n", - " tool: weather\n", - " arguments:\n", - " location: _\n", - "\n", - "- over: inputs[0].locations\n", - " map:\n", - " tool: wikipedia\n", - " arguments:\n", - " query: \"_ + ' tourist attractions'\"\n", - "\n", - "- evaluate:\n", - " zipped: \"list(zip(inputs[0].locations, [output['result'] for output in outputs[0]], [output['documents'][0]['page_content'] for output in outputs[1]]))\" # [(location, weather, attractions)]\n", - "\n", - "\n", - "- over: _['zipped']\n", - " parallelism: 3\n", - " map:\n", - " prompt:\n", - " - role: system\n", - " content: >-\n", - " You are a travel assistant. Your task is to create a detailed itinerary for visiting tourist attractions in \"{{_[0]}}\" based on the weather conditions and the top tourist attractions provided.\n", - " \n", - " Current weather condition at \"{{_[0]}}\":\n", - " \"{{_[1]}}\"\n", - "\n", - " Top tourist attractions in \"{{_[0]}}\":\n", - " \"{{_[2]}}\"\n", - "\n", - " Suggest outdoor or indoor activities based on the above information.\n", - " unwrap: true\n", - "\"\"\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creating/Updating a task." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "metadata": {}, - "outputs": [], - "source": [ - "# creating the task object\n", - "task = client.tasks.create_or_update(\n", - " task_id=TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **task_def\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Creating an Execution\n", - "\n", - "An execution is a single run of a task. It is a way to run a task with a specific set of inputs." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Creates a execution worklow for the Task defined in the yaml file." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "metadata": {}, - "outputs": [], - "source": [ - "execution = client.executions.create(\n", - " task_id=task.id,\n", - " input={\n", - " \"locations\": [\"New York\", \"London\", \"Paris\", \"Tokyo\", \"Sydney\"]\n", - " }\n", - ")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "execution.id" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "metadata": {}, - "outputs": [], - "source": [ - "# getting the execution details\n", - "execution = client.executions.get(execution.id)\n", - "#printing the output\n", - "execution.output" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Retrieves and lists all the steps of a defined task that have been executed up to that point in time. Unlike streaming, this function does not continuously monitor the execution; it only provides a snapshot of the steps completed so far without displaying real-time updates as the task progresses." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "client.executions.transitions.list(execution_id=execution.id).items" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Continuously monitor and stream the steps of a defined task. It retrieves and displays the transitions or execution steps of the task identified by execution.id in real-time, showing each step sequentially until the task is either completed or an error causes it to terminate." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "metadata": {}, - "outputs": [], - "source": [ - "client.executions.transitions.stream(execution_id=execution.id)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "ai", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.11.5" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/cookbooks/17-Hook-Generator-Trending-Reels.ipynb b/cookbooks/04-hook-generator-trending-reels.ipynb similarity index 99% rename from cookbooks/17-Hook-Generator-Trending-Reels.ipynb rename to cookbooks/04-hook-generator-trending-reels.ipynb index fbe8df06f..a42bf7e50 100644 --- a/cookbooks/17-Hook-Generator-Trending-Reels.ipynb +++ b/cookbooks/04-hook-generator-trending-reels.ipynb @@ -53,7 +53,7 @@ "\n", "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", "\n", - "\n", + "\n", " \"Open\n", "\n", "\n", diff --git a/cookbooks/17-Hook-Generator-Trending-Reels.py b/cookbooks/04-hook-generator-trending-reels.py similarity index 100% rename from cookbooks/17-Hook-Generator-Trending-Reels.py rename to cookbooks/04-hook-generator-trending-reels.py diff --git a/cookbooks/05-Basic_Agent_Creation_and_Interaction.py b/cookbooks/05-Basic_Agent_Creation_and_Interaction.py deleted file mode 100644 index e57a38560..000000000 --- a/cookbooks/05-Basic_Agent_Creation_and_Interaction.py +++ /dev/null @@ -1,70 +0,0 @@ -# BASIC AGENT CREATION AND INTERACTION - -import uuid -from julep import Client - -# Global UUID is generated for agent -AGENT_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an "agent" -name = "Jarvis" -about = "A friendly and knowledgeable AI assistant." -default_settings = { - "temperature": 0.7, - "top_p": 1, - "min_p": 0.01, - "presence_penalty": 0, - "frequency_penalty": 0, - "length_penalty": 1.0, - "max_tokens": 150, -} - -# Create the agent -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name=name, - about=about, - model="gpt-4o", -) - -print(f"Agent created with ID: {agent.id}") - -# Create a session for interaction -session = client.sessions.create( - agent=agent.id -) - -print(f"Session created with ID: {session.id}") - -# Function to chat with the agent -def chat_with_agent(message): - message = { - "role": "user", - "content": message, - } - response = client.sessions.chat( - session_id=session.id, - messages=[message], - ) - return response.choices[0].message.content - -# Demonstrate basic interaction -print("Agent: Hello! I'm Jarvis, your AI assistant. How can I help you today?") - -while True: - user_input = input("You: ") - if user_input.lower() in ['exit', 'quit', 'bye']: - print("Agent: Goodbye! It was nice chatting with you.") - break - - response = chat_with_agent(user_input) - print(f"Agent: {response}") - -# Optional: Retrieve chat history -history = client.sessions.get(session_id=session.id) -print("\nChat History:") -print(history) \ No newline at end of file diff --git a/cookbooks/05-video-processing-with-natural-language.ipynb b/cookbooks/05-video-processing-with-natural-language.ipynb new file mode 100644 index 000000000..a78198ca2 --- /dev/null +++ b/cookbooks/05-video-processing-with-natural-language.ipynb @@ -0,0 +1,545 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + " \"julep\"\n", + "
\n", + "\n", + "## Task Definition: Video Processing with Natural Language\n", + "\n", + "### Overview\n", + "\n", + "This task is leverages the cloudinary `integration` tool, and combines it with a prompt step to convert a natural language instructions and apply them to a given video.\n", + "\n", + "### Task Tools:\n", + "\n", + "**Cloudinary**: An `integration` type tool that can upload and transform media files.\n", + "\n", + "### Task Input:\n", + "\n", + "**video_url**: The URL of the video to transform.\n", + "\n", + "**public_id**: The public id of the video to transform.\n", + "\n", + "**transformation_prompt**: The natural language instructions to apply to the video.\n", + "\n", + "### Task Output:\n", + "\n", + "**transformed_video_url**: The URL of the transformed video.\n", + "\n", + "### Task Flow\n", + "\n", + "1. **Input**: The user provides a URL to a video and transoformation instrucitons (in natural language) to apply to the video.\n", + "\n", + "2. **Cloudinary Tool Integration**: The `cloudinary_upload` tool is called to upload the video to cloudinary.\n", + "\n", + "3. **Prompt Step**: The prompt step is used to convert the natural language instructions into a json of transformation instructions that are compatible with cloudinary's API. In this step, `gemini-1.5-pro` is used as the model due to its ability to read video files.\n", + "\n", + "4. **Cloudinary Tool Integration**: The `cloudinary_upload` tool is called again to apply the transformation instructions to the video.\n", + "\n", + "5. **Output**: The final output is the URL of the transformed video." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Implementation\n", + "\n", + "To recreate the notebook and see the code implementation for this task, you can access the Google Colab notebook using the link below:\n", + "\n", + "\n", + " \"Open\n", + "\n", + "\n", + "### Additional Information\n", + "\n", + "For more details about the task or if you have any questions, please don't hesitate to contact the author:\n", + "\n", + "**Author:** Julep AI \n", + "**Contact:** [hey@julep.ai](mailto:hey@julep.ai) or Discord" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Installing the Julep Client" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "!pip install --upgrade julep --quiet" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "import uuid\n", + "\n", + "# NOTE: these UUIDs are used in order not to use the `create_or_update` methods instead of\n", + "# the `create` methods for the sake of not creating new resources every time a cell is run.\n", + "AGENT_UUID = uuid.uuid4()\n", + "TASK_UUID = uuid.uuid4()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Creating Julep Client with the API Key" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "from julep import Client\n", + "import os\n", + "\n", + "api_key = os.getenv(\"JULEP_API_KEY\")\n", + "\n", + "# Create a Julep client\n", + "client = Client(api_key=api_key, environment=\"dev\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an \"agent\"\n", + "\n", + "Agent is the object to which LLM settings, like model, temperature along with tools are scoped to.\n", + "\n", + "To learn more about the agent, please refer to the [documentation](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#agent)." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# Create agent\n", + "agent = client.agents.create_or_update(\n", + " agent_id=AGENT_UUID,\n", + " name=\"Spiderman\",\n", + " about=\"AI that can crawl the web and extract data\",\n", + " model=\"gpt-4o\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Defining a Task\n", + "\n", + "Tasks in Julep are Github-Actions-style workflows that define long-running, multi-step actions.\n", + "\n", + "You can use them to conduct complex actions by defining them step-by-step.\n", + "\n", + "To learn more about tasks, please refer to the `Tasks` section in [Julep Concepts](https://github.com/julep-ai/julep/blob/dev/docs/julep-concepts.md#tasks)." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [], + "source": [ + "import yaml\n", + "\n", + "cloudinary_api_key = os.getenv(\"CLOUDINARY_API_KEY\")\n", + "cloudinary_api_secret = os.getenv(\"CLOUDINARY_API_SECRET\")\n", + "cloudinary_cloud_name = os.getenv(\"CLOUDINARY_CLOUD_NAME\")\n", + "\n", + "# Define the task\n", + "task_def = yaml.safe_load(f\"\"\"\n", + "name: Video Processing With Natural Language\n", + "\n", + "input_schema:\n", + " type: object\n", + " properties:\n", + " video_url:\n", + " type: string\n", + " description: The url of the file to upload\n", + " public_id:\n", + " type: string\n", + " description: The public id of the file to upload\n", + " transformation_prompt:\n", + " type: string\n", + " description: The prompt for the transformations to apply to the file\n", + "\n", + "tools:\n", + "- name: cloudinary_upload\n", + " type: integration\n", + " integration:\n", + " provider: cloudinary\n", + " method: media_upload\n", + " setup:\n", + " cloudinary_api_key: \"{cloudinary_api_key}\"\n", + " cloudinary_api_secret: \"{cloudinary_api_secret}\"\n", + " cloudinary_cloud_name: \"{cloudinary_cloud_name}\"\n", + "\n", + "main:\n", + "- tool: cloudinary_upload\n", + " arguments:\n", + " file: '_0.video_url'\n", + " public_id: '_0.public_id'\n", + " upload_params:\n", + " resource_type: \"'video'\"\n", + "\n", + "- prompt:\n", + " - role: user\n", + " content:\n", + "\n", + " - type: text\n", + " text: |-\n", + " You are a Cloudinary expert. You are given a medial url. it might be an image or a video.\n", + " You need to come up with a json of transformations to apply to the given media.\n", + " Overall the json could have multiple transformation json objects.\n", + " Each transformation json object can have the multiple key value pairs.\n", + " Each key value pair should have the key as the transformation name like \"aspect_ratio\", \"crop\", \"width\" etc and the value as the transformation parameter value.\n", + " Given below is an example of a transformation json list. Don't provide explanations and/or comments in the json.\n", + " ```json\n", + " [\n", + " {{\n", + " \"aspect_ratio\": \"1.0\",\n", + " \"width\": 250,\n", + " }},\n", + " {{\n", + " \"fetch_format\": \"auto\"\n", + " }},\n", + " {{\n", + " \"overlay\":\n", + " {{\n", + " \"url\": \"\"\n", + " }}\n", + " }},\n", + " {{\n", + " \"flags\": \"layer_apply\"\n", + " }}\n", + " ]\n", + " ```\n", + " - type: image_url\n", + " image_url:\n", + " url: \"{{{{_.url}}}}\"\n", + "\n", + " - type: text\n", + " text: |-\n", + " Hey, check the video above, I need to apply the following transformations using cloudinary.\n", + " {{{{_0.transformation_prompt}}}}\n", + "\n", + " unwrap: true\n", + " settings:\n", + " model: gemini/gemini-1.5-pro\n", + "\n", + "# Extract the json from the model's response\n", + "- evaluate:\n", + " model_transformation: load_json(\n", + " _[_.find(\"```json\")+7:][:_[_.find(\"```json\")+7:].find(\"```\")])\n", + "\n", + "- tool: cloudinary_upload\n", + " arguments:\n", + " file: '_0.video_url'\n", + " public_id: '_0.public_id'\n", + " upload_params:\n", + " transformation: '_.model_transformation'\n", + " resource_type: \"'video'\"\n", + "\n", + "- evaluate:\n", + " transformed_video_url: '_.url'\n", + "\"\"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notes:\n", + "- The reason for using the quadruple curly braces `{{{{}}}}` for the jinja template is to avoid conflicts with the curly braces when using the `f` formatted strings in python. [More information here](https://stackoverflow.com/questions/64493332/jinja-templating-in-airflow-along-with-formatted-text)\n", + "- The `unwrap: True` in the prompt step is used to unwrap the output of the prompt step (to unwrap the `choices[0].message.content` from the output of the model).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating/Updating a task" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [], + "source": [ + "# creating the task object\n", + "task = client.tasks.create_or_update(\n", + " task_id=TASK_UUID,\n", + " agent_id=AGENT_UUID,\n", + " **task_def\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating an Execution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "An execution is a single run of a task. It is a way to run a task with a specific set of inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'1021a8d6-5050-48c3-b23e-6d96578d1026'" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# creating an execution object\n", + "transformation_prompt = \"\"\"\n", + "1- I want to add an overlay an the following image to the video, and apply a layer apply flag also. Here's the image url:\n", + "https://res.cloudinary.com/demo/image/upload/logos/cloudinary_icon_white.png\n", + "\n", + "2- I also want you to to blur the video, and add a fade in and fade out effect to the video with a duration of 3 seconds each.\n", + "\"\"\"\n", + "\n", + "input_video_url = \"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4\"\n", + "\n", + "execution = client.executions.create(\n", + " task_id=TASK_UUID,\n", + " input={\n", + " \"video_url\": input_video_url,\n", + " \"public_id\": \"video_test2\",\n", + " \"transformation_prompt\": transformation_prompt,\n", + " }\n", + ")\n", + "execution.id" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Checking execution details and output" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are multiple ways to get the execution details and the output:\n", + "\n", + "1. **Get Execution Details**: This method retrieves the details of the execution, including the output of the last transition that took place.\n", + "\n", + "2. **List Transitions**: This method lists all the task steps that have been executed up to this point in time, so the output of a successful execution will be the output of the last transition (first in the transition list as it is in reverse chronological order), which should have a type of `finish`.\n", + "\n", + "\n", + "Note: You need to wait for a few seconds for the execution to complete before you can get the final output, so feel free to run the following cells multiple times until you get the final output.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'base64': None, 'meta_data': {'api_key': '518455844981529', 'asset_folder': '', 'asset_id': '069d70c84e88ee9293a1d753b3ca3898', 'audio': {'bit_rate': '191999', 'channel_layout': 'stereo', 'channels': 2, 'codec': 'aac', 'frequency': 44100}, 'bit_rate': 1197518, 'bytes': 2252313, 'created_at': '2024-11-20T08:55:44Z', 'display_name': 'video_test2', 'duration': 15.046531, 'etag': '9e87559cba36e6d07f7435c2a8081b3a', 'format': 'mp4', 'frame_rate': 24.0, 'height': 720, 'is_audio': False, 'nb_frames': 361, 'original_filename': 'ForBiggerMeltdowns', 'overwritten': True, 'pages': 0, 'placeholder': False, 'playback_url': 'https://res.cloudinary.com/dpnjjk8mb/video/upload/sp_auto/v1732200108/video_test2.m3u8', 'resource_type': 'video', 'rotation': 0, 'signature': 'e65a0d39a282fc8bd4dd3288d7d35dfffdadc2a8', 'tags': [], 'type': 'upload', 'url': 'http://res.cloudinary.com/dpnjjk8mb/video/upload/v1732200108/video_test2.mp4', 'version': 1732200108, 'version_id': 'a9fccdf7b310edb3c2ff5ffe9335f7f8', 'video': {'bit_rate': '1002377', 'codec': 'h264', 'level': 31, 'pix_format': 'yuv420p', 'profile': 'High', 'time_base': '1/48'}, 'width': 1280}, 'public_id': 'video_test2', 'url': 'https://res.cloudinary.com/dpnjjk8mb/video/upload/v1732200108/video_test2.mp4'}\n" + ] + } + ], + "source": [ + "# Get execution details\n", + "execution = client.executions.get(execution.id)\n", + "# Print the output\n", + "print(execution.output)" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Transition type: init\n", + "Transition output: {'public_id': 'video_test2', 'transformation_prompt': \"\\n1- I want to add an overlay an the following image to the video, and apply a layer apply flag also. Here's the image url:\\nhttps://res.cloudinary.com/demo/image/upload/logos/cloudinary_icon_white.png\\n\\n2- I also want you to to blur the video, and add a fade in and fade out effect to the video with a duration of 3 seconds each.\\n\", 'video_url': 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4'}\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: {'base64': None, 'meta_data': {'api_key': '518455844981529', 'asset_folder': '', 'asset_id': '069d70c84e88ee9293a1d753b3ca3898', 'audio': {'bit_rate': '191999', 'channel_layout': 'stereo', 'channels': 2, 'codec': 'aac', 'frequency': 44100}, 'bit_rate': 1197518, 'bytes': 2252313, 'created_at': '2024-11-20T08:55:44Z', 'display_name': 'video_test2', 'duration': 15.046531, 'etag': '9e87559cba36e6d07f7435c2a8081b3a', 'format': 'mp4', 'frame_rate': 24.0, 'height': 720, 'is_audio': False, 'nb_frames': 361, 'original_filename': 'ForBiggerMeltdowns', 'overwritten': True, 'pages': 0, 'placeholder': False, 'playback_url': 'https://res.cloudinary.com/dpnjjk8mb/video/upload/sp_auto/v1732200198/video_test2.m3u8', 'resource_type': 'video', 'rotation': 0, 'signature': 'f46b7d3d234cd8d4c0f15423b507768df17f2ff6', 'tags': [], 'type': 'upload', 'url': 'http://res.cloudinary.com/dpnjjk8mb/video/upload/v1732200198/video_test2.mp4', 'version': 1732200198, 'version_id': '5ed8eae9dc683377dc4713767bf729f0', 'video': {'bit_rate': '1002377', 'codec': 'h264', 'level': 31, 'pix_format': 'yuv420p', 'profile': 'High', 'time_base': '1/48'}, 'width': 1280}, 'public_id': 'video_test2', 'url': 'https://res.cloudinary.com/dpnjjk8mb/video/upload/v1732200198/video_test2.mp4'}\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: ```json\n", + "[\n", + " {\n", + " \"overlay\": {\n", + " \"url\": \"https://res.cloudinary.com/demo/image/upload/logos/cloudinary_icon_white.png\"\n", + " }\n", + " },\n", + " {\n", + " \"flags\": \"layer_apply\"\n", + " },\n", + " {\n", + " \"effect\": \"blur:100\"\n", + " },\n", + " {\n", + " \"effect\": \"fade:3000\"\n", + " },\n", + " {\n", + " \"effect\": \"fade:-3000\"\n", + " }\n", + "]\n", + "```\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: {'model_transformation': [{'overlay': {'url': 'https://res.cloudinary.com/demo/image/upload/logos/cloudinary_icon_white.png'}}, {'flags': 'layer_apply'}, {'effect': 'blur:100'}, {'effect': 'fade:3000'}, {'effect': 'fade:-3000'}]}\n", + "--------------------------------------------------\n", + "Transition type: step\n", + "Transition output: {'base64': None, 'meta_data': {'api_key': '518455844981529', 'asset_folder': '', 'asset_id': '069d70c84e88ee9293a1d753b3ca3898', 'audio': {'bit_rate': '128290', 'channel_layout': 'stereo', 'channels': 2, 'codec': 'aac', 'frequency': 44100}, 'bit_rate': 644662, 'bytes': 1212449, 'created_at': '2024-11-20T08:55:44Z', 'display_name': 'video_test2', 'duration': 15.046009, 'etag': '876869c16d0bfa291d55796e5cb1bc00', 'format': 'mp4', 'frame_rate': 24.0, 'height': 720, 'is_audio': False, 'nb_frames': 361, 'original_filename': 'ForBiggerMeltdowns', 'overwritten': True, 'pages': 0, 'placeholder': False, 'playback_url': 'https://res.cloudinary.com/dpnjjk8mb/video/upload/sp_auto/v1732200207/video_test2.m3u8', 'resource_type': 'video', 'rotation': 0, 'signature': '7df5ccaaf5cba28b4d62d2ffc59793f29dfea326', 'tags': [], 'type': 'upload', 'url': 'http://res.cloudinary.com/dpnjjk8mb/video/upload/v1732200207/video_test2.mp4', 'version': 1732200207, 'version_id': 'fdfd560e5e06e3327777a5355b2cc682', 'video': {'bit_rate': '509638', 'codec': 'h264', 'level': 31, 'pix_format': 'yuv420p', 'profile': 'High', 'time_base': '1/12288'}, 'width': 1280}, 'public_id': 'video_test2', 'url': 'https://res.cloudinary.com/dpnjjk8mb/video/upload/v1732200207/video_test2.mp4'}\n", + "--------------------------------------------------\n", + "Transition type: finish\n", + "Transition output: {'transformed_video_url': 'https://res.cloudinary.com/dpnjjk8mb/video/upload/v1732200207/video_test2.mp4'}\n", + "--------------------------------------------------\n" + ] + } + ], + "source": [ + "# Lists all the task steps that have been executed up to this point in time\n", + "transitions = client.executions.transitions.list(execution_id=execution.id).items\n", + "\n", + "# Transitions are retreived in reverse chronological order\n", + "for transition in reversed(transitions):\n", + " print(\"Transition type: \", transition.type)\n", + " print(\"Transition output: \", transition.output)\n", + " print(\"-\"*50)\n", + "\n", + "if transitions[0].type == \"finish\":\n", + " transformed_video_url = transitions[0].output['transformed_video_url']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Video Before Transformation" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 46, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from IPython.display import Video\n", + "\n", + "Video(input_video_url)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Video After Transformation" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 47, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from IPython.display import Video\n", + "\n", + "Video(transformed_video_url)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "ai", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/cookbooks/06-Designing_Multi-Step_Tasks.py b/cookbooks/06-Designing_Multi-Step_Tasks.py deleted file mode 100644 index b623ae378..000000000 --- a/cookbooks/06-Designing_Multi-Step_Tasks.py +++ /dev/null @@ -1,139 +0,0 @@ -import uuid -import yaml, time -from julep import Client - -# Global UUID is generated for agent and task -AGENT_UUID = uuid.uuid4() -TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an "agent" -name = "Multi-Step Task Agent" -about = "An agent capable of executing complex multi-step tasks." -default_settings = { - "temperature": 0.7, - "top_p": 1, - "min_p": 0.01, - "presence_penalty": 0, - "frequency_penalty": 0, - "length_penalty": 1.0, - "max_tokens": 150, -} - -# Create the agent -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name=name, - about=about, - model="gpt-4o", -) - -# Add a web search tool to the agent -client.agents.tools.create( - agent_id=AGENT_UUID, - name="web_search", - integration={ - "provider": "brave", - "method": "search", - "setup": {"api_key": "your_brave_api_key"}, - }, -) - -# Defining a Task with various step types -task_def = yaml.safe_load(""" -name: Multi-Step Task Demonstration - -input_schema: - type: object - properties: - topic: - type: string - description: The topic to research and summarize. - -tools: -- name: web_search - type: integration - integration: - provider: brave - setup: - api_key: "your_api_key" - -main: -# Step 1: Prompt - Initial research question -- prompt: - - role: system - content: "You are a research assistant. Your task is to formulate three specific research questions about the given topic: {{inputs[0].topic}}" - unwrap: true - -# Step 2: Tool Call - Web search for each question -- foreach: - in: _.split('\\n') - do: - tool: web_search - arguments: - query: _ - -# Step 3: Evaluate - Extract relevant information -- evaluate: - relevant_info: "[output for output in _]" - -# Step 4: Conditional Logic - Check if enough information is gathered -- if: "len(_.relevant_info) >= 3" - then: - prompt: - - role: system - content: "Summarize the following information about {{inputs[0].topic}}:\n{{_.relevant_info}}" - unwrap: true - else: - prompt: - - role: system - content: "Not enough information gathered. Please provide a brief overview of {{inputs[0].topic}} based on your knowledge." - unwrap: true - -# Step 5: Log - Record the summary -- log: "Summary for {{inputs[0].topic}}: {{_}}" - -# Step 6: Return - Final output -- return: - summary: "_" - topic: "inputs[0].topic" - -""") - -# Creating/Updating a task -task = client.tasks.create_or_update( - task_id=TASK_UUID, - agent_id=AGENT_UUID, - **task_def -) - -# Creating an Execution -execution = client.executions.create( - task_id=TASK_UUID, - input={ - "topic": "Artificial Intelligence in Healthcare" - } -) - -print(f"Execution ID: {execution.id}") - -# Wait for the execution to complete -time.sleep(10) - -# Getting the execution details -execution = client.executions.get(execution.id) -print("Execution Output:") -print(client.executions.transitions.list(execution_id=execution.id).items[0].output) - -# Listing all the steps of a defined task -transitions = client.executions.transitions.list(execution_id=execution.id).items -print("Execution Steps:") -for transition in transitions: - print(transition) - -# Stream the steps of the defined task -print("Streaming execution transitions:") -print(client.executions.transitions.stream(execution_id=execution.id)) \ No newline at end of file diff --git a/cookbooks/07-Integrating_External_Tools_and_APIs.py b/cookbooks/07-Integrating_External_Tools_and_APIs.py deleted file mode 100644 index 71d8780d3..000000000 --- a/cookbooks/07-Integrating_External_Tools_and_APIs.py +++ /dev/null @@ -1,128 +0,0 @@ -import uuid -import yaml -from julep import Client - -# Global UUID is generated for agent and task -AGENT_UUID = uuid.uuid4() -TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an "agent" -name = "Multi-Tool Analyst" -about = "An AI agent capable of using multiple external tools and APIs to gather and analyze information." - -# Create the agent -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name=name, - about=about, - model="gpt-4o", -) - -# Defining a Task with various step types -task_def = yaml.safe_load(""" -name: Comprehensive Analysis Report - -input_schema: - type: object - properties: - topic: - type: string - description: The main topic to analyze. - location: - type: string - description: A location related to the topic for weather and news analysis. - -tools: -- name: brave_search - type: integration - integration: - provider: brave - setup: - api_key: "YOUR_API_KEY" - -- name: weather - type: integration - integration: - provider: weather - setup: - openweathermap_api_key: "YOUR_API_KEY" - -- name: wikipedia - type: integration - integration: - provider: wikipedia - -main: -- tool: brave_search - arguments: - query: "inputs[0].topic + ' latest developments'" - -- tool: weather - arguments: - location: inputs[0].location - -- tool: wikipedia - arguments: - query: inputs[0].topic - -- prompt: - - role: system - content: >- - You are a comprehensive analyst. Your task is to create a detailed report on the topic {{inputs[0].topic}} - using the information gathered from various sources. Include the following sections in your report: - - 1. Overview (based on Wikipedia data) - 2. Latest Developments (based on Brave Search results) - 3. Weather Impact (if applicable, based on weather data for {{inputs[0].location}}) - 4. Analysis and Conclusions - - Use the following data for your report: - - Brave Search Results: {{outputs[0]}} - Weather Data: {{outputs[1]}} - Wikipedia Data: {{outputs[2]}} - - Provide a well-structured, informative report that synthesizes information from all these sources. - unwrap: true -""") - -# Creating/Updating a task -task = client.tasks.create_or_update( - task_id=TASK_UUID, - agent_id=AGENT_UUID, - **task_def -) - -# Creating an Execution -execution = client.executions.create( - task_id=task.id, - input={ - "topic": "Renewable Energy", - "location": "Berlin" - } -) - -print(f"Execution ID: {execution.id}") - -# Waiting for the execution to complete -import time -time.sleep(5) - -# Getting the execution details -execution = client.executions.get(execution.id) -print("Execution Output:") -print(execution.output) - -# List all steps of the executed task -transitions = client.executions.transitions.list(execution_id=execution.id).items -print("Execution Steps:") -for transition in transitions: - print(transition) - -# Stream the steps of the defined task -print("Streaming execution transitions:") -print(client.executions.transitions.stream(execution_id=execution.id)) \ No newline at end of file diff --git a/cookbooks/08-Managing_Persistent_Sessions.py b/cookbooks/08-Managing_Persistent_Sessions.py deleted file mode 100644 index ab2472ac8..000000000 --- a/cookbooks/08-Managing_Persistent_Sessions.py +++ /dev/null @@ -1,146 +0,0 @@ -# Managing Persistent Sessions Cookbook -# -# Plan: -# 1. Import necessary libraries and set up the Julep client -# 2. Create an agent for handling persistent sessions -# 3. Define a task for managing user context -# 4. Create a function to simulate user interactions -# 5. Implement a loop to demonstrate persistent sessions with context management -# 6. Show how to handle context overflow -# 7. Display the session history and context at the end - -import uuid -import yaml -from julep import Client -import time - -# Global UUID is generated for agent and task -AGENT_UUID = uuid.uuid4() -TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an agent for handling persistent sessions -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name="Session Manager", - about="An AI agent specialized in managing persistent sessions and context.", - model="gpt-4o", -) - -# Defining a task for managing user context -task_def = yaml.safe_load(""" -name: Manage User Context - -input_schema: - type: object - properties: - user_input: - type: string - session_context: - type: object - -main: -- prompt: - - role: system - content: >- - You are a session management agent. Your task is to maintain context - across user interactions. Here's the current context: {{inputs[0].session_context}} - - User input: {{inputs[0].user_input}} - - Respond to the user and update the context with any new relevant information. - unwrap: true - -- evaluate: - session_context: >- - { - **inputs[0].session_context, - 'last_interaction': inputs[0].user_input, - 'agent_response': _} - -- return: - response: _ - context: outputs[1].session_context -""") - -# Creating the task -task = client.tasks.create_or_update( - task_id=TASK_UUID, - agent_id=AGENT_UUID, - **task_def -) - -# Function to simulate user interactions -def user_interaction(prompt): - return input(prompt) - -# Create a session -session = client.sessions.create( - agent=agent.id, - context_overflow="adaptive" # Use adaptive context management -) - -# Initialize session context -context = {} - -# Simulate a conversation with persistent context -for i in range(5): - user_input = user_interaction(f"User (Interaction {i+1}): ") - - # Execute the task with user input and current context - execution = client.executions.create( - task_id=TASK_UUID, - input={ - "user_input": user_input, - "session_context": context - } - ) - - # Get the execution result - result = client.executions.get(execution.id) - - # Wait for the execution to complete - time.sleep(2) - - # Update the context and print the response - final_response = client.executions.transitions.list(execution_id=result.id).items[0].output - print(final_response) - # print(client.executions.transitions.list(execution_id=result.id).items[0]) - context = final_response['session_context'] - print(f"Agent: {final_response['session_context']['agent_response']}") - print(f"Updated Context: {context}") - print() - - # Simulate a delay between interactions - time.sleep(1) - -# Display final session information -print("Final Session Information:") -print(f"Session ID: {session.id}") -print(f"Final Context: {context}") - -# Demonstrate context overflow handling -print("\nDemonstrating Context Overflow Handling:") -large_input = "This is a very large input " * 1000 # Create a large input to trigger overflow -overflow_execution = client.executions.create( - task_id=TASK_UUID, - input={ - "user_input": large_input, - "session_context": context - } -) - -overflow_result = client.executions.get(overflow_execution.id) -# Wait for the execution to complete -time.sleep(2) -overflow_response = client.executions.transitions.list(execution_id=overflow_result.id).items[0].output -print(f"Agent response to large input: {overflow_response['session_context']['agent_response']}") -print(f"Updated context after overflow: {overflow_response['session_context']}") - -# Display session history -print("\nSession History:") -history = client.sessions.history(session_id=session.id) -print(history) diff --git a/cookbooks/09-User_Management_and_Personalization.py b/cookbooks/09-User_Management_and_Personalization.py deleted file mode 100644 index 50ada9570..000000000 --- a/cookbooks/09-User_Management_and_Personalization.py +++ /dev/null @@ -1,196 +0,0 @@ -# User Management and Personalization Cookbook -# -# Plan: -# 1. Import necessary libraries and set up the Julep client -# 2. Create an agent for handling user management and personalization -# 3. Define a task for user registration and profile creation -# 4. Define a task for personalized content recommendation -# 5. Create sample users with different preferences -# 6. Demonstrate user registration and profile creation -# 7. Show personalized content recommendations for different users -# 8. Implement a function to update user preferences -# 9. Display updated personalized recommendations after preference changes - -import uuid -import yaml, time -from julep import Client - -# Global UUIDs for agent and tasks -AGENT_UUID = uuid.uuid4() -REGISTRATION_TASK_UUID = uuid.uuid4() -RECOMMENDATION_TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an agent for user management and personalization -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name="Personalization Assistant", - about="An AI agent specialized in user management and personalized content recommendations.", - model="gpt-4o", -) - -# Defining a task for user registration and profile creation -registration_task_def = yaml.safe_load(""" -name: User Registration and Profile Creation - -input_schema: - type: object - properties: - username: - type: string - interests: - type: array - items: - type: string - -main: -- prompt: - - role: system - content: >- - You are a user registration assistant. Create a user profile based on the following information: - Username: {{inputs[0].username}} - Interests: {{inputs[0].interests}} - - Generate a brief bio and suggest some initial content preferences based on the user's interests. - unwrap: true - -- evaluate: - username: inputs[0].username - interests: inputs[0].interests - bio: _.split('\\n')[0] - content_preferences: _.split('\\n')[1] - -- return: - profile: _ -""") - -# Creating the registration task -registration_task = client.tasks.create_or_update( - task_id=REGISTRATION_TASK_UUID, - agent_id=AGENT_UUID, - **registration_task_def -) - -# Defining a task for personalized content recommendation -recommendation_task_def = yaml.safe_load(""" -name: Personalized Content Recommendation - -input_schema: - type: object - properties: - user_profile: - type: object - description: User's profile containing their interests and preferences. - content_list: - type: array - description: List of available content to recommend from. - items: - type: object - properties: - id: - type: integer - title: - type: string - category: - type: string - -main: -- prompt: - - role: system - content: >- - You are a content recommendation system. Based on the user's profile and the available content, - recommend 3 pieces of content that best match the user's interests and preferences. - - User Profile: - {{inputs[0].user_profile}} - - Available Content: - {{inputs[0].content_list}} - - Provide your recommendations in the following format: - 1. [Content ID] - [Content Title] - Reason for recommendation - 2. [Content ID] - [Content Title] - Reason for recommendation - 3. [Content ID] - [Content Title] - Reason for recommendation - unwrap: true -""") - -# Creating the recommendation task -recommendation_task = client.tasks.create_or_update( - task_id=RECOMMENDATION_TASK_UUID, - agent_id=AGENT_UUID, - **recommendation_task_def -) - -# Function to register a user and create their profile -def register_user(username, interests): - execution = client.executions.create( - task_id=REGISTRATION_TASK_UUID, - input={ - "username": username, - "interests": interests - } - ) - # Wait for the execution to complete - time.sleep(2) - result = client.executions.get(execution.id) - user_result = client.executions.transitions.list(execution_id=result.id).items[0].output - return user_result - -# Function to get personalized recommendations for a user -def get_recommendations(user_profile): - content_list = [ - {"id": 1, "title": "Introduction to AI", "category": "Technology"}, - {"id": 2, "title": "Healthy Eating Habits", "category": "Health"}, - {"id": 3, "title": "Financial Planning 101", "category": "Finance"}, - {"id": 4, "title": "The Art of Photography", "category": "Art"}, - {"id": 5, "title": "Beginner's Guide to Yoga", "category": "Fitness"} - ] - - execution = client.executions.create( - task_id=RECOMMENDATION_TASK_UUID, - input={ - "user_profile": user_profile, - "content_list": content_list - } - ) - # Wait for the execution to complete - time.sleep(2) - result = client.executions.get(execution.id) - recommendation_respose = client.executions.transitions.list(execution_id=result.id).items[0].output - return recommendation_respose - - -# Function to update user preferences -def update_user_preferences(user_profile, new_interests): - user_profile["interests"] = list(set(user_profile["interests"] + new_interests)) - return user_profile - -# Demonstrate user registration and personalization -print("Demonstrating User Management and Personalization:") - -# Register users -user1 = register_user("alice", ["technology", "finance"]) -user2 = register_user("bob", ["health", "fitness"]) - -print("\nUser Profiles:") -print(f"Alice: {user1}") -print(f"Bob: {user2}") - -# Get personalized recommendations -print("\nPersonalized Recommendations:") -print("Alice's Recommendations:") -print(get_recommendations(user1)) -print("\nBob's Recommendations:") -print(get_recommendations(user2)) - -# Update user preferences -print("\nUpdating User Preferences:") -updated_alice = update_user_preferences(user1, ["art"]) -print(f"Alice's Updated Profile: {updated_alice}") - -# Get updated recommendations -print("\nUpdated Personalized Recommendations for Alice:") -print(get_recommendations(updated_alice)) \ No newline at end of file diff --git a/cookbooks/10-Document_Management_and_Search.py b/cookbooks/10-Document_Management_and_Search.py deleted file mode 100644 index 2df493f8b..000000000 --- a/cookbooks/10-Document_Management_and_Search.py +++ /dev/null @@ -1,184 +0,0 @@ -# Document Management and Search Cookbook -# -# Plan: -# 1. Import necessary libraries and set up the Julep client -# 2. Create an agent for document management -# 3. Define a task for document upload and indexing -# 4. Define a task for document search -# 5. Create sample documents -# 6. Execute the document upload and indexing task -# 7. Execute the document search task -# 8. Display the search results - -import uuid -import yaml,time -from julep import Client - -# Global UUID is generated for agent and tasks -AGENT_UUID = uuid.uuid4() -UPLOAD_TASK_UUID = uuid.uuid4() -SEARCH_TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an agent for document management -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name="Document Manager", - about="An AI agent specialized in document management and search.", - model="gpt-4o", -) - -# Defining a task for document upload and indexing -upload_task_def = yaml.safe_load(f""" -name: Document Upload and Indexing - -input_schema: - type: object - properties: - documents: - type: array - items: - type: object - properties: - tile: - type: string - content: - type: string - metadata: - type: object - -tools: -- name: document_create - system: - resource: agent - subresource: doc - operation: create - -main: -- over: inputs[0].documents - map: - tool: document_create - arguments: - agent_id: "'{agent.id}'" - data: - title: _.title - content: _.content - metadata: _.metadata - -- prompt: - - role: system - content: >- - You have successfully uploaded and indexed {{len(outputs[0])}} documents. - Provide a summary of the uploaded documents. -""") - -# Creating the upload task -upload_task = client.tasks.create_or_update( - task_id=UPLOAD_TASK_UUID, - agent_id=AGENT_UUID, - **upload_task_def -) - -# Defining a task for document search -search_task_def = yaml.safe_load(f""" -name: Document Search - -input_schema: - type: object - properties: - query: - type: string - -tools: -- name: document_search - system: - resource: agent - subresource: doc - operation: search - -main: -- tool: document_search - arguments: - agent_id: "'{agent.id}'" - text: inputs[0].query - -- prompt: - - role: system - content: >- - Based on the search results, provide a summary of the most relevant documents found. - Search query: {{{{inputs[0].query}}}} - Number of results: {{len(outputs[0])}} - - Results: - {{{{outputs[0]}}}} -""") - -# Creating the search task -search_task = client.tasks.create_or_update( - task_id=SEARCH_TASK_UUID, - agent_id=AGENT_UUID, - **search_task_def -) - -# Sample documents -sample_documents = [ - { - "title": "The Impact of Technology on Society", - "content": "Artificial Intelligence (AI) is revolutionizing various industries, including healthcare, finance, and transportation.", - "metadata": {"category": "technology", "author": "John Doe"} - }, - { - "title": "Climate Change and Global Warming", - "content": "Climate change is a pressing global issue that requires immediate action from governments, businesses, and individuals.", - "metadata": {"category": "environment", "author": "Jane Smith"} - }, - { - "title": "Remote Work and Digital Transformation", - "content": "The COVID-19 pandemic has accelerated the adoption of remote work and digital technologies across many organizations.", - "metadata": {"category": "business", "author": "Alice Johnson"} - } -] - -# Execute the document upload and indexing task -upload_execution = client.executions.create( - task_id=UPLOAD_TASK_UUID, - input={"documents": sample_documents} -) - -print("Uploading and indexing documents...") -# Wait for the execution to complete -time.sleep(5) -upload_result = client.executions.get(upload_execution.id) -upload_response = client.executions.transitions.list(upload_execution.id).items[0].output -print("Upload Result:") -print(upload_response) - -# Execute the document search task -search_execution = client.executions.create( - task_id=SEARCH_TASK_UUID, - input={ - "query": "technology" - } -) - -print("\nSearching documents...") -# Wait for the execution to complete -time.sleep(5) -search_result = client.executions.get(search_execution.id) -# Display the search results -print("\nSearch Results:") -for transition in client.executions.transitions.list(execution_id=search_execution.id).items: - if transition.type == "step" and transition.metadata['step_type'] == "ToolCallStep": - doc_output = transition.output['docs'] - for doc in doc_output: - print(f"Owner: {doc['owner']}") - print(f"Title: {doc['title']}") - print(f"Distance: {doc['distance']}") - print(f"Content: {doc['snippets']}") - -print("\nSearch Summary:") -search_response = client.executions.transitions.list(search_result.id).items[0].output['choices'][0]['message']['content'] -print(search_response) \ No newline at end of file diff --git a/cookbooks/11-Advanced_Chat_Interactions.py b/cookbooks/11-Advanced_Chat_Interactions.py deleted file mode 100644 index 1cfa71555..000000000 --- a/cookbooks/11-Advanced_Chat_Interactions.py +++ /dev/null @@ -1,177 +0,0 @@ -# Advanced Chat Interactions Cookbook -# -# Plan: -# 1. Import necessary libraries and set up the Julep client -# 2. Create an agent for advanced chat interactions -# 3. Define a task for handling complex conversations with context management -# 4. Implement a function to simulate user input -# 5. Create a chat session and demonstrate advanced interactions: -# a. Multi-turn conversation with context retention -# b. Handling context overflow -# c. Conditional responses based on user input -# d. Integrating external information during the conversation -# 6. Display the chat history and any relevant metrics - -# UNDER CONSTRUCTION - Dynamic weather integration is not yet implemented, rest of the code is functional - -import uuid -import yaml -import os -from julep import Client -import time - -# Global UUIDs for agent and task -AGENT_UUID = uuid.uuid4() -CHAT_TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = os.getenv("JULEP_API_KEY") -if not api_key: - raise ValueError("JULEP_API_KEY not found in environment variables") - -client = Client(api_key=api_key, environment="dev") - -# Creating an agent for advanced chat interactions -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name="Advanced Chat Assistant", - about="An AI agent capable of handling complex conversations with context management and external integrations.", - model="gpt-4o", -) - -# Add a web search tool to the agent -client.agents.tools.create( - agent_id=AGENT_UUID, - name="web_search", - integration={ - "provider": "brave", - "method": "search", - "setup": {"api_key": "YOUR_BRAVE_API_KEY"}, - }, -) - -# Defining a task for handling complex conversations -chat_task_def = yaml.safe_load(""" -name: Advanced Chat Interaction - -input_schema: - type: object - properties: - user_input: - type: string - chat_history: - type: array - items: - type: object - properties: - role: - type: string - content: - type: string - -tools: -- name: weather_api - type: integration - integration: - provider: weather - setup: - api_key: "YOUR_WEATHER_API_KEY" - -main: -- if: "len(inputs[0].chat_history) > 5" - then: - evaluate: - summarized_history: str(inputs[0].chat_history[-5:]) - else: - evaluate: - summarized_history: str(inputs[0].chat_history) - -- if: "search_regex('weather', inputs[0].user_input)" - then: - tool: weather_api - arguments: - location: "'NEW YORK'" - else: - evaluate: - weather: "'No weather information requested'" - -- evaluate: - weather: outputs[1] - -- if: "search_regex('weather', inputs[0].user_input)" - then: - prompt: - - role: system - content: >- - You are an advanced chat assistant. Here's a summary of the recent conversation: - {{outputs[0].summarized_history}} - - The user mentioned weather. Here's the current weather information for NEW YORK - Incorporate this information into your response. - - {{_.weather}} - - Now, respond to the user's latest input: {{inputs[0].user_input}} - else: - prompt: - - role: system - content: >- - You are an advanced chat assistant. Here's a summary of the recent conversation: - {{outputs[0].summarized_history}} - - Now, respond to the user's latest input: {{inputs[0].user_input}} -""") - -# Creating the chat task -chat_task = client.tasks.create_or_update( - task_id=CHAT_TASK_UUID, - agent_id=AGENT_UUID, - **chat_task_def -) - -# Function to simulate user input -def get_user_input(): - return input("User: ") - -# Function to display chat history -def display_chat_history(chat_history): - for message in chat_history: - print(f"{message['role'].capitalize()}: {message['content']}") - -# Main chat loop -def run_chat_session(): - chat_history = [] - print("Starting advanced chat session. Type 'exit' to end the conversation.") - - while True: - user_input = get_user_input() - if user_input.lower() == 'exit': - break - - chat_history.append({"role": "user", "content": user_input}) - - execution = client.executions.create( - task_id=CHAT_TASK_UUID, - input={ - "user_input": user_input, - "chat_history": chat_history - } - ) - # Wait for the execution to complete - time.sleep(5) - result = client.executions.get(execution.id) - print(client.executions.transitions.list(execution.id).items) - print(f"Execution result: {result.output}") - assistant_response = result.output['choices'][0]['message']['content'] - - chat_history.append({"role": "assistant", "content": assistant_response}) - print(f"Assistant: { assistant_response}") - - # Simulate a delay for a more natural conversation flow - print("----------------------") - - print("\nChat session ended. Here's the complete chat history:") - display_chat_history(chat_history) - -# Run the chat session -run_chat_session() \ No newline at end of file diff --git a/cookbooks/12-Monitoring_Task_Executions.py b/cookbooks/12-Monitoring_Task_Executions.py deleted file mode 100644 index 675ff27a1..000000000 --- a/cookbooks/12-Monitoring_Task_Executions.py +++ /dev/null @@ -1,162 +0,0 @@ -# Monitoring Task Executions Cookbook -# -# Plan: -# 1. Import necessary libraries and set up the Julep client -# 2. Create an agent for task execution monitoring -# 3. Define a multi-step task that simulates a complex workflow -# 4. Implement functions for: -# a. Starting task execution -# b. Monitoring execution progress -# c. Handling execution status updates -# d. Logging execution metrics -# 5. Execute the task and demonstrate real-time monitoring -# 6. Display execution summary and metrics - -# UNDER CONSTRUCTION - NOT WORKING YET - -import uuid -import yaml -from julep import Client -import time - -# Global UUIDs for agent and task -AGENT_UUID = uuid.uuid4() -TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an agent for task execution monitoring -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name="Task Execution Monitor", - about="An AI agent designed to monitor and manage complex task executions.", - model="gpt-4o", -) - -# Defining a multi-step task that simulates a complex workflow -task_def = yaml.safe_load(""" -name: Complex Workflow Simulation - -input_schema: - type: object - properties: - project_name: - type: string - data_size: - type: integer - -tools: -- name: data_processor - type: integration - integration: - provider: mock - setup: - processing_time: 5 # Simulated processing time in seconds - -- name: report_generator - type: integration - integration: - provider: mock - setup: - generation_time: 3 # Simulated generation time in seconds - -main: -- prompt: - role: system - content: >- - Initiating project '{{inputs[0].project_name}}' with data size {{inputs[0].data_size}} units. - Prepare for data processing and report generation. - unwrap: true - -- tool: data_processor - arguments: - data_size: inputs[0].data_size - -- evaluate: - processed_data: "Processed " + str(inputs[0].data_size) + " units of data" - -- tool: report_generator - arguments: - data: outputs[2].processed_data - -- prompt: - role: system - content: >- - Project '{{inputs[0].project_name}}' completed. - Data processed: {{outputs[2].processed_data}} - Report generated: {{outputs[3]}} - - Summarize the project results. - unwrap: true - -- return: _ -""") - -# Creating the task -task = client.tasks.create_or_update( - task_id=TASK_UUID, - agent_id=AGENT_UUID, - **task_def -) - -def start_task_execution(project_name, data_size): - """Start the task execution and return the execution object.""" - execution = client.executions.create( - task_id=TASK_UUID, - input={ - "project_name": project_name, - "data_size": data_size - } - ) - print(f"Task execution started for project '{project_name}'") - return execution - -def monitor_execution_progress(execution_id): - """Monitor the execution progress in real-time.""" - print("Monitoring execution progress:") - for transition in client.executions.transitions.stream(execution_id=execution_id): - print(f"Step: {transition.type}, Status: {transition.status}") - if transition.status == "completed": - print(f" Output: {transition.output}") - elif transition.status == "failed": - print(f" Error: {transition.error}") - time.sleep(1) # Add a small delay to simulate real-time monitoring - -def get_execution_status(execution_id): - """Get the current status of the execution.""" - execution = client.executions.get(execution_id) - return execution.status - -def log_execution_metrics(execution_id): - """Log and display execution metrics.""" - print("\nExecution Metrics:") - transitions = client.executions.transitions.list(execution_id=execution_id).items - total_duration = sum(t.duration_ms for t in transitions) - for transition in transitions: - print(f"Step: {transition.type}, Duration: {transition.duration_ms}ms") - print(f"Total Execution Time: {total_duration}ms") - -# Main execution flow -def run_task_monitoring_demo(): - project_name = "Data Analysis Project" - data_size = 1000 - - print(f"Starting task execution for '{project_name}' with {data_size} units of data") - execution = start_task_execution(project_name, data_size) - - monitor_execution_progress(execution.id) - - final_status = get_execution_status(execution.id) - print(f"\nFinal Execution Status: {final_status}") - - if final_status == "completed": - result = client.executions.get(execution.id) - print("\nExecution Result:") - print(result.output) - - log_execution_metrics(execution.id) - -# Run the task monitoring demo -run_task_monitoring_demo() \ No newline at end of file diff --git a/cookbooks/13-Error_Handling_and_Recovery.py b/cookbooks/13-Error_Handling_and_Recovery.py deleted file mode 100644 index f0cdf68be..000000000 --- a/cookbooks/13-Error_Handling_and_Recovery.py +++ /dev/null @@ -1,165 +0,0 @@ -# Error Handling and Recovery Cookbook -# -# Plan: -# 1. Import necessary libraries and set up the Julep client -# 2. Create an agent for error handling demonstration -# 3. Define a task with potential errors and recovery mechanisms -# 4. Execute the task and demonstrate error handling -# 5. Implement a retry mechanism for failed steps -# 6. Show how to log and report errors -# 7. Demonstrate graceful degradation when a step fails - -# UNDER CONSTRUCTION - NOT WORKING YET - -import uuid -import yaml -import time -from julep import Client - -# Global UUID is generated for agent and task -AGENT_UUID = uuid.uuid4() -TASK_UUID = uuid.uuid4() - -# Creating Julep Client with the API Key -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -# Creating an agent for error handling demonstration -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name="Error Handler", - about="An AI agent specialized in demonstrating error handling and recovery mechanisms.", - model="gpt-4o", -) - -# Defining a task with potential errors and recovery mechanisms -task_def = yaml.safe_load(""" -name: Error Handling Demo - -input_schema: - type: object - properties: - operation: - type: string - enum: ["divide", "api_call", "process_data"] - value: - type: number - -tools: -- name: divide - type: function - function: - name: divide - description: Divide 100 by the given number - parameters: - type: object - properties: - divisor: - type: number - -- name: api_call - type: integration - integration: - provider: httpbin - method: get - -- name: process_data - type: function - function: - name: process_data - description: Process the given data - parameters: - type: object - properties: - data: - type: string - -main: - -- switch: - case: "inputs[0].operation == 'divide'" - tool: divide - arguments: - divisor: inputs[0].value - on_error: - retry: - max_attempts: 3 - delay: 2 - fallback: - return: "Error: Division by zero or invalid input" - case: "inputs[0].operation == 'api_call'" - tool: api_call - arguments: - endpoint: "/status/{{inputs[0].value}}" - on_error: - retry: - max_attempts: 3 - delay: 5 - fallback: - return: "Error: API call failed after multiple attempts" - case: "inputs[0].operation == 'process_data'" - evaluate: - data: "'Sample data: ' + str(inputs[0].value)" - tool: process_data - arguments: - data: _.data - on_error: - log: "Error occurred while processing data" - return: "Error: Data processing failed" - -- prompt: - - role: system - content: >- - Summarize the result of the operation: - Operation: {{inputs[0].operation}} - Result: {{_}}] - unwrap: true -""") - -# Creating the task -task = client.tasks.create_or_update( - task_id=TASK_UUID, - agent_id=AGENT_UUID, - **task_def -) - -# Function to execute task and handle errors -def execute_task_with_error_handling(operation, value): - try: - execution = client.executions.create( - task_id=TASK_UUID, - input={"operation": operation, "value": value} - ) - - print(f"Executing {operation} with value {value}...") - - # Stream execution to show progress and potential retries - for step in client.executions.transitions.stream(execution_id=execution.id): - if step.type == "tool_call": - print(f"Step: {step.tool}") - if step.status == "error": - print(f"Error occurred: {step.error}") - if step.retry: - print(f"Retrying... (Attempt {step.retry.attempt})") - elif step.type == "error": - print(f"Task error: {step.error}") - - # Get final execution result - result = client.executions.get(execution.id) - print(f"Final result: {result.output}") - - except Exception as e: - print(f"An unexpected error occurred: {str(e)}") - -# Demonstrate error handling for different scenarios -print("1. Division by zero (with retry and fallback):") -execute_task_with_error_handling("divide", 0) - -print("\n2. API call with server error (with retry):") -execute_task_with_error_handling("api_call", 500) - -print("\n3. Data processing error (with logging):") -execute_task_with_error_handling("process_data", "invalid_data") - -print("\n4. Successful operation:") -execute_task_with_error_handling("divide", 4) \ No newline at end of file diff --git a/cookbooks/14-Automated_Webinar_Scheduling_Workflow.ipynb b/cookbooks/14-Automated_Webinar_Scheduling_Workflow.ipynb deleted file mode 100644 index ec45946e9..000000000 --- a/cookbooks/14-Automated_Webinar_Scheduling_Workflow.ipynb +++ /dev/null @@ -1,306 +0,0 @@ -{ - "nbformat": 4, - "nbformat_minor": 0, - "metadata": { - "colab": { - "provenance": [] - }, - "kernelspec": { - "name": "python3", - "display_name": "Python 3" - }, - "language_info": { - "name": "python" - } - }, - "cells": [ - { - "cell_type": "code", - "source": [ - "\"\"\"\n", - "Automated_Webinar_Scheduling_Workflow.py\n", - "\"\"\"\n", - "\n", - "import uuid\n", - "import yaml\n", - "import time\n", - "from julep import Client\n", - "\n", - "AGENT_UUID = uuid.uuid4()\n", - "SCHEDULE_WEBINAR_TASK_UUID = uuid.uuid4()\n", - "SEND_REMINDER_TASK_UUID = uuid.uuid4()\n", - "FOLLOW_UP_TASK_UUID = uuid.uuid4()\n", - "\n", - "api_key = \"\" # Your API key here\n", - "client = Client(api_key=api_key, environment=\"dev\")\n", - "\n", - "agent = client.agents.create_or_update(\n", - " agent_id=AGENT_UUID,\n", - " name=\"Webinar Scheduler\",\n", - " about=\"An AI agent that automates webinar scheduling, reminders, and follow-ups.\",\n", - " model=\"gpt-4o\",\n", - ")\n", - "\n", - "schedule_webinar_task_def = yaml.safe_load(\"\"\"\n", - "name: Schedule Webinar\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " organizer:\n", - " type: string\n", - " participants:\n", - " type: array\n", - " items:\n", - " type: string\n", - " webinar_topic:\n", - " type: string\n", - " webinar_time:\n", - " type: string\n", - "\n", - "main:\n", - "- prompt:\n", - " - role: system\n", - " content: >-\n", - " You are a webinar scheduling assistant. Schedule a webinar with the following details:\n", - " Organizer: {{inputs[0].organizer}}\n", - " Participants: {{inputs[0].participants}}\n", - " Webinar Topic: {{inputs[0].webinar_topic}}\n", - " Time: {{inputs[0].webinar_time}}\n", - "\n", - " Confirm the event creation and return the webinar event ID.\n", - " unwrap: true\n", - "\n", - "- evaluate:\n", - " event_id: _.uuid()\n", - "\n", - "- return:\n", - " event_id: _\n", - "\"\"\")\n", - "\n", - "schedule_webinar_task = client.tasks.create_or_update(\n", - " task_id=SCHEDULE_WEBINAR_TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **schedule_webinar_task_def\n", - ")\n", - "\n", - "send_reminder_task_def = yaml.safe_load(\"\"\"\n", - "name: Send Reminder\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " event_id:\n", - " type: string\n", - " participants:\n", - " type: array\n", - " items:\n", - " type: string\n", - "\n", - "main:\n", - "- prompt:\n", - " - role: system\n", - " content: >-\n", - " You are a reminder assistant. Send a reminder for the following event:\n", - " Event ID: {{inputs[0].event_id}}\n", - " Participants: {{inputs[0].participants}}\n", - "\n", - " Confirm the reminder has been sent.\n", - " unwrap: true\n", - "\n", - "- return:\n", - " status: \"Reminder sent\"\n", - "\"\"\")\n", - "\n", - "send_reminder_task = client.tasks.create_or_update(\n", - " task_id=SEND_REMINDER_TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **send_reminder_task_def\n", - ")\n", - "\n", - "follow_up_task_def = yaml.safe_load(\"\"\"\n", - "name: Send Follow-Up\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " event_id:\n", - " type: string\n", - " participants:\n", - " type: array\n", - " items:\n", - " type: string\n", - " follow_up_message:\n", - " type: string\n", - "\n", - "main:\n", - "- prompt:\n", - " - role: system\n", - " content: >-\n", - " You are a follow-up assistant. Send the following follow-up message to participants after the event:\n", - " Event ID: {{inputs[0].event_id}}\n", - " Participants: {{inputs[0].participants}}\n", - " Message: {{inputs[0].follow_up_message}}\n", - "\n", - " Confirm the message has been sent.\n", - " unwrap: true\n", - "\n", - "- return:\n", - " status: \"Follow-up message sent\"\n", - "\"\"\")\n", - "\n", - "follow_up_task = client.tasks.create_or_update(\n", - " task_id=FOLLOW_UP_TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **follow_up_task_def\n", - ")\n", - "def schedule_webinar(organizer, participants, webinar_topic, webinar_time):\n", - " execution = client.executions.create(\n", - " task_id=SCHEDULE_WEBINAR_TASK_UUID,\n", - " input={\n", - " \"organizer\": organizer,\n", - " \"participants\": participants,\n", - " \"webinar_topic\": webinar_topic,\n", - " \"webinar_time\": webinar_time\n", - " }\n", - " )\n", - " time.sleep(2)\n", - " result = client.executions.get(execution.id)\n", - " output = client.executions.transitions.list(execution_id=result.id).items[0].output\n", - "\n", - " if isinstance(output, dict):\n", - " return output\n", - " else:\n", - " return {\"event_id\": output}\n", - "\n", - "def send_reminder(event_id, participants):\n", - " execution = client.executions.create(\n", - " task_id=SEND_REMINDER_TASK_UUID,\n", - " input={\n", - " \"event_id\": event_id,\n", - " \"participants\": participants\n", - " }\n", - " )\n", - " time.sleep(2)\n", - " result = client.executions.get(execution.id)\n", - " return client.executions.transitions.list(execution_id=result.id).items[0].output\n", - "\n", - "def send_follow_up(event_id, participants, message):\n", - " execution = client.executions.create(\n", - " task_id=FOLLOW_UP_TASK_UUID,\n", - " input={\n", - " \"event_id\": event_id,\n", - " \"participants\": participants,\n", - " \"follow_up_message\": message\n", - " }\n", - " )\n", - " time.sleep(2)\n", - " result = client.executions.get(execution.id)\n", - " return client.executions.transitions.list(execution_id=result.id).items[0].output\n", - "\n", - "def print_output(webinar_result, reminder_result, follow_up_result):\n", - " print(\"Demonstrating Automated Webinar Scheduling Workflow:\")\n", - "\n", - " print(\"Webinar Scheduled:\")\n", - " print(\"The webinar has been successfully scheduled with the following details:\\n\")\n", - " print(f\"- Organizer: {webinar_result['organizer']}\")\n", - " print(f\"- Participants: {', '.join(webinar_result['participants'])}\")\n", - " print(f\"- Webinar Topic: {webinar_result['webinar_topic']}\")\n", - " print(f\"- Time: {webinar_result['webinar_time']}\\n\")\n", - " print(f\"The Webinar Event ID is: {webinar_result['event_id']}\")\n", - "\n", - " print(\"Reminder Status:\")\n", - " print(\"Reminder has been sent successfully for the following webinar:\\n\")\n", - " print(f\"- Event ID: {reminder_result['event_id']}\")\n", - " print(f\"- Participants: {', '.join(reminder_result['participants'])}\\n\")\n", - "\n", - " print(\"Follow-up Status:\")\n", - " print(\"Follow-up message has been successfully sent for the following webinar:\\n\")\n", - " print(f\"- Event ID: {follow_up_result['event_id']}\")\n", - " print(f\"- Participants: {', '.join(follow_up_result['participants'])}\")\n", - " print(f\"- Follow-up Message: {follow_up_result['follow_up_message']}\\n\")\n", - "\n", - "\n", - "print(\"Demonstrating Automated Webinar Scheduling Workflow:\")\n", - "\n", - "organizer = \"organizer123\"\n", - "participants = [\"participant1\", \"participant2\", \"participant3\"]\n", - "webinar_topic = \"AI in Healthcare\"\n", - "webinar_time = \"2024-11-01 10:00:00\"\n", - "follow_up_message = \"Thank you for attending the webinar! Here is the recording link.\"\n", - "\n", - "webinar_result = schedule_webinar(organizer, participants, webinar_topic, webinar_time)\n", - "\n", - "webinar_result = {\n", - " \"organizer\": organizer,\n", - " \"participants\": participants,\n", - " \"webinar_topic\": webinar_topic,\n", - " \"webinar_time\": webinar_time,\n", - " \"event_id\": \"WBNR20241101-001\"\n", - "}\n", - "\n", - "reminder_result = {\n", - " \"event_id\": webinar_result[\"event_id\"],\n", - " \"participants\": participants\n", - "}\n", - "\n", - "follow_up_result = {\n", - " \"event_id\": webinar_result[\"event_id\"],\n", - " \"participants\": participants,\n", - " \"follow_up_message\": follow_up_message\n", - "}\n", - "\n", - "print_output(webinar_result, reminder_result, follow_up_result)\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "hFR_2RBzmNwB", - "outputId": "8cb4622a-8954-4f7b-e047-245426b419cd" - }, - "execution_count": 26, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Demonstrating Automated Webinar Scheduling Workflow:\n", - "Demonstrating Automated Webinar Scheduling Workflow:\n", - "Webinar Scheduled:\n", - "The webinar has been successfully scheduled with the following details:\n", - "\n", - "- Organizer: organizer123\n", - "- Participants: participant1, participant2, participant3\n", - "- Webinar Topic: AI in Healthcare\n", - "- Time: 2024-11-01 10:00:00\n", - "\n", - "The Webinar Event ID is: WBNR20241101-001\n", - "Reminder Status:\n", - "Reminder has been sent successfully for the following webinar:\n", - "\n", - "- Event ID: WBNR20241101-001\n", - "- Participants: participant1, participant2, participant3\n", - "\n", - "Follow-up Status:\n", - "Follow-up message has been successfully sent for the following webinar:\n", - "\n", - "- Event ID: WBNR20241101-001\n", - "- Participants: participant1, participant2, participant3\n", - "- Follow-up Message: Thank you for attending the webinar! Here is the recording link.\n", - "\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [], - "metadata": { - "id": "pk1LkRXQpIgg" - }, - "execution_count": null, - "outputs": [] - } - ] -} \ No newline at end of file diff --git a/cookbooks/14-Automated_Webinar_Scheduling_Workflow.py b/cookbooks/14-Automated_Webinar_Scheduling_Workflow.py deleted file mode 100644 index 34c29a37b..000000000 --- a/cookbooks/14-Automated_Webinar_Scheduling_Workflow.py +++ /dev/null @@ -1,244 +0,0 @@ -# -*- coding: utf-8 -*- -"""14-Automated_Webinar_Scheduling_Workflow.ipynb - -Automatically generated by Colab. - -Original file is located at - https://colab.research.google.com/drive/1VH-tuBMGOVKIZMJ6I6KuvJsad0is7IIF -""" - -""" -Automated_Webinar_Scheduling_Workflow.py -""" - -import uuid -import yaml -import time -from julep import Client - -AGENT_UUID = uuid.uuid4() -SCHEDULE_WEBINAR_TASK_UUID = uuid.uuid4() -SEND_REMINDER_TASK_UUID = uuid.uuid4() -FOLLOW_UP_TASK_UUID = uuid.uuid4() - -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name="Webinar Scheduler", - about="An AI agent that automates webinar scheduling, reminders, and follow-ups.", - model="gpt-4o", -) - -schedule_webinar_task_def = yaml.safe_load(""" -name: Schedule Webinar - -input_schema: - type: object - properties: - organizer: - type: string - participants: - type: array - items: - type: string - webinar_topic: - type: string - webinar_time: - type: string - -main: -- prompt: - - role: system - content: >- - You are a webinar scheduling assistant. Schedule a webinar with the following details: - Organizer: {{inputs[0].organizer}} - Participants: {{inputs[0].participants}} - Webinar Topic: {{inputs[0].webinar_topic}} - Time: {{inputs[0].webinar_time}} - - Confirm the event creation and return the webinar event ID. - unwrap: true - -- evaluate: - event_id: _.uuid() - -- return: - event_id: _ -""") - -schedule_webinar_task = client.tasks.create_or_update( - task_id=SCHEDULE_WEBINAR_TASK_UUID, - agent_id=AGENT_UUID, - **schedule_webinar_task_def -) - -send_reminder_task_def = yaml.safe_load(""" -name: Send Reminder - -input_schema: - type: object - properties: - event_id: - type: string - participants: - type: array - items: - type: string - -main: -- prompt: - - role: system - content: >- - You are a reminder assistant. Send a reminder for the following event: - Event ID: {{inputs[0].event_id}} - Participants: {{inputs[0].participants}} - - Confirm the reminder has been sent. - unwrap: true - -- return: - status: "Reminder sent" -""") - -send_reminder_task = client.tasks.create_or_update( - task_id=SEND_REMINDER_TASK_UUID, - agent_id=AGENT_UUID, - **send_reminder_task_def -) - -follow_up_task_def = yaml.safe_load(""" -name: Send Follow-Up - -input_schema: - type: object - properties: - event_id: - type: string - participants: - type: array - items: - type: string - follow_up_message: - type: string - -main: -- prompt: - - role: system - content: >- - You are a follow-up assistant. Send the following follow-up message to participants after the event: - Event ID: {{inputs[0].event_id}} - Participants: {{inputs[0].participants}} - Message: {{inputs[0].follow_up_message}} - - Confirm the message has been sent. - unwrap: true - -- return: - status: "Follow-up message sent" -""") - -follow_up_task = client.tasks.create_or_update( - task_id=FOLLOW_UP_TASK_UUID, - agent_id=AGENT_UUID, - **follow_up_task_def -) -def schedule_webinar(organizer, participants, webinar_topic, webinar_time): - execution = client.executions.create( - task_id=SCHEDULE_WEBINAR_TASK_UUID, - input={ - "organizer": organizer, - "participants": participants, - "webinar_topic": webinar_topic, - "webinar_time": webinar_time - } - ) - time.sleep(2) - result = client.executions.get(execution.id) - output = client.executions.transitions.list(execution_id=result.id).items[0].output - - if isinstance(output, dict): - return output - else: - return {"event_id": output} - -def send_reminder(event_id, participants): - execution = client.executions.create( - task_id=SEND_REMINDER_TASK_UUID, - input={ - "event_id": event_id, - "participants": participants - } - ) - time.sleep(2) - result = client.executions.get(execution.id) - return client.executions.transitions.list(execution_id=result.id).items[0].output - -def send_follow_up(event_id, participants, message): - execution = client.executions.create( - task_id=FOLLOW_UP_TASK_UUID, - input={ - "event_id": event_id, - "participants": participants, - "follow_up_message": message - } - ) - time.sleep(2) - result = client.executions.get(execution.id) - return client.executions.transitions.list(execution_id=result.id).items[0].output - -def print_output(webinar_result, reminder_result, follow_up_result): - print("Demonstrating Automated Webinar Scheduling Workflow:") - - print("Webinar Scheduled:") - print("The webinar has been successfully scheduled with the following details:\n") - print(f"- Organizer: {webinar_result['organizer']}") - print(f"- Participants: {', '.join(webinar_result['participants'])}") - print(f"- Webinar Topic: {webinar_result['webinar_topic']}") - print(f"- Time: {webinar_result['webinar_time']}\n") - print(f"The Webinar Event ID is: {webinar_result['event_id']}") - - print("Reminder Status:") - print("Reminder has been sent successfully for the following webinar:\n") - print(f"- Event ID: {reminder_result['event_id']}") - print(f"- Participants: {', '.join(reminder_result['participants'])}\n") - - print("Follow-up Status:") - print("Follow-up message has been successfully sent for the following webinar:\n") - print(f"- Event ID: {follow_up_result['event_id']}") - print(f"- Participants: {', '.join(follow_up_result['participants'])}") - print(f"- Follow-up Message: {follow_up_result['follow_up_message']}\n") - - -print("Demonstrating Automated Webinar Scheduling Workflow:") - -organizer = "organizer123" -participants = ["participant1", "participant2", "participant3"] -webinar_topic = "AI in Healthcare" -webinar_time = "2024-11-01 10:00:00" -follow_up_message = "Thank you for attending the webinar! Here is the recording link." - -webinar_result = schedule_webinar(organizer, participants, webinar_topic, webinar_time) - -webinar_result = { - "organizer": organizer, - "participants": participants, - "webinar_topic": webinar_topic, - "webinar_time": webinar_time, - "event_id": "WBNR20241101-001" -} - -reminder_result = { - "event_id": webinar_result["event_id"], - "participants": participants -} - -follow_up_result = { - "event_id": webinar_result["event_id"], - "participants": participants, - "follow_up_message": follow_up_message -} - -print_output(webinar_result, reminder_result, follow_up_result) - diff --git a/cookbooks/15-Personal_Finance_Tracker.ipynb b/cookbooks/15-Personal_Finance_Tracker.ipynb deleted file mode 100644 index cd6909944..000000000 --- a/cookbooks/15-Personal_Finance_Tracker.ipynb +++ /dev/null @@ -1,208 +0,0 @@ -{ - "nbformat": 4, - "nbformat_minor": 0, - "metadata": { - "colab": { - "provenance": [] - }, - "kernelspec": { - "name": "python3", - "display_name": "Python 3" - }, - "language_info": { - "name": "python" - } - }, - "cells": [ - { - "cell_type": "code", - "source": [ - "import uuid\n", - "import yaml\n", - "import time\n", - "from julep import Client\n", - "\n", - "TRACKER_UUID = uuid.uuid4()\n", - "BUDGET_TASK_UUID = uuid.uuid4()\n", - "ADVICE_TASK_UUID = uuid.uuid4()\n", - "\n", - "api_key = \"\" # Your API key here\n", - "client = Client(api_key=api_key, environment=\"dev\")\n", - "\n", - "agent = client.agents.create_or_update(\n", - " agent_id=TRACKER_UUID,\n", - " name=\"Personal Finance Tracker\",\n", - " about=\"Tracks user expenses, analyzes spending patterns, and provides financial advice.\",\n", - " model=\"gpt-4o\",\n", - ")\n", - "\n", - "log_expense_task_def = yaml.safe_load(f\"\"\"\n", - "name: Log Expense\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " amount:\n", - " type: number\n", - " category:\n", - " type: string\n", - " description:\n", - " type: string\n", - "\n", - "tools:\n", - "- name: finance_tool\n", - " system:\n", - " resource: agent\n", - " subresource: tool\n", - " operation: create\n", - "\n", - "main:\n", - "- tool: finance_tool\n", - " arguments:\n", - " agent_id: \"'{agent.id}'\"\n", - " data:\n", - " amount: inputs[0].amount\n", - " category: inputs[0].category\n", - " description: inputs[0].description\n", - "\"\"\")\n", - "\n", - "log_expense_task = client.tasks.create_or_update(\n", - " task_id=TRACKER_UUID,\n", - " agent_id=TRACKER_UUID,\n", - " **log_expense_task_def\n", - ")\n", - "\n", - "set_budget_task_def = yaml.safe_load(f\"\"\"\n", - "name: Set Budget\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " category:\n", - " type: string\n", - " budget_amount:\n", - " type: number\n", - "\n", - "tools:\n", - "- name: finance_tool\n", - " system:\n", - " resource: agent\n", - " subresource: tool\n", - " operation: create\n", - "\n", - "main:\n", - "- tool: finance_tool\n", - " arguments:\n", - " agent_id: \"'{agent.id}'\"\n", - " data:\n", - " category: inputs[0].category\n", - " budget_amount: inputs[0].budget_amount\n", - "\"\"\")\n", - "\n", - "set_budget_task = client.tasks.create_or_update(\n", - " task_id=BUDGET_TASK_UUID,\n", - " agent_id=TRACKER_UUID,\n", - " **set_budget_task_def\n", - ")\n", - "\n", - "send_advice_task_def = yaml.safe_load(f\"\"\"\n", - "name: Send Financial Advice\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " advice:\n", - " type: string\n", - " email:\n", - " type: string\n", - "\n", - "tools:\n", - "- name: email_tool\n", - " system:\n", - " resource: agent\n", - " subresource: tool\n", - " operation: create\n", - "\n", - "main:\n", - "- tool: email_tool\n", - " arguments:\n", - " agent_id: \"'{agent.id}'\"\n", - " to: inputs[0].email\n", - " subject: \"Financial Advice\"\n", - " body: inputs[0].advice\n", - "\"\"\")\n", - "\n", - "send_advice_task = client.tasks.create_or_update(\n", - " task_id=ADVICE_TASK_UUID,\n", - " agent_id=TRACKER_UUID,\n", - " **send_advice_task_def\n", - ")\n", - "\n", - "def log_expense(amount, category, description):\n", - " execution = client.executions.create(\n", - " task_id=TRACKER_UUID,\n", - " input={\"amount\": amount, \"category\": category, \"description\": description}\n", - " )\n", - " print(\"Logging expense...\")\n", - " time.sleep(5)\n", - " result = client.executions.get(execution.id)\n", - " print(f\"Expense logged: {description} of ${amount} in {category} category.\")\n", - "\n", - "def set_budget(category, budget_amount):\n", - " execution = client.executions.create(\n", - " task_id=BUDGET_TASK_UUID,\n", - " input={\"category\": category, \"budget_amount\": budget_amount}\n", - " )\n", - " print(\"Setting budget...\")\n", - " time.sleep(5)\n", - " result = client.executions.get(execution.id)\n", - " print(f\"Budget set for {category}: ${budget_amount}.\")\n", - "\n", - "def send_financial_advice(email, advice):\n", - " execution = client.executions.create(\n", - " task_id=ADVICE_TASK_UUID,\n", - " input={\"advice\": advice, \"email\": email}\n", - " )\n", - " print(\"Sending financial advice...\")\n", - " time.sleep(5)\n", - " result = client.executions.get(execution.id)\n", - " print(f\"Advice sent to {email}: '{advice}'.\")\n", - "\n", - "log_expense(50, \"Groceries\", \"Weekly grocery shopping\")\n", - "set_budget(\"Groceries\", 200)\n", - "send_financial_advice(\"user@example.com\", \"Consider reducing your grocery budget to save more.\")\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "32Q7ccRJs_h5", - "outputId": "3ffa8354-ec10-4fed-9da8-9bf7c234a35d" - }, - "execution_count": 7, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Logging expense...\n", - "Expense logged: Weekly grocery shopping of $50 in Groceries category.\n", - "Setting budget...\n", - "Budget set for Groceries: $200.\n", - "Sending financial advice...\n", - "Advice sent to user@example.com: 'Consider reducing your grocery budget to save more.'.\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [], - "metadata": { - "id": "k9fvuTaGtGBp" - }, - "execution_count": null, - "outputs": [] - } - ] -} \ No newline at end of file diff --git a/cookbooks/15-Personal_Finance_Tracker.py b/cookbooks/15-Personal_Finance_Tracker.py deleted file mode 100644 index ffda91b17..000000000 --- a/cookbooks/15-Personal_Finance_Tracker.py +++ /dev/null @@ -1,164 +0,0 @@ -# -*- coding: utf-8 -*- -"""15_Personal_Finance_Tracker.ipynb - -Automatically generated by Colab. - -Original file is located at - https://colab.research.google.com/drive/1jzy4evusmnkPxntEdpibh_Xm12T-m8in -""" - -import uuid -import yaml -import time -from julep import Client - -TRACKER_UUID = uuid.uuid4() -BUDGET_TASK_UUID = uuid.uuid4() -ADVICE_TASK_UUID = uuid.uuid4() - -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -agent = client.agents.create_or_update( - agent_id=TRACKER_UUID, - name="Personal Finance Tracker", - about="Tracks user expenses, analyzes spending patterns, and provides financial advice.", - model="gpt-4o", -) - -log_expense_task_def = yaml.safe_load(f""" -name: Log Expense - -input_schema: - type: object - properties: - amount: - type: number - category: - type: string - description: - type: string - -tools: -- name: finance_tool - system: - resource: agent - subresource: tool - operation: create - -main: -- tool: finance_tool - arguments: - agent_id: "'{agent.id}'" - data: - amount: inputs[0].amount - category: inputs[0].category - description: inputs[0].description -""") - -log_expense_task = client.tasks.create_or_update( - task_id=TRACKER_UUID, - agent_id=TRACKER_UUID, - **log_expense_task_def -) - -set_budget_task_def = yaml.safe_load(f""" -name: Set Budget - -input_schema: - type: object - properties: - category: - type: string - budget_amount: - type: number - -tools: -- name: finance_tool - system: - resource: agent - subresource: tool - operation: create - -main: -- tool: finance_tool - arguments: - agent_id: "'{agent.id}'" - data: - category: inputs[0].category - budget_amount: inputs[0].budget_amount -""") - -set_budget_task = client.tasks.create_or_update( - task_id=BUDGET_TASK_UUID, - agent_id=TRACKER_UUID, - **set_budget_task_def -) - -send_advice_task_def = yaml.safe_load(f""" -name: Send Financial Advice - -input_schema: - type: object - properties: - advice: - type: string - email: - type: string - -tools: -- name: email_tool - system: - resource: agent - subresource: tool - operation: create - -main: -- tool: email_tool - arguments: - agent_id: "'{agent.id}'" - to: inputs[0].email - subject: "Financial Advice" - body: inputs[0].advice -""") - -send_advice_task = client.tasks.create_or_update( - task_id=ADVICE_TASK_UUID, - agent_id=TRACKER_UUID, - **send_advice_task_def -) - -def log_expense(amount, category, description): - execution = client.executions.create( - task_id=TRACKER_UUID, - input={"amount": amount, "category": category, "description": description} - ) - print("Logging expense...") - time.sleep(5) - result = client.executions.get(execution.id) - print(f"Expense logged: {description} of ${amount} in {category} category.") - -def set_budget(category, budget_amount): - execution = client.executions.create( - task_id=BUDGET_TASK_UUID, - input={"category": category, "budget_amount": budget_amount} - ) - print("Setting budget...") - time.sleep(5) - result = client.executions.get(execution.id) - print(f"Budget set for {category}: ${budget_amount}.") - -def send_financial_advice(email, advice): - execution = client.executions.create( - task_id=ADVICE_TASK_UUID, - input={"advice": advice, "email": email} - ) - print("Sending financial advice...") - time.sleep(5) - result = client.executions.get(execution.id) - print(f"Advice sent to {email}: '{advice}'.") - -log_expense(50, "Groceries", "Weekly grocery shopping") -set_budget("Groceries", 200) -send_financial_advice("user@example.com", "Consider reducing your grocery budget to save more.") - diff --git a/cookbooks/16-E_commerce_Order_Processing_Workflow.ipynb b/cookbooks/16-E_commerce_Order_Processing_Workflow.ipynb deleted file mode 100644 index bf4e741ca..000000000 --- a/cookbooks/16-E_commerce_Order_Processing_Workflow.ipynb +++ /dev/null @@ -1,381 +0,0 @@ -{ - "nbformat": 4, - "nbformat_minor": 0, - "metadata": { - "colab": { - "provenance": [] - }, - "kernelspec": { - "name": "python3", - "display_name": "Python 3" - }, - "language_info": { - "name": "python" - } - }, - "cells": [ - { - "cell_type": "code", - "source": [ - "import uuid\n", - "import yaml\n", - "import time\n", - "from julep import Client" - ], - "metadata": { - "id": "QIJXVEzBYrRv" - }, - "execution_count": 3, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "AGENT_UUID = uuid.uuid4()\n", - "ORDER_PLACEMENT_TASK_UUID = uuid.uuid4()\n", - "INVENTORY_CHECK_TASK_UUID = uuid.uuid4()\n", - "PAYMENT_PROCESSING_TASK_UUID = uuid.uuid4()\n", - "SHIPMENT_TRACKING_TASK_UUID = uuid.uuid4()" - ], - "metadata": { - "id": "tCqfsDHuYu4V" - }, - "execution_count": 4, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "api_key = \"\" # Your API key here\n", - "client = Client(api_key=api_key, environment=\"dev\")" - ], - "metadata": { - "id": "mSBH1k6OYxUW" - }, - "execution_count": 5, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "agent = client.agents.create_or_update(\n", - " agent_id=AGENT_UUID,\n", - " name=\"Order Processing Assistant\",\n", - " about=\"An AI agent specialized in automating the order processing workflow for e-commerce.\",\n", - " model=\"gpt-4o\",\n", - ")" - ], - "metadata": { - "id": "loTLYbQ8Y1i5" - }, - "execution_count": 6, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "order_placement_task_def = yaml.safe_load(\"\"\"\n", - "name: Order Placement\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " user_id:\n", - " type: string\n", - " order_details:\n", - " type: object\n", - " properties:\n", - " item_id:\n", - " type: integer\n", - " quantity:\n", - " type: integer\n", - "\n", - "main:\n", - "- prompt:\n", - " - role: system\n", - " content: >-\n", - " You are an order placement assistant. Process the following order:\n", - " User ID: {{inputs[0].user_id}}\n", - " Order Details: {{inputs[0].order_details}}\n", - "\n", - " Confirm the order placement and return the order ID.\n", - " unwrap: true\n", - "\n", - "- evaluate:\n", - " order_id: _.uuid()\n", - "\n", - "- return:\n", - " order_id: _\n", - "\"\"\")" - ], - "metadata": { - "id": "UDsmzc_pY4Dx" - }, - "execution_count": 7, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "order_placement_task = client.tasks.create_or_update(\n", - " task_id=ORDER_PLACEMENT_TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **order_placement_task_def\n", - ")\n" - ], - "metadata": { - "id": "cc76A2UxY-Z7" - }, - "execution_count": 8, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "inventory_check_task_def = yaml.safe_load(\"\"\"\n", - "name: Inventory Check\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " item_id:\n", - " type: integer\n", - " quantity:\n", - " type: integer\n", - "\n", - "main:\n", - "- prompt:\n", - " - role: system\n", - " content: >-\n", - " You are an inventory checker. Check the availability of the following item:\n", - " Item ID: {{inputs[0].item_id}}\n", - " Quantity Requested: {{inputs[0].quantity}}\n", - "\n", - " Return true if available, otherwise return false.\n", - " unwrap: true\n", - "\"\"\")\n", - "\n" - ], - "metadata": { - "id": "uCdVhA98ZBPB" - }, - "execution_count": 9, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "inventory_check_task = client.tasks.create_or_update(\n", - " task_id=INVENTORY_CHECK_TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **inventory_check_task_def\n", - ")\n" - ], - "metadata": { - "id": "ZICp9jXiZEgO" - }, - "execution_count": 10, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "payment_processing_task_def = yaml.safe_load(\"\"\"\n", - "name: Payment Processing\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " user_id:\n", - " type: string\n", - " order_id:\n", - " type: string\n", - " amount:\n", - " type: number\n", - "\n", - "main:\n", - "- prompt:\n", - " - role: system\n", - " content: >-\n", - " You are a payment processor. Process payment for the following order:\n", - " User ID: {{inputs[0].user_id}}\n", - " Order ID: {{inputs[0].order_id}}\n", - " Amount: {{inputs[0].amount}}\n", - "\n", - " Confirm payment status (success or failure).\n", - " unwrap: true\n", - "\n", - "- evaluate:\n", - " payment_status: \"success\" # Simulating a successful payment\n", - "\n", - "- return:\n", - " payment_status: _\n", - "\"\"\")\n", - "\n", - "payment_processing_task = client.tasks.create_or_update(\n", - " task_id=PAYMENT_PROCESSING_TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **payment_processing_task_def\n", - ")\n", - "\n", - "shipment_tracking_task_def = yaml.safe_load(\"\"\"\n", - "name: Shipment Tracking\n", - "\n", - "input_schema:\n", - " type: object\n", - " properties:\n", - " order_id:\n", - " type: string\n", - "\n", - "main:\n", - "- prompt:\n", - " - role: system\n", - " content: >-\n", - " You are a shipment tracker. Track the shipment for the following order:\n", - " Order ID: {{inputs[0].order_id}}\n", - "\n", - " Return the current status of the shipment.\n", - " unwrap: true\n", - "\"\"\")\n" - ], - "metadata": { - "id": "lr0M9XWKZG9N" - }, - "execution_count": 11, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "shipment_tracking_task = client.tasks.create_or_update(\n", - " task_id=SHIPMENT_TRACKING_TASK_UUID,\n", - " agent_id=AGENT_UUID,\n", - " **shipment_tracking_task_def\n", - ")" - ], - "metadata": { - "id": "-k0Wl-o8ZJw7" - }, - "execution_count": 12, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "def place_order(user_id, item_id, quantity):\n", - " execution = client.executions.create(\n", - " task_id=ORDER_PLACEMENT_TASK_UUID,\n", - " input={\n", - " \"user_id\": user_id,\n", - " \"order_details\": {\n", - " \"item_id\": item_id,\n", - " \"quantity\": quantity\n", - " }\n", - " }\n", - " )\n", - " time.sleep(2)\n", - " result = client.executions.get(execution.id)\n", - " output = client.executions.transitions.list(execution_id=result.id).items[0].output\n", - "\n", - " if isinstance(output, dict):\n", - " return output\n", - " else:\n", - " return {\"order_id\": output}\n", - "\n", - "def check_inventory(item_id, quantity):\n", - " execution = client.executions.create(\n", - " task_id=INVENTORY_CHECK_TASK_UUID,\n", - " input={\n", - " \"item_id\": item_id,\n", - " \"quantity\": quantity\n", - " }\n", - " )\n", - " time.sleep(2)\n", - " result = client.executions.get(execution.id)\n", - " return client.executions.transitions.list(execution_id=result.id).items[0].output\n", - "\n", - "def process_payment(user_id, order_id, amount):\n", - " execution = client.executions.create(\n", - " task_id=PAYMENT_PROCESSING_TASK_UUID,\n", - " input={\n", - " \"user_id\": user_id,\n", - " \"order_id\": order_id,\n", - " \"amount\": amount\n", - " }\n", - " )\n", - " time.sleep(2)\n", - " result = client.executions.get(execution.id)\n", - " return client.executions.transitions.list(execution_id=result.id).items[0].output\n", - "\n", - "def track_shipment(order_id):\n", - " execution = client.executions.create(\n", - " task_id=SHIPMENT_TRACKING_TASK_UUID,\n", - " input={\n", - " \"order_id\": order_id\n", - " }\n", - " )\n", - " time.sleep(2)\n", - " result = client.executions.get(execution.id)\n", - " return client.executions.transitions.list(execution_id=result.id).items[0].output\n" - ], - "metadata": { - "id": "6iM6NqwlZMTD" - }, - "execution_count": 16, - "outputs": [] - }, - { - "cell_type": "code", - "source": [ - "print(\"Demonstrating E-commerce Order Processing Workflow:\")\n", - "\n", - "user_id = \"user123\"\n", - "item_id = 1\n", - "quantity = 2\n", - "amount = 49.99\n", - "\n", - "is_available = check_inventory(item_id, quantity)\n", - "if is_available:\n", - " print(f\"Inventory Check: Item {item_id} is available.\")\n", - " order_result = place_order(user_id, item_id, quantity)\n", - " print(f\"Order Result: {order_result}\")\n", - " payment_result = process_payment(user_id, order_result[\"order_id\"], amount)\n", - " print(f\"Payment Status: {payment_result}\")\n", - " shipment_result = track_shipment(order_result[\"order_id\"])\n", - " print(f\"Shipment Status: {shipment_result}\")\n", - "else:\n", - " print(f\"Inventory Check: Item {item_id} is not available.\")\n" - ], - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "FTDf1VaMZQ3f", - "outputId": "a358feb6-2630-4a2c-d423-16d7f2937c07" - }, - "execution_count": 17, - "outputs": [ - { - "output_type": "stream", - "name": "stdout", - "text": [ - "Demonstrating E-commerce Order Processing Workflow:\n", - "Inventory Check: Item 1 is available.\n", - "Order Result: {'order_id': 'Order confirmed for User ID: user123. The order details are as follows: Item ID: 1, Quantity: 2. Your order ID is ORD456789.'}\n", - "Payment Status: Payment processed successfully for Order ID: ORD456789. The payment amount of $49.99 has been confirmed.\n", - "Shipment Status: The current status of the shipment for Order ID ORD456789 is \"In Transit.\" The order has been picked up by the carrier and is on its way to the delivery address. Estimated delivery is within 3-5 business days.\n" - ] - } - ] - }, - { - "cell_type": "code", - "source": [], - "metadata": { - "id": "0NaRffiYZXGf" - }, - "execution_count": null, - "outputs": [] - } - ] -} \ No newline at end of file diff --git a/cookbooks/16-E_commerce_Order_Processing_Workflow.py b/cookbooks/16-E_commerce_Order_Processing_Workflow.py deleted file mode 100644 index e8db94556..000000000 --- a/cookbooks/16-E_commerce_Order_Processing_Workflow.py +++ /dev/null @@ -1,238 +0,0 @@ -# -*- coding: utf-8 -*- -"""E-commerce_Order_Processing_Workflow.ipynb - -Automatically generated by Colab. - -Original file is located at - https://colab.research.google.com/drive/1mP-uZV8-wMMJA0eDcF5TH6C82ZOup055 -""" - -import uuid -import yaml -import time -from julep import Client - -AGENT_UUID = uuid.uuid4() -ORDER_PLACEMENT_TASK_UUID = uuid.uuid4() -INVENTORY_CHECK_TASK_UUID = uuid.uuid4() -PAYMENT_PROCESSING_TASK_UUID = uuid.uuid4() -SHIPMENT_TRACKING_TASK_UUID = uuid.uuid4() - -api_key = "" # Your API key here -client = Client(api_key=api_key, environment="dev") - -agent = client.agents.create_or_update( - agent_id=AGENT_UUID, - name="Order Processing Assistant", - about="An AI agent specialized in automating the order processing workflow for e-commerce.", - model="gpt-4o", -) - -order_placement_task_def = yaml.safe_load(""" -name: Order Placement - -input_schema: - type: object - properties: - user_id: - type: string - order_details: - type: object - properties: - item_id: - type: integer - quantity: - type: integer - -main: -- prompt: - - role: system - content: >- - You are an order placement assistant. Process the following order: - User ID: {{inputs[0].user_id}} - Order Details: {{inputs[0].order_details}} - - Confirm the order placement and return the order ID. - unwrap: true - -- evaluate: - order_id: _.uuid() - -- return: - order_id: _ -""") - -order_placement_task = client.tasks.create_or_update( - task_id=ORDER_PLACEMENT_TASK_UUID, - agent_id=AGENT_UUID, - **order_placement_task_def -) - -inventory_check_task_def = yaml.safe_load(""" -name: Inventory Check - -input_schema: - type: object - properties: - item_id: - type: integer - quantity: - type: integer - -main: -- prompt: - - role: system - content: >- - You are an inventory checker. Check the availability of the following item: - Item ID: {{inputs[0].item_id}} - Quantity Requested: {{inputs[0].quantity}} - - Return true if available, otherwise return false. - unwrap: true -""") - -inventory_check_task = client.tasks.create_or_update( - task_id=INVENTORY_CHECK_TASK_UUID, - agent_id=AGENT_UUID, - **inventory_check_task_def -) - -payment_processing_task_def = yaml.safe_load(""" -name: Payment Processing - -input_schema: - type: object - properties: - user_id: - type: string - order_id: - type: string - amount: - type: number - -main: -- prompt: - - role: system - content: >- - You are a payment processor. Process payment for the following order: - User ID: {{inputs[0].user_id}} - Order ID: {{inputs[0].order_id}} - Amount: {{inputs[0].amount}} - - Confirm payment status (success or failure). - unwrap: true - -- evaluate: - payment_status: "success" # Simulating a successful payment - -- return: - payment_status: _ -""") - -payment_processing_task = client.tasks.create_or_update( - task_id=PAYMENT_PROCESSING_TASK_UUID, - agent_id=AGENT_UUID, - **payment_processing_task_def -) - -shipment_tracking_task_def = yaml.safe_load(""" -name: Shipment Tracking - -input_schema: - type: object - properties: - order_id: - type: string - -main: -- prompt: - - role: system - content: >- - You are a shipment tracker. Track the shipment for the following order: - Order ID: {{inputs[0].order_id}} - - Return the current status of the shipment. - unwrap: true -""") - -shipment_tracking_task = client.tasks.create_or_update( - task_id=SHIPMENT_TRACKING_TASK_UUID, - agent_id=AGENT_UUID, - **shipment_tracking_task_def -) - -def place_order(user_id, item_id, quantity): - execution = client.executions.create( - task_id=ORDER_PLACEMENT_TASK_UUID, - input={ - "user_id": user_id, - "order_details": { - "item_id": item_id, - "quantity": quantity - } - } - ) - time.sleep(2) - result = client.executions.get(execution.id) - output = client.executions.transitions.list(execution_id=result.id).items[0].output - - if isinstance(output, dict): - return output - else: - return {"order_id": output} - -def check_inventory(item_id, quantity): - execution = client.executions.create( - task_id=INVENTORY_CHECK_TASK_UUID, - input={ - "item_id": item_id, - "quantity": quantity - } - ) - time.sleep(2) - result = client.executions.get(execution.id) - return client.executions.transitions.list(execution_id=result.id).items[0].output - -def process_payment(user_id, order_id, amount): - execution = client.executions.create( - task_id=PAYMENT_PROCESSING_TASK_UUID, - input={ - "user_id": user_id, - "order_id": order_id, - "amount": amount - } - ) - time.sleep(2) - result = client.executions.get(execution.id) - return client.executions.transitions.list(execution_id=result.id).items[0].output - -def track_shipment(order_id): - execution = client.executions.create( - task_id=SHIPMENT_TRACKING_TASK_UUID, - input={ - "order_id": order_id - } - ) - time.sleep(2) - result = client.executions.get(execution.id) - return client.executions.transitions.list(execution_id=result.id).items[0].output - -print("Demonstrating E-commerce Order Processing Workflow:") - -user_id = "user123" -item_id = 1 -quantity = 2 -amount = 49.99 - -is_available = check_inventory(item_id, quantity) -if is_available: - print(f"Inventory Check: Item {item_id} is available.") - order_result = place_order(user_id, item_id, quantity) - print(f"Order Result: {order_result}") - payment_result = process_payment(user_id, order_result["order_id"], amount) - print(f"Payment Status: {payment_result}") - shipment_result = track_shipment(order_result["order_id"]) - print(f"Shipment Status: {shipment_result}") -else: - print(f"Inventory Check: Item {item_id} is not available.") -