lingobot / interfaces /table.py
Gent (PG/R - Comp Sci & Elec Eng)
add demos
a20ccd6
import gradio as gr
from langchain import LLMMathChain, OpenAI
import pandas as pd
from langchain.tools import BaseTool, StructuredTool, Tool, tool
from pydantic import BaseModel, Field
import os
import yaml
from langchain.agents import (
create_json_agent,
AgentExecutor
)
from langchain.agents.agent_toolkits import JsonToolkit
from langchain.chains import LLMChain
from langchain.requests import TextRequestsWrapper
from langchain.tools.json.tool import JsonSpec
template = """Assistant is a large language model owned by Mintyea.
Assistant is designed to be able to use tools and coordinate with humans to finish tasks. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
Assistant is a powerful to understand and utilize a wide range of tools. Assistant does not handle the task directly, but instead uses tools to help humans finish tasks. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
TOOLS:
------
Assistant has access to the following tools:
> Waiter is a tool that can help you to serve in the restaurant. It can help the customer to find a table, take an order, serve the food, and pay the bill. Waiter can take actions to help humans finish tasks step by step. For example, you can say "(waiter) Please follow me to your table. [lead to table]". The customer can only talk to the waiter.
> Order List is a tool that can help you to take an order. The customer cannot talk to the order list directly. The customer can only talk to the waiter. The order list can tell the waiter the details if the costomer requires. For example, you can say "(waiter) I want to order a dessert. [order a dessert]". The waiter will use the order list to take the order.
To use a tool, please use the following format:
```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [The order list, Waiter]
Action Input: the input to the action
Observation: the result of the action
```
When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
```
Thought: Do I need to use a tool? No
AI: [your response here]
```
Begin!
Previous conversation history:
New input: order a dessert.
"""
#%%
class OrderList():
name = "Order"
description = "The list of orders."
list = pd.DataFrame(columns=["Item", "translation (Chinese)", "Price"])
def __init__(self):
super().__init__()
def add(self, item: str, translation: str, price: str):
self.list = pd.concat([
self.list ,
pd.DataFrame([{"Item":item, "translation (Chinese)":translation, "Price":price}])],
ignore_index=True,axis=0)
def delete(self, item):
self.list = self.list[self.list["Item"] != item]
def __str__(self) -> str:
return self.list.to_markdown(index=None)
def run(self, query: str):
print("\n########### call run:", query)
params = {}
for pair in query.split(","):
k,v = pair.split(":")
params[k.lower()] = v.strip()
item, translation, price = params.values()
self.add(item, translation, price)
return "You have ordered {} ({}), which costs {}.".format(item, translation, price)
def print(self, query: str):
print("\n########### call print:", query)
return "Your order has: \n" +str(self.list.to_markdown(index=None))
order_list = OrderList()
#%%
with open("data.txt") as f:
data = eval(f.read())
json_spec = JsonSpec(dict_=data, max_value_length=4000)
json_toolkit = JsonToolkit(spec=json_spec)
#%%
agent = create_json_agent(
llm=OpenAI(temperature=0),
toolkit=json_toolkit,
verbose=True
)
#%%
with gr.Blocks() as demo:
with gr.Row():
# inputs
with gr.Column():
prompt = gr.Textbox(agent.agent.llm_chain.prompt.template, lines=10, label="prompt",placeholder="Enter your prompt")
msg = gr.Textbox(lines=1, label="input",placeholder="Enter your message")
# outputs
with gr.Column():
chatbot = gr.Chatbot()
df = gr.DataFrame(headers=["Item", "translation (Chinese)", "Price"],
datatype=["str", "str", "number"],)
history = []
def respond( customer_input):
print("(Q:) ", customer_input)
response = agent.run(customer_input)
print("(A:) ", response)
history.append((customer_input, response))
return history, order_list.list
msg.submit(respond, [msg], [chatbot,df])
with gr.Row():
clear = gr.Button("Clear")
btn = gr.Button("导出", type="button", label="导出")
outputs = gr.JSON()
def export():
stats_history = {}
for i,item in enumerate(chatbot.value):
user,assistant = item
stats_history[str(i)] = {
"user": user,
"assistant": assistant
}
chatbot.value = []
return [], stats_history, None
btn.click(export, None, [ chatbot, outputs, df])
if __name__ == '__main__':
agent.run("get the first item")
demo.launch(show_error=True,share=False)