Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain import hub
|
2 |
+
from langchain.agents import AgentExecutor, create_openai_tools_agent, load_tools
|
3 |
+
from langchain_openai import ChatOpenAI
|
4 |
+
from gradio import ChatMessage
|
5 |
+
import gradio as gr
|
6 |
+
import os
|
7 |
+
|
8 |
+
if not (os.getenv("SERPAPI_API_KEY") and os.getenv("OPENAI_API_KEY")):
|
9 |
+
with gr.Blocks() as demo:
|
10 |
+
gr.Markdown("""
|
11 |
+
# Chat with a LangChain Agent π¦βοΈ and see its thoughts π
|
12 |
+
|
13 |
+
In order to run this space, duplicate it and add the following space secrets:
|
14 |
+
|
15 |
+
* SERPAPI_API_KEY - create an account at serpapi.com and get an API key
|
16 |
+
* OPENAI_API_KEY - create an openai account and get an API key
|
17 |
+
""")
|
18 |
+
|
19 |
+
model = ChatOpenAI(temperature=0, streaming=True)
|
20 |
+
|
21 |
+
tools = load_tools(["serpapi"])
|
22 |
+
|
23 |
+
# Get the prompt to use - you can modify this!
|
24 |
+
prompt = hub.pull("hwchase17/openai-tools-agent")
|
25 |
+
# print(prompt.messages) -- to see the prompt
|
26 |
+
agent = create_openai_tools_agent(
|
27 |
+
model.with_config({"tags": ["agent_llm"]}), tools, prompt
|
28 |
+
)
|
29 |
+
agent_executor = AgentExecutor(agent=agent, tools=tools).with_config(
|
30 |
+
{"run_name": "Agent"}
|
31 |
+
)
|
32 |
+
|
33 |
+
|
34 |
+
async def interact_with_langchain_agent(prompt, messages):
|
35 |
+
messages.append(ChatMessage(role="user", content=prompt))
|
36 |
+
yield messages
|
37 |
+
async for chunk in agent_executor.astream(
|
38 |
+
{"input": prompt}
|
39 |
+
):
|
40 |
+
if "steps" in chunk:
|
41 |
+
for step in chunk["steps"]:
|
42 |
+
messages.append(ChatMessage(role="assistant", content=step.action.log,
|
43 |
+
metadata={"title": f"π οΈ Used tool {step.action.tool}"}))
|
44 |
+
yield messages
|
45 |
+
if "output" in chunk:
|
46 |
+
messages.append(ChatMessage(role="assistant", content=chunk["output"]))
|
47 |
+
yield messages
|
48 |
+
|
49 |
+
|
50 |
+
with gr.Blocks() as demo:
|
51 |
+
gr.Markdown("# Chat with a LangChain Agent π¦βοΈ and see its thoughts π")
|
52 |
+
chatbot_2 = gr.Chatbot(
|
53 |
+
msg_format="messages",
|
54 |
+
label="Agent",
|
55 |
+
avatar_images=(
|
56 |
+
None,
|
57 |
+
"https://em-content.zobj.net/source/twitter/141/parrot_1f99c.png",
|
58 |
+
),
|
59 |
+
)
|
60 |
+
input_2 = gr.Textbox(lines=1, label="Chat Message")
|
61 |
+
input_2.submit(interact_with_langchain_agent, [input_2, chatbot_2], [chatbot_2])
|
62 |
+
|
63 |
+
demo.launch()
|