A programming framework for agentic AI
Improvements to AutoGen Assistant (#828)
Victor Dibia5547e3b91944
diff --git a/samples/apps/autogen-assistant/README.md b/samples/apps/autogen-assistant/README.mdindex 2e4a5ccc5..35d1f9932 100644--- a/samples/apps/autogen-assistant/README.md+++ b/samples/apps/autogen-assistant/README.md@@ -19,64 +19,57 @@ Project Structure:- _autogenra/_ code for the backend classes and web api (FastAPI)- _frontend/_ code for the webui, built with Gatsby and Tailwind-## Getting Started--AutoGen requires access to an LLM. Please see the [AutoGen docs](https://microsoft.github.io/autogen/docs/FAQ#set-your-api-endpoints) on how to configure access to your LLM provider. In this sample, We recommend setting up your `OPENAI_API_KEY` or `AZURE_OPENAI_API_KEY` environment variable and then specifying the exact model parameters to be used in the `llm_config` that is passed to each agent specification. See the `get_default_agent_config()` method in `utils.py` to see an example of setting up `llm_config`. The example below shows how to configure access to an Azure OPENAI LLM.--```python-llm_config = LLMConfig(- config_list=[{- "model": "gpt-4",- "api_key": "<azure_api_key>",- "api_base": "<azure api base>",- "api_type": "azure",- "api_version": "2023-06-01-preview"- }],- temperature=0,- )-```+### Installation-```bash-export OPENAI_API_KEY=<your_api_key>-```+1. **Install from PyPi**-### Install and Run+ We recommend using a virtual environment (e.g., conda) to avoid conflicts with existing Python packages. With Python 3.10 or newer active in your virtual environment, use pip to install AutoGen Assistant:-To install a prebuilt version of the app from PyPi. We highly recommend using a virtual environment (e.g. miniconda) and **python 3.10+** to avoid dependency conflicts.+ ```bash+ pip install autogenra+ ```-```bash-pip install autogenra-autogenra ui --port 8081 # run the web ui on port 8081-```+2. **Install from Source**-### Install from Source+ > Note: This approach requires some familiarity with building interfaces in React.-To install the app from source, clone the repository and install the dependencies.+ If you prefer to install from source, ensure you have Python 3.10+ and Node.js (version above 14.15.0) installed. Here's how you get started:-```bash-pip install -e .-```+ - Clone the AutoGen Assistant repository and install its Python dependencies:-You will also need to build the app front end. Note that your Gatsby requires node > 14.15.0 . You may need to [upgrade your node](https://stackoverflow.com/questions/10075990/upgrading-node-js-to-latest-version) version as needed.+ ```bash+ pip install -e .+ ```-```bash-npm install --global yarn-cd frontend-yarn install-yarn build-```+ - Navigate to the `samples/apps/autogen-assistant/frontend` directory, install dependencies, and build the UI:-The command above will build the frontend ui and copy the build artifacts to the `autogenra` web ui folder. Note that you may have to run `npm install --force --legacy-peer-deps` to force resolve some peer dependencies.+ ```bash+ npm install -g gatsby-cli+ npm install --global yarn+ cd frontend+ yarn install+ yarn build+ ```-Run the web ui:+ For Windows users, to build the frontend, you may need alternative commands to build the frontend.++ ```bash++ gatsby clean && rmdir /s /q ..\\autogenra\\web\\ui && (set \"PREFIX_PATH_VALUE=\" || ver>nul) && gatsby build --prefix-paths && xcopy /E /I /Y public ..\\autogenra\\web\\ui++ ````++### Running the Application++Once installed, run the web UI by entering the following in your terminal:```bash-autogenra ui --port 8081 # run the web ui on port 8081+autogenra ui --port 8081```-Navigate to <http://localhost:8081/> to view the web ui.+This will start the application on the specified port. Open your web browser and go to `http://localhost:8081/` to begin using AutoGen Assistant.-To update the web ui, navigate to the frontend directory, make changes and rebuild the ui.+Now that you have AutoGen Assistant installed and running, you are ready to explore its capabilities, including defining and modifying agent workflows, interacting with agents and sessions, and expanding agent skills.## Capabilities@@ -108,12 +101,18 @@ The agents responds by _writing and executing code_ to create a python program t## FAQ-- How do I add more skills to the research assistant? This can be done by adding a new file with documented functions to `autogenra/web/skills/global` directory.-- How do I specify the agent configuration (e.g. temperature, model, agent system message, model etc). You can do either from the UI interface or by modifying the default agent configuration in `utils.py` (`get_default_agent_config()` method)-- How do I reset the conversation? You can reset the conversation by deleting the `database.sqlite` file. You can also delete user files by deleting the `autogenra/web/files/user/<user_id_md5hash>` folder.-- How do I view messages generated by agents? You can view the messages generated by the agents in the debug console. You can also view the messages in the `database.sqlite` file.+**Q: How can I add more skills to the AutoGen Assistant?**+A: You can extend the capabilities of your agents by adding new Python functions. The AutoGen Assistant interface also lets you directly paste functions that can be reused in the agent workflow.++**Q: Where can I adjust the agent configurations and settings?**+A: You can modify agent configurations directly from the UI or by editing the default configurations in the `utils.py` file under the `get_default_agent_config()` method (assuming you are building your own UI).++**Q: If I want to reset the conversation with an agent, how do I go about it?**+A: To reset your conversation history, you can delete the `database.sqlite` file. If you need to clear user-specific data, remove the relevant `autogenra/web/files/user/<user_id_md5hash>` folder.++**Q: Is it possible to view the output and messages generated by the agents during interactions?**+A: Yes, you can view the generated messages in the debug console of the web UI, providing insights into the agent interactions. Alternatively, you can inspect the `database.sqlite` file for a comprehensive record of messages.## Acknowledgements-Based on the [AutoGen](https://microsoft.github.io/autogen) project.-Adapted in October 2023 from a research prototype (original credits: Gagan Bansal, Adam Fourney, Victor Dibia, Piali Choudhury, Saleema Amershi, Ahmed Awadallah, Chi Wang)+AutoGen assistant is Based on the [AutoGen](https://microsoft.github.io/autogen) project. It is adapted in October 2023 from a research prototype (original credits: Gagan Bansal, Adam Fourney, Victor Dibia, Piali Choudhury, Saleema Amershi, Ahmed Awadallah, Chi Wang)diff --git a/samples/apps/autogen-assistant/autogenra/__init__.py b/samples/apps/autogen-assistant/autogenra/__init__.pyindex e69de29bb..db6a9e38f 100644--- a/samples/apps/autogen-assistant/autogenra/__init__.py+++ b/samples/apps/autogen-assistant/autogenra/__init__.py@@ -0,0 +1,3 @@+from .autogenflow import *+from .autogenchat import *+from .datamodel import *diff --git a/samples/apps/autogen-assistant/autogenra/autogenchat.py b/samples/apps/autogen-assistant/autogenra/autogenchat.pyindex b39781b08..b13a0e684 100644--- a/samples/apps/autogen-assistant/autogenra/autogenchat.py+++ b/samples/apps/autogen-assistant/autogenra/autogenchat.py@@ -1,17 +1,17 @@import jsonimport timefrom typing import List-from .datamodel import FlowConfig, Message+from .datamodel import AgentWorkFlowConfig, Messagefrom .utils import extract_successful_code_blocks, get_default_agent_config, get_modified_files-from .autogenflow import AutoGenFlow+from .autogenflow import AutoGenWorkFlowManagerimport os-class ChatManager:+class AutoGenChatManager:def __init__(self) -> None:pass- def chat(self, message: Message, history: List, flow_config: FlowConfig = None, **kwargs) -> None:+ def chat(self, message: Message, history: List, flow_config: AgentWorkFlowConfig = None, **kwargs) -> None:work_dir = kwargs.get("work_dir", None)scratch_dir = os.path.join(work_dir, "scratch")skills_suffix = kwargs.get("skills_prompt", "")@@ -21,7 +21,9 @@ class ChatManager:flow_config = get_default_agent_config(scratch_dir, skills_suffix=skills_suffix)# print("Flow config: ", flow_config)- flow = AutoGenFlow(config=flow_config, history=history, work_dir=scratch_dir, asst_prompt=skills_suffix)+ flow = AutoGenWorkFlowManager(+ config=flow_config, history=history, work_dir=scratch_dir, assistant_prompt=skills_suffix+ )message_text = message.content.strip()output = ""@@ -36,11 +38,7 @@ class ChatManager:successful_code_blocks = extract_successful_code_blocks(agent_chat_messages)successful_code_blocks = "\n\n".join(successful_code_blocks)output = (- (- flow.sender.last_message()["content"]- + "\n The following code snippets were used: \n"- + successful_code_blocks- )+ (flow.sender.last_message()["content"] + "\n" + successful_code_blocks)if successful_code_blockselse flow.sender.last_message()["content"])@@ -51,7 +49,7 @@ class ChatManager:modified_files = get_modified_files(start_time, end_time, scratch_dir, dest_dir=work_dir)metadata["files"] = modified_files- print("Modified files: ", modified_files)+ print("Modified files: ", len(modified_files))output_message = Message(user_id=message.user_id,@@ -59,6 +57,7 @@ class ChatManager:role="assistant",content=output,metadata=json.dumps(metadata),+ session_id=message.session_id,)return output_messagediff --git a/samples/apps/autogen-assistant/autogenra/autogenflow.py b/samples/apps/autogen-assistant/autogenra/autogenflow.pyindex 731aab63a..df83ffd0f 100644--- a/samples/apps/autogen-assistant/autogenra/autogenflow.py+++ b/samples/apps/autogen-assistant/autogenra/autogenflow.py@@ -1,16 +1,20 @@from typing import List, Optionalfrom dataclasses import asdictimport autogen-from .datamodel import AgentFlowSpec, FlowConfig, Message+from .datamodel import AgentFlowSpec, AgentWorkFlowConfig, Message-class AutoGenFlow:+class AutoGenWorkFlowManager:"""- AutoGenFlow class to load agents from a provided configuration and run a chat between them+ AutoGenWorkFlowManager class to load agents from a provided configuration and run a chat between them"""def __init__(- self, config: FlowConfig, history: Optional[List[Message]] = None, work_dir: str = None, asst_prompt: str = None+ self,+ config: AgentWorkFlowConfig,+ history: Optional[List[Message]] = None,+ work_dir: str = None,+ assistant_prompt: str = None,) -> None:"""Initializes the AutoGenFlow with agents specified in the config and optional@@ -21,8 +25,8 @@ class AutoGenFlow:history: An optional list of previous messages to populate the agents' history."""- self.work_dir = work_dir- self.asst_prompt = asst_prompt+ self.work_dir = work_dir or "work_dir"+ self.assistant_prompt = assistant_prompt or ""self.sender = self.load(config.sender)self.receiver = self.load(config.receiver)@@ -87,13 +91,14 @@ class AutoGenFlow:code_execution_config = agent_spec.config.code_execution_config or {}code_execution_config["work_dir"] = self.work_diragent_spec.config.code_execution_config = code_execution_config+if agent_spec.type == "assistant":agent_spec.config.system_message = (autogen.AssistantAgent.DEFAULT_SYSTEM_MESSAGE+ "\n\n"+ agent_spec.config.system_message+ "\n\n"- + self.asst_prompt+ + self.assistant_prompt)return agent_specdiff --git a/samples/apps/autogen-assistant/autogenra/datamodel.py b/samples/apps/autogen-assistant/autogenra/datamodel.pyindex 7c9294569..43da52d97 100644--- a/samples/apps/autogen-assistant/autogenra/datamodel.py+++ b/samples/apps/autogen-assistant/autogenra/datamodel.py@@ -2,7 +2,7 @@ import uuidfrom datetime import datetimefrom typing import Any, Callable, Dict, List, Literal, Optional, Unionfrom pydantic.dataclasses import dataclass-from dataclasses import field+from dataclasses import asdict, field@dataclass@@ -17,6 +17,7 @@ class Message(object):ra: Optional[str] = Nonecode: Optional[str] = Nonemetadata: Optional[Any] = None+ session_id: Optional[str] = Nonedef __post_init__(self):if self.msg_id is None:@@ -25,18 +26,9 @@ class Message(object):self.timestamp = datetime.now()def dict(self):- return {- "user_id": self.user_id,- "role": self.role,- "content": self.content,- "root_msg_id": self.root_msg_id,- "msg_id": self.msg_id,- "timestamp": self.timestamp,- "personalize": self.personalize,- "ra": self.ra,- "code": self.code,- "metadata": self.metadata,- }+ result = asdict(self)+ result["timestamp"] = result["timestamp"].isoformat()+ return result# web api data models@@ -69,7 +61,7 @@ class AgentConfig:"""Data model for Agent Config for Autogen"""name: str- llm_config: Optional[LLMConfig] = None+ llm_config: Optional[Union[LLMConfig, bool]] = Falsehuman_input_mode: str = "NEVER"max_consecutive_auto_reply: int = 10system_message: Optional[str] = None@@ -86,7 +78,7 @@ class AgentFlowSpec:@dataclass-class FlowConfig:+class AgentWorkFlowConfig:"""Data model for Flow Config for Autogen"""name: str@@ -94,27 +86,78 @@ class FlowConfig:receiver: Union[AgentFlowSpec, List[AgentFlowSpec]]type: Literal["default", "groupchat"] = "default"+ def dict(self):+ return asdict(self)+++@dataclass+class Session(object):+ """Data model for AutoGen Chat Session"""++ user_id: str+ session_id: Optional[str] = None+ timestamp: Optional[datetime] = None+ flow_config: AgentWorkFlowConfig = None++ def __post_init__(self):+ if self.timestamp is None:+ self.timestamp = datetime.now()+ if self.session_id is None:+ self.session_id = str(uuid.uuid4())++ def dict(self):+ result = asdict(self)+ result["timestamp"] = self.timestamp.isoformat()+ return result+++@dataclass+class Gallery(object):+ """Data model for Gallery Item"""++ session: Session+ messages: List[Message]+ tags: List[str]+ id: Optional[str] = None+ timestamp: Optional[datetime] = None++ def __post_init__(self):+ if self.timestamp is None:+ self.timestamp = datetime.now()+ if self.id is None:+ self.id = str(uuid.uuid4())++ def dict(self):+ result = asdict(self)+ result["timestamp"] = self.timestamp.isoformat()+ return result+@dataclassclass ChatWebRequestModel(object):"""Data model for Chat Web Request for Web End"""message: Message- flow_config: FlowConfig+ flow_config: AgentWorkFlowConfig@dataclassclass DeleteMessageWebRequestModel(object):user_id: strmsg_id: str+ session_id: Optional[str] = None@dataclass-class ClearDBWebRequestModel(object):+class CreateSkillWebRequestModel(object):user_id: str+ skills: Union[str, List[str]]@dataclass-class CreateSkillWebRequestModel(object):+class DBWebRequestModel(object):user_id: str- skills: Union[str, List[str]]+ msg_id: Optional[str] = None+ session: Optional[Session] = None+ skills: Optional[Union[str, List[str]]] = None+ tags: Optional[List[str]] = Nonediff --git a/samples/apps/autogen-assistant/autogenra/db.py b/samples/apps/autogen-assistant/autogenra/db.pydeleted file mode 100644index 235cd789f..000000000--- a/samples/apps/autogen-assistant/autogenra/db.py+++ /dev/null@@ -1,114 +0,0 @@-import logging-import sqlite3-import threading-import os-from typing import Any, List, Dict, Tuple--lock = threading.Lock()-logger = logging.getLogger()---class DBManager:- """- A database manager class that handles the creation and interaction with an SQLite database.- """-- def __init__(self, path: str = "database.sqlite", **kwargs: Any) -> None:- """- Initializes the DBManager object, creates a database if it does not exist, and establishes a connection.-- Args:- path (str): The file path to the SQLite database file.- **kwargs: Additional keyword arguments to pass to the sqlite3.connect method.- """- self.path = path- # check if the database exists, if not create it- if not os.path.exists(self.path):- logger.info("Creating database")- self.init_db(path=self.path, **kwargs)-- try:- self.conn = sqlite3.connect(self.path, check_same_thread=False, **kwargs)- self.cursor = self.conn.cursor()- except Exception as e:- logger.error("Error connecting to database: %s", e)- raise e-- def init_db(self, path: str = "database.sqlite", **kwargs: Any) -> None:- """- Initializes the database by creating necessary tables.-- Args:- path (str): The file path to the SQLite database file.- **kwargs: Additional keyword arguments to pass to the sqlite3.connect method.- """- # Connect to the database (or create a new one if it doesn't exist)- self.conn = sqlite3.connect(path, check_same_thread=False, **kwargs)- self.cursor = self.conn.cursor()-- # Create the table with the specified columns, appropriate data types, and a UNIQUE constraint on (root_msg_id, msg_id)- self.cursor.execute(- """- CREATE TABLE IF NOT EXISTS messages (- user_id TEXT NOT NULL,- root_msg_id TEXT NOT NULL,- msg_id TEXT,- role TEXT NOT NULL,- content TEXT NOT NULL,- metadata TEXT,- timestamp DATETIME,- UNIQUE (user_id, root_msg_id, msg_id)- )- """- )-- # Create a table for personalization profiles- self.cursor.execute(- """- CREATE TABLE IF NOT EXISTS personalization_profiles (- user_id INTEGER NOT NULL,- profile TEXT,- timestamp DATETIME NOT NULL,- UNIQUE (user_id)- )- """- )-- # Commit the changes and close the connection- self.conn.commit()-- def query(self, query: str, args: Tuple = (), json: bool = False) -> List[Dict[str, Any]]:- """- Executes a given SQL query and returns the results.-- Args:- query (str): The SQL query to execute.- args (Tuple): The arguments to pass to the SQL query.- json (bool): If True, the results will be returned as a list of dictionaries.-- Returns:- List[Dict[str, Any]]: The result of the SQL query.- """- try:- with lock:- self.cursor.execute(query, args)- result = self.cursor.fetchall()- self.commit()- if json:- result = [dict(zip([key[0] for key in self.cursor.description], row)) for row in result]- return result- except Exception as e:- logger.error("Error running query with query %s and args %s: %s", query, args, e)- raise e-- def commit(self) -> None:- """- Commits the current transaction to the database.- """- self.conn.commit()-- def close(self) -> None:- """- Closes the database connection.- """- self.conn.close()diff --git a/samples/apps/autogen-assistant/autogenra/utils/__init__.py b/samples/apps/autogen-assistant/autogenra/utils/__init__.pynew file mode 100644index 000000000..f37b0b048--- /dev/null+++ b/samples/apps/autogen-assistant/autogenra/utils/__init__.py@@ -0,0 +1,2 @@+from .dbutils import *+from .utils import *diff --git a/samples/apps/autogen-assistant/autogenra/utils/dbutils.py b/samples/apps/autogen-assistant/autogenra/utils/dbutils.pynew file mode 100644index 000000000..7ed163da3--- /dev/null+++ b/samples/apps/autogen-assistant/autogenra/utils/dbutils.py@@ -0,0 +1,325 @@+import json+import logging+import sqlite3+import threading+import os+from typing import Any, List, Dict, Tuple+from ..datamodel import Gallery, Message, Session+++MESSAGES_TABLE_SQL = """+ CREATE TABLE IF NOT EXISTS messages (+ user_id TEXT NOT NULL,+ session_id TEXT,+ root_msg_id TEXT NOT NULL,+ msg_id TEXT,+ role TEXT NOT NULL,+ content TEXT NOT NULL,+ metadata TEXT,+ timestamp DATETIME,+ UNIQUE (user_id, root_msg_id, msg_id)+ )+ """++SESSIONS_TABLE_SQL = """+ CREATE TABLE IF NOT EXISTS sessions (+ session_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ timestamp DATETIME NOT NULL,+ flow_config TEXT,+ UNIQUE (user_id, session_id)+ )+ """++SKILLS_TABLE_SQL = """+ CREATE TABLE IF NOT EXISTS sessions (+ session_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ timestamp DATETIME NOT NULL,+ flow_config TEXT,+ UNIQUE (user_id, session_id)+ )+ """+GALLERY_TABLE_SQL = """+ CREATE TABLE IF NOT EXISTS gallery (+ gallery_id TEXT NOT NULL,+ session TEXT,+ messages TEXT,+ tags TEXT,+ timestamp DATETIME NOT NULL,+ UNIQUE ( gallery_id)+ )+ """+++lock = threading.Lock()+logger = logging.getLogger()+++class DBManager:+ """+ A database manager class that handles the creation and interaction with an SQLite database.+ """++ def __init__(self, path: str = "database.sqlite", **kwargs: Any) -> None:+ """+ Initializes the DBManager object, creates a database if it does not exist, and establishes a connection.++ Args:+ path (str): The file path to the SQLite database file.+ **kwargs: Additional keyword arguments to pass to the sqlite3.connect method.+ """+ self.path = path+ # check if the database exists, if not create it+ if not os.path.exists(self.path):+ logger.info("Creating database")+ self.init_db(path=self.path, **kwargs)++ try:+ self.conn = sqlite3.connect(self.path, check_same_thread=False, **kwargs)+ self.cursor = self.conn.cursor()+ except Exception as e:+ logger.error("Error connecting to database: %s", e)+ raise e++ def init_db(self, path: str = "database.sqlite", **kwargs: Any) -> None:+ """+ Initializes the database by creating necessary tables.++ Args:+ path (str): The file path to the SQLite database file.+ **kwargs: Additional keyword arguments to pass to the sqlite3.connect method.+ """+ # Connect to the database (or create a new one if it doesn't exist)+ self.conn = sqlite3.connect(path, check_same_thread=False, **kwargs)+ self.cursor = self.conn.cursor()++ # Create the table with the specified columns, appropriate data types, and a UNIQUE constraint on (root_msg_id, msg_id)+ self.cursor.execute(MESSAGES_TABLE_SQL)++ # Create a sessions table+ self.cursor.execute(SESSIONS_TABLE_SQL)++ # Create a skills+ self.cursor.execute(SKILLS_TABLE_SQL)++ # Create a gallery table+ self.cursor.execute(GALLERY_TABLE_SQL)++ # Commit the changes and close the connection+ self.conn.commit()++ def query(self, query: str, args: Tuple = (), return_json: bool = False) -> List[Dict[str, Any]]:+ """+ Executes a given SQL query and returns the results.++ Args:+ query (str): The SQL query to execute.+ args (Tuple): The arguments to pass to the SQL query.+ return_json (bool): If True, the results will be returned as a list of dictionaries.++ Returns:+ List[Dict[str, Any]]: The result of the SQL query.+ """+ try:+ with lock:+ self.cursor.execute(query, args)+ result = self.cursor.fetchall()+ self.commit()+ if return_json:+ result = [dict(zip([key[0] for key in self.cursor.description], row)) for row in result]+ return result+ except Exception as e:+ logger.error("Error running query with query %s and args %s: %s", query, args, e)+ raise e++ def commit(self) -> None:+ """+ Commits the current transaction to the database.+ """+ self.conn.commit()++ def close(self) -> None:+ """+ Closes the database connection.+ """+ self.conn.close()+++def save_message(message: Message, dbmanager: DBManager) -> None:+ """+ Save a message in the database using the provided database manager.++ :param message: The Message object containing message data+ :param dbmanager: The DBManager instance used to interact with the database+ """+ query = "INSERT INTO messages (user_id, root_msg_id, msg_id, role, content, metadata, timestamp, session_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"+ args = (+ message.user_id,+ message.root_msg_id,+ message.msg_id,+ message.role,+ message.content,+ message.metadata,+ message.timestamp,+ message.session_id,+ )+ dbmanager.query(query=query, args=args)+++def load_messages(user_id: str, session_id: str, dbmanager: DBManager) -> List[dict]:+ """+ Load messages for a specific user and session from the database, sorted by timestamp.++ :param user_id: The ID of the user whose messages are to be loaded+ :param session_id: The ID of the session whose messages are to be loaded+ :param dbmanager: The DBManager instance to interact with the database++ :return: A list of dictionaries, each representing a message+ """+ query = "SELECT * FROM messages WHERE user_id = ? AND session_id = ?"+ args = (user_id, session_id)+ result = dbmanager.query(query=query, args=args, return_json=True)+ # Sort by timestamp ascending+ result = sorted(result, key=lambda k: k["timestamp"], reverse=False)+ return result+++def get_sessions(user_id: str, dbmanager: DBManager) -> List[dict]:+ """+ Load sessions for a specific user from the database, sorted by timestamp.++ :param user_id: The ID of the user whose sessions are to be loaded+ :param dbmanager: The DBManager instance to interact with the database+ :return: A list of dictionaries, each representing a session+ """+ query = "SELECT * FROM sessions WHERE user_id = ?"+ args = (user_id,)+ result = dbmanager.query(query=query, args=args, return_json=True)+ # Sort by timestamp ascending+ result = sorted(result, key=lambda k: k["timestamp"], reverse=True)+ for row in result:+ row["flow_config"] = json.loads(row["flow_config"])+ return result+++def create_session(user_id: str, session: Session, dbmanager: DBManager) -> List[dict]:+ """+ Create a new session for a specific user in the database.++ :param user_id: The ID of the user whose session is to be created+ :param dbmanager: The DBManager instance to interact with the database+ :return: A list of dictionaries, each representing a session+ """++ query = "INSERT INTO sessions (user_id, session_id, timestamp, flow_config) VALUES (?, ?, ?,?)"+ args = (session.user_id, session.session_id, session.timestamp, json.dumps(session.flow_config.dict()))+ dbmanager.query(query=query, args=args)+ sessions = get_sessions(user_id=user_id, dbmanager=dbmanager)++ return sessions+++def publish_session(session: Session, dbmanager: DBManager, tags: List[str] = []) -> Gallery:+ """+ Publish a session to the gallery table in the database. Fetches the session messages first, then saves session and messages object to the gallery database table.+ :param session: The Session object containing session data+ :param dbmanager: The DBManager instance used to interact with the database+ :param tags: A list of tags to associate with the session+ :return: A gallery object containing the session and messages objects+ """++ messages = load_messages(user_id=session.user_id, session_id=session.session_id, dbmanager=dbmanager)+ gallery_item = Gallery(session=session, messages=messages, tags=tags)+ query = "INSERT INTO gallery (gallery_id, session, messages, tags, timestamp) VALUES (?, ?, ?, ?,?)"+ args = (+ gallery_item.id,+ json.dumps(gallery_item.session.dict()),+ json.dumps([message.dict() for message in gallery_item.messages]),+ json.dumps(gallery_item.tags),+ gallery_item.timestamp,+ )+ dbmanager.query(query=query, args=args)+ return gallery_item+++def get_gallery(gallery_id, dbmanager: DBManager) -> List[Gallery]:+ """+ Load gallery items from the database, sorted by timestamp. If gallery_id is provided, only the gallery item with the matching gallery_id will be returned.++ :param gallery_id: The ID of the gallery item to be loaded+ :param dbmanager: The DBManager instance to interact with the database+ :return: A list of Gallery objects+ """++ if gallery_id:+ query = "SELECT * FROM gallery WHERE gallery_id = ?"+ args = (gallery_id,)+ else:+ query = "SELECT * FROM gallery"+ args = ()+ result = dbmanager.query(query=query, args=args, return_json=True)+ # Sort by timestamp ascending+ result = sorted(result, key=lambda k: k["timestamp"], reverse=True)+ gallery = []+ for row in result:+ gallery_item = Gallery(+ id=row["gallery_id"],+ session=Session(**json.loads(row["session"])),+ messages=[Message(**message) for message in json.loads(row["messages"])],+ tags=json.loads(row["tags"]),+ timestamp=row["timestamp"],+ )+ gallery.append(gallery_item)+ return gallery+++def delete_user_sessions(user_id: str, session_id: str, dbmanager: DBManager, delete_all: bool = False) -> List[dict]:+ """+ Delete a specific session or all sessions for a user from the database.++ :param user_id: The ID of the user whose session is to be deleted+ :param session_id: The ID of the specific session to be deleted (ignored if delete_all is True)+ :param dbmanager: The DBManager instance to interact with the database+ :param delete_all: If True, all sessions for the user will be deleted+ :return: A list of the remaining sessions if not all were deleted, otherwise an empty list+ """+ if delete_all:+ query = "DELETE FROM sessions WHERE user_id = ?"+ args = (user_id,)+ dbmanager.query(query=query, args=args)+ return []+ else:+ query = "DELETE FROM sessions WHERE user_id = ? AND session_id = ?"+ args = (user_id, session_id)+ dbmanager.query(query=query, args=args)+ sessions = get_sessions(user_id=user_id, dbmanager=dbmanager)++ return sessions+++def delete_message(+ user_id: str, msg_id: str, session_id: str, dbmanager: DBManager, delete_all: bool = False+) -> List[dict]:+ """+ Delete a specific message or all messages for a user and session from the database.++ :param user_id: The ID of the user whose messages are to be deleted+ :param msg_id: The ID of the specific message to be deleted (ignored if delete_all is True)+ :param session_id: The ID of the session whose messages are to be deleted+ :param dbmanager: The DBManager instance to interact with the database+ :param delete_all: If True, all messages for the user will be deleted+ :return: A list of the remaining messages if not all were deleted, otherwise an empty list+ """++ if delete_all:+ query = "DELETE FROM messages WHERE user_id = ? AND session_id = ?"+ args = (user_id, session_id)+ dbmanager.query(query=query, args=args)+ return []+ else:+ query = "DELETE FROM messages WHERE user_id = ? AND msg_id = ? AND session_id = ?"+ args = (user_id, msg_id, session_id)+ dbmanager.query(query=query, args=args)+ messages = load_messages(user_id=user_id, session_id=session_id, dbmanager=dbmanager)+ return messagesdiff --git a/samples/apps/autogen-assistant/autogenra/utils.py b/samples/apps/autogen-assistant/autogenra/utils/utils.pysimilarity index 77%rename from samples/apps/autogen-assistant/autogenra/utils.pyrename to samples/apps/autogen-assistant/autogenra/utils/utils.pyindex a482e8069..6e47ac979 100644--- a/samples/apps/autogen-assistant/autogenra/utils.py+++ b/samples/apps/autogen-assistant/autogenra/utils/utils.py@@ -1,13 +1,12 @@import ast+import base64import hashlib-from typing import List, Dict, Union+from typing import List, Dict, Tuple, Unionimport osimport shutilimport re-import uuidimport autogen-from .datamodel import AgentConfig, AgentFlowSpec, FlowConfig, LLMConfig, Message-from .db import DBManager+from ..datamodel import AgentConfig, AgentFlowSpec, AgentWorkFlowConfig, LLMConfigdef md5_hash(text: str) -> str:@@ -20,67 +19,105 @@ def md5_hash(text: str) -> str:return hashlib.md5(text.encode()).hexdigest()-def save_message(message: Message, dbmanager: DBManager) -> None:+def get_file_type(file_path: str) -> str:"""- Save a message in the database using the provided database manager.- :param message: The Message object containing message data- :param dbmanager: The DBManager instance used to interact with the database- """- query = "INSERT INTO messages (user_id, root_msg_id, msg_id, role, content, metadata, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)"- args = (- message.user_id,- message.root_msg_id,- message.msg_id,- message.role,- message.content,- message.metadata,- message.timestamp,- )- dbmanager.query(query=query, args=args)+ Get file type determined by the file extension. If the file extension is not+ recognized, 'unknown' will be used as the file type.-def load_messages(user_id: str, dbmanager: DBManager) -> List[dict]:+ :param file_path: The path to the file to be serialized.+ :return: A string containing the file type."""- Load messages for a specific user from the database, sorted by timestamp.- :param user_id: The ID of the user whose messages are to be loaded- :param dbmanager: The DBManager instance to interact with the database- :return: A list of dictionaries, each representing a message- """- query = "SELECT * FROM messages WHERE user_id = ?"- args = (user_id,)- result = dbmanager.query(query=query, args=args, json=True)- # Sort by timestamp ascending- result = sorted(result, key=lambda k: k["timestamp"], reverse=False)- return result+ # Extended list of file extensions for code and text files+ CODE_EXTENSIONS = {+ ".py",+ ".js",+ ".jsx",+ ".java",+ ".c",+ ".cpp",+ ".cs",+ ".ts",+ ".tsx",+ ".html",+ ".css",+ ".scss",+ ".less",+ ".json",+ ".xml",+ ".yaml",+ ".yml",+ ".md",+ ".rst",+ ".tex",+ ".sh",+ ".bat",+ ".ps1",+ ".php",+ ".rb",+ ".go",+ ".swift",+ ".kt",+ ".hs",+ ".scala",+ ".lua",+ ".pl",+ ".sql",+ ".config",+ }++ # Supported image extensions+ IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".svg", ".webp"}++ # Supported PDF extension+ PDF_EXTENSION = ".pdf"++ # Determine the file extension+ _, file_extension = os.path.splitext(file_path)++ # Determine the file type based on the extension+ if file_extension in CODE_EXTENSIONS:+ file_type = "code"+ elif file_extension in IMAGE_EXTENSIONS:+ file_type = "image"+ elif file_extension == PDF_EXTENSION:+ file_type = "pdf"+ else:+ file_type = "unknown"++ return file_type-def delete_message(user_id: str, msg_id: str, dbmanager: DBManager, delete_all: bool = False) -> List[dict]:+def serialize_file(file_path: str) -> Tuple[str, str]:"""- Delete a specific message or all messages for a user from the database.+ Reads a file from a given file path, base64 encodes its content,+ and returns the base64 encoded string along with the file type.- :param user_id: The ID of the user whose messages are to be deleted- :param msg_id: The ID of the specific message to be deleted (ignored if delete_all is True)- :param dbmanager: The DBManager instance to interact with the database- :param delete_all: If True, all messages for the user will be deleted- :return: A list of the remaining messages if not all were deleted, otherwise an empty list+ The file type is determined by the file extension. If the file extension is not+ recognized, 'unknown' will be used as the file type.++ :param file_path: The path to the file to be serialized.+ :return: A tuple containing the base64 encoded string of the file and the file type."""- if delete_all:- query = "DELETE FROM messages WHERE user_id = ?"- args = (user_id,)- dbmanager.query(query=query, args=args)- return []- else:- query = "DELETE FROM messages WHERE user_id = ? AND msg_id = ?"- args = (user_id, msg_id)- dbmanager.query(query=query, args=args)- messages = load_messages(user_id=user_id, dbmanager=dbmanager)- return messages+ file_type = get_file_type(file_path)+ # Read the file and encode its contents+ try:+ with open(file_path, "rb") as file:+ file_content = file.read()+ base64_encoded_content = base64.b64encode(file_content).decode("utf-8")+ except Exception as e:+ raise IOError(f"An error occurred while reading the file: {e}")-def get_modified_files(start_timestamp: float, end_timestamp: float, source_dir: str, dest_dir: str) -> List[str]:+ return base64_encoded_content, file_type+++def get_modified_files(+ start_timestamp: float, end_timestamp: float, source_dir: str, dest_dir: str+) -> List[Dict[str, str]]:"""Copy files from source_dir that were modified within a specified timestamp rangeto dest_dir, renaming files if they already exist there. The function excludes@@ -91,7 +128,8 @@ def get_modified_files(start_timestamp: float, end_timestamp: float, source_dir::param source_dir: The directory to search for modified files.:param dest_dir: The destination directory to copy modified files to.- :return: A list of file paths in dest_dir that were modified and copied over.+ :return: A list of dictionaries with details of file paths in dest_dir that were modified and copied over.+ Dictionary format: {path: "", name: "", extension: ""}Files with extensions "__pycache__", "*.pyc", "__init__.py", and "*.cache"are ignored."""@@ -123,11 +161,20 @@ def get_modified_files(start_timestamp: float, end_timestamp: float, source_dir:# Copying the modified file to the destination directoryshutil.copy2(file_path, dest_file_path)- uid = dest_dir.split("/")[-1]- print("******", uid)- file_path = f"files/user/{uid}/{dest_file_path.split('/')[-1]}"- modified_files.append(file_path)+ # Extract user id from the dest_dir and file path+ uid = dest_dir.split("/")[-1]+ relative_file_path = os.path.relpath(dest_file_path, start=dest_dir)+ file_type = get_file_type(dest_file_path)+ file_dict = {+ "path": f"files/user/{uid}/{relative_file_path}",+ "name": file_name,+ "extension": file_ext.replace(".", ""),+ "type": file_type,+ }+ modified_files.append(file_dict)+ # sort by extension+ modified_files.sort(key=lambda x: x["extension"])return modified_files@@ -280,7 +327,7 @@ def delete_files_in_folder(folders: Union[str, List[str]]) -> None:print(f"Failed to delete {path}. Reason: {e}")-def get_default_agent_config(work_dir: str, skills_suffix: str = "") -> FlowConfig:+def get_default_agent_config(work_dir: str, skills_suffix: str = "") -> AgentWorkFlowConfig:"""Get a default agent flow config ."""@@ -318,7 +365,7 @@ def get_default_agent_config(work_dir: str, skills_suffix: str = "") -> FlowConf),)- flow_config = FlowConfig(+ flow_config = AgentWorkFlowConfig(name="default",sender=userproxy_spec,receiver=assistant_spec,diff --git a/samples/apps/autogen-assistant/autogenra/version.py b/samples/apps/autogen-assistant/autogenra/version.pyindex 76450728f..005ced7ab 100644--- a/samples/apps/autogen-assistant/autogenra/version.py+++ b/samples/apps/autogen-assistant/autogenra/version.py@@ -1,2 +1,2 @@-VERSION = "0.0.05a"+VERSION = "0.0.09a"APP_NAME = "autogenra"diff --git a/samples/apps/autogen-assistant/autogenra/web/app.py b/samples/apps/autogen-assistant/autogenra/web/app.pyindex 47617db09..13b0aa5d3 100644--- a/samples/apps/autogen-assistant/autogenra/web/app.py+++ b/samples/apps/autogen-assistant/autogenra/web/app.py@@ -5,18 +5,18 @@ from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFilesfrom fastapi import HTTPException-from ..db import DBManager++from ..datamodel import (ChatWebRequestModel,- ClearDBWebRequestModel,+ DBWebRequestModel,CreateSkillWebRequestModel,DeleteMessageWebRequestModel,Message,+ Session,)-from ..autogenchat import ChatManagerfrom ..utils import (create_skills_from_code,- delete_files_in_folder,get_all_skills,load_messages,md5_hash,@@ -24,8 +24,17 @@ from ..utils import (delete_message,init_webserver_folders,get_skills_prompt,+ get_sessions,+ create_session,+ delete_user_sessions,+ publish_session,+ get_gallery,+ DBManager,)+from ..autogenchat import AutoGenChatManager++app = FastAPI()@@ -57,13 +66,13 @@ api.mount("/files", StaticFiles(directory=folders["files_static_root"], html=Trudb_path = os.path.join(root_file_path, "database.sqlite")dbmanager = DBManager(path=db_path) # manage database operations-chatmanager = ChatManager() # manage calls to autogen+chatmanager = AutoGenChatManager() # manage calls to autogen@api.post("/messages")async def add_message(req: ChatWebRequestModel):message = Message(**req.message.dict())- user_history = load_messages(user_id=message.user_id, dbmanager=dbmanager)+ user_history = load_messages(user_id=message.user_id, session_id=req.message.session_id, dbmanager=dbmanager)# save incoming message to dbsave_message(message=message, dbmanager=dbmanager)@@ -104,16 +113,103 @@ async def add_message(req: ChatWebRequestModel):@api.get("/messages")-def get_messages(user_id: str = None):+def get_messages(user_id: str = None, session_id: str = None):if user_id is None:raise HTTPException(status_code=400, detail="user_id is required")- user_history = load_messages(user_id=user_id, dbmanager=dbmanager)+ try:+ user_history = load_messages(user_id=user_id, session_id=session_id, dbmanager=dbmanager)- return {- "status": True,- "data": user_history,- "message": "Messages retrieved successfully",- }+ return {+ "status": True,+ "data": user_history,+ "message": "Messages retrieved successfully",+ }+ except Exception as ex_error:+ print(ex_error)+ return {+ "status": False,+ "message": "Error occurred while retrieving messages: " + str(ex_error),+ }++[email protected]("/gallery")+def get_gallery_items(gallery_id: str = None):+ try:+ gallery = get_gallery(gallery_id=gallery_id, dbmanager=dbmanager)+ return {+ "status": True,+ "data": gallery,+ "message": "Gallery items retrieved successfully",+ }+ except Exception as ex_error:+ print(ex_error)+ return {+ "status": False,+ "message": "Error occurred while retrieving messages: " + str(ex_error),+ }++[email protected]("/sessions")+def get_user_sessions(user_id: str = None):+ """Return a list of all sessions for a user"""+ if user_id is None:+ raise HTTPException(status_code=400, detail="user_id is required")++ try:+ user_sessions = get_sessions(user_id=user_id, dbmanager=dbmanager)++ return {+ "status": True,+ "data": user_sessions,+ "message": "Sessions retrieved successfully",+ }+ except Exception as ex_error:+ print(ex_error)+ return {+ "status": False,+ "message": "Error occurred while retrieving sessions: " + str(ex_error),+ }++[email protected]("/sessions")+async def create_user_session(req: DBWebRequestModel):+ """Create a new session for a user"""+ # print(req.session, "**********" )++ try:+ session = Session(user_id=req.session.user_id, flow_config=req.session.flow_config)+ user_sessions = create_session(user_id=req.user_id, session=session, dbmanager=dbmanager)+ return {+ "status": True,+ "message": "Session created successfully",+ "data": user_sessions,+ }+ except Exception as ex_error:+ print(ex_error)+ return {+ "status": False,+ "message": "Error occurred while creating session: " + str(ex_error),+ }++[email protected]("/sessions/publish")+async def publish_user_session_to_gallery(req: DBWebRequestModel):+ """Create a new session for a user"""+ print(req.session, "**********")++ try:+ gallery_item = publish_session(req.session, tags=req.tags, dbmanager=dbmanager)+ return {+ "status": True,+ "message": "Session successfully published",+ "data": gallery_item,+ }+ except Exception as ex_error:+ print(traceback.format_exc())+ return {+ "status": False,+ "message": "Error occurred while publishing session: " + str(ex_error),+ }@api.post("/messages/delete")@@ -121,7 +217,9 @@ async def remove_message(req: DeleteMessageWebRequestModel):"""Delete a message from the database"""try:- messages = delete_message(user_id=req.user_id, msg_id=req.msg_id, dbmanager=dbmanager)+ messages = delete_message(+ user_id=req.user_id, msg_id=req.msg_id, session_id=req.session_id, dbmanager=dbmanager+ )return {"status": True,"message": "Message deleted successfully",@@ -136,18 +234,24 @@ async def remove_message(req: DeleteMessageWebRequestModel):@api.post("/cleardb")-async def clear_db(req: ClearDBWebRequestModel):+async def clear_db(req: DBWebRequestModel):"""Clear user conversation history database and files"""- user_files_dir = os.path.join(folders["files_static_root"], "user", md5_hash(req.user_id))+ # user_files_dir = os.path.join(folders["files_static_root"], "user", md5_hash(req.user_id))# user_skills_dir = os.path.join(folders["user_skills_dir"], md5_hash(req.user_id))- delete_files_in_folder([user_files_dir])+ # delete_files_in_folder([user_files_dir])try:- delete_message(user_id=req.user_id, msg_id=None, dbmanager=dbmanager, delete_all=True)+ delete_message(+ user_id=req.user_id, msg_id=None, session_id=req.session.session_id, dbmanager=dbmanager, delete_all=True+ )+ sessions = delete_user_sessions(user_id=req.user_id, session_id=req.session.session_id, dbmanager=dbmanager)return {"status": True,+ "data": {+ "sessions": sessions,+ },"message": "Messages and files cleared successfully",}except Exception as ex_error:@@ -165,7 +269,7 @@ def get_skills(user_id: str):return {"status": True,"message": "Skills retrieved successfully",- "skills": skills,+ "data": skills,}@@ -193,7 +297,7 @@ def create_user_skills(req: CreateSkillWebRequestModel):return {"status": True,"message": "Skills retrieved successfully",- "skills": skills,+ "data": skills,}except Exception as ex_error:diff --git a/samples/apps/autogen-assistant/autogenra/web/skills/global/generate_images.py b/samples/apps/autogen-assistant/autogenra/web/skills/global/generate_images.pynew file mode 100644index 000000000..7090730be--- /dev/null+++ b/samples/apps/autogen-assistant/autogenra/web/skills/global/generate_images.py@@ -0,0 +1,51 @@+# filename: generate_images.py++from typing import List+import uuid+import requests # to perform HTTP requests+from pathlib import Path++from openai import OpenAI+++def generate_and_save_images(query: str, image_size: str = "1024x1024") -> List[str]:+ """+ Function to paint, draw or illustrate images based on the users query or request. Generates images from a given query using OpenAI's DALL-E model and saves them to disk. Use the code below anytime there is a request to create an image.++ :param query: A natural language description of the image to be generated.+ :param image_size: The size of the image to be generated. (default is "1024x1024")+ :return: A list of filenames for the saved images.+ """++ client = OpenAI() # Initialize the OpenAI client+ response = client.images.generate(model="dall-e-3", prompt=query, n=1, size=image_size) # Generate images++ # List to store the file names of saved images+ saved_files = []++ # Check if the response is successful+ if response.data:+ for image_data in response.data:+ # Generate a random UUID as the file name+ file_name = str(uuid.uuid4()) + ".png" # Assuming the image is a PNG+ file_path = Path(file_name)++ img_url = image_data.url+ img_response = requests.get(img_url)+ if img_response.status_code == 200:+ # Write the binary content to a file+ with open(file_path, "wb") as img_file:+ img_file.write(img_response.content)+ print(f"Image saved to {file_path}")+ saved_files.append(str(file_path))+ else:+ print(f"Failed to download the image from {img_url}")+ else:+ print("No image data found in the response!")++ # Return the list of saved files+ return saved_files+++# Example usage of the function:+# generate_and_save_images("A cute baby sea otter")diff --git a/samples/apps/autogen-assistant/docs/ara_stockprices.png b/samples/apps/autogen-assistant/docs/ara_stockprices.pngindex bfafe3b5b..6bd17465e 100644Binary files a/samples/apps/autogen-assistant/docs/ara_stockprices.png and b/samples/apps/autogen-assistant/docs/ara_stockprices.png differdiff --git a/samples/apps/autogen-assistant/frontend/gatsby-config.ts b/samples/apps/autogen-assistant/frontend/gatsby-config.tsindex d65fbab4f..e36580dca 100644--- a/samples/apps/autogen-assistant/frontend/gatsby-config.ts+++ b/samples/apps/autogen-assistant/frontend/gatsby-config.ts@@ -8,7 +8,7 @@ const config: GatsbyConfig = {pathPrefix: `${process.env.PREFIX_PATH_VALUE}`,siteMetadata: {title: `AutoGen Assistant`,- description: `Build LLM Enabled Agents`,+ description: `Build Multi-Agent Apps`,siteUrl: `http://tbd.place`,},flags: {diff --git a/samples/apps/autogen-assistant/frontend/package.json b/samples/apps/autogen-assistant/frontend/package.jsonindex 877e16b76..3dd768a54 100644--- a/samples/apps/autogen-assistant/frontend/package.json+++ b/samples/apps/autogen-assistant/frontend/package.json@@ -45,7 +45,7 @@"react-dom": "^18.2.0","react-inner-image-zoom": "^3.0.2","react-markdown": "^8.0.7",- "react-resizable": "^3.0.4",+ "react-resizable": "^3.0.5","react-router-dom": "^6.3.0","react-syntax-highlighter": "^15.5.0","remark-gfm": "^3.0.1",diff --git a/samples/apps/autogen-assistant/frontend/src/components/atoms.tsx b/samples/apps/autogen-assistant/frontend/src/components/atoms.tsxindex 08731ca9b..3d18ed3ae 100644--- a/samples/apps/autogen-assistant/frontend/src/components/atoms.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/atoms.tsx@@ -5,6 +5,8 @@ import {XMarkIcon,ClipboardIcon,PlusIcon,+ ArrowPathIcon,+ ArrowDownRightIcon,} from "@heroicons/react/24/outline";import React, { ReactNode, useRef, useState } from "react";import Icon from "./icons";@@ -15,6 +17,7 @@ import { atomDark } from "react-syntax-highlighter/dist/esm/styles/prism";import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";import { truncateText } from "./utils";import { IModelConfig } from "./types";+import { ResizableBox } from "react-resizable";interface CodeProps {node?: any;@@ -36,6 +39,7 @@ interface IProps {open?: boolean;hoverable?: boolean;onClick?: () => void;+ loading?: boolean;}export const SectionHeader = ({@@ -136,6 +140,7 @@ export const Card = ({</div>)}<div>{subtitle}</div>+ {children}</div></div>);@@ -274,33 +279,89 @@ export const GroupView = ({ children, title, className = "" }: any) => {);};-export const ExpandView = ({ children, className = "" }: any) => {+export const ExpandView = ({+ children,+ icon = null,+ className = "",+ title = "Detail View",+}: any) => {const [isOpen, setIsOpen] = React.useState(false);+ let windowAspect = 1;+ if (typeof window !== "undefined") {+ windowAspect = window.innerWidth / window.innerHeight;+ }+ const minImageWidth = 400;return (- <div className={` rounded mb-6 border-secondary ${className}`}>+ <div+ style={{+ minHeight: "100px",+ }}+ className={`h-full rounded mb-6 border-secondary ${className}`}+ ><divrole="button"onClick={() => {setIsOpen(true);}}- className="text-xs mb-2 break-words"+ className="text-xs mb-2 h-full w-full break-words">- {children}+ {icon ? icon : children}</div>{isOpen && (<Modal+ title={title}width={800}open={isOpen}onCancel={() => setIsOpen(false)}footer={null}>+ {/* <ResizableBox+ // handle={<span className="text-accent">resize</span>}+ lockAspectRatio={false}+ handle={+ <div className="absolute right-0 bottom-0 cursor-se-resize font-semibold boprder p-3 bg-secondary">+ <ArrowDownRightIcon className="h-4 w-4 inline-block" />+ </div>+ }+ width={800}+ height={minImageWidth * windowAspect}+ minConstraints={[minImageWidth, minImageWidth * windowAspect]}+ maxConstraints={[900, 900 * windowAspect]}+ className="overflow-auto w-full rounded select-none "+ > */}{children}+ {/* </ResizableBox> */}</Modal>)}</div>);};+export const LoadingOverlay = ({ children, loading }: IProps) => {+ return (+ <>+ {loading && (+ <>+ <div+ className="absolute inset-0 bg-secondary flex"+ style={{ opacity: 0.5 }}+ >+ {/* Overlay background */}+ </div>+ <div+ className="absolute inset-0 flex items-center justify-center"+ style={{ pointerEvents: "none" }}+ >+ {/* Center BounceLoader without inheriting the opacity */}+ <BounceLoader />+ </div>+ </>+ )}+ <div className="relative">{children}</div>+ </>+ );+};+export const MarkdownView = ({data,className = "",@@ -327,6 +388,7 @@ export const MarkdownView = ({onClick={() => {setCodeVisible(!codeVisible);}}+ className=" flex-1 mr-4 ">{!codeVisible && (<div className=" text-white hover:text-accent duration-300">@@ -343,7 +405,7 @@ export const MarkdownView = ({</div>)}</div>- <div className="flex-1"></div>+ {/* <div className="flex-1"></div> */}<div>{showCopied && (<div className="inline-block text-sm text-white">@@ -672,3 +734,110 @@ export const ModelSelector = ({</div>);};++export const BounceLoader = ({+ className,+ title = "",+}: {+ className?: string;+ title?: string;+}) => {+ return (+ <div>+ <div className="inline-flex gap-2">+ <span className=" rounded-full bg-accent h-2 w-2 inline-block"></span>+ <span className="animate-bounce rounded-full bg-accent h-3 w-3 inline-block"></span>+ <span className=" rounded-full bg-accent h-2 w-2 inline-block"></span>+ </div>+ <span className=" text-sm">{title}</span>+ </div>+ );+};++export const ImageLoader = ({+ src,+ className = "",+}: {+ src: string;+ className?: string;+}) => {+ const [isLoading, setIsLoading] = useState(true);++ return (+ <div className="w-full rounded relative">+ {isLoading && (+ <div className="absolute h-24 inset-0 flex items-center justify-center">+ <BounceLoader title=" loading .." />{" "}+ </div>+ )}+ <img+ alt="Dynamic content"+ src={src}+ className={`w-full rounded ${+ isLoading ? "opacity-0" : "opacity-100"+ } ${className}`}+ onLoad={() => setIsLoading(false)}+ />+ </div>+ );+};++export const CodeLoader = ({+ url,+ className,+}: {+ url: string;+ className?: string;+}) => {+ const [isLoading, setIsLoading] = useState(true);+ const [code, setCode] = useState<string | null>(null);++ React.useEffect(() => {+ fetch(url)+ .then((response) => response.text())+ .then((data) => {+ setCode(data);+ setIsLoading(false);+ });+ }, [url]);++ return (+ <div className={`w-full rounded relative ${className}`}>+ {isLoading && (+ <div className="absolute h-24 inset-0 flex items-center justify-center">+ <BounceLoader />+ </div>+ )}++ {!isLoading && <CodeBlock code={code || ""} language={"python"} />}+ </div>+ );+};++export const PdfViewer = ({ url }: { url: string }) => {+ const [loading, setLoading] = useState<boolean>(true);++ React.useEffect(() => {+ // Assuming the URL is directly usable as the source for the <object> tag+ setLoading(false);+ // Note: No need to handle the creation and cleanup of a blob URL or converting file content as it's not provided anymore.+ }, [url]);++ // Render the PDF viewer+ return (+ <div className="h-full">+ {loading && <p>Loading PDF...</p>}+ {!loading && (+ <object+ className="w-full rounded"+ data={url}+ type="application/pdf"+ width="100%"+ height="450px"+ >+ <p>PDF cannot be displayed.</p>+ </object>+ )}+ </div>+ );+};diff --git a/samples/apps/autogen-assistant/frontend/src/components/header.tsx b/samples/apps/autogen-assistant/frontend/src/components/header.tsxindex 6ed91ef87..67ac6e9b4 100644--- a/samples/apps/autogen-assistant/frontend/src/components/header.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/header.tsx@@ -23,7 +23,8 @@ const Header = ({ meta, link }: any) => {const user_id = user ? user.username : "unknown";const links: any[] = [- // { name: "Gallery", href: "/" },+ { name: "Home", href: "/" },+ { name: "Gallery", href: "/gallery" },// { name: "Data Explorer", href: "/explorer" },];diff --git a/samples/apps/autogen-assistant/frontend/src/components/icons.tsx b/samples/apps/autogen-assistant/frontend/src/components/icons.tsxindex 24b110d80..5d7fceab7 100644--- a/samples/apps/autogen-assistant/frontend/src/components/icons.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/icons.tsx@@ -26,6 +26,110 @@ const Icon = ({ icon = "app", size = 4, className = "" }: Props) => {);}+ if (icon === "python") {+ return (+ <svg+ className={` ${sizeClass} inline-block `}+ aria-hidden="true"+ fill="currentColor"+ viewBox="0 0 50 63"+ >+ <path+ d="M42.6967 62.1044H13.464C11.5281 62.1021 9.67207 61.3321 8.30315 59.9632C6.93422 58.5942 6.16417 56.7382 6.16193 54.8023V45.2659C6.16193 44.9442 6.28972 44.6357 6.5172 44.4082C6.74467 44.1807 7.0532 44.0529 7.3749 44.0529C7.6966 44.0529 8.00513 44.1807 8.2326 44.4082C8.46008 44.6357 8.58787 44.9442 8.58787 45.2659V54.8023C8.58948 56.095 9.10373 57.3344 10.0178 58.2485C10.9319 59.1626 12.1713 59.6768 13.464 59.6784H42.6967C43.9896 59.6768 45.229 59.1626 46.1433 58.2485C47.0576 57.3345 47.5721 56.0951 47.5741 54.8023V43.8746C47.5741 43.5529 47.7019 43.2444 47.9293 43.0169C48.1568 42.7894 48.4653 42.6616 48.787 42.6616C49.1087 42.6616 49.4173 42.7894 49.6447 43.0169C49.8722 43.2444 50 43.5529 50 43.8746V54.8023C49.9975 56.7383 49.2271 58.5944 47.858 59.9632C46.4889 61.3321 44.6328 62.1021 42.6967 62.1044Z"+ fill="currentColor"+ />+ <path+ d="M48.7822 41.6183C48.4605 41.6183 48.152 41.4906 47.9245 41.2631C47.697 41.0356 47.5692 40.7271 47.5692 40.4054V12.5967C47.5681 12.2529 47.4946 11.9131 47.3533 11.5995C47.212 11.286 47.0062 11.0058 46.7492 10.7773L38.0522 3.04699C37.6064 2.64832 37.0297 2.42731 36.4317 2.42595H14.677C13.0616 2.42852 11.5131 3.07163 10.3712 4.21425C9.22922 5.35686 8.58704 6.90572 8.58543 8.52114V23.3037C8.58543 23.6254 8.45764 23.9339 8.23016 24.1614C8.00268 24.3888 7.69416 24.5166 7.37246 24.5166C7.05076 24.5166 6.74223 24.3888 6.51476 24.1614C6.28728 23.9339 6.15948 23.6254 6.15948 23.3037V8.52114C6.16173 6.26251 7.05971 4.09698 8.65646 2.49955C10.2532 0.902118 12.4184 0.0032109 14.677 9.10874e-08H36.4317C37.6233 -0.000230408 38.7736 0.437008 39.6643 1.22874L48.3613 8.96024C48.8752 9.41695 49.2866 9.97738 49.5682 10.6046C49.8498 11.2318 49.9953 11.9116 49.9952 12.5992V40.4054C49.9952 40.7271 49.8674 41.0356 49.6399 41.2631C49.4124 41.4906 49.1039 41.6183 48.7822 41.6183Z"+ fill="currentColor"+ />+ <path+ d="M48.7203 13.1681H41.474C40.1838 13.1665 38.947 12.6533 38.0347 11.741C37.1224 10.8287 36.6091 9.59184 36.6075 8.30167V1.49325C36.6075 1.17155 36.7353 0.863022 36.9628 0.635545C37.1903 0.408069 37.4988 0.280273 37.8205 0.280273C38.1422 0.280273 38.4507 0.408069 38.6782 0.635545C38.9057 0.863022 39.0335 1.17155 39.0335 1.49325V8.30167C39.0341 8.94874 39.2915 9.56911 39.749 10.0267C40.2066 10.4842 40.8269 10.7415 41.474 10.7422H48.7203C49.042 10.7422 49.3505 10.87 49.578 11.0974C49.8055 11.3249 49.9333 11.6334 49.9333 11.9551C49.9333 12.2768 49.8055 12.5854 49.578 12.8129C49.3505 13.0403 49.042 13.1681 48.7203 13.1681Z"+ fill="currentColor"+ />+ <path+ d="M17.1575 40.3774C16.8358 40.3774 16.5273 40.2496 16.2998 40.0222C16.0723 39.7947 15.9445 39.4862 15.9445 39.1644V29.4036C15.9445 29.0819 16.0723 28.7734 16.2998 28.5459C16.5273 28.3185 16.8358 28.1907 17.1575 28.1907C17.4792 28.1907 17.7877 28.3185 18.0152 28.5459C18.2427 28.7734 18.3705 29.0819 18.3705 29.4036V39.1644C18.3705 39.4862 18.2427 39.7947 18.0152 40.0222C17.7877 40.2496 17.4792 40.3774 17.1575 40.3774Z"+ fill="currentColor"+ />+ <path+ d="M17.1757 36.1381C16.8552 36.1381 16.5478 36.0113 16.3205 35.7854C16.0933 35.5595 15.9646 35.2528 15.9627 34.9324C15.9627 34.913 15.9506 32.9201 15.9506 32.1583C15.9506 31.53 15.9445 29.4073 15.9445 29.4073C15.9445 29.0856 16.0723 28.7771 16.2998 28.5496C16.5273 28.3221 16.8358 28.1943 17.1575 28.1943H19.8746C22.0919 28.1943 23.8968 29.9738 23.8968 32.162C23.8968 34.3502 22.0919 36.1296 19.8746 36.1296C19.1334 36.1296 17.206 36.1417 17.183 36.1417L17.1757 36.1381ZM18.3741 30.6166C18.3741 31.2086 18.3741 31.8551 18.3741 32.1583C18.3741 32.5125 18.3741 33.1384 18.3802 33.7049H19.8721C20.7418 33.7 21.4696 32.9929 21.4696 32.1583C21.4696 31.3238 20.7418 30.6166 19.8733 30.6166H18.3741Z"+ fill="currentColor"+ />+ <path+ d="M29.73 35.3921C29.5283 35.3923 29.3296 35.3421 29.1522 35.2462C28.9747 35.1502 28.8239 35.0115 28.7135 34.8426L25.5938 30.0672C25.4235 29.7979 25.366 29.4725 25.4336 29.1612C25.5013 28.8499 25.6887 28.5777 25.9554 28.4034C26.222 28.2291 26.5466 28.1668 26.8588 28.2298C27.1711 28.2928 27.4461 28.4761 27.6243 28.7402L29.7252 31.9582L31.803 28.7668C31.8899 28.633 32.0023 28.5175 32.1338 28.4271C32.2653 28.3366 32.4134 28.273 32.5695 28.2398C32.7256 28.2065 32.8867 28.2044 33.0437 28.2334C33.2006 28.2625 33.3503 28.3221 33.4842 28.409C33.6181 28.4959 33.7335 28.6083 33.824 28.7398C33.9144 28.8714 33.978 29.0194 34.0113 29.1755C34.0445 29.3316 34.0467 29.4927 34.0176 29.6497C33.9886 29.8066 33.9289 29.9563 33.842 30.0902L30.7501 34.8402C30.64 35.0096 30.4894 35.1487 30.3119 35.2451C30.1344 35.3415 29.9356 35.392 29.7337 35.3921H29.73Z"+ fill="currentColor"+ />+ <path+ d="M29.7179 40.3776C29.3962 40.3776 29.0876 40.2498 28.8602 40.0223C28.6327 39.7948 28.5049 39.4863 28.5049 39.1646L28.5182 34.1781C28.5182 33.8564 28.646 33.5478 28.8735 33.3204C29.101 33.0929 29.4095 32.9651 29.7312 32.9651C30.0529 32.9651 30.3614 33.0929 30.5889 33.3204C30.8164 33.5478 30.9442 33.8564 30.9442 34.1781L30.9308 39.1682C30.9299 39.4893 30.8016 39.7969 30.5743 40.0236C30.3469 40.2503 30.0389 40.3776 29.7179 40.3776Z"+ fill="currentColor"+ />+ <path+ d="M6.10975 52.2791H4.24541C3.11946 52.2791 2.03962 51.8319 1.24345 51.0357C0.447283 50.2395 0 49.1597 0 48.0337C0 46.9078 0.447283 45.8279 1.24345 45.0318C2.03962 44.2356 3.11946 43.7883 4.24541 43.7883H9.75474C10.0764 43.7883 10.385 43.9161 10.6124 44.1436C10.8399 44.3711 10.9677 44.6796 10.9677 45.0013C10.9677 45.323 10.8399 45.6315 10.6124 45.859C10.385 46.0865 10.0764 46.2143 9.75474 46.2143H4.24541C3.76286 46.2143 3.30007 46.406 2.95886 46.7472C2.61764 47.0884 2.42595 47.5512 2.42595 48.0337C2.42595 48.5163 2.61764 48.9791 2.95886 49.3203C3.30007 49.6615 3.76286 49.8532 4.24541 49.8532H6.11339C6.43509 49.8532 6.74361 49.981 6.97109 50.2085C7.19857 50.4359 7.32636 50.7445 7.32636 51.0662C7.32636 51.3879 7.19857 51.6964 6.97109 51.9239C6.74361 52.1514 6.43509 52.2791 6.11339 52.2791H6.10975Z"+ fill="currentColor"+ />+ <path+ d="M1.22872 48.8975C0.90702 48.8975 0.598496 48.7697 0.371019 48.5423C0.143542 48.3148 0.0157471 48.0063 0.0157471 47.6846L0.067905 26.3362C0.069833 25.2115 0.517967 24.1336 1.31393 23.339C2.10989 22.5444 3.18862 22.0981 4.31331 22.0981L48.7846 22.0896C49.1063 22.0896 49.4148 22.2174 49.6423 22.4449C49.8698 22.6723 49.9976 22.9809 49.9976 23.3026V45.0015C49.9976 45.3232 49.8698 45.6317 49.6423 45.8592C49.4148 46.0866 49.1063 46.2144 48.7846 46.2144H5.52386C5.20216 46.2144 4.89364 46.0866 4.66616 45.8592C4.43868 45.6317 4.31089 45.3232 4.31089 45.0015C4.31089 44.6798 4.43868 44.3712 4.66616 44.1438C4.89364 43.9163 5.20216 43.7885 5.52386 43.7885H47.5692V24.5083L4.30967 24.5168C3.82712 24.5168 3.36434 24.7085 3.02312 25.0497C2.68191 25.3909 2.49021 25.8537 2.49021 26.3362L2.43806 47.6846C2.43806 48.0056 2.31076 48.3136 2.08407 48.541C1.85738 48.7684 1.54979 48.8966 1.22872 48.8975Z"+ fill="currentColor"+ />+ </svg>+ );+ }++ if (icon === "pdf") {+ return (+ <svg+ className={` ${sizeClass} inline-block `}+ aria-hidden="true"+ fill="currentColor"+ viewBox="0 0 50 63"+ >+ <path+ d="M42.6966 62.1044H13.464C11.528 62.1021 9.67201 61.3321 8.30308 59.9632C6.93416 58.5942 6.16411 56.7382 6.16187 54.8023V45.2659C6.16187 44.9442 6.28966 44.6357 6.51714 44.4082C6.74461 44.1807 7.05314 44.0529 7.37484 44.0529C7.69654 44.0529 8.00507 44.1807 8.23254 44.4082C8.46002 44.6357 8.58781 44.9442 8.58781 45.2659V54.8023C8.58942 56.095 9.10367 57.3344 10.0178 58.2485C10.9319 59.1626 12.1712 59.6768 13.464 59.6784H42.6966C43.9895 59.6768 45.229 59.1626 46.1433 58.2485C47.0576 57.3345 47.5721 56.0951 47.574 54.8023V43.8746C47.574 43.5529 47.7018 43.2444 47.9293 43.0169C48.1568 42.7894 48.4653 42.6616 48.787 42.6616C49.1087 42.6616 49.4172 42.7894 49.6447 43.0169C49.8722 43.2444 50 43.5529 50 43.8746V54.8023C49.9974 56.7383 49.2271 58.5944 47.858 59.9632C46.4888 61.3321 44.6327 62.1021 42.6966 62.1044Z"+ fill="currentColor"+ />+ <path+ d="M48.7821 41.6183C48.4604 41.6183 48.1519 41.4906 47.9244 41.2631C47.6969 41.0356 47.5691 40.7271 47.5691 40.4054V12.5967C47.5681 12.2529 47.4945 11.9131 47.3532 11.5995C47.2119 11.286 47.0061 11.0058 46.7492 10.7773L38.0521 3.04699C37.6064 2.64832 37.0297 2.42731 36.4316 2.42595H14.6769C13.0615 2.42852 11.513 3.07163 10.3711 4.21425C9.22916 5.35686 8.58698 6.90572 8.58537 8.52114V23.3037C8.58537 23.6254 8.45758 23.9339 8.2301 24.1614C8.00262 24.3888 7.6941 24.5166 7.3724 24.5166C7.0507 24.5166 6.74217 24.3888 6.5147 24.1614C6.28722 23.9339 6.15942 23.6254 6.15942 23.3037V8.52114C6.16167 6.26251 7.05965 4.09698 8.6564 2.49955C10.2532 0.902118 12.4183 0.0032109 14.6769 9.10874e-08H36.4316C37.6233 -0.000230408 38.7736 0.437008 39.6642 1.22874L48.3612 8.96024C48.8752 9.41695 49.2865 9.97738 49.5681 10.6046C49.8497 11.2318 49.9953 11.9116 49.9951 12.5992V40.4054C49.9951 40.7271 49.8673 41.0356 49.6398 41.2631C49.4123 41.4906 49.1038 41.6183 48.7821 41.6183Z"+ fill="currentColor"+ />+ <path+ d="M48.7203 13.1681H41.474C40.1838 13.1665 38.947 12.6533 38.0347 11.741C37.1224 10.8287 36.6091 9.59184 36.6075 8.30167V1.49325C36.6075 1.17155 36.7353 0.863022 36.9628 0.635545C37.1903 0.408069 37.4988 0.280273 37.8205 0.280273C38.1422 0.280273 38.4507 0.408069 38.6782 0.635545C38.9057 0.863022 39.0335 1.17155 39.0335 1.49325V8.30167C39.0341 8.94874 39.2915 9.56911 39.749 10.0267C40.2066 10.4842 40.8269 10.7415 41.474 10.7422H48.7203C49.042 10.7422 49.3505 10.87 49.578 11.0974C49.8055 11.3249 49.9333 11.6334 49.9333 11.9551C49.9333 12.2768 49.8055 12.5854 49.578 12.8129C49.3505 13.0403 49.042 13.1681 48.7203 13.1681Z"+ fill="currentColor"+ />+ <path+ d="M34.2362 40.3774C33.9145 40.3774 33.6059 40.2496 33.3785 40.0222C33.151 39.7947 33.0232 39.4862 33.0232 39.1644V29.4036C33.0232 29.0819 33.151 28.7734 33.3785 28.5459C33.6059 28.3185 33.9145 28.1907 34.2362 28.1907H38.1929C38.5146 28.1907 38.8231 28.3185 39.0506 28.5459C39.2781 28.7734 39.4059 29.0819 39.4059 29.4036C39.4059 29.7253 39.2781 30.0339 39.0506 30.2613C38.8231 30.4888 38.5146 30.6166 38.1929 30.6166H35.4491V39.1644C35.4491 39.4862 35.3213 39.7947 35.0939 40.0222C34.8664 40.2496 34.5579 40.3774 34.2362 40.3774Z"+ fill="currentColor"+ />+ <path+ d="M37.8788 35.4042H34.2398C33.9181 35.4042 33.6096 35.2764 33.3821 35.0489C33.1546 34.8215 33.0269 34.5129 33.0269 34.1912C33.0269 33.8695 33.1546 33.561 33.3821 33.3335C33.6096 33.1061 33.9181 32.9783 34.2398 32.9783H37.8788C38.2005 32.9783 38.509 33.1061 38.7365 33.3335C38.9639 33.561 39.0917 33.8695 39.0917 34.1912C39.0917 34.5129 38.9639 34.8215 38.7365 35.0489C38.509 35.2764 38.2005 35.4042 37.8788 35.4042Z"+ fill="currentColor"+ />+ <path+ d="M22.161 40.2198C21.8393 40.2198 21.5308 40.092 21.3033 39.8645C21.0759 39.6371 20.9481 39.3285 20.9481 39.0068V29.4146C20.9481 29.0929 21.0759 28.7844 21.3033 28.5569C21.5308 28.3295 21.8393 28.2017 22.161 28.2017C22.4827 28.2017 22.7913 28.3295 23.0187 28.5569C23.2462 28.7844 23.374 29.0929 23.374 29.4146V39.0068C23.374 39.3285 23.2462 39.6371 23.0187 39.8645C22.7913 40.092 22.4827 40.2198 22.161 40.2198Z"+ fill="currentColor"+ />+ <path+ d="M22.1817 40.3774C21.86 40.3774 21.5514 40.2496 21.324 40.0221C21.0965 39.7947 20.9687 39.4861 20.9687 39.1644C20.9687 39.1293 20.9553 35.6104 20.9553 34.2689C20.9553 33.1554 20.9481 29.4012 20.9481 29.4012C20.9481 29.0795 21.0759 28.771 21.3033 28.5435C21.5308 28.316 21.8393 28.1882 22.161 28.1882H24.9254C28.0088 28.1882 30.0805 30.6372 30.0805 34.2822C30.0805 37.7489 27.9554 40.3022 25.0285 40.3531C24.2401 40.3677 22.269 40.375 22.1853 40.375L22.1817 40.3774ZM23.3764 30.6166C23.3764 31.8162 23.3764 33.5714 23.3764 34.2737C23.3764 35.1082 23.3764 36.7906 23.3849 37.9454C23.9672 37.9454 24.6149 37.9369 24.9812 37.9308C26.8249 37.8981 27.6497 36.0762 27.6497 34.2846C27.6497 32.5113 26.9329 30.6166 24.9205 30.6166H23.3764Z"+ fill="currentColor"+ />+ <path+ d="M11.7865 40.3774C11.4648 40.3774 11.1562 40.2496 10.9288 40.0222C10.7013 39.7947 10.5735 39.4862 10.5735 39.1644V29.4036C10.5735 29.0819 10.7013 28.7734 10.9288 28.5459C11.1562 28.3185 11.4648 28.1907 11.7865 28.1907C12.1082 28.1907 12.4167 28.3185 12.6442 28.5459C12.8716 28.7734 12.9994 29.0819 12.9994 29.4036V39.1644C12.9994 39.4862 12.8716 39.7947 12.6442 40.0222C12.4167 40.2496 12.1082 40.3774 11.7865 40.3774Z"+ fill="currentColor"+ />+ <path+ d="M11.8047 36.1381C11.4842 36.1381 11.1768 36.0113 10.9496 35.7854C10.7223 35.5595 10.5936 35.2528 10.5917 34.9324C10.5917 34.913 10.5796 32.9201 10.5796 32.1583C10.5796 31.53 10.5796 29.4073 10.5796 29.4073C10.5796 29.0856 10.7074 28.7771 10.9349 28.5496C11.1623 28.3221 11.4709 28.1943 11.7926 28.1943H14.5096C16.7269 28.1943 18.5318 29.9738 18.5318 32.162C18.5318 34.3502 16.7269 36.1296 14.5096 36.1296C13.7685 36.1296 11.8411 36.1417 11.8192 36.1417L11.8047 36.1381ZM13.0031 30.6166C13.0031 31.2086 13.0031 31.8563 13.0031 32.1583C13.0031 32.5125 13.0031 33.1384 13.0031 33.7049H14.4951C15.3599 33.7049 16.0913 32.9989 16.0913 32.1632C16.0913 31.3274 15.3636 30.6215 14.4951 30.6215L13.0031 30.6166Z"+ fill="currentColor"+ />+ <path+ d="M6.10975 52.2791H4.24541C3.11946 52.2791 2.03962 51.8319 1.24345 51.0357C0.447283 50.2395 0 49.1597 0 48.0337C0 46.9078 0.447283 45.8279 1.24345 45.0318C2.03962 44.2356 3.11946 43.7883 4.24541 43.7883H9.75474C10.0764 43.7883 10.385 43.9161 10.6124 44.1436C10.8399 44.3711 10.9677 44.6796 10.9677 45.0013C10.9677 45.323 10.8399 45.6315 10.6124 45.859C10.385 46.0865 10.0764 46.2143 9.75474 46.2143H4.24541C3.76286 46.2143 3.30007 46.406 2.95886 46.7472C2.61764 47.0884 2.42595 47.5512 2.42595 48.0337C2.42595 48.5163 2.61764 48.9791 2.95886 49.3203C3.30007 49.6615 3.76286 49.8532 4.24541 49.8532H6.11339C6.43509 49.8532 6.74361 49.981 6.97109 50.2085C7.19857 50.4359 7.32636 50.7445 7.32636 51.0662C7.32636 51.3879 7.19857 51.6964 6.97109 51.9239C6.74361 52.1514 6.43509 52.2791 6.11339 52.2791H6.10975Z"+ fill="currentColor"+ />+ <path+ d="M1.22872 48.8973C0.90702 48.8973 0.598496 48.7695 0.371019 48.542C0.143542 48.3145 0.0157471 48.006 0.0157471 47.6843L0.067905 26.336C0.069833 25.2113 0.517967 24.1333 1.31393 23.3387C2.10989 22.5441 3.18862 22.0978 4.31331 22.0978L48.7846 22.0894C49.1063 22.0894 49.4148 22.2171 49.6423 22.4446C49.8698 22.6721 49.9976 22.9806 49.9976 23.3023V45.0012C49.9976 45.3229 49.8698 45.6314 49.6423 45.8589C49.4148 46.0864 49.1063 46.2142 48.7846 46.2142H5.52386C5.20216 46.2142 4.89364 46.0864 4.66616 45.8589C4.43868 45.6314 4.31089 45.3229 4.31089 45.0012C4.31089 44.6795 4.43868 44.371 4.66616 44.1435C4.89364 43.916 5.20216 43.7882 5.52386 43.7882H47.5692V24.508L4.30967 24.5165C3.82712 24.5165 3.36434 24.7082 3.02312 25.0494C2.68191 25.3906 2.49021 25.8534 2.49021 26.336L2.43806 47.6843C2.43806 48.0054 2.31076 48.3134 2.08407 48.5407C1.85738 48.7681 1.54979 48.8963 1.22872 48.8973Z"+ fill="currentColor"+ />+ </svg>+ );+ }+if (icon === "microsoft") {return (<svgdiff --git a/samples/apps/autogen-assistant/frontend/src/components/types.ts b/samples/apps/autogen-assistant/frontend/src/components/types.tsindex a5fa8622b..0cfcdd722 100644--- a/samples/apps/autogen-assistant/frontend/src/components/types.ts+++ b/samples/apps/autogen-assistant/frontend/src/components/types.ts@@ -9,6 +9,7 @@ export interface IMessage {timestamp?: string;personalize?: boolean;ra?: string;+ session_id?: string;}export interface IStatus {@@ -33,7 +34,7 @@ export interface ILLMConfig {export interface IAgentConfig {name: string;- llm_config?: ILLMConfig;+ llm_config?: ILLMConfig | boolean;human_input_mode: string;max_consecutive_auto_reply: number;system_message: string | "";@@ -60,3 +61,26 @@ export interface IModelConfig {base_url?: string;api_type?: string;}++export interface IMetadataFile {+ name: string;+ path: string;+ extension: string;+ content: string;+ type: string;+}++export interface IChatSession {+ session_id: string;+ timestamp: string;+ user_id: string;+ flow_config: IFlowConfig;+}++export interface IGalleryItem {+ id: string;+ messages: Array<IMessage>;+ session: IChatSession;+ tags: Array<string>;+ timestamp: string;+}diff --git a/samples/apps/autogen-assistant/frontend/src/components/utils.ts b/samples/apps/autogen-assistant/frontend/src/components/utils.tsindex e79340dd9..f1977f66b 100644--- a/samples/apps/autogen-assistant/frontend/src/components/utils.ts+++ b/samples/apps/autogen-assistant/frontend/src/components/utils.ts@@ -256,11 +256,10 @@ export const getDefaultConfigFlows = () => {const userProxyConfig: IAgentConfig = {name: "userproxy",- llm_config: llm_config,human_input_mode: "NEVER",max_consecutive_auto_reply: 5,- system_message:- "You are a helpful assistant that can respond with a conscise summary of the previous conversation. The summary must be written as a coherent helpful response to the user request e.g. 'Sure, here is result to your request ' or 'The tallest mountain in Africa is ..' etc. The summary MUST end with the word TERMINATE. If the user request is pleasantry or greeting, you should respond with a pleasantry or greeting and TERMINATE.",+ system_message: "",+ llm_config: false,code_execution_config: {work_dir: null,use_docker: false,@@ -273,10 +272,11 @@ export const getDefaultConfigFlows = () => {const assistantConfig: IAgentConfig = {name: "primary_assistant",- llm_config: llm_config_35turbo,+ llm_config: llm_config,human_input_mode: "NEVER",max_consecutive_auto_reply: 8,- system_message: "",+ system_message:+ "You are a helpful assistant that can use available functions when needed to solve problems. At each point, do your best to determine if the user's request has been addressed. IF THE REQUEST HAS NOT BEEN ADDRESSED, RESPOND WITH CODE TO ADDRESS IT. IF A FAILURE OCCURRED (e.g., due to a missing library) AND SOME ADDITIONAL CODE WAS WRITTEN (e.g. code to install the library), ENSURE THAT THE ORIGINAL CODE TO ADDRESS THE TASK STILL GETS EXECUTED. If the request HAS been addressed, respond with a summary of the result. The summary must be written as a coherent helpful response to the user request e.g. 'Sure, here is result to your request ' or 'The tallest mountain in Africa is ..' etc. The summary MUST end with the word TERMINATE. If the user request is pleasantry or greeting, you should respond with a pleasantry or greeting and TERMINATE.",};const visualizationAssistantConfig: IAgentConfig = {@@ -284,7 +284,7 @@ export const getDefaultConfigFlows = () => {llm_config: llm_config,human_input_mode: "NEVER",max_consecutive_auto_reply: 4,- system_message: `Your task is to ensure you generate a high quality visualization for the user. Your visualizations must follow best practices and you must articulate your reasoning for your choices. The visualization must not have grid or outline box. The visualization should have an APPROPRIATE ASPECT RATIO e..g rectangular for time series data. The title must be bold. Importantly, if THE CHART IS A LINE CHART, you MUST ADD ALINE OF BEST FIT and ADD TEXT ON THE SLOPE OF EACH LINE. Note that today's date is ${new Date().toLocaleDateString()}. YOUR RESPONSE MUST NOT CONTAIN THE WORD TERMINATE.`,+ system_message: `Your task is to ensure you generate a high quality visualization for the user. Your visualizations must follow best practices and you must articulate your reasoning for your choices. The visualization must not have grid or outline box. The visualization should have an APPROPRIATE ASPECT RATIO e..g rectangular for time series data. The title must be bold. Importantly, if THE CHART IS A LINE CHART, you MUST ADD ALINE OF BEST FIT and ADD TEXT ON THE SLOPE OF EACH LINE. Note that today's date is ${new Date().toLocaleDateString()}. At each point, do your best to determine if the user's request has been addressed and if so, respond with a summary. The summary must be written as a coherent helpful response to the user request e.g. 'Sure, here is result to your request '. The summary MUST end with the word TERMINATE. If the user request is pleasantry or greeting, you should respond with a pleasantry or greeting and TERMINATE.`,};const visualizationAssistantFlowSpec: IAgentFlowSpec = {@@ -298,13 +298,13 @@ export const getDefaultConfigFlows = () => {};const GeneralFlowConfig: IFlowConfig = {- name: "General Assistant",+ name: "General Agent Workflow",sender: userProxyFlowSpec,receiver: assistantFlowSpec,type: "default",};const VisualizationChatFlowConfig: IFlowConfig = {- name: "Visualization Assistant",+ name: "Visualization Agent Workflow",sender: userProxyFlowSpec,receiver: visualizationAssistantFlowSpec,type: "default",@@ -372,3 +372,63 @@ export const getSampleSkill = () => {plt.close(fig)`;return catSkill;};++export const timeAgo = (dateString: string): string => {+ // Parse the date string into a Date object+ const timestamp = new Date(dateString);++ // Check for invalid date+ if (isNaN(timestamp.getTime())) {+ throw new Error("Invalid date string provided.");+ }++ // Get the current time+ const now = new Date();++ // Calculate the difference in milliseconds+ const timeDifference = now.getTime() - timestamp.getTime();++ // Convert time difference to minutes and hours+ const minutesAgo = Math.floor(timeDifference / (1000 * 60));+ const hoursAgo = Math.floor(minutesAgo / 60);++ // Format the date into a readable format e.g. "November 27"+ const options: Intl.DateTimeFormatOptions = { month: "long", day: "numeric" };+ const formattedDate = timestamp.toLocaleDateString(undefined, options);++ // Determine the time difference string+ let timeAgoStr: string;+ if (minutesAgo < 1) {+ timeAgoStr = "just now";+ } else if (minutesAgo < 60) {+ // Less than an hour ago, display minutes+ timeAgoStr = `${minutesAgo} ${minutesAgo === 1 ? "minute" : "minutes"} ago`;+ } else if (hoursAgo < 24) {+ // Less than a day ago, display hours+ timeAgoStr = `${hoursAgo} ${hoursAgo === 1 ? "hour" : "hours"} ago`;+ } else {+ // More than a day ago, display the formatted date+ timeAgoStr = formattedDate;+ }++ // Return the final readable string+ return timeAgoStr;+};++export const examplePrompts = [+ {+ title: "Stock Price",+ prompt:+ "Plot a chart of NVDA and TESLA stock price YTD. Save the result to a file named nvda_tesla.png",+ },+ {+ title: "Sine Wave",+ prompt:+ "Write a python script to plot a sine wave and save it to disc as a png file sine_wave.png",+ },+ {+ title: "Markdown",+ prompt:+ "List out the top 5 rivers in africa and their length and return that as a markdown table. Do not try to write any code, just write the table",+ },+];diff --git a/samples/apps/autogen-assistant/frontend/src/components/views/gallery/gallery.tsx b/samples/apps/autogen-assistant/frontend/src/components/views/gallery/gallery.tsxnew file mode 100644index 000000000..91077b491--- /dev/null+++ b/samples/apps/autogen-assistant/frontend/src/components/views/gallery/gallery.tsx@@ -0,0 +1,208 @@+import * as React from "react";+import { appContext } from "../../../hooks/provider";+import { fetchJSON, getServerUrl, timeAgo, truncateText } from "../../utils";+import { IGalleryItem, IStatus } from "../../types";+import { Button, message } from "antd";+import { BounceLoader, Card } from "../../atoms";+import {+ ChevronLeftIcon,+ InformationCircleIcon,+} from "@heroicons/react/24/outline";+import { navigate } from "gatsby";+import ChatBox from "../ra/chatbox";++const GalleryView = ({ location }: any) => {+ const serverUrl = getServerUrl();+ const { user } = React.useContext(appContext);+ const [loading, setLoading] = React.useState(false);+ const [gallery, setGallery] = React.useState<null | IGalleryItem[]>(null);+ const [currentGallery, setCurrentGallery] =+ React.useState<null | IGalleryItem>(null);+ const listGalleryUrl = `${serverUrl}/gallery?user_id=${user?.email}`;+ const [error, setError] = React.useState<IStatus | null>({+ status: true,+ message: "All good",+ });+ const [currentGalleryId, setCurrentGalleryId] = React.useState<string | null>(+ null+ );++ React.useEffect(() => {+ // get gallery id from url+ const urlParams = new URLSearchParams(location.search);+ const galleryId = urlParams.get("id");++ if (galleryId) {+ // Fetch gallery details using the galleryId+ fetchGallery(galleryId);+ setCurrentGalleryId(galleryId);+ } else {+ // Redirect to an error page or home page if the id is not found+ // navigate("/");+ fetchGallery(null);+ }+ }, []);++ const fetchGallery = (galleryId: string | null) => {+ const fetchGalleryUrl = galleryId+ ? `${serverUrl}/gallery?gallery_id=${galleryId}`+ : listGalleryUrl;+ setError(null);+ setLoading(true);+ // const fetch;+ const payLoad = {+ method: "GET",+ headers: {+ "Content-Type": "application/json",+ },+ };++ const onSuccess = (data: any) => {+ console.log(data);+ if (data && data.status) {+ message.success(data.message);+ console.log("gallery", data);+ if (galleryId) {+ // Set the currently viewed gallery item+ setCurrentGallery(data.data[0]);+ } else {+ setGallery(data.data);+ }+ // Set the list of gallery items+ } else {+ message.error(data.message);+ }+ setLoading(false);+ };+ const onError = (err: any) => {+ setError(err);+ message.error(err.message);+ setLoading(false);+ };+ fetchJSON(fetchGalleryUrl, payLoad, onSuccess, onError);+ };++ const GalleryContent = ({ item }: { item: IGalleryItem }) => {+ return (+ <div>+ <div className="mb-4 text-sm">+ This session contains {item.messages.length} messages and was created{" "}+ {timeAgo(item.timestamp)}+ </div>+ <div className="">+ <ChatBox initMessages={item.messages} editable={false} />+ </div>+ </div>+ );+ };++ const TagsView = ({ tags }: { tags: string[] }) => {+ const tagsView = tags.map((tag: string, index: number) => {+ return (+ <div key={"tag" + index} className="mr-2 inline-block">+ <span className="text-xs bg-secondary border px-3 p-1 rounded">+ {tag}+ </span>+ </div>+ );+ });+ return <div className="flex flex-wrap">{tagsView}</div>;+ };++ const galleryRows = gallery?.map((item: IGalleryItem, index: number) => {+ const isSelected = currentGallery?.id === item.id;+ return (+ <div key={"galleryrow" + index} className="">+ <Card+ active={isSelected}+ onClick={() => {+ setCurrentGallery(item);+ // add to history+ navigate(`/gallery?id=${item.id}`);+ }}+ className="h-full p-2 cursor-pointer"+ title={truncateText(item.messages[0].content, 20)}+ >+ <div className="my-2">+ {" "}+ {truncateText(item.messages[0].content, 80)}+ </div>+ <div className="text-xs">+ {" "}+ {item.messages.length} messsage{item.messages.length > 1 && "s"}+ </div>+ <div className="my-2 border-t border-dashed w-full pt-2 inline-flex gap-2 ">+ <TagsView tags={item.tags} />{" "}+ </div>+ <div className="text-xs">{timeAgo(item.timestamp)}</div>+ </Card>+ </div>+ );+ });++ return (+ <div className=" ">+ <div className="mb-4 text-2xl">Gallery</div>++ {/* back to gallery button */}++ {currentGallery && (+ <div className="mb-4 w-full">+ <Button+ type="primary"+ onClick={() => {+ setCurrentGallery(null);+ // add to history+ navigate(`/gallery?_=${Date.now()}`);+ if (currentGalleryId) {+ fetchGallery(null);+ setCurrentGalleryId(null);+ }+ }}+ className="bg-primary text-white px-2 py-1 rounded"+ >+ <ChevronLeftIcon className="h-4 w-4 inline mr-1" />+ Back to gallery+ </Button>+ </div>+ )}++ {!currentGallery && (+ <>+ <div>+ View a collection of AutoGen agent specifications and sessions{" "}+ </div>+ <div className="mt-4 grid gap-3 grid-cols-2 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">+ {galleryRows}+ </div>+ </>+ )}++ {gallery && gallery.length === 0 && (+ <div className="text-sm border rounded text-secondary p-2">+ <InformationCircleIcon className="h-4 w-4 inline mr-1" />+ No gallery items found. Please create a chat session and publish to+ gallery.+ </div>+ )}++ {currentGallery && (+ <div className="mt-4 border-t pt-2">+ <GalleryContent item={currentGallery} />+ </div>+ )}++ {loading && (+ <div className="w-full text-center boder mt-4">+ <div>+ {" "}+ <BounceLoader />+ </div>+ loading gallery+ </div>+ )}+ </div>+ );+};++export default GalleryView;diff --git a/samples/apps/autogen-assistant/frontend/src/components/views/ra/agents.tsx b/samples/apps/autogen-assistant/frontend/src/components/views/ra/agents.tsxindex 7a2e93280..1add93a8b 100644--- a/samples/apps/autogen-assistant/frontend/src/components/views/ra/agents.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/views/ra/agents.tsx@@ -293,14 +293,14 @@ const AgentsView = () => {// );return (- <div className="h-full mb-4 ">+ <div className=" mb-4 "><div className="font-semibold pb-2 border-b">Agents </div><div className="text-xs mt-2 mb-2 pb-1 ">{" "}Select or create an agent workflow.{" "}</div><div className="text-xs text-secondary mt-2 flex">- <div>Default Agent</div>+ <div>Agent Workflow</div><div className="flex-1"><AgentsControlViewflowConfig={flowConfig}diff --git a/samples/apps/autogen-assistant/frontend/src/components/views/ra/chatbox.tsx b/samples/apps/autogen-assistant/frontend/src/components/views/ra/chatbox.tsxindex 09cd1087e..b55904694 100644--- a/samples/apps/autogen-assistant/frontend/src/components/views/ra/chatbox.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/views/ra/chatbox.tsx@@ -2,27 +2,33 @@ import {ArrowPathIcon,Cog6ToothIcon,ExclamationTriangleIcon,+ InformationCircleIcon,PaperAirplaneIcon,TrashIcon,} from "@heroicons/react/24/outline";import { Button, Dropdown, MenuProps, message } from "antd";import * as React from "react";-import { IChatMessage, IFlowConfig, IMessage, IStatus } from "../../types";-import { fetchJSON, getServerUrl, guid } from "../../utils";+import {+ IChatMessage,+ IChatSession,+ IFlowConfig,+ IMessage,+ IStatus,+} from "../../types";+import { examplePrompts, fetchJSON, getServerUrl, guid } from "../../utils";import { appContext } from "../../../hooks/provider";import MetaDataView from "./metadata";-import { MarkdownView } from "../../atoms";+import { BounceLoader, MarkdownView } from "../../atoms";import { useConfigStore } from "../../../hooks/store";const ChatBox = ({- config,initMessages,- skillup,+ editable = true,}: {- config: any;- initMessages: any[];- skillup: any;+ initMessages: IMessage[] | null;+ editable: boolean;}) => {+ const session: IChatSession | null = useConfigStore((state) => state.session);const queryInputRef = React.useRef<HTMLInputElement>(null);const messageBoxInputRef = React.useRef<HTMLDivElement>(null);const { user } = React.useContext(appContext);@@ -47,7 +53,7 @@ const ChatBox = ({}const parseMessages = (messages: any) => {- return messages.map((message: any) => {+ return messages?.map((message: any) => {let meta;try {meta = JSON.parse(message.metadata);@@ -70,12 +76,6 @@ const ChatBox = ({setMessages(initMsgs);}, [initMessages]);- function processString(inputString: string): string {- inputString = inputString.replace(/\n/g, " \n");- const markdownPattern = /```markdown\s+([\s\S]*?)\s+```/g;- return inputString?.replace(markdownPattern, (match, content) => content);- }-const deleteMessage = (messageId: string) => {setError(null);setLoading(true);@@ -85,7 +85,11 @@ const ChatBox = ({headers: {"Content-Type": "application/json",},- body: JSON.stringify({ user_id: user?.email, msg_id: messageId }),+ body: JSON.stringify({+ user_id: user?.email,+ msg_id: messageId,+ session_id: session?.session_id,+ }),};const onSuccess = (data: any) => {@@ -110,24 +114,6 @@ const ChatBox = ({fetchJSON(deleteMsgUrl, payLoad, onSuccess, onError);};- const examplePrompts = [- {- title: "Stock Price",- prompt:- "Plot a chart of NVDA and TESLA stock price YTD. Save the result to a file named nvda_tesla.png",- },- {- title: "Sine Wave",- prompt:- "Write a python script to plot a sine wave and save it to disc as a png file sine_wave.png",- },- {- title: "Markdown",- prompt:- "List out the top 5 rivers in africa and their length and return that as a markdown table. Do not try to write any code, just write the table",- },- ];-const promptButtons = examplePrompts.map((prompt, i) => {return (<Button@@ -144,15 +130,7 @@ const ChatBox = ({);});- const checkIsSkill = (message: string) => {- // check if message contains lowercase of 'Learned a new skill'- if (message.toLowerCase().includes("learned a new skill")) {- skillup.set(new Date().toLocaleTimeString());- console.log("learned a new skill .. updating UI ");- }- };-- const messageListView = messages.map((message: IChatMessage, i: number) => {+ const messageListView = messages?.map((message: IChatMessage, i: number) => {const isUser = message.sender === "user";const css = isUser ? "bg-accent text-white " : "bg-light";// console.log("message", message);@@ -308,9 +286,9 @@ const ChatBox = ({// }}, []);- const chatHistory = (messages: IChatMessage[]) => {+ const chatHistory = (messages: IChatMessage[] | null) => {let history = "";- messages.forEach((message) => {+ messages?.forEach((message) => {history += message.text + "\n"; // message.sender + ": " + message.text + "\n";});return history;@@ -326,7 +304,6 @@ const ChatBox = ({const getCompletion = (query: string) => {setError(null);let messageHolder = Object.assign([], messages);- let history = chatHistory(messages);const userMessage: IChatMessage = {text: query,@@ -342,8 +319,11 @@ const ChatBox = ({msg_id: userMessage.msg_id,user_id: user?.email || "",root_msg_id: "0",+ session_id: session?.session_id || "",};+ console.log("messagePayload", messagePayload);+const textUrl = `${serverUrl}/messages`;const postData = {method: "POST",@@ -370,7 +350,6 @@ const ChatBox = ({metadata: data.metadata,msg_id: data.msg_id,};- checkIsSkill(data.message);// if (data.metadata) {// setMetadata(data.metadata);// }@@ -392,7 +371,7 @@ const ChatBox = ({message.error("Connection error. Ensure server is up and running.");}})- .catch((err) => {+ .catch(() => {setLoading(false);message.error("Connection error. Ensure server is up and running.");@@ -406,90 +385,106 @@ const ChatBox = ({className="flex h-full flex-col rounded scroll pr-2 overflow-auto "style={{ minHeight: "300px", maxHeight: chatMaxHeight }}>+ <div className="scroll-gradient h-10">+ {" "}+ <span className=" inline-block h-6"></span>{" "}+ </div><div className="flex-1 boder mt-4"></div>+ {!messages && messages !== null && (+ <div className="w-full text-center boder mt-4">+ <div>+ {" "}+ <BounceLoader />+ </div>+ loading messages+ </div>+ )}++ {messages && messages?.length === 0 && (+ <div className="ml-2 text-sm text-secondary ">+ <InformationCircleIcon className="inline-block h-6 mr-2" />+ No messages in the current session. Start a conversation to begin.+ </div>+ )}<div className="ml-2"> {messageListView}</div><div className="ml-2 h-6 mb-4 mt-2 ">- {loading && (- <div className="inline-flex gap-2">- <span className=" rounded-full bg-accent h-2 w-2 inline-block"></span>- <span className="animate-bounce rounded-full bg-accent h-3 w-3 inline-block"></span>- <span className=" rounded-full bg-accent h-2 w-2 inline-block"></span>- </div>- )}+ {loading && <BounceLoader />}</div></div>- <div className="mt-2 p-2 absolute bg-primary bottom-0 w-full">- <div- className={`mt-2 rounded p-2 shadow-lg flex mb-1 gap-2 ${- loading ? " opacity-50 pointer-events-none" : ""- }`}- >- {/* <input className="flex-1 p-2 ring-2" /> */}- <form- autoComplete="on"- className="flex-1 "- onSubmit={(e) => {- e.preventDefault();- // if (queryInputRef.current && !loading) {- // getCompletion(queryInputRef.current?.value);- // }- }}+ {editable && (+ <div className="mt-2 p-2 absolute bg-primary bottom-0 w-full">+ <div+ className={`mt-2 rounded p-2 shadow-lg flex mb-1 gap-2 ${+ loading ? " opacity-50 pointer-events-none" : ""+ }`}>- <input- id="queryInput"- name="queryInput"+ {/* <input className="flex-1 p-2 ring-2" /> */}+ <formautoComplete="on"- onKeyDown={(e) => {- if (e.key === "Enter" && queryInputRef.current && !loading) {+ className="flex-1 "+ onSubmit={(e) => {+ e.preventDefault();+ // if (queryInputRef.current && !loading) {+ // getCompletion(queryInputRef.current?.value);+ // }+ }}+ >+ <input+ id="queryInput"+ name="queryInput"+ autoComplete="on"+ onKeyDown={(e) => {+ if (e.key === "Enter" && queryInputRef.current && !loading) {+ getCompletion(queryInputRef.current?.value);+ }+ }}+ ref={queryInputRef}+ className="w-full text-gray-600 bg-white p-2 ring-2 rounded-sm"+ />+ </form>+ <div+ role={"button"}+ onClick={() => {+ if (queryInputRef.current && !loading) {getCompletion(queryInputRef.current?.value);}}}- ref={queryInputRef}- className="w-full text-gray-600 bg-white p-2 ring-2 rounded-sm"- />- </form>- <div- role={"button"}- onClick={() => {- if (queryInputRef.current && !loading) {- getCompletion(queryInputRef.current?.value);- }- }}- className="bg-accent hover:brightness-75 transition duration-300 rounded pt-2 px-5 "- >- {" "}- {!loading && (- <div className="inline-block ">- <PaperAirplaneIcon className="h-6 text-white inline-block" />{" "}- </div>- )}- {loading && (- <div className="inline-block ">- <Cog6ToothIcon className="relative -pb-2 text-white animate-spin inline-flex rounded-full h-6 w-6" />- </div>- )}- </div>- </div>{" "}- <div>- <div className="mt-2 text-xs text-secondary">- Blank slate? Try one of the example prompts below{" "}- </div>- <div- className={`mt-2 inline-flex gap-2 flex-wrap ${- loading ? "brightness-75 pointer-events-none" : ""- }`}- >- {promptButtons}+ className="bg-accent hover:brightness-75 transition duration-300 rounded pt-2 px-5 "+ >+ {" "}+ {!loading && (+ <div className="inline-block ">+ <PaperAirplaneIcon className="h-6 text-white inline-block" />{" "}+ </div>+ )}+ {loading && (+ <div className="inline-block ">+ <Cog6ToothIcon className="relative -pb-2 text-white animate-spin inline-flex rounded-full h-6 w-6" />+ </div>+ )}+ </div>+ </div>{" "}+ <div>+ <div className="mt-2 text-xs text-secondary">+ Blank slate? Try one of the example prompts below{" "}+ </div>+ <div+ className={`mt-2 inline-flex gap-2 flex-wrap ${+ loading ? "brightness-75 pointer-events-none" : ""+ }`}+ >+ {promptButtons}+ </div></div>+ {error && !error.status && (+ <div className="p-2 border rounded mt-4 text-orange-500 text-sm">+ {" "}+ <ExclamationTriangleIcon className="h-5 text-orange-500 inline-block mr-2" />{" "}+ {error.message}+ </div>+ )}</div>- {error && !error.status && (- <div className="p-2 border rounded mt-4 text-orange-500 text-sm">- {" "}- <ExclamationTriangleIcon className="h-5 text-orange-500 inline-block mr-2" />{" "}- {error.message}- </div>- )}- </div>+ )}</div>);};diff --git a/samples/apps/autogen-assistant/frontend/src/components/views/ra/metadata.tsx b/samples/apps/autogen-assistant/frontend/src/components/views/ra/metadata.tsxindex 37cf9edb7..4819f8d87 100644--- a/samples/apps/autogen-assistant/frontend/src/components/views/ra/metadata.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/views/ra/metadata.tsx@@ -1,94 +1,165 @@-import { DocumentTextIcon } from "@heroicons/react/24/outline";+import { DocumentTextIcon, PhotoIcon } from "@heroicons/react/24/outline";import * as React from "react";-import { CollapseBox, ExpandView, MarkdownView } from "../../atoms";+import {+ CodeBlock,+ CodeLoader,+ CollapseBox,+ ExpandView,+ ImageLoader,+ MarkdownView,+ PdfViewer,+} from "../../atoms";import { formatDuration, getServerUrl } from "../../utils";+import { IMetadataFile } from "../../types";+import Icon from "../../icons";const MetaDataView = ({ metadata }: { metadata: any | null }) => {+ console.log(metadata);const serverUrl = getServerUrl();+ const renderFileContent = (file: IMetadataFile, i: number) => {+ const file_type = file.extension;+ const is_image = ["image"].includes(file.type);+ const is_code = ["code"].includes(file.type);+ const is_pdf = ["pdf"].includes(file.type);+ const file_name = file.name || "unknown";+ const file_path = file.path || "unknown";- const renderFile = (file: string, i: number) => {- const file_type = file.split(".").pop() || "";- const image_types = ["png", "jpg", "jpeg", "gif", "svg"];- const is_image = image_types.includes(file_type);- const time_nonce = new Date().getTime().toString();- const file_name = file.split("/").pop() || "";-+ let fileView = null;+ let fileTitle = (+ <div>+ {file.type === "image" ? (+ <PhotoIcon className="h-4 mr-1 inline-block" />+ ) : (+ <DocumentTextIcon className="h-4 mr-1 inline-block" />+ )}{" "}+ <span className="break-all ">{file_name}</span>{" "}+ </div>+ );+ let icon = (+ <div className="p-2 bg-secondary rounded flex items-center justify-center h-full">+ <div className="">+ <div style={{ fontSize: "2em" }} className=" text-center mb-2">+ {file.extension}+ </div>+ <div>{fileTitle}</div>+ </div>+ </div>+ );if (is_image) {- return (- <div key={"metafilesrow" + i} className="text-primary ">- <ExpandView className="lg:w-3/4 xl:w-1/2 2xl:w-1/4 mb-1">- <div className="mb-2">- <DocumentTextIcon className="h-4 mr-1 inline-block" /> {file_name}- </div>- <img- src={`${serverUrl}/${file}?t=${time_nonce}`}- className="w-full rounded"- />- </ExpandView>+ fileView = (+ <div>+ <div className="mb-2">{fileTitle}</div>+ <ImageLoader+ src={`${serverUrl}/${file_path}`}+ className="w-full rounded"+ /></div>);- } else {- return (- <div key={"metafilesrow" + i} className="text-primary text-xs">- <DocumentTextIcon className="h-4 mr-1 inline-block" /> {file_name}+ icon = fileView;+ } else if (is_code) {+ fileView = (+ <div className="h">+ <div className="mb-4">{fileTitle}</div>+ <CodeLoader+ url={`${serverUrl}/${file_path}`}+ className="w-full rounded"+ />+ </div>+ );+ icon = (+ <div className=" relative rounded h-full">+ <div className="absolute rounded p-2 bg-secondary top-0 ">+ {fileTitle}+ </div>+ <div+ style={{ minHeight: "150px" }}+ className="bg-secondary h-full w-full rounded flex items-center justify-center text-primary"+ >+ <Icon icon="python" size={14} />+ </div>+ </div>+ );+ } else if (is_pdf) {+ fileView = (+ <div className="h-full">+ <div className="mb-4">{fileTitle}</div>+ <PdfViewer url={`${serverUrl}/${file_path}`} />+ </div>+ );++ icon = (+ <div className=" relative rounded h-full">+ <div className="absolute rounded p-2 bg-secondary top-0 ">+ {fileTitle}+ </div>+ <div+ style={{ minHeight: "150px" }}+ className="bg-secondary h-full w-full rounded flex items-center justify-center text-primary "+ >+ <Icon icon="pdf" size={14} />+ </div></div>);+ } else {+ fileView = <span>Unsupported file type.</span>;}- };- const files = (metadata.files || []).map((file: string, i: number) => {return (- <div- key={"metafilesrow" + i}- className="text-primary border-b border-dashed py-2"- >- {renderFile(file, i)}+ <div className=" h-full rounded">+ <ExpandView className="mb-1" icon={icon} title={file_name}>+ {fileView}+ </ExpandView></div>);- });+ };- const messages = (metadata.messages || []).map((message: any, i: number) => {- return (- <div className="border-b border-dashed" key={"messagerow" + i}>- <MarkdownView data={message?.content} className="text-sm" />- </div>- );- });+ const renderFile = (file: IMetadataFile, i: number) => (+ <div key={"metafilesrow" + i} className="text-primary ">+ {renderFileContent(file, i)}+ </div>+ );++ const files = (metadata.files || []).map(renderFile);++ const messages = (metadata.messages || []).map((message: any, i: number) => (+ <div className="border-b border-dashed" key={"messagerow" + i}>+ <MarkdownView data={message?.content} className="text-sm" />+ </div>+ ));const hasContent = files.length > 0;const hasMessages = messages.length > 0;+return (<div>{hasMessages && (- <div className=" rounded bg-primary p-2 ">+ <div className="rounded bg-primary p-2"><CollapseBoxopen={false}title={`Agent Messages (${messages.length} message${messages.length > 1 ? "s" : ""}) | ${formatDuration(metadata?.time)}`}>- <div- // style={{ maxHeight: "300px" }}- className=" "- >- {messages}- </div>+ {messages}</CollapseBox></div>)}{hasContent && (- <div className=" rounded bg-primary p-2 ">+ <div className="rounded bg-primary p-2"><CollapseBoxopen={true}title={`Results (${files.length} file${files.length > 1 ? "s" : ""})`}>- <div className="mt-2 ">{files}</div>+ <div className="mt-2 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">+ {files}+ </div></CollapseBox></div>)}</div>);};+export default MetaDataView;diff --git a/samples/apps/autogen-assistant/frontend/src/components/views/ra/ra.tsx b/samples/apps/autogen-assistant/frontend/src/components/views/ra/ra.tsxindex 2bcf7e6e0..160634a66 100644--- a/samples/apps/autogen-assistant/frontend/src/components/views/ra/ra.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/views/ra/ra.tsx@@ -1,14 +1,16 @@import * as React from "react";-import { IMessage, IStatus } from "../../types";+import { IChatSession, IMessage, IStatus } from "../../types";import { fetchJSON, getServerUrl, setLocalStorage } from "../../utils";import ChatBox from "./chatbox";import { appContext } from "../../../hooks/provider";import { message } from "antd";import SideBarView from "./sidebar";+import { useConfigStore } from "../../../hooks/store";const RAView = () => {+ const session: IChatSession | null = useConfigStore((state) => state.session);const [loading, setLoading] = React.useState(false);- const [messages, setMessages] = React.useState<IMessage[]>([]);+ const [messages, setMessages] = React.useState<IMessage[] | null>(null);const [skillUpdated, setSkillUpdated] = React.useState("default");const skillup = {@@ -29,11 +31,12 @@ const RAView = () => {const { user } = React.useContext(appContext);const serverUrl = getServerUrl();- const fetchMessagesUrl = `${serverUrl}/messages?user_id=${user?.email}`;+ const fetchMessagesUrl = `${serverUrl}/messages?user_id=${user?.email}&session_id=${session?.session_id}`;const fetchMessages = () => {setError(null);setLoading(true);+ setMessages(null);// const fetch;const payLoad = {method: "GET",@@ -62,11 +65,11 @@ const RAView = () => {};React.useEffect(() => {- if (user) {+ if (user && session) {// console.log("fetching messages", messages);fetchMessages();}- }, []);+ }, [session]);return (<div className="h-full ">diff --git a/samples/apps/autogen-assistant/frontend/src/components/views/ra/sessions.tsx b/samples/apps/autogen-assistant/frontend/src/components/views/ra/sessions.tsxnew file mode 100644index 000000000..7ac11d616--- /dev/null+++ b/samples/apps/autogen-assistant/frontend/src/components/views/ra/sessions.tsx@@ -0,0 +1,260 @@+import {+ ClockIcon,+ PlusIcon,+ QueueListIcon,+ TrashIcon,+} from "@heroicons/react/24/outline";+import { Modal, message } from "antd";+import * as React from "react";+import { IChatSession, IStatus } from "../../types";+import { appContext } from "../../../hooks/provider";+import {+ fetchJSON,+ getSampleSkill,+ getServerUrl,+ timeAgo,+ truncateText,+} from "../../utils";+import {+ CodeBlock,+ CollapseBox,+ LaunchButton,+ LoadBox,+ LoadingOverlay,+ MarkdownView,+} from "../../atoms";+import { useConfigStore } from "../../../hooks/store";+import TextArea from "antd/es/input/TextArea";++const SessionsView = ({}: any) => {+ const [loading, setLoading] = React.useState(false);+ const [error, setError] = React.useState<IStatus | null>({+ status: true,+ message: "All good",+ });++ const { user } = React.useContext(appContext);+ const serverUrl = getServerUrl();+ const listSessionUrl = `${serverUrl}/sessions?user_id=${user?.email}`;+ const createSessionUrl = `${serverUrl}/sessions`;+ const publishSessionUrl = `${serverUrl}/sessions/publish`;++ const sessions = useConfigStore((state) => state.sessions);+ const flowConfig = useConfigStore((state) => state.flowConfig);+ const setSessions = useConfigStore((state) => state.setSessions);+ // const [session, setSession] =+ // React.useState<IChatSession | null>(null);+ const session = useConfigStore((state) => state.session);+ const setSession = useConfigStore((state) => state.setSession);++ const fetchSessions = () => {+ setError(null);+ setLoading(true);+ // const fetch;+ const payLoad = {+ method: "GET",+ headers: {+ "Content-Type": "application/json",+ },+ };++ const onSuccess = (data: any) => {+ console.log(data);+ if (data && data.status) {+ message.success(data.message);+ console.log("sesssions", data);+ setSessions(data.data);+ if (data.data && data.data.length === 0) {+ createSession();+ }+ } else {+ message.error(data.message);+ }+ setLoading(false);+ };+ const onError = (err: any) => {+ setError(err);+ message.error(err.message);+ setLoading(false);+ };+ fetchJSON(listSessionUrl, payLoad, onSuccess, onError);+ };++ const publishSession = () => {+ setError(null);+ setLoading(true);++ const body = {+ user_id: user?.email,+ session: session,+ tags: ["published"],+ };+ // const fetch;+ const payLoad = {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(body),+ };++ const onSuccess = (data: any) => {+ console.log(data);+ if (data && data.status) {+ message.success(data.message);+ // setSessions(data.data);+ } else {+ message.error(data.message);+ }+ setLoading(false);+ };+ const onError = (err: any) => {+ setError(err);+ message.error(err.message);+ setLoading(false);+ };+ fetchJSON(publishSessionUrl, payLoad, onSuccess, onError);+ };++ React.useEffect(() => {+ if (sessions && sessions.length > 0) {+ setSession(sessions[0]);+ }+ }, [sessions]);++ const createSession = () => {+ setError(null);+ setLoading(true);++ const body = {+ user_id: user?.email,+ session:+ session === null+ ? {+ user_id: user?.email,+ flow_config: flowConfig,+ session_id: null,+ }+ : session,+ };+ // const fetch;+ const payLoad = {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(body),+ };++ console.log("payload", body);+ const onSuccess = (data: any) => {+ console.log(data);+ if (data && data.status) {+ message.success(data.message);+ setSessions(data.data);+ } else {+ message.error(data.message);+ }+ setLoading(false);+ };+ const onError = (err: any) => {+ setError(err);+ message.error(err.message);+ setLoading(false);+ };+ fetchJSON(createSessionUrl, payLoad, onSuccess, onError);+ };++ React.useEffect(() => {+ if (user) {+ // console.log("fetching messages", messages);+ fetchSessions();+ }+ }, []);++ const sessionRows = sessions.map((data: IChatSession, index: number) => {+ const isSelected = session?.session_id === data.session_id;+ const rowClass = isSelected+ ? "bg-accent text-white"+ : "bg-secondary text-primary";+ return (+ <div key={"sessionsrow" + index} className=" mb-2 pb-1 ">+ <div+ className={`rounded p-2 cursor-pointer ${rowClass}`}+ role="button"+ onClick={() => {+ setSession(data);+ }}+ >+ <div className="text-xs">{truncateText(data.session_id, 27)}</div>+ <div className="text-xs text-right ">{timeAgo(data.timestamp)} </div>+ </div>+ <div className="flex mt-1 text-secondary">+ <div className="flex-1"></div>++ <div+ role="button"+ onClick={() => {+ console.log("pubish session", data);+ publishSession();+ }}+ className="text-xs px-2 hover:text-accent cursor-pointer"+ >+ {" "}+ publish{" "}+ </div>+ </div>+ {/* <div className="border-b border-dashed mx-2 mt-1"></div> */}+ </div>+ );+ });++ let windowHeight, skillsMaxHeight;+ if (typeof window !== "undefined") {+ windowHeight = window.innerHeight;+ skillsMaxHeight = windowHeight - 400 + "px";+ }++ return (+ <div className=" ">+ <div className="mb-2 relative">+ <LoadingOverlay loading={loading} />+ <div className="">+ <div className="font-semibold mb-2 pb-1 border-b">Sessions </div>+ <div className="text-xs mb-2 pb-1 ">+ {" "}+ Create a new session or select an existing session to view chat.+ </div>+ <div+ style={{+ maxHeight: "300px",+ }}+ className="mb-4 overflow-y-scroll scroll rounded "+ >+ {sessionRows}+ </div>+ {(!sessions || sessions.length == 0) && (+ <div className="text-xs text-gray-500">+ No sessions found. Create a new session to get started.+ </div>+ )}+ </div>+ <div className="flex gap-x-2">+ <div className="flex-1"></div>+ <LaunchButton+ className="text-sm p-2 px-3"+ onClick={() => {+ createSession();+ }}+ >+ {" "}+ <PlusIcon className="w-5 h-5 inline-block mr-1" />+ New+ </LaunchButton>+ </div>+ </div>+ </div>+ );+};++export default SessionsView;diff --git a/samples/apps/autogen-assistant/frontend/src/components/views/ra/sidebar.tsx b/samples/apps/autogen-assistant/frontend/src/components/views/ra/sidebar.tsxindex 054695cfe..b3752edc5 100644--- a/samples/apps/autogen-assistant/frontend/src/components/views/ra/sidebar.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/views/ra/sidebar.tsx@@ -2,19 +2,32 @@ import { ChevronLeftIcon, ChevronRightIcon } from "@heroicons/react/24/outline";import * as React from "react";import SkillsView from "./skills";import AgentsView from "./agents";+import SessionsView from "./sessions";const SideBarView = ({ setMessages, notify, skillup, config }: any) => {const [isOpen, setIsOpen] = React.useState(true);const minWidth = isOpen ? "270px" : "50px";+ let windowHeight, sidebarMaxHeight;+ if (typeof window !== "undefined") {+ windowHeight = window.innerHeight;+ sidebarMaxHeight = windowHeight - 180 + "px";+ }+return (<div- style={{ minWidth: minWidth, maxWidth: minWidth }}- className="transition overflow-hidden duration-300 flex flex-col h-full p-2 "+ style={{+ minWidth: minWidth,+ maxWidth: minWidth,+ // maxHeight: sidebarMaxHeight,+ height: "calc(100vh - 190px)",+ }}+ className=" ">- <div className="flex-1 ">- <div className={`${isOpen ? "" : "hidden"}`}>+ <div className=" transition overflow-hidden duration-300 flex flex-col h-full p-2 overflow-y-scroll scroll rounded ">+ <div className={`${isOpen ? "" : "hidden"} `}><AgentsView />+ <SessionsView config={config} /><SkillsViewnotify={notify}setMessages={setMessages}@@ -29,11 +42,11 @@ const SideBarView = ({ setMessages, notify, skillup, config }: any) => {className=" hover:text-accent duration-150 ">{isOpen ? (- <>+ <div className="mt-4 ">{" "}<ChevronLeftIcon className="w-6 h-6 inline-block rounded" />{" "}<span className="text-xs "> close sidebar</span>- </>+ </div>) : (<ChevronRightIcon className="w-6 h-6 inline-block font-bold rounded " />)}diff --git a/samples/apps/autogen-assistant/frontend/src/components/views/ra/skills.tsx b/samples/apps/autogen-assistant/frontend/src/components/views/ra/skills.tsxindex 37b2bee1a..361fae482 100644--- a/samples/apps/autogen-assistant/frontend/src/components/views/ra/skills.tsx+++ b/samples/apps/autogen-assistant/frontend/src/components/views/ra/skills.tsx@@ -14,6 +14,7 @@ import {CollapseBox,LaunchButton,LoadBox,+ LoadingOverlay,MarkdownView,} from "../../atoms";import { useConfigStore } from "../../../hooks/store";@@ -25,6 +26,7 @@ const SkillsView = ({ setMessages, skillup }: any) => {status: true,message: "All good",});+ const setSessions = useConfigStore((state) => state.setSessions);const { user } = React.useContext(appContext);const serverUrl = getServerUrl();@@ -43,6 +45,8 @@ const SkillsView = ({ setMessages, skillup }: any) => {const sampleSkill = getSampleSkill();const [skillCode, setSkillCode] = React.useState(sampleSkill);+ const session = useConfigStore((state) => state.session);+// console.log("skukkup", skillup);const clearDb = () => {@@ -56,6 +60,7 @@ const SkillsView = ({ setMessages, skillup }: any) => {},body: JSON.stringify({user_id: user?.email,+ session: session,}),};console.log("payload", payLoad);@@ -64,6 +69,7 @@ const SkillsView = ({ setMessages, skillup }: any) => {if (data && data.status) {message.success(data.message);setMessages([]);+ setSessions(data.data?.sessions);} else {message.error(data.message);}@@ -102,8 +108,8 @@ const SkillsView = ({ setMessages, skillup }: any) => {console.log(data);if (data && data.status) {message.success(data.message);- console.log("skills", data.skills);- setSkills(data.skills);+ console.log("skills", data.data);+ setSkills(data.data);} else {message.error(data.message);}@@ -144,8 +150,8 @@ const SkillsView = ({ setMessages, skillup }: any) => {console.log(data);if (data && data.status) {message.success(data.message);- console.log("skills", data.skills);- setSkills(data.skills);+ console.log("skills", data.data);+ setSkills(data.data);} else {message.error(data.message);}@@ -282,7 +288,8 @@ const SkillsView = ({ setMessages, skillup }: any) => {</></Modal>- <div className="mb-2">+ <div className="mb-2 relative">+ <LoadingOverlay loading={loading} /><divstyle={{maxHeight: skillsMaxHeight,diff --git a/samples/apps/autogen-assistant/frontend/src/hooks/provider.tsx b/samples/apps/autogen-assistant/frontend/src/hooks/provider.tsxindex 25d20b789..b4251189d 100644--- a/samples/apps/autogen-assistant/frontend/src/hooks/provider.tsx+++ b/samples/apps/autogen-assistant/frontend/src/hooks/provider.tsx@@ -29,12 +29,9 @@ export const appContext = React.createContext<AppContextType>({} as AppContextType);const Provider = ({ children }: any) => {+ const storedValue = getLocalStorage("darkmode", false);const [darkMode, setDarkMode] = useState(- getLocalStorage("darkmode", false) === null- ? "dark"- : getLocalStorage("darkmode", false) !== ("dark" || "light")- ? getLocalStorage("darkmode", false)- : "light"+ storedValue === null ? "light" : storedValue === "dark" ? "dark" : "light");const logout = () => {diff --git a/samples/apps/autogen-assistant/frontend/src/hooks/store.tsx b/samples/apps/autogen-assistant/frontend/src/hooks/store.tsxindex 085a3a57c..79f972999 100644--- a/samples/apps/autogen-assistant/frontend/src/hooks/store.tsx+++ b/samples/apps/autogen-assistant/frontend/src/hooks/store.tsx@@ -1,14 +1,18 @@import { create } from "zustand";import { getDefaultConfigFlows } from "../components/utils";-import { IChatMessage, IFlowConfig } from "../components/types";+import { IChatMessage, IChatSession, IFlowConfig } from "../components/types";interface ConfigState {flowConfigs: IFlowConfig[];setFlowConfigs: (flowConfigs: IFlowConfig[]) => void;flowConfig: IFlowConfig;setFlowConfig: (flowConfig: IFlowConfig) => void;- messages: IChatMessage[];+ messages: IChatMessage[] | null;setMessages: (messages: IChatMessage[]) => void;+ session: IChatSession | null;+ setSession: (session: IChatSession) => void;+ sessions: IChatSession[];+ setSessions: (sessions: IChatSession[]) => void;}export const useConfigStore = create<ConfigState>()((set) => ({@@ -16,6 +20,10 @@ export const useConfigStore = create<ConfigState>()((set) => ({setFlowConfigs: (flowConfigs) => set({ flowConfigs }),flowConfig: getDefaultConfigFlows()[0],setFlowConfig: (flowConfig) => set({ flowConfig }),- messages: [],+ messages: null,setMessages: (messages) => set({ messages }),+ session: null,+ setSession: (session) => set({ session }),+ sessions: [],+ setSessions: (sessions) => set({ sessions }),}));diff --git a/samples/apps/autogen-assistant/frontend/src/pages/gallery/index.tsx b/samples/apps/autogen-assistant/frontend/src/pages/gallery/index.tsxnew file mode 100644index 000000000..30faf790b--- /dev/null+++ b/samples/apps/autogen-assistant/frontend/src/pages/gallery/index.tsx@@ -0,0 +1,28 @@+import * as React from "react";+import { graphql } from "gatsby";+import Layout from "../../components/layout";+import GalleryView from "../../components/views/gallery/gallery";++// markup+const GalleryPage = ({ location, data }: any) => {+ return (+ <Layout meta={data.site.siteMetadata} title="Gallery" link={"/gallery"}>+ <main style={{ height: "100%" }} className=" h-full ">+ <GalleryView location={location} />+ </main>+ </Layout>+ );+};++export const query = graphql`+ query HomePageQuery {+ site {+ siteMetadata {+ description+ title+ }+ }+ }+`;++export default GalleryPage;diff --git a/samples/apps/autogen-assistant/frontend/src/styles/global.css b/samples/apps/autogen-assistant/frontend/src/styles/global.cssindex fd27b29b6..f2905feff 100644--- a/samples/apps/autogen-assistant/frontend/src/styles/global.css+++ b/samples/apps/autogen-assistant/frontend/src/styles/global.css@@ -190,10 +190,15 @@ iiz__zoom-img {right: 0;}}-.scroll::-webkit-scrollbar {- width: 8px; /* width of the entire scrollbar */+ width: 8px;height: 8px;+ opacity: 0; /* Make scrollbar fully transparent by default */+ transition: opacity 0.25s ease; /* Transition for the opacity */+}++.scroll:hover::-webkit-scrollbar {+ opacity: 1; /* Make scrollbar fully opaque on hover */}.scroll::-webkit-scrollbar-track {@@ -203,8 +208,32 @@ iiz__zoom-img {.scroll::-webkit-scrollbar-thumb {@apply bg-accent;- border-radius: 20px; /* roundness of the scroll thumb */- border: 3px solid rgb(214, 214, 214); /* creates padding around scroll thumb */+ border-radius: 20px;+ border: 3px solid rgb(214, 214, 214);+}++.dark .scroll-gradient {+ background: linear-gradient(+ to bottom,+ rgba(17, 24, 39, 1),+ rgba(17, 24, 39, 0)+ );+}++.light .scroll-gradient {+ background: linear-gradient(+ to bottom,+ rgba(255, 255, 255, 1),+ rgba(255, 255, 255, 0)+ );+}++.scroll-gradient {+ position: sticky;+ top: 0;+ height: 15px;+ z-index: 2; /* Above the content but below the scrollbar */+ pointer-events: none; /* So it doesn't block interaction with the content */}.vega-embed {diff --git a/samples/apps/autogen-assistant/notebooks/agent_spec.json b/samples/apps/autogen-assistant/notebooks/agent_spec.jsonnew file mode 100644index 000000000..95f1026df--- /dev/null+++ b/samples/apps/autogen-assistant/notebooks/agent_spec.json@@ -0,0 +1,44 @@+{+ "name": "General Agent Workflow",+ "sender": {+ "type": "userproxy",+ "config": {+ "name": "userproxy",+ "human_input_mode": "NEVER",+ "max_consecutive_auto_reply": 5,+ "system_message": "",+ "llm_config": false,+ "code_execution_config": {+ "work_dir": null,+ "use_docker": false+ }+ }+ },+ "receiver": {+ "type": "assistant",+ "config": {+ "name": "primary_assistant",+ "llm_config": {+ "config_list": [+ {+ "model": "gpt-4-1106-preview"+ },+ {+ "model": "gpt-3.5-turbo-16k"+ },+ {+ "model": "TheBloke/zephyr-7B-alpha-AWQ",+ "base_url": "http://localhost:8000/v1"+ }+ ],+ "temperature": 0.1,+ "timeout": 600,+ "cache_seed": null+ },+ "human_input_mode": "NEVER",+ "max_consecutive_auto_reply": 8,+ "system_message": "You are a helpful assistant that can use available functions when needed to solve problems. At each point, do your best to determine if the user's request has been addressed. IF THE REQUEST HAS NOT BEEN ADDRESSED, RESPOND WITH CODE TO ADDRESS IT. IF A FAILURE OCCURRED (e.g., due to a missing library) AND SOME ADDITIONAL CODE WAS WRITTEN (e.g. code to install the library), ENSURE THAT THE ORIGINAL CODE TO ADDRESS THE TASK STILL GETS EXECUTED. If the request HAS been addressed, respond with a summary of the result. The summary must be written as a coherent helpful response to the user request e.g. 'Sure, here is result to your request ' or 'The tallest mountain in Africa is ..' etc. The summary MUST end with the word TERMINATE. If the user request is pleasantry or greeting, you should respond with a pleasantry or greeting and TERMINATE."+ }+ },+ "type": "default"+}diff --git a/samples/apps/autogen-assistant/notebooks/tutorial.ipynb b/samples/apps/autogen-assistant/notebooks/tutorial.ipynbnew file mode 100644index 000000000..bdc2b702e--- /dev/null+++ b/samples/apps/autogen-assistant/notebooks/tutorial.ipynb@@ -0,0 +1,80 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## AutoGen Assistant API\n",+ "\n",+ "This notebook focuses on demonstrating capabilities of the autogen assistant python api. \n",+ "\n",+ "- Declarative Specification of an Agent Workflow \n",+ "- Loading the specification and runnning the resulting agent\n",+ "\n",+ "\n",+ "> Note: The notebook currently demonstrates support for a two agent setup. Support for GroupChat is currently in development."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "userproxy (to primary_assistant):\n",+ "\n",+ "What is the height of the Eiffel Tower?\n",+ "\n",+ "--------------------------------------------------------------------------------\n",+ "primary_assistant (to userproxy):\n",+ "\n",+ "The Eiffel Tower, located in Paris, France, has a height of approximately 300 meters (984 feet) to the tip. Its height can vary slightly due to temperature changes that cause the metal to expand and contract. Including antennas, the total height of the Eiffel Tower is about 330 meters (1,083 feet). TERMINATE\n",+ "\n",+ "--------------------------------------------------------------------------------\n"+ ]+ }+ ],+ "source": [+ "import json \n",+ "from autogenra import AutoGenWorkFlowManager, FlowConfig \n",+ "\n",+ "# load an agent specification in JSON \n",+ "agent_spec= json.load(open('agent_spec.json'))\n",+ "\n",+ "# Creat a An AutoGen Workflow Configuration from the agent specification\n",+ "agent_work_flow_config = FlowConfig(**agent_spec)\n",+ "\n",+ "# Create a Workflow from the configuration \n",+ "agent_work_flow = AutoGenWorkFlowManager(agent_work_flow_config) \n",+ "\n",+ "# Run the workflow on a task\n",+ "task_query = \"What is the height of the Eiffel Tower?\"\n",+ "agent_work_flow.run(message=task_query)"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "coral",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.11.4"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/samples/apps/autogen-assistant/pyproject.toml b/samples/apps/autogen-assistant/pyproject.tomlindex d9d6409bb..86d024554 100644--- a/samples/apps/autogen-assistant/pyproject.toml+++ b/samples/apps/autogen-assistant/pyproject.toml@@ -24,7 +24,7 @@ dependencies = ["typer","uvicorn","arxiv",- "pyautogen==0.2.0b5"+ "pyautogen==0.2.0"]optional-dependencies = {web = ["fastapi", "uvicorn"]}