Spaces:
No application file
No application file
File size: 5,486 Bytes
a20ccd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | 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)
|