Saturday, August 3, 2024

Workflows in LlamaIndex - Tutorial to Build Complex AI Applications with Events

 This video shows how to install and use LlamaIndex Workflows which is a mechanism for orchestrating actions in the increasingly complex AI application.


Code:

conda create -n workflow python=3.11 -y && conda activate workflow

pip install llama-index
pip install llama-index-llms-openai

conda install jupyter -y
pip uninstall charset_normalizer -y
pip install charset_normalizer
jupyter notebook

from llama_index.core.workflow import (
    Event,
    StartEvent,
    StopEvent,
    Workflow,
    step,
)

from llama_index.llms.openai import OpenAI

class WeatherEvent(Event):
    location: str
    forecast: str | None

class WeatherFlow(Workflow):
    llm = OpenAI()

    @step()
    async def get_location(self, ev: StartEvent) -> WeatherEvent:
        location = "Sydney"
        forecast = ""  # or some default value
        return WeatherEvent(location=location, forecast=forecast)

    @step()
    async def get_forecast(self, ev: WeatherEvent) -> WeatherEvent:
        location = ev.location
        prompt = f"Get the current weather forecast for {location}."
        response = await self.llm.acomplete(prompt)
        return WeatherEvent(location=location, forecast=str(response))

    @step()
    async def format_forecast(self, ev: WeatherEvent) -> StopEvent:
        location = ev.location
        forecast = ev.forecast
        formatted_forecast = f"Weather in {location}: {forecast}"
        return StopEvent(result=formatted_forecast)

w = WeatherFlow(timeout=60, verbose=False)
result = await w.run()
print(str(result))

No comments: