Streamlit
Streamlit 是更快建立和分享資料應用程式的方式。 Streamlit 在幾分鐘內將資料腳本轉換為可分享的網路應用程式。全部使用純 Python。無需前端經驗。請參閱 streamlit.io/generative-ai 以瞭解更多範例。
在本指南中,我們將示範如何使用 StreamlitCallbackHandler
在互動式 Streamlit 應用程式中顯示 Agent 的想法和動作。使用下方的執行中應用程式和 MRKL Agent 試用看看
安裝與設定
pip install langchain streamlit
您可以執行 streamlit hello
以載入範例應用程式並驗證您的安裝是否成功。請參閱 Streamlit 的入門文件以取得完整說明。
顯示想法和動作
若要建立 StreamlitCallbackHandler
,您只需要提供父容器來呈現輸出。
from langchain_community.callbacks.streamlit import (
StreamlitCallbackHandler,
)
import streamlit as st
st_callback = StreamlitCallbackHandler(st.container())
自訂顯示行為的其他關鍵字引數在API 參考中說明。
情境 1:搭配工具使用 Agent
目前主要支援的使用案例是視覺化搭配工具的 Agent(或 Agent Executor)的動作。您可以在您的 Streamlit 應用程式中建立 Agent,並將 StreamlitCallbackHandler
傳遞至 agent.run()
,以便在您的應用程式中即時視覺化想法和動作。
import streamlit as st
from langchain import hub
from langchain.agents import AgentExecutor, create_react_agent, load_tools
from langchain_openai import OpenAI
llm = OpenAI(temperature=0, streaming=True)
tools = load_tools(["ddg-search"])
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
if prompt := st.chat_input():
st.chat_message("user").write(prompt)
with st.chat_message("assistant"):
st_callback = StreamlitCallbackHandler(st.container())
response = agent_executor.invoke(
{"input": prompt}, {"callbacks": [st_callback]}
)
st.write(response["output"])
注意: 您需要設定 OPENAI_API_KEY
,上述應用程式程式碼才能成功執行。最簡單的方法是透過 Streamlit secrets.toml 或任何其他本地 ENV 管理工具來執行。
其他情境
目前 StreamlitCallbackHandler
旨在與 LangChain Agent Executor 搭配使用。未來將新增對其他 Agent 類型、直接與 Chains 搭配使用等的支援。
您可能也會對將 StreamlitChatMessageHistory 用於 LangChain 感興趣。