# check out https://solara.dev/ for documentation
# or https://github.com/widgetti/solara/
# And check out https://py.cafe/maartenbreddels for more examples
import solara
from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
from langchain_openai import ChatOpenAI
import pandas as pd
import plotly.express as px
from typing import List
try:
import pycafe
reason = """We need an OpenAI API key to generate text.
Go to [OpenAI](https://platform.openai.com/account/api-keys) to get one.
Or read [this](https://www.rebelmouse.com/openai-account-set-up) article for
more information.
Or read more [about secrets on PyCafe](/docs/secrets)
"""
openai_api_key = pycafe.get_secret("OPENAI_API_KEY", reason=reason)
except ModuleNotFoundError:
openai_api_key = os.environ.get("OPENAI_API_KEY")
llm = ChatOpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
# data from https://www.kaggle.com/datasets/nelgiriyewithana/world-stock-prices-daily-updating
df_stocks = pd.read_csv("https://raw.githubusercontent.com/Coding-with-Adam/Dash-by-Plotly/master/LangChain/Agents/Pandas-Agent/World-Stock-Prices-Data-small.csv")
df_stocks['Date'] = pd.to_datetime(df_stocks['Date'], utc=True)
df_stocks['Date'] = df_stocks['Date'].dt.date
stocks = solara.reactive(['AAPL','TSLA'])
@solara.component
def Page():
with solara.Card(
"Stocks assistant",
):
solara.SelectMultiple(values=stocks, all_values=sorted(df_stocks['Ticker'].unique()), label="")
# solara.FigurePlotly(fig)
async def ask_ai():
if openai_api_key is None:
return "`OPENAI_API_KEY` is not set"
# Use pandas agent to analyze the dataset
df = df_stocks[df_stocks['Ticker'].isin(stocks.value)]
agent = create_pandas_dataframe_agent(llm=llm,
df=df,
max_iterations=2,
verbose=True,
agent_type="tool-calling",
handle_parsing_errors=True,
allow_dangerous_code=True)
response = agent.invoke("What is the dataset telling us about the performance of the stocks? "
"Only consider the 'High' and the 'Ticker' columns. "
"Please provide a summary at the end.")
return response["output"]
# re-runs only when the stocks changes
result = solara.lab.use_task(ask_ai, dependencies=[stocks.value])
if result.pending:
solara.ProgressLinear()
solara.Markdown("*Asking AI to analyse the performance of the stock*")
else:
df = df_stocks[df_stocks['Ticker'].isin(stocks.value)]
print(df.head())
fig = px.line(df, x='Date', y='High', color='Ticker')
display(fig)
solara.Markdown(result.value)