Replies: 1 comment 4 replies
-
To implement a stop button that interrupts the agent's execution in LangChain, you can use
Here's an example of how you can modify your import asyncio
async def invoke(self, query: str) -> str:
messages = [("human", query)]
response = ""
total_tokens = 0
try:
# Use stream instead of invoke, but collect the entire result
async for chunk in self.__agent_executor.stream(
{"messages": messages},
self.__config,
stream_mode="values",
):
if "messages" in chunk and chunk["messages"]:
all_msgs = chunk["messages"]
new_msgs = []
found_last = False
for i in range(len(all_msgs) - 1, -1, -1):
if all_msgs[i].id == self.last_message_id and self.last_message_id is not None:
found_last = True
new_msgs = all_msgs[i + 1:]
break
if not found_last:
new_msgs = all_msgs
for msg in new_msgs:
print(msg.type)
if self.__show_token_usage and 'token_usage' in msg.response_metadata:
total_tokens += msg.response_metadata['token_usage']['total_tokens']
self.last_message_id = new_msgs[-1].id
latest_msg = chunk["messages"][-1]
response = latest_msg.content
if self.__show_token_usage:
print(f"Token usage: {total_tokens}")
except asyncio.CancelledError:
print("Task cancelled!")
# Call a tool to stop the robot here
await self.stop_robot_tool()
return "Execution stopped by user."
except Exception as e:
return f"An error occurred: {str(e)}"
return response
# Example usage
async def main():
task = asyncio.create_task(invoke(query="Your query here"))
# Simulate a stop button press after some time
await asyncio.sleep(1) # Adjust the sleep time as needed
task.cancel()
try:
await task
except asyncio.CancelledError:
print("Task was cancelled successfully.")
# Run the main function
asyncio.run(main()) Key Points:
This setup should allow you to interrupt the agent's execution and handle the stop action gracefully. To continue talking to Dosu, mention @dosu. Help Dosu learn! Give it feedback: Great Response | Irrelevant Answer | Incorrect Sources | Too Verbose | Hallucination | Bug Report | Other |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I am using the ReAct agent to control a robot via tools, i want to implement a stop button in my application, which should interrupt the agents query execution. I would like it to work like this:
I am using create_react_agent() with MemorySaver() as checkpointer
This is my current implementation of query invocation:
However when i try to run invoke with asyncio and then cancel the task, it doesnt seem to work, the agent prints an error, that the tool call has not been finished and then proceeds to finish from there
Beta Was this translation helpful? Give feedback.
All reactions