Skip to content

A programming framework for agentic AI

Add visualization of Agent Message Transitions State in AGS (#4148)

Victor Dibiab9f72828307a
diff --git a/python/packages/autogen-studio/autogenstudio/database/component_factory.py b/python/packages/autogen-studio/autogenstudio/database/component_factory.py
index 708a292d6..7c0275275 100644
--- a/python/packages/autogen-studio/autogenstudio/database/component_factory.py
+++ b/python/packages/autogen-studio/autogenstudio/database/component_factory.py
@@ -178,6 +178,15 @@ class ComponentFactory:
async def load_team(self, config: TeamConfig) -> TeamComponent:
"""Create team instance from configuration."""
+
+ default_selector_prompt = """You are in a role play game. The following roles are available:
+{roles}.
+Read the following conversation. Then select the next role from {participants} to play. Only return the role.
+
+{history}
+
+Read the above conversation. Then select the next role from {participants} to play. Only return the role.
+"""
try:
# Load participants (agents)
participants = []
@@ -206,10 +215,12 @@ class ComponentFactory:
if not model_client:
raise ValueError(
"SelectorGroupChat requires a model_client")
+ selector_prompt = config.selector_prompt if config.selector_prompt else default_selector_prompt
return SelectorGroupChat(
participants=participants,
model_client=model_client,
- termination_condition=termination
+ termination_condition=termination,
+ selector_prompt=selector_prompt
)
else:
raise ValueError(f"Unsupported team type: {config.team_type}")
diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/types.py b/python/packages/autogen-studio/autogenstudio/datamodel/types.py
index 3f059eba1..ad8f2088e 100644
--- a/python/packages/autogen-studio/autogenstudio/datamodel/types.py
+++ b/python/packages/autogen-studio/autogenstudio/datamodel/types.py
@@ -91,6 +91,7 @@ class TeamConfig(BaseConfig):
participants: List[AgentConfig]
team_type: TeamTypes
model_client: Optional[ModelConfig] = None
+ selector_prompt: Optional[str] = None
termination_condition: Optional[TerminationConfig] = None
component_type: ComponentType = ComponentType.TEAM
diff --git a/python/packages/autogen-studio/autogenstudio/web/managers/connection.py b/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
index b46887b7a..0a0d5fb7c 100644
--- a/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
+++ b/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
@@ -1,4 +1,4 @@
-# managers/connection.py
+from autogen_agentchat.base._task import TaskResult
from fastapi import WebSocket, WebSocketDisconnect
from typing import Dict, Optional, Any
from uuid import UUID
@@ -7,7 +7,7 @@ from datetime import datetime, timezone
from ...datamodel import Run, RunStatus, TeamResult
from ...database import DatabaseManager
-from autogen_agentchat.messages import InnerMessage, ChatMessage
+from autogen_agentchat.messages import InnerMessage, ChatMessage, TextMessage
from autogen_core.base import CancellationToken
logger = logging.getLogger(__name__)
@@ -20,6 +20,11 @@ class WebSocketManager:
self.db_manager = db_manager
self._connections: Dict[UUID, WebSocket] = {}
self._cancellation_tokens: Dict[UUID, CancellationToken] = {}
+ # Track explicitly closed connections
+ self._closed_connections: set[UUID] = set()
+
+ self._cancel_message = TeamResult(task_result=TaskResult(messages=[TextMessage(
+ source="user", content="Run cancelled by user")], stop_reason="cancelled by user"), usage="", duration=0).model_dump()
async def connect(self, websocket: WebSocket, run_id: UUID) -> bool:
"""Initialize WebSocket connection for a run
@@ -34,6 +39,8 @@ class WebSocketManager:
try:
await websocket.accept()
self._connections[run_id] = websocket
+ # Remove from closed set if reconnecting
+ self._closed_connections.discard(run_id)
run = await self._get_run(run_id)
if run:
@@ -59,7 +66,7 @@ class WebSocketManager:
task: str,
team_config: dict
) -> None:
- """Start streaming task execution
+ """Start streaming task execution with improved error handling
Args:
run_id: UUID of the run
@@ -67,7 +74,7 @@ class WebSocketManager:
task: Task string to execute
team_config: Team configuration dictionary
"""
- if run_id not in self._connections:
+ if run_id not in self._connections or run_id in self._closed_connections:
raise ValueError(f"No active connection for run {run_id}")
cancellation_token = CancellationToken()
@@ -79,27 +86,22 @@ class WebSocketManager:
team_config=team_config,
cancellation_token=cancellation_token
):
-
- if cancellation_token.is_cancelled():
- logger.info(f"Stream cancelled for run {run_id}")
+ if cancellation_token.is_cancelled() or run_id in self._closed_connections:
+ logger.info(
+ f"Stream cancelled or connection closed for run {run_id}")
break
formatted_message = self._format_message(message)
if formatted_message:
await self._send_message(run_id, formatted_message)
- # Only send completion if not cancelled
- if not cancellation_token.is_cancelled():
- # await self._send_message(run_id, {
- # "type": "completion",
- # "status": "complete",
- # "timestamp": datetime.now(timezone.utc).isoformat()
- # })
+ if not cancellation_token.is_cancelled() and run_id not in self._closed_connections:
await self._update_run_status(run_id, RunStatus.COMPLETE)
else:
await self._send_message(run_id, {
"type": "completion",
"status": "cancelled",
+ "data": self._cancel_message,
"timestamp": datetime.now(timezone.utc).isoformat()
})
await self._update_run_status(run_id, RunStatus.STOPPED)
@@ -115,14 +117,15 @@ class WebSocketManager:
"""Stop a running task"""
if run_id in self._cancellation_tokens:
logger.info(f"Stopping run {run_id}")
- self._cancellation_tokens[run_id].cancel()
+ # self._cancellation_tokens[run_id].cancel()
- # Send final message if connection still exists
- if run_id in self._connections:
+ # Send final message if connection still exists and not closed
+ if run_id in self._connections and run_id not in self._closed_connections:
try:
await self._send_message(run_id, {
"type": "completion",
"status": "cancelled",
+ "data": self._cancel_message,
"timestamp": datetime.now(timezone.utc).isoformat()
})
except Exception:
@@ -132,49 +135,61 @@ class WebSocketManager:
"""Clean up connection and associated resources"""
logger.info(f"Disconnecting run {run_id}")
- # First cancel any running tasks
+ # Mark as closed before cleanup to prevent any new messages
+ self._closed_connections.add(run_id)
+
+ # Cancel any running tasks
await self.stop_run(run_id)
- # Then clean up resources without trying to close the socket again
- if run_id in self._connections:
- self._connections.pop(run_id, None)
- self._cancellation_tokens.pop(run_id, None)
+ # Clean up resources
+ self._connections.pop(run_id, None)
+ self._cancellation_tokens.pop(run_id, None)
async def _send_message(self, run_id: UUID, message: dict) -> None:
- """Send a message through the WebSocket
+ """Send a message through the WebSocket with connection state checking
Args:
run_id: UUID of the run
message: Message dictionary to send
"""
+ if run_id in self._closed_connections:
+ logger.warning(
+ f"Attempted to send message to closed connection for run {run_id}")
+ return
+
try:
if run_id in self._connections:
- await self._connections[run_id].send_json(message)
+ websocket = self._connections[run_id]
+ await websocket.send_json(message)
except WebSocketDisconnect:
logger.warning(
f"WebSocket disconnected while sending message for run {run_id}")
await self.disconnect(run_id)
except Exception as e:
- logger.error(f"Error sending message for run {run_id}: {e}")
- await self._handle_stream_error(run_id, e)
+ logger.error(
+ f"Error sending message for run {run_id}: {e}, {message}")
+ # Don't try to send error message here to avoid potential recursive loop
+ await self._update_run_status(run_id, RunStatus.ERROR, str(e))
+ await self.disconnect(run_id)
async def _handle_stream_error(self, run_id: UUID, error: Exception) -> None:
- """Handle stream errors consistently
+ """Handle stream errors with connection state awareness
Args:
run_id: UUID of the run
error: Exception that occurred
"""
- try:
- await self._send_message(run_id, {
- "type": "completion",
- "status": "error",
- "error": str(error),
- "timestamp": datetime.now(timezone.utc).isoformat()
- })
- except Exception as send_error:
- logger.error(
- f"Failed to send error message for run {run_id}: {send_error}")
+ if run_id not in self._closed_connections:
+ try:
+ await self._send_message(run_id, {
+ "type": "completion",
+ "status": "error",
+ "error": str(error),
+ "timestamp": datetime.now(timezone.utc).isoformat()
+ })
+ except Exception as send_error:
+ logger.error(
+ f"Failed to send error message for run {run_id}: {send_error}")
await self._update_run_status(run_id, RunStatus.ERROR, str(error))
@@ -239,7 +254,7 @@ class WebSocketManager:
@property
def active_connections(self) -> set[UUID]:
"""Get set of active run IDs"""
- return set(self._connections.keys())
+ return set(self._connections.keys()) - self._closed_connections
@property
def active_runs(self) -> set[UUID]:
diff --git a/python/packages/autogen-studio/frontend/package.json b/python/packages/autogen-studio/frontend/package.json
index 24ba03e19..0123df464 100644
--- a/python/packages/autogen-studio/frontend/package.json
+++ b/python/packages/autogen-studio/frontend/package.json
@@ -19,11 +19,13 @@
"dependencies": {
"@ant-design/charts": "^2.2.1",
"@ant-design/plots": "^2.2.2",
+ "@dagrejs/dagre": "^1.1.4",
"@headlessui/react": "^1.7.16",
"@heroicons/react": "^2.0.18",
"@mdx-js/react": "^3.1.0",
"@monaco-editor/react": "^4.6.0",
"@tailwindcss/typography": "^0.5.9",
+ "@xyflow/react": "^12.3.5",
"antd": "^5.1.0",
"autoprefixer": "^10.4.20",
"gatsby": "^5.13.7",
diff --git a/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts b/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
index da4999d37..d46fe1b71 100644
--- a/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
+++ b/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
@@ -3,12 +3,74 @@ export interface RequestUsage {
completion_tokens: number;
}
-export interface MessageConfig {
- source: string;
+export interface ImageContent {
+ url: string;
+ alt?: string;
+}
+
+export interface FunctionCall {
+ id: string;
+ arguments: string; // JSON string
+ name: string;
+}
+
+export interface FunctionExecutionResult {
+ call_id: string;
content: string;
+}
+
+// Base message configuration (maps to Python BaseMessage)
+export interface BaseMessageConfig {
+ source: string;
models_usage?: RequestUsage;
}
+// Message configurations (mapping directly to Python classes)
+export interface TextMessageConfig extends BaseMessageConfig {
+ content: string;
+}
+
+export interface MultiModalMessageConfig extends BaseMessageConfig {
+ content: (string | ImageContent)[];
+}
+
+export interface StopMessageConfig extends BaseMessageConfig {
+ content: string;
+}
+
+export interface HandoffMessageConfig extends BaseMessageConfig {
+ content: string;
+ target: string;
+}
+
+export interface ToolCallMessageConfig extends BaseMessageConfig {
+ content: FunctionCall[];
+}
+
+export interface ToolCallResultMessageConfig extends BaseMessageConfig {
+ content: FunctionExecutionResult[];
+}
+
+// Message type unions (matching Python type aliases)
+export type InnerMessageConfig =
+ | ToolCallMessageConfig
+ | ToolCallResultMessageConfig;
+
+export type ChatMessageConfig =
+ | TextMessageConfig
+ | MultiModalMessageConfig
+ | StopMessageConfig
+ | HandoffMessageConfig;
+
+export type AgentMessageConfig =
+ | TextMessageConfig
+ | MultiModalMessageConfig
+ | StopMessageConfig
+ | HandoffMessageConfig
+ | ToolCallMessageConfig
+ | ToolCallResultMessageConfig;
+
+// Database model
export interface DBModel {
id?: number;
user_id?: string;
@@ -17,26 +79,36 @@ export interface DBModel {
}
export interface Message extends DBModel {
- config: MessageConfig;
+ config: AgentMessageConfig;
session_id: number;
run_id: string;
}
export interface Session extends DBModel {
name: string;
- team_id?: string;
+ team_id?: number;
}
-export interface TeamConfig {
- name: string;
- participants: AgentConfig[];
- team_type: TeamTypes;
- model_client?: ModelConfig;
- termination_condition?: TerminationConfig;
+// WebSocket message types
+export type ThreadStatus = "streaming" | "complete" | "error" | "cancelled";
+
+export interface WebSocketMessage {
+ type: "message" | "result" | "completion";
+ data: {
+ source: string;
+ models_usage?: RequestUsage;
+ content: unknown;
+ task_result?: TaskResult;
+ };
+ status?: ThreadStatus;
+ error?: string;
}
-export interface Team extends DBModel {
- config: TeamConfig;
+export interface TaskResult {
+ messages: AgentMessageConfig[];
+ usage: string;
+ duration: number;
+ stop_reason?: string;
}
export type ModelTypes = "OpenAIChatCompletionClient";
@@ -62,7 +134,6 @@ export interface ToolConfig {
description: string;
content: string;
}
-
export interface AgentConfig {
name: string;
agent_type: AgentTypes;
@@ -71,16 +142,21 @@ export interface AgentConfig {
tools?: ToolConfig[];
description?: string;
}
-
export interface TerminationConfig {
termination_type: TerminationTypes;
max_messages?: number;
text?: string;
}
-export interface TaskResult {
- messages: MessageConfig[];
- usage: string;
- duration: number;
- stop_reason?: string;
+export interface TeamConfig {
+ name: string;
+ participants: AgentConfig[];
+ team_type: TeamTypes;
+ model_client?: ModelConfig;
+ termination_condition?: TerminationConfig;
+ selector_config?: string;
+}
+
+export interface Team extends DBModel {
+ config: TeamConfig;
}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/agentflow.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/agentflow.tsx
new file mode 100644
index 000000000..f02275cb0
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/agentflow.tsx
@@ -0,0 +1,369 @@
+import React, { useCallback, useState, useEffect } from "react";
+import {
+ ReactFlow,
+ Node,
+ Edge,
+ Background,
+ Controls,
+ NodeTypes,
+ useReactFlow,
+ ReactFlowProvider,
+} from "@xyflow/react";
+import Dagre from "@dagrejs/dagre";
+import "@xyflow/react/dist/style.css";
+import AgentNode from "./agentnode";
+import {
+ AgentMessageConfig,
+ AgentConfig,
+ TeamConfig,
+} from "../../../../types/datamodel";
+import { ThreadState, ThreadStatus } from "../types";
+import { CustomEdge, EdgeTooltipContent } from "./edge";
+import { Tooltip } from "antd";
+
+interface AgentFlowProps {
+ teamConfig: TeamConfig;
+ messages: AgentMessageConfig[];
+ threadState: ThreadState;
+ direction?: "TB" | "LR";
+}
+
+interface MessageSequence {
+ source: string;
+ target: string;
+ count: number;
+ totalTokens: number;
+ messages: AgentMessageConfig[];
+}
+
+const NODE_DIMENSIONS = {
+ default: { width: 150, height: 100 },
+ end: { width: 120, height: 80 },
+};
+
+const getLayoutedElements = (
+ nodes: Node[],
+ edges: Edge[],
+ direction: "TB" | "LR"
+) => {
+ const g = new Dagre.graphlib.Graph().setDefaultEdgeLabel(() => ({}));
+ g.setGraph({
+ rankdir: direction,
+ nodesep: direction === "TB" ? 100 : 80, // Adjust for orientation
+ ranksep: direction === "TB" ? 80 : 100, // Adjust for orientation
+ align: direction === "TB" ? "DL" : "UL", // Adjust alignment
+ ranker: "network-simplex",
+ marginx: 30,
+ marginy: 30,
+ });
+
+ edges.forEach((edge) => g.setEdge(edge.source, edge.target));
+ nodes.forEach((node) => {
+ const dimensions =
+ node.data.type === "end" ? NODE_DIMENSIONS.end : NODE_DIMENSIONS.default;
+ g.setNode(node.id, { ...node, ...dimensions });
+ });
+
+ Dagre.layout(g);
+
+ return {
+ nodes: nodes.map((node) => {
+ const { x, y } = g.node(node.id);
+ const dimensions =
+ node.data.type === "end"
+ ? NODE_DIMENSIONS.end
+ : NODE_DIMENSIONS.default;
+ return {
+ ...node,
+ position: {
+ x: x - dimensions.width / 2,
+ y: y - dimensions.height / 2,
+ },
+ };
+ }),
+ edges,
+ };
+};
+
+const createNode = (
+ id: string,
+ type: "user" | "agent" | "end",
+ agentConfig?: AgentConfig,
+ isActive: boolean = false,
+ threadState?: ThreadState
+): Node => {
+ if (type === "user") {
+ return {
+ id,
+ type: "agentNode",
+ position: { x: 0, y: 0 },
+ data: {
+ type: "user",
+ label: "User",
+ agentType: "user",
+ description: "Human user",
+ isActive,
+ status: "",
+ reason: "",
+ },
+ };
+ }
+
+ if (type === "end") {
+ return {
+ id,
+ type: "agentNode",
+ position: { x: 0, y: 0 },
+ data: {
+ type: "end",
+ label: "End",
+ status: threadState?.status,
+ reason: threadState?.reason || "",
+ agentType: "",
+ description: "",
+ isActive: false,
+ },
+ };
+ }
+
+ return {
+ id,
+ type: "agentNode",
+ position: { x: 0, y: 0 },
+ data: {
+ type: "agent",
+ label: id,
+ agentType: agentConfig?.agent_type || "",
+ description: agentConfig?.description || "",
+ isActive,
+ status: "",
+ reason: "",
+ },
+ };
+};
+
+const nodeTypes: NodeTypes = {
+ agentNode: AgentNode,
+};
+
+const edgeTypes = {
+ custom: CustomEdge,
+};
+
+const AgentFlow: React.FC<AgentFlowProps> = ({
+ teamConfig,
+ messages,
+ threadState,
+ direction = "TB",
+}) => {
+ const { fitView } = useReactFlow();
+ const [nodes, setNodes] = useState<Node[]>([]);
+ const [edges, setEdges] = useState<Edge[]>([]);
+
+ // ...previous imports remain same
+
+ const processMessages = useCallback(
+ (messages: AgentMessageConfig[]) => {
+ if (messages.length === 0) return { nodes: [], edges: [] };
+
+ const sequences: MessageSequence[] = [];
+ const nodeMap = new Map<string, Node>();
+ const transitionCounts = new Map<string, MessageSequence>();
+
+ // Process first message source
+ const firstAgentConfig = teamConfig.participants.find(
+ (p) => p.name === messages[0].source
+ );
+ nodeMap.set(
+ messages[0].source,
+ createNode(
+ messages[0].source,
+ messages[0].source === "user" ? "user" : "agent",
+ firstAgentConfig,
+ false
+ )
+ );
+
+ // Group messages by transitions (including self-transitions)
+ for (let i = 0; i < messages.length - 1; i++) {
+ const currentMsg = messages[i];
+ const nextMsg = messages[i + 1];
+ const transitionKey = `${currentMsg.source}->${nextMsg.source}`;
+
+ if (!transitionCounts.has(transitionKey)) {
+ transitionCounts.set(transitionKey, {
+ source: currentMsg.source,
+ target: nextMsg.source,
+ count: 1,
+ totalTokens:
+ (currentMsg.models_usage?.prompt_tokens || 0) +
+ (currentMsg.models_usage?.completion_tokens || 0),
+ messages: [currentMsg],
+ });
+ } else {
+ const transition = transitionCounts.get(transitionKey)!;
+ transition.count++;
+ transition.totalTokens +=
+ (currentMsg.models_usage?.prompt_tokens || 0) +
+ (currentMsg.models_usage?.completion_tokens || 0);
+ transition.messages.push(currentMsg);
+ }
+
+ // Ensure all nodes are in the nodeMap
+ if (!nodeMap.has(nextMsg.source)) {
+ const agentConfig = teamConfig.participants.find(
+ (p) => p.name === nextMsg.source
+ );
+ nodeMap.set(
+ nextMsg.source,
+ createNode(
+ nextMsg.source,
+ nextMsg.source === "user" ? "user" : "agent",
+ agentConfig,
+ false
+ )
+ );
+ }
+ }
+
+ // Create edges from transitions
+ const newEdges: Edge[] = Array.from(transitionCounts.entries()).map(
+ ([key, transition], index) => {
+ // const avgTokens = Math.round(
+ // transition.totalTokens / transition.count
+ // );
+ const label =
+ transition.totalTokens > 0
+ ? `${transition.count > 1 ? `${transition.count}x` : ""} (${
+ transition.totalTokens
+ } tokens)`
+ : "";
+
+ return {
+ id: `${transition.source}-${transition.target}-${index}`,
+ source: transition.source,
+ target: transition.target,
+ type: "custom",
+ data: {
+ label,
+ messages: transition.messages,
+ },
+ animated:
+ threadState?.status === "streaming" &&
+ index === transitionCounts.size - 1,
+ style: {
+ stroke: "#2563eb",
+ strokeWidth: Math.min(Math.max(transition.count, 1), 5),
+ // Add curved style for self-referential edges
+ ...(transition.source === transition.target && {
+ borderRadius: 20,
+ curvature: 0.5,
+ }),
+ },
+ };
+ }
+ );
+
+ // Handle end node logic (keeping existing end node logic)
+ if (threadState && messages.length > 0) {
+ const lastMessage = messages[messages.length - 1];
+
+ if (["complete", "error", "cancelled"].includes(threadState.status)) {
+ nodeMap.set(
+ "end",
+ createNode("end", "end", undefined, false, threadState)
+ );
+
+ const edgeColor =
+ {
+ complete: "#2563eb",
+ cancelled: "red",
+ error: "red",
+ streaming: "#2563eb",
+ }[threadState.status] || "#2563eb";
+
+ newEdges.push({
+ id: `${lastMessage.source}-end`,
+ source: lastMessage.source,
+ target: "end",
+ type: "custom",
+ data: {
+ label: "ended",
+ messages: [],
+ },
+ animated: false,
+ style: {
+ stroke: edgeColor,
+ opacity: 1,
+ zIndex: 100,
+ },
+ });
+ }
+ }
+
+ // Set active state for the last message source
+ const lastActiveSource = messages[messages.length - 1]?.source;
+ nodeMap.forEach((node) => {
+ node.data.isActive =
+ node.id === lastActiveSource && threadState?.status === "streaming";
+ });
+
+ return {
+ nodes: Array.from(nodeMap.values()),
+ edges: newEdges,
+ };
+ },
+ [teamConfig.participants, threadState]
+ );
+
+ useEffect(() => {
+ const { nodes: newNodes, edges: newEdges } = processMessages(messages);
+ const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
+ newNodes,
+ newEdges,
+ direction
+ );
+
+ setNodes(layoutedNodes);
+ setEdges(layoutedEdges);
+
+ if (messages.length > 0) {
+ setTimeout(() => {
+ fitView({ padding: 0.2, duration: 200 });
+ }, 50);
+ }
+ }, [messages, processMessages, direction, threadState, fitView]);
+
+ return (
+ <div className="w-full h-full bg-tertiary rounded-lg min-h-[300px]">
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={nodeTypes}
+ edgeTypes={edgeTypes}
+ defaultViewport={{ x: 0, y: 0, zoom: 1 }}
+ minZoom={0.5}
+ maxZoom={2}
+ proOptions={{ hideAttribution: true }}
+ onInit={() => {
+ if (messages.length > 0) {
+ setTimeout(() => {
+ fitView({ padding: 0.2, duration: 200 });
+ }, 50);
+ }
+ }}
+ >
+ <Background />
+ <Controls />
+ </ReactFlow>
+ </div>
+ );
+};
+
+export default function WrappedAgentFlow(props: AgentFlowProps) {
+ return (
+ <ReactFlowProvider>
+ <AgentFlow {...props} />
+ </ReactFlowProvider>
+ );
+}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/agentnode.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/agentnode.tsx
new file mode 100644
index 000000000..e03a2bbee
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/agentnode.tsx
@@ -0,0 +1,156 @@
+import React, { useCallback } from "react";
+import { Handle, Position } from "@xyflow/react";
+import {
+ CheckCircle,
+ AlertTriangle,
+ StopCircle,
+ UserCircle,
+ Bot,
+ Flag,
+} from "lucide-react";
+import { ThreadStatus } from "../../../../types/datamodel";
+
+export type NodeType = "agent" | "user" | "end";
+
+export interface AgentNodeData {
+ type: NodeType;
+ label: string;
+ agentType?: string;
+ description?: string;
+ isActive?: boolean;
+ status?: ThreadStatus | null;
+ reason?: string | null;
+}
+
+interface AgentNodeProps {
+ data: AgentNodeData;
+ isConnectable: boolean;
+}
+
+function AgentNode({ data, isConnectable }: AgentNodeProps) {
+ const handleClick = useCallback(() => {
+ if (data.type !== "end") {
+ console.log(`${data.type} ${data.label} clicked`);
+ }
+ }, [data.type, data.label]);
+
+ const getHeaderIcon = () => {
+ switch (data.type) {
+ case "user":
+ return <UserCircle className="text-primary" size={20} />;
+ case "agent":
+ return <Bot className="text-primary" size={20} />;
+ case "end":
+ return <Flag className="text-primary" size={20} />;
+ }
+ };
+
+ const getStatusIcon = () => {
+ if (data.type !== "end" || !data.status) return null;
+
+ switch (data.status) {
+ case "complete":
+ return <CheckCircle className="text-accent" size={24} />;
+ case "error":
+ return <AlertTriangle className="text-red-500" size={24} />;
+ case "cancelled":
+ return <StopCircle className="text-red-500" size={24} />;
+ default:
+ return null;
+ }
+ };
+
+ const getNodeStyles = () => {
+ const activeStyles = data.isActive ? "ring-2 ring-accent/50 " : " ";
+
+ if (data.type === "end") {
+ return {
+ wrapper: `relative min-w-[120px] shadow rounded-lg overflow-hidden ${activeStyles}`,
+ border:
+ data.status === "complete"
+ ? "var(--accent)"
+ : data.status === "error"
+ ? "rgb(239 68 68)"
+ : "var(--secondary)",
+ };
+ }
+
+ return {
+ wrapper: `min-w-[150px] rounded-lg shadow overflow-hidden ${activeStyles}`,
+ border: undefined,
+ };
+ };
+
+ const styles = getNodeStyles();
+
+ return (
+ <div
+ className={styles.wrapper}
+ onClick={handleClick}
+ style={styles.border ? { borderColor: styles.border } : undefined}
+ >
+ {/* Input handle - always show for all nodes */}
+ <Handle
+ type="target"
+ position={Position.Top}
+ style={{ background: "#555" }}
+ isConnectable={isConnectable}
+ id="target"
+ />
+
+ {/* Header Section */}
+ <div className="flex items-center gap-2 px-3 py-2 bg-secondary border-b border-border">
+ {getHeaderIcon()}
+ <span className="text-sm font-medium text-primary truncate">
+ {data.label}
+ </span>
+ </div>
+
+ {/* Content Section */}
+ <div className="bg-tertiary px-3 py-2">
+ {data.type === "end" ? (
+ <>
+ <div className="flex items-center justify-center gap-2">
+ {getStatusIcon()}
+ <span className="text-primary text-sm font-medium">
+ {data.status &&
+ data.status.charAt(0).toUpperCase() + data.status.slice(1)}
+ </span>
+ </div>
+ {data.reason && (
+ <div className="mt-1 text-xs text-secondary max-w-[200px] text-center">
+ {data.reason.length > 100
+ ? `${data.reason.substring(0, 97)}...`
+ : data.reason}
+ </div>
+ )}
+ </>
+ ) : (
+ <>
+ {data.agentType && (
+ <div className="text-sm text-secondary">{data.agentType}</div>
+ )}
+ {data.description && (
+ <div className="text-xs text-secondary mt-1 truncate max-w-[200px]">
+ {data.description}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+
+ {/* Output handle - only for non-end nodes */}
+ {data.type !== "end" && (
+ <Handle
+ type="source"
+ position={Position.Bottom}
+ id="source"
+ style={{ background: "#555" }}
+ isConnectable={isConnectable}
+ />
+ )}
+ </div>
+ );
+}
+
+export default AgentNode;
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/edge.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/edge.tsx
new file mode 100644
index 000000000..d3008d94c
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/agentflow/edge.tsx
@@ -0,0 +1,133 @@
+import React from "react";
+import { message, Tabs, Tooltip } from "antd";
+import { AgentMessageConfig } from "../../../../types/datamodel";
+import {
+ EdgeLabelRenderer,
+ type EdgeProps,
+ getSmoothStepPath, // Add this import
+} from "@xyflow/react";
+import { RenderMessage } from "../rendermessage";
+
+interface EdgeTooltipContentProps {
+ messages: AgentMessageConfig[];
+}
+
+interface CustomEdgeData {
+ label?: string;
+ messages: AgentMessageConfig[];
+}
+
+export const EdgeTooltipContent: React.FC<EdgeTooltipContentProps> = ({
+ messages,
+}) => {
+ return (
+ <div className="p-2 overflow-auto max-h-[200px] scroll max-w-[350px]">
+ <div className="text-xs mb-2">{messages.length} messages</div>
+ <div className="edge-tooltip ">
+ {messages.map((message, index) => (
+ <RenderMessage key={index} message={message} />
+ ))}
+ </div>
+ </div>
+ );
+};
+
+interface CustomEdgeProps extends Omit<EdgeProps, "data"> {
+ data: CustomEdgeData;
+}
+
+export const CustomEdge: React.FC<CustomEdgeProps> = ({
+ id,
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ source,
+ target,
+ data,
+ style = {},
+ markerEnd,
+ sourcePosition,
+ targetPosition,
+}) => {
+ const isSelfLoop = source === target;
+
+ let edgePath = "";
+ let labelX = 0;
+ let labelY = 0;
+
+ if (isSelfLoop) {
+ const rightOffset = 120; // How far right the path extends
+ const verticalOffset = sourceY - targetY; // Base vertical distance between handles
+ const verticalPadding = 6; // Extra padding above/below handles
+ const radius = 8; // Radius for rounded corners
+
+ // Start and end slightly beyond the handles using verticalPadding
+ edgePath = `
+ M ${sourceX} ${targetY - verticalPadding}
+ L ${sourceX + rightOffset - radius} ${targetY - verticalPadding}
+ Q ${sourceX + rightOffset} ${targetY - verticalPadding} ${
+ sourceX + rightOffset
+ } ${targetY - verticalPadding + radius}
+ L ${sourceX + rightOffset} ${sourceY + verticalPadding - radius}
+ Q ${sourceX + rightOffset} ${sourceY + verticalPadding} ${
+ sourceX + rightOffset - radius
+ } ${sourceY + verticalPadding}
+ L ${sourceX} ${sourceY + verticalPadding}
+ `;
+
+ // Adjust label position to account for padding
+ labelX = sourceX + rightOffset + 10;
+ labelY = targetY + verticalOffset / 2;
+ } else {
+ [edgePath, labelX, labelY] = getSmoothStepPath({
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ });
+ }
+
+ return (
+ <>
+ <path
+ id={id}
+ className="react-flow__edge-path"
+ d={edgePath}
+ style={{
+ ...style,
+ strokeWidth: isSelfLoop
+ ? Math.max((style.strokeWidth as number) || 1, 2)
+ : style.strokeWidth,
+ }}
+ markerEnd={markerEnd}
+ />
+ {data?.label && (
+ <EdgeLabelRenderer>
+ <div
+ style={{
+ position: "absolute",
+ transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
+ pointerEvents: "all",
+ }}
+ >
+ <Tooltip
+ title={
+ data.messages && data.messages.length > 0 ? (
+ <EdgeTooltipContent messages={data.messages} />
+ ) : (
+ data?.label
+ )
+ }
+ overlayStyle={{ maxWidth: "none" }}
+ >
+ <div className="px-2 py-1 rounded bg-secondary bg-opacity-50 text-primary text-sm">
+ {data.label}
+ </div>
+ </Tooltip>
+ </div>
+ </EdgeLabelRenderer>
+ )}
+ </>
+ );
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
index 55a837d52..cdb0ac667 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
@@ -10,6 +10,8 @@ import ChatInput from "./chatinput";
import { ModelUsage, SocketMessage, ThreadState, ThreadStatus } from "./types";
import { MessageList } from "./messagelist";
import TeamManager from "../../shared/team/manager";
+import { teamAPI } from "../../shared/team/api";
+import AgentFlow from "./agentflow/agentflow";
const logo = require("../../../../images/landing/welcome.svg").default;
@@ -36,6 +38,8 @@ export default function ChatView({
Record<string, WebSocket>
>({});
+ const [teamConfig, setTeamConfig] = React.useState<any>(null);
+
React.useEffect(() => {
if (chatContainerRef.current) {
chatContainerRef.current.scrollTo({
@@ -45,6 +49,15 @@ export default function ChatView({
}
}, [messages, threadMessages]);
+ React.useEffect(() => {
+ if (session && session.team_id && user && user.email) {
+ teamAPI.getTeam(session.team_id, user?.email).then((team) => {
+ setTeamConfig(team.config);
+ // console.log("Team Config", team.config);
+ });
+ }
+ }, [session]);
+
React.useEffect(() => {
return () => {
Object.values(activeSockets).forEach((socket) => socket.close());
@@ -194,6 +207,7 @@ export default function ChatView({
socket.onmessage = (event) => {
const message: SocketMessage = JSON.parse(event.data);
+ // console.log("WebSocket message received:", message);
switch (message.type) {
case "message":
@@ -245,6 +259,7 @@ export default function ChatView({
const reason =
message.data?.task_result?.stop_reason ||
(message.error ? `Error: ${message.error}` : undefined);
+ console.log("All Messages", currentThread.messages);
return {
...prev,
@@ -424,10 +439,11 @@ export default function ChatView({
onRetry={runTask}
onCancel={cancelRun}
loading={loading}
+ teamConfig={teamConfig}
/>
</div>
- {sessions?.length === 0 ? (
+ {sessions && sessions?.length === 0 ? (
<div className="flex h-[calc(100%-100px)] flex-col items-center justify-center w-full">
<div className="mt-4 text-sm text-secondary text-center">
<img src={logo} alt="Welcome" className="w-72 h-72 mb-4" />
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/messagelist.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/messagelist.tsx
index 49c216aa7..613f96fd2 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/messagelist.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/messagelist.tsx
@@ -1,7 +1,39 @@
-import React, { useEffect, useRef } from "react";
-import { ChevronDown, ChevronRight, RotateCcw, User, Bot } from "lucide-react";
-import { ThreadView } from "./thread";
-import { MessageListProps } from "./types";
+import React from "react";
+import { ThreadState } from "./types";
+import {
+ AgentMessageConfig,
+ Message,
+ TeamConfig,
+} from "../../../types/datamodel";
+import { RenderMessage } from "./rendermessage";
+import {
+ StopCircle,
+ User,
+ Network,
+ MessageSquare,
+ Loader2,
+ CheckCircle,
+ AlertTriangle,
+} from "lucide-react";
+import AgentFlow from "./agentflow/agentflow";
+import ThreadView from "./threadview";
+
+interface MessageListProps {
+ messages: Message[];
+ threadMessages: Record<string, ThreadState>;
+ setThreadMessages: React.Dispatch<
+ React.SetStateAction<Record<string, ThreadState>>
+ >;
+ onRetry: (content: string) => void;
+ onCancel: (runId: string) => void;
+ loading?: boolean;
+ teamConfig?: TeamConfig;
+}
+
+interface MessagePair {
+ userMessage: Message;
+ botMessage: Message;
+}
export const MessageList: React.FC<MessageListProps> = ({
messages,
@@ -9,12 +41,11 @@ export const MessageList: React.FC<MessageListProps> = ({
setThreadMessages,
onRetry,
onCancel,
- loading,
+ loading = false,
+ teamConfig,
}) => {
- const messageListRef = useRef<HTMLDivElement>(null);
-
const messagePairs = React.useMemo(() => {
- const pairs = [];
+ const pairs: MessagePair[] = [];
for (let i = 0; i < messages.length; i += 2) {
if (messages[i] && messages[i + 1]) {
pairs.push({
@@ -26,114 +57,182 @@ export const MessageList: React.FC<MessageListProps> = ({
return pairs;
}, [messages]);
+ // Create a ref map to store refs for each thread container
+ const threadContainerRefs = React.useRef<
+ Record<string, HTMLDivElement | null>
+ >({});
+
+ // Effect to handle scrolling when thread messages update
+ React.useEffect(() => {
+ Object.entries(threadMessages).forEach(([runId, thread]) => {
+ if (thread.isExpanded && threadContainerRefs.current[runId]) {
+ const container = threadContainerRefs.current[runId];
+ if (container) {
+ container.scrollTo({
+ top: container.scrollHeight,
+ behavior: "smooth",
+ });
+ }
+ }
+ });
+ }, [threadMessages]); // This will trigger when any thread messages update
+
const toggleThread = (runId: string) => {
setThreadMessages((prev) => ({
...prev,
[runId]: {
...prev[runId],
- isExpanded: !prev[runId].isExpanded,
+ isExpanded: !prev[runId]?.isExpanded,
},
}));
};
+ const calculateThreadTokens = (messages: AgentMessageConfig[]) => {
+ return messages.reduce((total, msg) => {
+ if (!msg.models_usage) return total;
+ return (
+ total +
+ (msg.models_usage.prompt_tokens || 0) +
+ (msg.models_usage.completion_tokens || 0)
+ );
+ }, 0);
+ };
+
+ const getStatusIcon = (status: ThreadState["status"]) => {
+ switch (status) {
+ case "streaming":
+ return (
+ <div className="inline-block mr-1">
+ <Loader2
+ size={20}
+ className="inline-block mr-1 text-accent animate-spin"
+ />{" "}
+ Processing ...
+ </div>
+ );
+
+ case "complete":
+ return (
+ <CheckCircle size={20} className="inline-block mr-1 text-accent" />
+ );
+ case "error":
+ return (
+ <AlertTriangle size={20} className="inline-block mr-1 text-red-500" />
+ );
+ case "cancelled":
+ return (
+ <StopCircle size={20} className="inline-block mr-1 text-red-500" />
+ );
+ default:
+ return null;
+ }
+ };
+
return (
- <div
- ref={messageListRef}
- className="flex flex-col space-y-4 p-4 overflow-y-hidden overflow-x-hidden"
- >
- {messagePairs.map(({ userMessage, botMessage }, idx) => {
+ <div className="space-y-6 p-4 h-full">
+ {messagePairs.map(({ userMessage, botMessage }, pairIndex) => {
+ const isLast = pairIndex === messagePairs.length - 1;
const thread = threadMessages[botMessage.run_id];
+ const hasThread = thread && thread.messages.length > 0;
const isStreaming = thread?.status === "streaming";
- const isError = thread?.status === "error";
return (
- <div key={idx} className="space-y-2 text-primary">
- {/* User Message */}
- <div className="flex items-start gap-2 ]">
- <div className="p-1.5 rounded bg-light text-accent">
- <User size={24} />
- </div>
- <div className="flex-1">
- <div className="p-2 bg-accent rounded text-white">
- {userMessage.config.content}
+ <div key={`pair-${botMessage.run_id}`} className="space-y-6">
+ {/* User message - first */}
+ <div className="flex flex-col items-end">
+ <div className="flex items-center gap-2 mb-1">
+ <span className="text-sm font-medium text-primary">User</span>
+ <div className="p-1.5 rounded bg-secondary text-accent">
+ <User size={20} />
</div>
- {userMessage.config.models_usage && (
- <div className="text-xs text-secondary mt-1">
- Tokens:{" "}
- {userMessage.config.models_usage.prompt_tokens +
- userMessage.config.models_usage.completion_tokens}
- </div>
- )}
+ </div>
+ <div className="w-[95%]">
+ <RenderMessage message={userMessage.config} isLast={false} />
</div>
</div>
+ {/* Team response - second */}
+ <div className="flex flex-col items-start">
+ <div className="flex items-center gap-2 mb-1">
+ <div className="p-1.5 rounded bg-secondary text-primary">
+ <Network size={20} />
+ </div>
+ <span className="text-sm font-medium text-primary">
+ Agent Team
+ </span>
+ </div>
- {/* Bot Response */}
- <div className="flex items-start gap-2 ml-auto ">
- <div className="flex-1">
- <div className="p-2 bg-secondary rounded text-primary">
- <div className="flex items-center justify-between">
- <div className="flex-1 text-sm">
- {isStreaming ? (
- <>Processing...</>
- ) : (
- <>
- {" "}
- {thread?.finalResult?.content}
- <div className="mt-2 mb-2 text-sm text-secondary">
- {thread?.reason}
- </div>
- </>
- )}
- </div>
- <div className="flex items-center gap-1">
- {isError && (
- <button
- onClick={() => onRetry(userMessage.config.content)}
- className="p-1 text-secondary hover:text-primary transition-colors"
- >
- <RotateCcw size={14} />
- </button>
- )}
- {thread && thread.messages?.length > 0 && (
+ {/* Main response container */}
+ <div className="w-[95%]">
+ <div className="p-4 bg-secondary border border-secondary rounded-lg">
+ <div className="text-primary">
+ {getStatusIcon(thread?.status)}{" "}
+ {thread?.finalResult?.content}
+ </div>
+ </div>
+
+ {/* Thread section with left border for hierarchy */}
+ {hasThread && (
+ <div className="mt-2 pl-4 border-l-2 border-secondary/30">
+ <div className="flex">
+ <div className="flex-1">
<button
onClick={() => toggleThread(botMessage.run_id)}
- className="p-1 text-secondary hover:text-primary transition-colors"
+ className="flex items-center gap-1 text-sm text-secondary hover:text-primary transition-colors"
>
- {thread.isExpanded ? (
- <ChevronDown size={14} />
- ) : (
- <ChevronRight size={14} />
- )}
+ <MessageSquare size={16} />
+ <span className="text-accent">
+ {thread.isExpanded ? "Hide" : "Show"}
+ </span>{" "}
+ agent discussion
</button>
- )}
+ </div>
+
+ <div className="text-sm text-secondary">
+ {calculateThreadTokens(thread.messages)} tokens |{" "}
+ {thread.messages.length} messages
+ </div>
</div>
- </div>
- {botMessage.config.models_usage && (
- <div className="text-sm text-secondary -mt-4">
- {botMessage.config.models_usage.prompt_tokens +
- botMessage.config.models_usage.completion_tokens}{" "}
- tokens | {thread.messages.length} messages
+ <div className="flex flex-row gap-4">
+ <div className="flex-1">
+ {" "}
+ {thread.isExpanded && (
+ <ThreadView
+ thread={thread}
+ isStreaming={isStreaming}
+ runId={botMessage.run_id}
+ onCancel={onCancel}
+ threadContainerRef={(el) =>
+ (threadContainerRefs.current[botMessage.run_id] =
+ el)
+ }
+ />
+ )}
+ </div>
+ <div className="bg-tertiary flex-1 rounded mt-2">
+ {teamConfig && thread.isExpanded && (
+ <AgentFlow
+ teamConfig={teamConfig}
+ messages={thread.messages}
+ threadState={thread} // Add this prop
+ />
+ )}
+ </div>
</div>
- )}
- {/* Thread View */}
- {thread && thread.isExpanded && (
- <ThreadView
- messages={thread.messages}
- status={thread.status}
- onCancel={onCancel}
- runId={botMessage.run_id}
- />
- )}
- </div>
- </div>
- <div className="p-1.5 rounded bg-light text-primary">
- <Bot size={24} />
+ </div>
+ )}
</div>
</div>
</div>
);
})}
+
+ {messages.length === 0 && !loading && (
+ <div className="text-center text-secondary h-full ">
+ {/* <img src={landing} alt="No messages" /> */}
+ <div className="text-sm mt-4"> Send a message to begin! </div>
+ </div>
+ )}
</div>
);
};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx
new file mode 100644
index 000000000..54035bf7e
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx
@@ -0,0 +1,160 @@
+import React from "react";
+import { User, Bot } from "lucide-react";
+import {
+ AgentMessageConfig,
+ FunctionCall,
+ FunctionExecutionResult,
+ ImageContent,
+} from "../../../types/datamodel";
+
+export const messageUtils = {
+ isToolCallContent(content: unknown): content is FunctionCall[] {
+ if (!Array.isArray(content)) return false;
+ return content.every(
+ (item) =>
+ typeof item === "object" &&
+ item !== null &&
+ "id" in item &&
+ "arguments" in item &&
+ "name" in item
+ );
+ },
+
+ isMultiModalContent(content: unknown): content is (string | ImageContent)[] {
+ if (!Array.isArray(content)) return false;
+ return content.every(
+ (item) =>
+ typeof item === "string" ||
+ (typeof item === "object" && item !== null && "url" in item)
+ );
+ },
+
+ isFunctionExecutionResult(
+ content: unknown
+ ): content is FunctionExecutionResult[] {
+ if (!Array.isArray(content)) return false;
+ return content.every(
+ (item) =>
+ typeof item === "object" &&
+ item !== null &&
+ "call_id" in item &&
+ "content" in item
+ );
+ },
+
+ isUser(source: string): boolean {
+ return source === "user";
+ },
+};
+
+interface MessageProps {
+ message: AgentMessageConfig;
+ isLast?: boolean;
+ className?: string;
+}
+
+const RenderToolCall: React.FC<{ content: FunctionCall[] }> = ({ content }) => (
+ <div className="space-y-2">
+ {content.map((call) => (
+ <div key={call.id} className="border rounded p-2">
+ <div className="font-medium">Function: {call.name}</div>
+ <pre className="text-sm mt-1 bg-secondary p-2 rounded">
+ {JSON.stringify(JSON.parse(call.arguments), null, 2)}
+ </pre>
+ </div>
+ ))}
+ </div>
+);
+
+const RenderMultiModal: React.FC<{ content: (string | ImageContent)[] }> = ({
+ content,
+}) => (
+ <div className="space-y-2">
+ {content.map((item, index) =>
+ typeof item === "string" ? (
+ <p key={index}>{item}</p>
+ ) : (
+ <img
+ key={index}
+ src={item.url}
+ alt={item.alt || ""}
+ className="max-w-full h-auto"
+ />
+ )
+ )}
+ </div>
+);
+
+const RenderToolResult: React.FC<{ content: FunctionExecutionResult[] }> = ({
+ content,
+}) => (
+ <div className="space-y-2">
+ {content.map((result) => (
+ <div key={result.call_id} className=" rounded p-2">
+ <div className="font-medium">Result ID: {result.call_id}</div>
+ <pre className="text-sm mt-1 bg-secondary p-2 border rounded">
+ {result.content}
+ </pre>
+ </div>
+ ))}
+ </div>
+);
+
+export const RenderMessage: React.FC<MessageProps> = ({
+ message,
+ isLast = false,
+ className = "",
+}) => {
+ const isUser = messageUtils.isUser(message.source);
+ const content = message.content;
+
+ return (
+ <div className={`relative group ${!isLast ? "mb-2" : ""} ${className}`}>
+ <div
+ className={`
+ flex items-start gap-2 p-2 rounded
+ ${isUser ? "bg-secondary" : "bg-tertiary"}
+ border border-secondary
+ transition-all duration-200
+ `}
+ >
+ <div
+ className={`
+ p-1.5 rounded bg-light
+ ${isUser ? "text-accent" : "text-primary"}
+ `}
+ >
+ {isUser ? <User size={14} /> : <Bot size={14} />}
+ </div>
+
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-semibold text-primary">
+ {message.source}
+ </span>
+ </div>
+
+ <div className="text-sm text-secondary">
+ {messageUtils.isToolCallContent(content) ? (
+ <RenderToolCall content={content} />
+ ) : messageUtils.isMultiModalContent(content) ? (
+ <RenderMultiModal content={content} />
+ ) : messageUtils.isFunctionExecutionResult(content) ? (
+ <RenderToolResult content={content} />
+ ) : (
+ <div className="whitespace-pre-wrap">{content}</div>
+ )}
+ </div>
+
+ {message.models_usage && (
+ <div className="text-xs text-secondary mt-1">
+ Tokens:{" "}
+ {(message.models_usage.prompt_tokens || 0) +
+ (message.models_usage.completion_tokens || 0)}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/thread.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/thread.tsx
deleted file mode 100644
index d3d2f356a..000000000
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/thread.tsx
+++ /dev/null
@@ -1,212 +0,0 @@
-import React, { useEffect, useRef } from "react";
-import {
- CheckCircle,
- AlertCircle,
- Loader2,
- User,
- Bot,
- StopCircle,
-} from "lucide-react";
-import { Tooltip } from "antd";
-import { MessageConfig } from "../../../types/datamodel";
-import { ThreadState } from "./types";
-
-interface ThreadViewProps {
- messages: MessageConfig[];
- status: ThreadState["status"];
- reason?: string; // Add reason
- onCancel: (runId: string) => void;
- runId: string;
-}
-
-interface StatusBannerProps {
- status: ThreadState["status"];
- reason?: string; // Add reason prop
- onCancel: (runId: string) => void;
- runId: string;
-}
-
-const StatusBanner = ({
- status,
- reason,
- onCancel,
- runId,
-}: StatusBannerProps) => {
- // Define variants FIRST
- const variants = {
- streaming: {
- wrapper: "bg-secondary border border-secondary",
- text: "text-primary",
- icon: "text-accent",
- },
- complete: {
- wrapper: "bg-secondary p-2",
- text: "text-accent",
- icon: " ",
- },
- error: {
- wrapper: "bg-secondary border border-secondary",
- text: "text-primary",
- icon: "text-red-500",
- },
- cancelled: {
- wrapper: "bg-secondary border border-secondary",
- text: "text-red-500",
- icon: "text-red-500",
- },
- } as const;
-
- const content = {
- streaming: {
- icon: <Loader2 className="animate-spin" size={16} />,
- text: "Processing",
- showStop: true,
- },
- complete: {
- icon: <CheckCircle size={16} />,
- text: reason || "Completed",
- showStop: false,
- },
- error: {
- icon: <AlertCircle size={16} />,
- text: reason || "Error occurred",
- showStop: false,
- },
- cancelled: {
- icon: <StopCircle size={16} />,
- text: reason || "Cancelled",
- showStop: false,
- },
- } as const;
-
- // THEN check valid status and use variants
- const validStatus = status && status in variants ? status : "error";
- const currentVariant = variants[validStatus];
- const currentContent = content[validStatus];
-
- // Rest of component remains the same...
- return (
- <div
- className={`flex items-center mt-2 justify-between p-2 rounded transition-all duration-200 ${currentVariant.wrapper}`}
- >
- <div className={`flex items-center gap-2 ${currentVariant.text}`}>
- <span className={currentVariant.icon}>{currentContent.icon}</span>
- <span className="text-sm font-medium">{currentContent.text}</span>
- {currentContent.showStop && (
- <Tooltip title="Stop processing" placement="right">
- <button
- onClick={() => onCancel(runId)}
- className="ml-2 flex items-center gap-1 px-2 py-1 rounded bg-red-500 hover:bg-red-600 text-white text-xs font-medium transition-colors duration-200"
- >
- <StopCircle size={12} />
- <span>Stop</span>
- </button>
- </Tooltip>
- )}
- </div>
- </div>
- );
-};
-
-const Message = ({ msg, isLast }: { msg: MessageConfig; isLast: boolean }) => {
- const isUser = msg.source === "user";
-
- return (
- <div className={`relative group ${!isLast ? "mb-2" : ""}`}>
- <div
- className={`
- flex items-start gap-2 p-2 rounded
- ${isUser ? "bg-secondary" : "bg-tertiary"}
- border border-secondary
- transition-all duration-200
- `}
- >
- <div
- className={`
- p-1.5 rounded bg-light
- ${isUser ? " text-accent" : "text-primary"}
- `}
- >
- {isUser ? <User size={14} /> : <Bot size={14} />}
- </div>
-
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-sm font-semibold text-primary">
- {msg.source}
- </span>
- </div>
-
- <div className="text-sm text-secondary whitespace-pre-wrap">
- {msg.content || ""}
- </div>
-
- {msg.models_usage && (
- <div className="text-xs text-secondary mt-1">
- Tokens:{" "}
- {(msg.models_usage.prompt_tokens || 0) +
- (msg.models_usage.completion_tokens || 0)}
- </div>
- )}
- </div>
- </div>
- </div>
- );
-};
-
-export const ThreadView: React.FC<ThreadViewProps> = ({
- messages = [],
- status,
- reason,
- onCancel,
- runId,
-}) => {
- const scrollRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (scrollRef.current && status === "streaming") {
- scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
- }
- }, [messages, status]);
-
- // const displayMessages = messages.filter(
- // (msg): msg is MessageConfig =>
- // msg && typeof msg.content === "string" && msg.content !== "TERMINATE"
- // );
- const displayMessages = messages;
-
- return (
- <div>
- <div className="space-y-2">
- <StatusBanner
- status={status}
- reason={reason}
- onCancel={onCancel}
- runId={runId}
- />
-
- <div
- ref={scrollRef}
- style={{ maxHeight: "300px" }}
- className="overflow-y-scroll scroll p-2 space-y-2 bg-primary rounded border border-secondary"
- >
- {displayMessages.map((msg, idx) => (
- <Message
- key={idx}
- msg={msg}
- isLast={idx === displayMessages.length - 1}
- />
- ))}
-
- {displayMessages.length === 0 && status !== "streaming" && (
- <div className="text-sm text-secondary text-center p-2">
- No messages to display
- </div>
- )}
- </div>
- </div>
- </div>
- );
-};
-
-export default ThreadView;
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/threadview.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/threadview.tsx
new file mode 100644
index 000000000..3f036e194
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/threadview.tsx
@@ -0,0 +1,67 @@
+import React from "react";
+import { StopCircle } from "lucide-react";
+import { ThreadState } from "./types";
+import { AgentMessageConfig } from "../../../types/datamodel";
+import { RenderMessage } from "./rendermessage";
+
+interface ThreadViewProps {
+ thread: ThreadState;
+ isStreaming: boolean;
+ runId: string;
+ onCancel: (runId: string) => void;
+ threadContainerRef: (el: HTMLDivElement | null) => void;
+}
+
+const ThreadView: React.FC<ThreadViewProps> = ({
+ thread,
+ isStreaming,
+ runId,
+ onCancel,
+ threadContainerRef,
+}) => {
+ return (
+ <div className="mt-2 border border-secondary rounded bg-primary">
+ {/* Status bar - fixed at top */}
+ <div className="sticky top-0 z-10 flex bg-primary rounded-t items-center justify-between p-3 border-b border-secondary bg-secondary/10">
+ <div className="text-sm text-primary">
+ {isStreaming ? (
+ "Agents discussing..."
+ ) : (
+ <>
+ <span className="font-semibold mr-2">Stop Reason</span>
+ {thread.reason}
+ </>
+ )}
+ </div>
+ {isStreaming && (
+ <button
+ onClick={() => onCancel(runId)}
+ className="flex items-center gap-1 px-3 py-1 rounded bg-red-500 hover:bg-red-600 text-white text-xs font-medium transition-colors"
+ >
+ <StopCircle size={12} />
+ <span>Stop</span>
+ </button>
+ )}
+ </div>
+
+ {/* Thread messages and flow visualization in tabs */}
+ <div
+ ref={threadContainerRef}
+ className="max-h-[400px] overflow-y-auto scroll"
+ >
+ <div className="p-3 space-y-3">
+ {thread.messages.map((threadMsg, threadIndex) => (
+ <div key={`thread-${threadIndex}`}>
+ <RenderMessage
+ message={threadMsg}
+ isLast={threadIndex === thread.messages.length - 1}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default ThreadView;
diff --git a/python/packages/autogen-studio/frontend/src/components/views/shared/atoms.tsx b/python/packages/autogen-studio/frontend/src/components/views/shared/atoms.tsx
new file mode 100644
index 000000000..c03099173
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/shared/atoms.tsx
@@ -0,0 +1,8 @@
+import React from "react";
+import { Loader2 } from "lucide-react";
+
+export const LoadingIndicator = ({ size = 16 }: { size: number }) => (
+ <div className="inline-flex items-center gap-2 text-accent mr-2">
+ <Loader2 size={size} className="animate-spin" />
+ </div>
+);
diff --git a/python/packages/autogen-studio/frontend/yarn.lock b/python/packages/autogen-studio/frontend/yarn.lock
index 05fea7543..8aaa3126b 100644
--- a/python/packages/autogen-studio/frontend/yarn.lock
+++ b/python/packages/autogen-studio/frontend/yarn.lock
@@ -1392,6 +1392,18 @@
resolved "https://registry.yarnpkg.com/@ctrl/tinycolor/-/tinycolor-3.6.1.tgz#b6c75a56a1947cc916ea058772d666a2c8932f31"
integrity sha512-SITSV6aIXsuVNV3f3O0f2n/cgyEDWoSqtZMYiAmcsYHydcKrOz3gUxB/iXd/Qf08+IZX4KpgNbvUdMBmWz+kcA==
+"@dagrejs/dagre@^1.1.4":
+ version "1.1.4"
+ resolved "https://registry.yarnpkg.com/@dagrejs/dagre/-/dagre-1.1.4.tgz#66f9c0e2b558308f2c268f60e2c28f22ee17e339"
+ integrity sha512-QUTc54Cg/wvmlEUxB+uvoPVKFazM1H18kVHBQNmK2NbrDR5ihOCR6CXLnDSZzMcSQKJtabPUWridBOlJM3WkDg==
+ dependencies:
+ "@dagrejs/graphlib" "2.2.4"
+
+"@dagrejs/[email protected]":
+ version "2.2.4"
+ resolved "https://registry.yarnpkg.com/@dagrejs/graphlib/-/graphlib-2.2.4.tgz#d77bfa9ff49e2307c0c6e6b8b26b5dd3c05816c4"
+ integrity sha512-mepCf/e9+SKYy1d02/UkvSy6+6MoyXhVxP8lLDfA7BPE1X1d4dR0sZznmbM8/XVJ1GPM+Svnx7Xj6ZweByWUkw==
+
"@emotion/hash@^0.8.0":
version "0.8.0"
resolved "https://registry.yarnpkg.com/@emotion/hash/-/hash-0.8.0.tgz#bbbff68978fefdbe68ccb533bc8cbe1d1afb5413"
@@ -2593,6 +2605,45 @@
dependencies:
"@types/node" "*"
+"@types/d3-color@*":
+ version "3.1.3"
+ resolved "https://registry.yarnpkg.com/@types/d3-color/-/d3-color-3.1.3.tgz#368c961a18de721da8200e80bf3943fb53136af2"
+ integrity sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==
+
+"@types/d3-drag@^3.0.7":
+ version "3.0.7"
+ resolved "https://registry.yarnpkg.com/@types/d3-drag/-/d3-drag-3.0.7.tgz#b13aba8b2442b4068c9a9e6d1d82f8bcea77fc02"
+ integrity sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==
+ dependencies:
+ "@types/d3-selection" "*"
+
+"@types/d3-interpolate@*":
+ version "3.0.4"
+ resolved "https://registry.yarnpkg.com/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz#412b90e84870285f2ff8a846c6eb60344f12a41c"
+ integrity sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==
+ dependencies:
+ "@types/d3-color" "*"
+
+"@types/d3-selection@*", "@types/d3-selection@^3.0.10":
+ version "3.0.11"
+ resolved "https://registry.yarnpkg.com/@types/d3-selection/-/d3-selection-3.0.11.tgz#bd7a45fc0a8c3167a631675e61bc2ca2b058d4a3"
+ integrity sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==
+
+"@types/d3-transition@^3.0.8":
+ version "3.0.9"
+ resolved "https://registry.yarnpkg.com/@types/d3-transition/-/d3-transition-3.0.9.tgz#1136bc57e9ddb3c390dccc9b5ff3b7d2b8d94706"
+ integrity sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==
+ dependencies:
+ "@types/d3-selection" "*"
+
+"@types/d3-zoom@^3.0.8":
+ version "3.0.8"
+ resolved "https://registry.yarnpkg.com/@types/d3-zoom/-/d3-zoom-3.0.8.tgz#dccb32d1c56b1e1c6e0f1180d994896f038bc40b"
+ integrity sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==
+ dependencies:
+ "@types/d3-interpolate" "*"
+ "@types/d3-selection" "*"
+
"@types/debug@^0.0.30":
version "0.0.30"
resolved "https://registry.yarnpkg.com/@types/debug/-/debug-0.0.30.tgz#dc1e40f7af3b9c815013a7860e6252f6352a84df"
@@ -3108,6 +3159,28 @@
resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d"
integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==
+"@xyflow/react@^12.3.5":
+ version "12.3.5"
+ resolved "https://registry.yarnpkg.com/@xyflow/react/-/react-12.3.5.tgz#88ca2efe2ddf1300bc171a2ef797f7cb41386ca4"
+ integrity sha512-wAYqpicdrVo1rxCu0X3M9s3YIF45Agqfabw0IBryTGqjWvr2NyfciI8gIP4MB+NKpWWN5kxZ9tiZ9u8lwC7iAg==
+ dependencies:
+ "@xyflow/system" "0.0.46"
+ classcat "^5.0.3"
+ zustand "^4.4.0"
+
+"@xyflow/[email protected]":
+ version "0.0.46"
+ resolved "https://registry.yarnpkg.com/@xyflow/system/-/system-0.0.46.tgz#b0a5915d59c0ea5ca6d24e1eb90c5a0d7eda7864"
+ integrity sha512-bmFXvboVdiydIFZmDCjrbBCYgB0d5pYdkcZPWbAxGmhMRUZ+kW3CksYgYxWabrw51rwpWitLEadvLrivG0mVfA==
+ dependencies:
+ "@types/d3-drag" "^3.0.7"
+ "@types/d3-selection" "^3.0.10"
+ "@types/d3-transition" "^3.0.8"
+ "@types/d3-zoom" "^3.0.8"
+ d3-drag "^3.0.0"
+ d3-selection "^3.0.0"
+ d3-zoom "^3.0.0"
+
abortcontroller-polyfill@^1.1.9:
version "1.7.5"
resolved "https://registry.yarnpkg.com/abortcontroller-polyfill/-/abortcontroller-polyfill-1.7.5.tgz#6738495f4e901fbb57b6c0611d0c75f76c485bed"
@@ -4193,6 +4266,11 @@ [email protected], ci-info@^2.0.0:
resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46"
integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==
+classcat@^5.0.3:
+ version "5.0.5"
+ resolved "https://registry.yarnpkg.com/classcat/-/classcat-5.0.5.tgz#8c209f359a93ac302404a10161b501eba9c09c77"
+ integrity sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==
+
[email protected], classnames@^2.2.1, classnames@^2.2.3, classnames@^2.2.5, classnames@^2.2.6, classnames@^2.3.1, classnames@^2.3.2, classnames@^2.5.1:
version "2.5.1"
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.5.1.tgz#ba774c614be0f016da105c858e7159eae8e7687b"
@@ -4736,6 +4814,14 @@ csstype@^3.0.2, csstype@^3.0.8, csstype@^3.1.3:
resolved "https://registry.yarnpkg.com/d3-dispatch/-/d3-dispatch-3.0.1.tgz#5fc75284e9c2375c36c839411a0cf550cbfc4d5e"
integrity sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==
+"d3-drag@2 - 3", d3-drag@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/d3-drag/-/d3-drag-3.0.0.tgz#994aae9cd23c719f53b5e10e3a0a6108c69607ba"
+ integrity sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==
+ dependencies:
+ d3-dispatch "1 - 3"
+ d3-selection "3"
+
d3-dsv@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/d3-dsv/-/d3-dsv-3.0.1.tgz#c63af978f4d6a0d084a52a673922be2160789b73"
@@ -4745,6 +4831,11 @@ d3-dsv@^3.0.1:
iconv-lite "0.6"
rw "1"
+"d3-ease@1 - 3":
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/d3-ease/-/d3-ease-3.0.1.tgz#9658ac38a2140d59d346160f1f6c30fda0bd12f4"
+ integrity sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==
+
d3-force@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/d3-force/-/d3-force-3.0.0.tgz#3e2ba1a61e70888fe3d9194e30d6d14eece155c4"
@@ -4796,6 +4887,11 @@ d3-scale-chromatic@^3.0.0:
d3-color "1 - 3"
d3-interpolate "1 - 3"
+"d3-selection@2 - 3", d3-selection@3, d3-selection@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/d3-selection/-/d3-selection-3.0.0.tgz#c25338207efa72cc5b9bd1458a1a41901f1e1b31"
+ integrity sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==
+
d3-shape@^3.2.0:
version "3.2.0"
resolved "https://registry.yarnpkg.com/d3-shape/-/d3-shape-3.2.0.tgz#a1a839cbd9ba45f28674c69d7f855bcf91dfc6a5"
@@ -4808,6 +4904,28 @@ d3-shape@^3.2.0:
resolved "https://registry.yarnpkg.com/d3-timer/-/d3-timer-3.0.1.tgz#6284d2a2708285b1abb7e201eda4380af35e63b0"
integrity sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==
+"d3-transition@2 - 3":
+ version "3.0.1"
+ resolved "https://registry.yarnpkg.com/d3-transition/-/d3-transition-3.0.1.tgz#6869fdde1448868077fdd5989200cb61b2a1645f"
+ integrity sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==
+ dependencies:
+ d3-color "1 - 3"
+ d3-dispatch "1 - 3"
+ d3-ease "1 - 3"
+ d3-interpolate "1 - 3"
+ d3-timer "1 - 3"
+
+d3-zoom@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/d3-zoom/-/d3-zoom-3.0.0.tgz#d13f4165c73217ffeaa54295cd6969b3e7aee8f3"
+ integrity sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==
+ dependencies:
+ d3-dispatch "1 - 3"
+ d3-drag "2 - 3"
+ d3-interpolate "1 - 3"
+ d3-selection "2 - 3"
+ d3-transition "2 - 3"
+
d@1, d@^1.0.1, d@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/d/-/d-1.0.2.tgz#2aefd554b81981e7dccf72d6842ae725cb17e5de"
@@ -12977,6 +13095,11 @@ url-loader@^4.1.1:
mime-types "^2.1.27"
schema-utils "^3.0.0"
+ version "1.2.2"
+ resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.2.2.tgz#c3b6390f3a30eba13200d2302dcdf1e7b57b2ef9"
+ integrity sha512-PElTlVMwpblvbNqQ82d2n6RjStvdSoNe9FG28kNfz3WiXilJm4DdNkEzRhCZuIDwY8U08WVihhGR5iRqAwfDiw==
+
util-deprecate@^1.0.1, util-deprecate@^1.0.2, util-deprecate@~1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
@@ -13444,6 +13567,13 @@ yurnalist@^2.1.0:
read "^1.0.7"
strip-ansi "^5.2.0"
+zustand@^4.4.0:
+ version "4.5.5"
+ resolved "https://registry.yarnpkg.com/zustand/-/zustand-4.5.5.tgz#f8c713041543715ec81a2adda0610e1dc82d4ad1"
+ integrity sha512-+0PALYNJNgK6hldkgDq2vLrw5f6g/jCInz52n9RTpropGgeAf/ioFUCdtsjCqu4gNhW9D01rUQBROoRjdzyn2Q==
+ dependencies:
+ use-sync-external-store "1.2.2"
+
zustand@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/zustand/-/zustand-5.0.1.tgz#2bdca5e4be172539558ce3974fe783174a48fdcf"
diff --git a/python/packages/autogen-studio/notebooks/tutorial.ipynb b/python/packages/autogen-studio/notebooks/tutorial.ipynb
index 31561e5be..4825d6580 100644
--- a/python/packages/autogen-studio/notebooks/tutorial.ipynb
+++ b/python/packages/autogen-studio/notebooks/tutorial.ipynb
@@ -234,6 +234,83 @@
"all_teams = dbmanager.get(Team)\n",
"print(len(all_teams.data), \"teams in database\")"
]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from autogen_agentchat.agents import AssistantAgent\n",
+ "from autogen_agentchat.task import TextMentionTermination\n",
+ "from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat\n",
+ "from autogen_ext.models import OpenAIChatCompletionClient \n",
+ "\n",
+ "planner_agent = AssistantAgent(\n",
+ " \"planner_agent\",\n",
+ " model_client=OpenAIChatCompletionClient(model=\"gpt-4\"),\n",
+ " description=\"A helpful assistant that can plan trips.\",\n",
+ " system_message=\"You are a helpful assistant that can suggest a travel plan for a user based on their request.\",\n",
+ ")\n",
+ "\n",
+ "local_agent = AssistantAgent(\n",
+ " \"local_agent\",\n",
+ " model_client=OpenAIChatCompletionClient(model=\"gpt-4\"),\n",
+ " description=\"A local assistant that can suggest local activities or places to visit.\",\n",
+ " system_message=\"You are a helpful assistant that can suggest authentic and interesting local activities or places to visit for a user and can utilize any context information provided.\",\n",
+ ")\n",
+ "\n",
+ "language_agent = AssistantAgent(\n",
+ " \"language_agent\",\n",
+ " model_client=OpenAIChatCompletionClient(model=\"gpt-4\"),\n",
+ " description=\"A helpful assistant that can provide language tips for a given destination.\",\n",
+ " system_message=\"You are a helpful assistant that can review travel plans, providing feedback on important/critical tips about how best to address language or communication challenges for the given destination. If the plan already includes language tips, you can mention that the plan is satisfactory, with rationale.\",\n",
+ ")\n",
+ "\n",
+ "travel_summary_agent = AssistantAgent(\n",
+ " \"travel_summary_agent\",\n",
+ " model_client=OpenAIChatCompletionClient(model=\"gpt-4\"),\n",
+ " description=\"A helpful assistant that can summarize the travel plan.\",\n",
+ " system_message=\"You are a helpful assistant that can take in all of the suggestions and advice from the other agents and provide a detailed tfinal travel plan. You must ensure th b at the final plan is integrated and complete. YOUR FINAL RESPONSE MUST BE THE COMPLETE PLAN. When the plan is complete and all perspectives are integrated, you can respond with TERMINATE.\",\n",
+ ")\n",
+ "\n",
+ "termination = TextMentionTermination(\"TERMINATE\")\n",
+ "group_chat = RoundRobinGroupChat(\n",
+ " [planner_agent, local_agent, language_agent, travel_summary_agent], termination_condition=termination\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "source='user' models_usage=None content='Plan a 3 day trip to Nepal.'\n",
+ "source='planner_agent' models_usage=RequestUsage(prompt_tokens=40, completion_tokens=394) content=\"Sure, here is a simple 3-day itinerary for a trip to Nepal:\\n\\n**Day 1: Explore Kathmandu:**\\n\\n- Morning: Arrival in Tribhuvan International Airport. Take an airport taxi to your hotel in Thamel area – the touristic heart of Kathmandu. Freshen up after your journey.\\n\\n- Afternoon: Visit the historical and cultural hub - Kathmandu Durbar Square. This square is a complex of palaces, courtyards and temples. You can enjoy vibrant local life and activities around the square.\\n\\n- Evening: You can explore lots of shops, cafes and restaurants in the Thamel. Experience local food and artisanal delicacies.\\n\\n**Day 2: Visit Bhaktapur and Nagarkot:**\\n\\n- Morning/Early Afternoon: Take a short ride to Bhaktapur city. Visit sites like Bhaktapur Durbar Square, Nyatapola Temple and Bhaktapur National Art Gallery.\\n\\n- Afternoon/Evening: Travel to Nagarkot. If the weather is clear, this place offers great panoramic views of the Himalayan range including Mount Everest during sunset. It's also quite known for hiking so make sure to check out the trails if you're into that.\\n\\n**Day 3: Experience Patan and Return to Kathmandu:**\\n\\n- Morning: Travel back towards Patan, another royal city of Nepal. Visit the Patan Museum, Golden Temple and the Patan Durbar Square.\\n\\n- Afternoon: Return to Kathmandu and wrap up your trip by visiting a few more sites like Swayambhunath Stupa and Pashupatinath Temple.\\n\\n- Evening: Check out any last minute souvenirs from local markets and try some local Nepalese cuisine. \\n\\nPlease ensure to check travel advisories and any necessary travel documentations before your trip. It's also important to make arrangement for proper accommodation and transportation in advance of your trip.\\n\"\n",
+ "source='local_agent' models_usage=RequestUsage(prompt_tokens=451, completion_tokens=394) content=\"Sure, here is a simple 3-day itinerary for a trip to Nepal:\\n\\n**Day 1: Explore Kathmandu:**\\n\\n- Morning: Arrival in Tribhuvan International Airport. Take an airport taxi to your hotel in Thamel area – the touristic heart of Kathmandu. Freshen up after your journey.\\n\\n- Afternoon: Visit the historical and cultural hub - Kathmandu Durbar Square. This square is a complex of palaces, courtyards and temples. You can enjoy vibrant local life and activities around the square.\\n\\n- Evening: You can explore lots of shops, cafes and restaurants in the Thamel. Experience local food and artisanal delicacies.\\n\\n**Day 2: Visit Bhaktapur and Nagarkot:**\\n\\n- Morning/Early Afternoon: Take a short ride to Bhaktapur city. Visit sites like Bhaktapur Durbar Square, Nyatapola Temple and Bhaktapur National Art Gallery.\\n\\n- Afternoon/Evening: Travel to Nagarkot. If the weather is clear, this place offers great panoramic views of the Himalayan range including Mount Everest during sunset. It's also quite known for hiking so make sure to check out the trails if you're into that.\\n\\n**Day 3: Experience Patan and Return to Kathmandu:**\\n\\n- Morning: Travel back towards Patan, another royal city of Nepal. Visit the Patan Museum, Golden Temple and the Patan Durbar Square.\\n\\n- Afternoon: Return to Kathmandu and wrap up your trip by visiting a few more sites like Swayambhunath Stupa and Pashupatinath Temple.\\n\\n- Evening: Check out any last minute souvenirs from local markets and try some local Nepalese cuisine. \\n\\nPlease ensure to check travel advisories and any necessary travel documentations before your trip. It's also important to make arrangement for proper accommodation and transportation in advance of your trip.\"\n",
+ "source='language_agent' models_usage=RequestUsage(prompt_tokens=876, completion_tokens=246) content=\"Your travel itinerary seems to be well designed and comprehensive. However, communication and language fluency can significantly impact your travel experience. Here are some essential tips on this topic:\\n\\n1. The official language of Nepal is Nepali, but English is understood by a significant portion of the population in urban areas and tourist spots. Nevertheless, it can be helpful if you learn some basic Nepali phrases such as greetings, thanking, apologizing, and expressing urgency.\\n\\n2. Download a translator app on your phone like Google Translate in case you encounter someone who only speaks Nepali or for translating signs and menus.\\n\\n3. Be mindful of cultural sensitivities when communicating. Nepalese people are generally very friendly and hospitable, but it's important to respect their traditions and culture. Avoid criticism and negative comments about their culture and religion.\\n\\n4. Guide books, travel blogs, and forums can offer insights and useful phrases in Nepali that can enhance your interaction with locals.\\n\\n5. If you prefer, you may hire a local tour guide who can communicate in English to assist you, especially in rural areas.\\n\\nFeel free to modify your plan as per your preferences and ensure that you are well-prepared to handle communication challenges to have a seamless experience.\"\n",
+ "source='travel_summary_agent' models_usage=RequestUsage(prompt_tokens=1146, completion_tokens=484) content=\"Here is the final integrated 3-day travel plan for your trip to Nepal:\\n\\n**Day 1: Explore Kathmandu:**\\n\\n- Morning: Arrival in Tribhuvan International Airport. Take an airport taxi to your hotel in the Thamel area – the touristic heart of Kathmandu. Freshen up after your journey.\\n\\n- Afternoon: Visit the historic Kathmandu Durbar Square, a complex of palaces, courtyards and temples where you can enjoy vibrant local life and activities.\\n\\n- Evening: Wander around the Thamel district, checking out the array of shops, cafes and restaurants. Try local food and artisanal delicacies.\\n\\n**Day 2: Immerse in Bhaktapur and Relax in Nagarkot:**\\n\\n- Morning/Early Afternoon: Take a short trip to Bhaktapur, a culturally rich city known for its preserved palace courtyards and old city center. Visit sites like Bhaktapur Durbar Square, Nyatapola Temple, and Bhaktapur National Art Gallery.\\n\\n- Late Afternoon/Evening: Travel to Nagarkot, known for its stunning Himalayan views, including Mount Everest during clear weather. Consider going hiking if you're into outdoor activities.\\n\\n**Day 3: Experience Patan and Return to Kathmandu:**\\n\\n- Morning: Travel back towards Patan, another royal city of Nepal. Visit the Patan Museum, Golden Temple, and the Patan Durbar Square.\\n\\n- Afternoon: Return to Kathmandu and wrap up your trip by visiting the Swayambhunath Stupa and Pashupatinath Temple.\\n\\n- Evening: Explore local markets for last minute souvenirs and sample more of the delicious local Nepalese cuisine. \\n\\n_Note on communication:_ Although English is understood in urban areas and major tourist spots, learning a few basic Nepali phrases can help you during your travels. Be mindful of cultural sensitivities, and consider downloading a translation app.\\n\\nIt's also important to secure accommodations in advance, comply with travel document requirements and check travel advisories before your trip. If you want more seamless communication, especially in rural areas, consider hiring a local English-speaking tour guide. \\n\\nYou are now all set for a memorable journey to Nepal. Use this plan as a guideline and feel free to modify it to better suit your preferences and schedule. Safe travels!\\n\\nTERMINATE\"\n",
+ "TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Plan a 3 day trip to Nepal.'), TextMessage(source='planner_agent', models_usage=RequestUsage(prompt_tokens=40, completion_tokens=394), content=\"Sure, here is a simple 3-day itinerary for a trip to Nepal:\\n\\n**Day 1: Explore Kathmandu:**\\n\\n- Morning: Arrival in Tribhuvan International Airport. Take an airport taxi to your hotel in Thamel area – the touristic heart of Kathmandu. Freshen up after your journey.\\n\\n- Afternoon: Visit the historical and cultural hub - Kathmandu Durbar Square. This square is a complex of palaces, courtyards and temples. You can enjoy vibrant local life and activities around the square.\\n\\n- Evening: You can explore lots of shops, cafes and restaurants in the Thamel. Experience local food and artisanal delicacies.\\n\\n**Day 2: Visit Bhaktapur and Nagarkot:**\\n\\n- Morning/Early Afternoon: Take a short ride to Bhaktapur city. Visit sites like Bhaktapur Durbar Square, Nyatapola Temple and Bhaktapur National Art Gallery.\\n\\n- Afternoon/Evening: Travel to Nagarkot. If the weather is clear, this place offers great panoramic views of the Himalayan range including Mount Everest during sunset. It's also quite known for hiking so make sure to check out the trails if you're into that.\\n\\n**Day 3: Experience Patan and Return to Kathmandu:**\\n\\n- Morning: Travel back towards Patan, another royal city of Nepal. Visit the Patan Museum, Golden Temple and the Patan Durbar Square.\\n\\n- Afternoon: Return to Kathmandu and wrap up your trip by visiting a few more sites like Swayambhunath Stupa and Pashupatinath Temple.\\n\\n- Evening: Check out any last minute souvenirs from local markets and try some local Nepalese cuisine. \\n\\nPlease ensure to check travel advisories and any necessary travel documentations before your trip. It's also important to make arrangement for proper accommodation and transportation in advance of your trip.\\n\"), TextMessage(source='local_agent', models_usage=RequestUsage(prompt_tokens=451, completion_tokens=394), content=\"Sure, here is a simple 3-day itinerary for a trip to Nepal:\\n\\n**Day 1: Explore Kathmandu:**\\n\\n- Morning: Arrival in Tribhuvan International Airport. Take an airport taxi to your hotel in Thamel area – the touristic heart of Kathmandu. Freshen up after your journey.\\n\\n- Afternoon: Visit the historical and cultural hub - Kathmandu Durbar Square. This square is a complex of palaces, courtyards and temples. You can enjoy vibrant local life and activities around the square.\\n\\n- Evening: You can explore lots of shops, cafes and restaurants in the Thamel. Experience local food and artisanal delicacies.\\n\\n**Day 2: Visit Bhaktapur and Nagarkot:**\\n\\n- Morning/Early Afternoon: Take a short ride to Bhaktapur city. Visit sites like Bhaktapur Durbar Square, Nyatapola Temple and Bhaktapur National Art Gallery.\\n\\n- Afternoon/Evening: Travel to Nagarkot. If the weather is clear, this place offers great panoramic views of the Himalayan range including Mount Everest during sunset. It's also quite known for hiking so make sure to check out the trails if you're into that.\\n\\n**Day 3: Experience Patan and Return to Kathmandu:**\\n\\n- Morning: Travel back towards Patan, another royal city of Nepal. Visit the Patan Museum, Golden Temple and the Patan Durbar Square.\\n\\n- Afternoon: Return to Kathmandu and wrap up your trip by visiting a few more sites like Swayambhunath Stupa and Pashupatinath Temple.\\n\\n- Evening: Check out any last minute souvenirs from local markets and try some local Nepalese cuisine. \\n\\nPlease ensure to check travel advisories and any necessary travel documentations before your trip. It's also important to make arrangement for proper accommodation and transportation in advance of your trip.\"), TextMessage(source='language_agent', models_usage=RequestUsage(prompt_tokens=876, completion_tokens=246), content=\"Your travel itinerary seems to be well designed and comprehensive. However, communication and language fluency can significantly impact your travel experience. Here are some essential tips on this topic:\\n\\n1. The official language of Nepal is Nepali, but English is understood by a significant portion of the population in urban areas and tourist spots. Nevertheless, it can be helpful if you learn some basic Nepali phrases such as greetings, thanking, apologizing, and expressing urgency.\\n\\n2. Download a translator app on your phone like Google Translate in case you encounter someone who only speaks Nepali or for translating signs and menus.\\n\\n3. Be mindful of cultural sensitivities when communicating. Nepalese people are generally very friendly and hospitable, but it's important to respect their traditions and culture. Avoid criticism and negative comments about their culture and religion.\\n\\n4. Guide books, travel blogs, and forums can offer insights and useful phrases in Nepali that can enhance your interaction with locals.\\n\\n5. If you prefer, you may hire a local tour guide who can communicate in English to assist you, especially in rural areas.\\n\\nFeel free to modify your plan as per your preferences and ensure that you are well-prepared to handle communication challenges to have a seamless experience.\"), TextMessage(source='travel_summary_agent', models_usage=RequestUsage(prompt_tokens=1146, completion_tokens=484), content=\"Here is the final integrated 3-day travel plan for your trip to Nepal:\\n\\n**Day 1: Explore Kathmandu:**\\n\\n- Morning: Arrival in Tribhuvan International Airport. Take an airport taxi to your hotel in the Thamel area – the touristic heart of Kathmandu. Freshen up after your journey.\\n\\n- Afternoon: Visit the historic Kathmandu Durbar Square, a complex of palaces, courtyards and temples where you can enjoy vibrant local life and activities.\\n\\n- Evening: Wander around the Thamel district, checking out the array of shops, cafes and restaurants. Try local food and artisanal delicacies.\\n\\n**Day 2: Immerse in Bhaktapur and Relax in Nagarkot:**\\n\\n- Morning/Early Afternoon: Take a short trip to Bhaktapur, a culturally rich city known for its preserved palace courtyards and old city center. Visit sites like Bhaktapur Durbar Square, Nyatapola Temple, and Bhaktapur National Art Gallery.\\n\\n- Late Afternoon/Evening: Travel to Nagarkot, known for its stunning Himalayan views, including Mount Everest during clear weather. Consider going hiking if you're into outdoor activities.\\n\\n**Day 3: Experience Patan and Return to Kathmandu:**\\n\\n- Morning: Travel back towards Patan, another royal city of Nepal. Visit the Patan Museum, Golden Temple, and the Patan Durbar Square.\\n\\n- Afternoon: Return to Kathmandu and wrap up your trip by visiting the Swayambhunath Stupa and Pashupatinath Temple.\\n\\n- Evening: Explore local markets for last minute souvenirs and sample more of the delicious local Nepalese cuisine. \\n\\n_Note on communication:_ Although English is understood in urban areas and major tourist spots, learning a few basic Nepali phrases can help you during your travels. Be mindful of cultural sensitivities, and consider downloading a translation app.\\n\\nIt's also important to secure accommodations in advance, comply with travel document requirements and check travel advisories before your trip. If you want more seamless communication, especially in rural areas, consider hiring a local English-speaking tour guide. \\n\\nYou are now all set for a memorable journey to Nepal. Use this plan as a guideline and feel free to modify it to better suit your preferences and schedule. Safe travels!\\n\\nTERMINATE\")], stop_reason=\"Text 'TERMINATE' mentioned\")\n"
+ ]
+ }
+ ],
+ "source": [
+ "\n",
+ "result = group_chat.run_stream(task=\"Plan a 3 day trip to Nepal.\")\n",
+ "async for response in result:\n",
+ " print(response) "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {