-
Notifications
You must be signed in to change notification settings - Fork 5.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enable human interaction in AutoGenStudio #3445
Closed
SailorJoe6
wants to merge
12
commits into
microsoft:autogenstudio
from
SailorJoe6:issue_#1358_human_input
Closed
Changes from 1 commit
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
2e77d3b
Fix AutoGen Studio pathPrefix error on Windows (#3406)
New-World-2019 5861bd9
fix: tool calling cohere (#3355)
Anirudh31415926535 9429355
Enable human interaction in AutoGenStudio
SailorJoe6 084532e
[.Net] add output schema to generateReplyOption (#3450)
LittleLittleCloud d3cf0c8
Formatting checks suggested by linter, plus remove some unused imports
SailorJoe6 4577524
Use utf-8 encoding at subprocess.run() (#3454)
giorgossideris f37bb7f
This commit handles the UI issues and occasional errors caused by an …
SailorJoe6 5b6a73a
Fix for `UnboundLocalError: local variable 'data' referenced before a…
SailorJoe6 0f95d64
Merge branch 'microsoft:main' into issue_#1358_human_input
SailorJoe6 a6e6b95
Merge branch 'autogenstudio' into issue_#1358_human_input
SailorJoe6 a2b2dc8
Creating a new session or clicking on a different session while waiti…
SailorJoe6 8182af2
Disable the "New" session button too. Not sure how I missed this one…
SailorJoe6 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,3 @@ | ||
from .chatmanager import * | ||
from .datamodel import * | ||
from .version import __version__ | ||
from .workflowmanager import * |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
samples/apps/autogen-studio/autogenstudio/web/chatmanager.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
import asyncio | ||
import os | ||
from datetime import datetime | ||
from queue import Queue | ||
from typing import Any, Dict, List, Optional | ||
from loguru import logger | ||
import websockets | ||
from fastapi import WebSocket, WebSocketDisconnect | ||
|
||
from ..datamodel import Message | ||
from ..workflowmanager import WorkflowManager | ||
from .websocketmanager import WebSocketConnectionManager | ||
|
||
#temp, for troubleshooting | ||
import traceback | ||
|
||
class AutoGenChatManager: | ||
""" | ||
This class handles the automated generation and management of chat interactions | ||
using an automated workflow configuration and message queue. | ||
""" | ||
|
||
def __init__(self, message_queue: Queue = None, websocket_manager:WebSocketConnectionManager = None) -> None: | ||
""" | ||
Initializes the AutoGenChatManager with a message queue. | ||
|
||
:param message_queue: A queue to use for sending messages asynchronously. | ||
""" | ||
self.message_queue = message_queue | ||
self.websocket_manager = websocket_manager | ||
|
||
def send(self, message: dict) -> None: | ||
""" | ||
Sends a message by putting it into the message queue. | ||
|
||
:param message: The message string to be sent. | ||
""" | ||
# Since we are no longer blocking the event loop in the main app.py, | ||
# we can safely avoid using the other thread, which increases complexity and | ||
# reduces certainty about the order in which messages will be sent. | ||
# if self.message_queue is not None: | ||
# self.message_queue.put_nowait(message) | ||
for connection, socket_client_id in self.websocket_manager.active_connections: | ||
if message["connection_id"] == socket_client_id: | ||
logger.info( | ||
f"Sending message to connection_id: {message['connection_id']}. Connection ID: {socket_client_id}, Message: {message}" | ||
) | ||
asyncio.run(self.websocket_manager.send_message(message, connection)) | ||
else: | ||
logger.info( | ||
f"Skipping message for connection_id: {message['connection_id']}. Connection ID: {socket_client_id}" | ||
) | ||
|
||
|
||
def get_user_input(self, user_prompt: dict, timeout: int) -> str: | ||
""" | ||
waits on the websocket for a response from the user. | ||
|
||
:param prompt: the string to prompt the user with | ||
:param timeout: The amount of seconds to wait before considering the user inactive. | ||
:returns the user's response, or a default message to terminate the chat if the user is inactive. | ||
""" | ||
response = "" | ||
for connection, socket_client_id in self.websocket_manager.active_connections: | ||
if user_prompt["connection_id"] == socket_client_id: | ||
logger.info( | ||
f"Sending user prompt to connection_id: {user_prompt['connection_id']}. Connection ID: {socket_client_id}, Prompt: {user_prompt}" | ||
) | ||
response = asyncio.run(self.websocket_manager.get_user_input(user_prompt, timeout, connection)) | ||
else: | ||
logger.info( | ||
f"Skipping message for connection_id: {user_prompt['connection_id']}. Connection ID: {socket_client_id}" | ||
) | ||
|
||
return response | ||
|
||
|
||
def chat( | ||
self, | ||
message: Message, | ||
history: List[Dict[str, Any]], | ||
workflow: Any = None, | ||
connection_id: Optional[str] = None, | ||
user_dir: Optional[str] = None, | ||
human_input_function: Optional[callable] = None, | ||
**kwargs, | ||
) -> Message: | ||
""" | ||
Processes an incoming message according to the agent's workflow configuration | ||
and generates a response. | ||
|
||
:param message: An instance of `Message` representing an incoming message. | ||
:param history: A list of dictionaries, each representing a past interaction. | ||
:param flow_config: An instance of `AgentWorkFlowConfig`. If None, defaults to a standard configuration. | ||
:param connection_id: An optional connection identifier. | ||
:param kwargs: Additional keyword arguments. | ||
:param user_dir: An optional base path to use as the temporary working folder. | ||
:param human_input_function: an optional callable to enable human input during workflows. | ||
:return: An instance of `Message` representing a response. | ||
""" | ||
|
||
# create a working director for workflow based on user_dir/session_id/time_hash | ||
work_dir = os.path.join( | ||
user_dir, | ||
str(message.session_id), | ||
datetime.now().strftime("%Y%m%d_%H-%M-%S"), | ||
) | ||
os.makedirs(work_dir, exist_ok=True) | ||
|
||
# if no flow config is provided, use the default | ||
if workflow is None: | ||
raise ValueError("Workflow must be specified") | ||
|
||
workflow_manager = WorkflowManager( | ||
workflow=workflow, | ||
history=history, | ||
work_dir=work_dir, | ||
send_message_function=self.send, | ||
human_input_function=human_input_function, | ||
connection_id=connection_id, | ||
) | ||
|
||
message_text = message.content.strip() | ||
# Temporary, for troubleshooting | ||
try: | ||
result_message: Message = workflow_manager.run(message=f"{message_text}", clear_history=False, history=history) | ||
except Exception as e: | ||
traceback.print_exc() | ||
raise | ||
|
||
result_message.user_id = message.user_id | ||
result_message.session_id = message.session_id | ||
return result_message | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@SailorJoe6
Thanks for the rewrite and
3.10
support.I am seeing some errors while testing ... .
With that fixed on my local version, I am still seeing a few other socket connection errors.
Tried to address this using a asynccontext manager but still seeing some of the timeout/delay issues where receive_json() does not return.
Overall, once the core errors are addressed (even without the delay), I am happy to mark this feature as experimental (always/terminate human input), merge in and then improve iteratively.
Also, if you can attach a quick recording of how you are testing and results, that would be useful. Thanks.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'll address these issues to the best of my abilities tomorrow. Thanks again for the review!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey @victordibia, I'm working on these issues now. I see there's a new commit on autogenstudio branch. I can merge or rebase. Personally, I prefer rebase, but it's your call. Do you have a preference?