Lang Chain Agent
Lang Chain Agent
# return_policy.txt
# -----------------
# return_policy:
# Our return policy allows returns within 30 days of purchase.
# for Tablet , the return policy allows return within 10 days of purchase.
# order_tracking:
# You can track your order status using your order ID.
# product_info:
# Product information includes specifications and features.
# orders.json
# ------------
# {
# "123": {
# "customer_name": "John Doe",
# "order_date": "2022-01-01",
# "products": ["Laptop", "Monitor"],
# "total": 1500.00
# },
# "124": {
# "customer_name": "Jane Doe",
# "order_date": "2022-01-15",
# "products": ["Phone", "Keyboard"],
# "total": 800.00
# },
# "125": {
# "customer_name": "Bob Smith",
# "order_date": "2024-11-30",
# "products": ["Tablet", "Laptop"],
# "total": 2500.00
# }
# }
# product_info.json
# -----------------
# {
# "Laptop": "A high-performance laptop with 16GB RAM and 512GB SSD.",
# "Phone": "A smartphone with a 6.1-inch display and 128GB storage.",
# "Tablet": "A tablet with a 10.5-inch display and 256GB storage.",
# "Monitor": "A 24-inch full HD monitor.",
# "Keyboard": "A mechanical keyboard with RGB backlighting."
# }
# order_status.json
# -----------------
# {
:
# "123": "Delivered",
# "124": "Processing",
# "125": "Delivered",
# "126": "Cancelled",
# "127": "Returned",
# "128": "Out for Delivery"
# }
# '''
#!pip install faiss-cpu langchain langchain_openai langchain_community
def get_order_status_tool(order_id):
if not order_id.startswith("order_id = "):
return "Please provide an order ID in the format: 'order_id = <your_o
try:
order_id = order_id.replace("order_id = ", "")
with open('order_status.json', 'r') as file:
order_status = json.load(file)
return order_status.get(str(order_id), "Order ID not found")
except Exception as e:
print(f"Error reading order_status.json: {e}")
return "Order ID not found"
def save_order_status_returned_tool(order_id):
try:
# Read the existing data from the file
try:
with open('order_status.json', 'r') as file:
order_status = json.load(file)
except FileNotFoundError:
order_status = {}
except json.JSONDecodeError:
order_status = {}
except Exception as e:
print(f"Error saving order_status.json: {e}")
return "Failed to save order status."
def get_product_info_tool(product_name):
if not product_name.startswith("product_name = "):
return "Please provide a product name in the format: 'product_name =
try:
product_name = product_name.replace('product_name = ', '')
print(f" product_name {product_name}")
with open('product_info.json', 'r') as file:
product_info = json.load(file)
return product_info.get(product_name, "Product not found")
except Exception as e:
print(f"Error reading product_info.json: {e}")
return "Product not found"
def get_order_info_tool(order_id):
if not order_id.startswith("order_id = "):
return "Please provide an order ID in the format: 'order_id = <your_o
try:
order_id = order_id.replace("order_id = ", "")
with open('orders.json', 'r') as file:
orders = json.load(file)
return orders.get(str(order_id), "Order ID not found")
except Exception as e:
print(f"Error reading orders.json: {e}")
return "Order ID not found"
def get_today_date(today):
from datetime import datetime
today = datetime.now().strftime("%Y-%m-%d")
return f"today is {today}"
input_tool = Tool(
name="get_input_from_user",
func=input,
description="Get the input from the user."
)
order_status_tool = Tool(
name="get_order_status",
func=get_order_status_tool,
description="Get the status of an order given an order ID."
)
product_info_tool = Tool(
name="get_product_info",
:
func=get_product_info_tool,
description="Get information about a product given its name."
)
order_info_tool = Tool(
name="get_order_info",
func=get_order_info_tool,
description="Get information about an order given its ID."
)
order_status_returned_tool = Tool(
name="save_order_status_returned",
func=save_order_status_returned_tool,
description="Change the status of the order for the given order ID."
)
get_today_date_tool = Tool(
name="get_today_date",
func=get_today_date,
description="Get today's date in the format 'YYYY-MM-DD'."
)
os.environ["OPENAI_API_KEY"] = "sk-proj-Z-abcdef"
llm = ChatOpenAI(model="gpt-4o", temperature=0)
#https://python.langchain.com/docs/how_to/agent_executor/#using-language-mode
tool_search = create_retriever_tool(
retriever=retriever,
:
name="search_return_policy",
description="Searches and returns policy, product, etc."
)
# https://python.langchain.com/v0.1/docs/modules/agents/agent_types/
# https://python.langchain.com/v0.1/docs/modules/agents/agent_types/react/
def prompt_user_for_info(query):
response = agent_executor.invoke({"input": query})
if "Please provide" in response["output"]:
new_input = input(response["output"]) # Prompt the user for addition
return prompt_user_for_info(new_input)
else:
return response
/opt/conda/lib/python3.10/site-packages/langsmith/client.py:241: La
ngSmithMissingAPIKeyWarning: API key must be provided when using ho
sted LangSmith API
warnings.warn(
Action: get_input_from_user
Action Input: "Please provide the order ID to retrieve the product
information."
:
125I have the order ID. Now, I need to retrieve the order informati
on using this ID to get the product details.
Action: get_order_info
Action Input: 125Please provide an order ID in the format: 'order_i
d = <your_order_id>' . for the correct format, don't ask the user
again. you prepare the correct format if you have enough informatio
nI need to format the order ID correctly to retrieve the order info
rmation.
Action: get_order_info
Action Input: order_id = 125{'customer_name': 'Bob Smith', 'order_d
ate': '2024-11-30', 'products': ['Tablet', 'Laptop'], 'total': 250
0.0}I have retrieved the order information. The products in the ord
er are a Tablet and a Laptop.
Final Answer: The products in the order are a Tablet and a Laptop.
Action: get_input_from_user
Action Input: "Please provide your order ID so I can check the orde
r date."
:
125I have the order ID. Now, I need to retrieve the order informati
on to find out the order date.
Action: get_order_info
Action Input: 125Please provide an order ID in the format: 'order_i
d = <your_order_id>' . for the correct format, don't ask the user
again. you prepare the correct format if you have enough informatio
nI need to format the order ID correctly to retrieve the order info
rmation.
Action: get_order_info
Action Input: order_id = 125{'customer_name': 'Bob Smith', 'order_d
ate': '2024-11-30', 'products': ['Tablet', 'Laptop'], 'total': 250
0.0}I have the order date, which is November 30, 2024. Now, I need
to find out today's date to calculate the number of days since the
order was placed.
Action: get_today_date
Action Input: Nonetoday is 2024-12-05I have both the order date and
today's date. The order was placed on November 30, 2024, and today
is December 5, 2024. To calculate the number of days since the orde
r was placed, I subtract the order date from today's date.
Action: get_input_from_user
Action Input: "Please provide your order ID so I can assist you wit
h the return process."
:
123I have the order ID. Now, I need to check the status of the orde
r to proceed with the return process.
Action: get_order_status
Action Input: 123Please provide an order ID in the format: 'order_i
d = <your_order_id>'. for the correct format, don't ask the user ag
ain. you prepare the correct format if you have enough informationI
t seems I need to format the order ID correctly to proceed. Let me
do that.
Action: get_order_status
Action Input: order_id = 123DeliveredThe order with ID 123 has been
delivered. To proceed with the return process, I need to check the
return policy to ensure the product is eligible for return.
Action: search_return_policy
Action Input: "return policy"return_policy:
Our return policy allows returns within 30 days of purchase.
for Tablet , the return policy allows return within 10 days of purc
hase.
order_tracking:
You can track your order status using your order ID.
product_info:
Product information includes specifications and features.The return
policy allows returns within 30 days of purchase for most products,
but for tablets, the return period is only 10 days. To proceed, I n
eed to check if your product is eligible for return based on these
conditions. Let's find out more about your order.
Action: get_order_info
Action Input: order_id = 123{'customer_name': 'John Doe', 'order_da
te': '2022-01-01', 'products': ['Laptop', 'Monitor'], 'total': 150
0.0}The order includes a Laptop and a Monitor, and it was placed on
2022-01-01. Since the return policy allows returns within 30 days o
f purchase, and the order date is well beyond this period, the prod
ucts are not eligible for return.
Action: get_input_from_user
Action Input: Please provide your order ID.
125To proceed with the return process, I need to check the status o
f your order using the provided order ID.
Action: get_order_status
Action Input: 125Please provide an order ID in the format: 'order_i
d = <your_order_id>'. for the correct format, don't ask the user ag
ain. you prepare the correct format if you have enough informationI
need to format the order ID correctly to check the status. Let's fo
rmat it and try again.
Action: get_order_status
Action Input: order_id = 125DeliveredThe order with ID 125 has been
delivered. I can proceed with initiating the return process for thi
s order.
Action: save_order_status_returned
Action Input: 125Please provide an order ID in the format: 'order_i
d = <your_order_id>'. for the correct format, don't ask the user ag
ain. you prepare the correct format if you have enough informationI
need to format the order ID correctly to update the status. Let's f
ormat it and try again.
Action: save_order_status_returned
Action Input: order_id = 125Order status saved successfully.The ret
urn process for your order with ID 125 has been successfully initia
ted. If you have any further questions or need additional assistanc
e, feel free to ask!Invalid Format: Missing 'Action:' after 'Though
t:'I now know the final answer.
Final Answer: The return process for your order with ID 125 has bee
n successfully initiated. If you have any further questions or need
additional assistance, feel free to ask!
In [ ]:
: