Replies: 4 comments 4 replies
-
If you use Here is my current approach. If I want a tool result (type is Any), I will use artifacts, allowing my tool func to return a tuple of (content, artifact). My I receive the results of |
Beta Was this translation helpful? Give feedback.
-
langchain-ai/langchain#25095 (comment) Currently, for some reasons, the DataFrame seems unable to be passed in |
Beta Was this translation helpful? Give feedback.
-
update I'm not sure what import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
from langchain_core.tools import BaseTool, tool
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
load_dotenv()
class Agent:
def __init__(
self, model: ChatOpenAI, tools: list[BaseTool], system: str = ""
) -> None:
self.system = system
self.model = model.bind_tools(tools)
graph = StateGraph(MessagesState)
graph.add_node("llm", self.call_openai)
graph.add_node("pandas", ToolNode(tools=tools))
graph.add_node("plot", self.plot_chart)
graph.add_edge(START, "llm")
graph.add_conditional_edges(
"llm", tools_condition, {"tools": "pandas", END: END}
)
graph.add_edge("pandas", "plot")
graph.add_edge("plot", END)
self.graph = graph.compile()
def call_openai(self, state: MessagesState) -> MessagesState:
messages = state["messages"]
if self.system:
messages = [SystemMessage(content=self.system)] + messages
return {"messages": [self.model.invoke(messages)]}
def plot_chart(self, state: MessagesState) -> None:
tool_message: ToolMessage = state["messages"][-1]
table = tool_message.artifact
x_axis, y_axis = table["Date"], table["Price"]
plt.figure(figsize=(10, 5))
plt.plot(x_axis, y_axis, marker="o")
plt.title("Price History")
plt.xlabel("Date")
plt.ylabel("Price")
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
# plt.show()
path = "123.png"
plt.savefig(path)
plt.close()
print(f"Your chart is saved as {path}")
@tool(response_format="content_and_artifact")
def get_price_history(start_date: str, end_date: str) -> tuple[str, pd.DataFrame]:
"""Get price history data."""
dates = pd.date_range(start=start_date, end=end_date)
prices = np.random.rand(len(dates)) * 100
return "", pd.DataFrame({"Date": dates, "Price": prices})
model = ChatOpenAI(model="gpt-4o-2024-08-06")
tools = [get_price_history]
graph = Agent(model, tools).graph
graph.invoke(
{
"messages": [
HumanMessage(
content="I want to see the price history between 2023-01-01 and 2023-01-10"
)
]
}
) |
Beta Was this translation helpful? Give feedback.
-
@hepbc Original inputs = {"messages": [HumanMessage(content="I want to see the price history between 2023-01-01 and 2023-01-10")]}
graph.invoke(inputs) Revised inputs = {"messages": [HumanMessage(content="I want to see the price history between 2023-01-01 and 2023-01-10")]}
outputs = graph.invoke(inputs) I will report this issue to Langchain again. |
Beta Was this translation helpful? Give feedback.
-
Hi guys: I am building a simple agent that takes input and executes tools till it gets an END msg. I have bound a bunch of tools to the agent. One of the tools (get_price_history) outputs a pandas dataframe (dates and stock prices on those dates) and another (plot_chart) plots dates and prices. The expected output is that the get_price_history tool gives the prices and the agent routes this data to the plot_chart tool for the chart.
This works ok if the price data is upto a few days. Otherwise, it takes the first few days and the last few days and does not output the graph correctly: see example of a 6 month chart below.
I noticed that I am converting the tool output to a string in the take_action fn of the agent:
This seems to be losing data as most of it is replaced by "..."
I tried passing as json but get a number of tokens limit error.
Can someone pls guide me here? Is it possible to pass a dataframe as is - if not how can I maintain the integrity of the string output so all the price data is preserved? More generally how can I pass output in different formats between tools.
Look forward to the community working its magic.
Thanks
BC
Beta Was this translation helpful? Give feedback.
All reactions