Conversation!!!! With Agents as participants

This commit is contained in:
Mahesh Kommareddi 2024-07-17 03:43:55 -04:00
parent a355bf3183
commit e0b542d243
26 changed files with 388 additions and 152 deletions

View File

@ -2,13 +2,15 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { connectWebSocket, subscribeToTopic } from './services/websocket'; import { connectWebSocket, subscribeToTopic } from './services/websocket';
import AgentNetworkGraph from './components/AgentNetworkGraph'; import AgentNetworkGraph from './components/AgentNetworkGraph';
import ConversationStateDiagram from './components/ConversationStateDiagram'; import ConversationDisplay from './components/ConversationDisplay';
import TaskProgressIndicator from './components/TaskProgressIndicator'; import TaskProgressIndicator from './components/TaskProgressIndicator';
import TreeOfThoughtVisual from './components/TreeOfThoughtVisual'; import TreeOfThoughtVisual from './components/TreeOfThoughtVisual';
function App() { function App() {
const [agentNetwork, setAgentNetwork] = useState(null); const [agentNetwork, setAgentNetwork] = useState(null);
const [conversationState, setConversationState] = useState({ currentState: '', possibleTransitions: [] }); const [conversationState, setConversationState] = useState({ currentState: '', possibleTransitions: [] });
const [conversationMessages, setConversationMessages] = useState([]);
const [conversationParticipants, setConversationParticipants] = useState([]);
const [taskProgress, setTaskProgress] = useState({ taskId: '', status: '', progressPercentage: 0 }); const [taskProgress, setTaskProgress] = useState({ taskId: '', status: '', progressPercentage: 0 });
const [treeOfThought, setTreeOfThought] = useState(null); const [treeOfThought, setTreeOfThought] = useState(null);
@ -16,6 +18,8 @@ function App() {
connectWebSocket(() => { connectWebSocket(() => {
subscribeToTopic('agent_network', setAgentNetwork); subscribeToTopic('agent_network', setAgentNetwork);
subscribeToTopic('conversation_state', setConversationState); subscribeToTopic('conversation_state', setConversationState);
subscribeToTopic('conversation_message', (message) => setConversationMessages(prev => [...prev, message]));
subscribeToTopic('conversation_participants', setConversationParticipants);
subscribeToTopic('task_progress', setTaskProgress); subscribeToTopic('task_progress', setTaskProgress);
subscribeToTopic('tree_of_thought', setTreeOfThought); subscribeToTopic('tree_of_thought', setTreeOfThought);
}); });
@ -29,10 +33,10 @@ function App() {
{agentNetwork && <AgentNetworkGraph data={agentNetwork} />} {agentNetwork && <AgentNetworkGraph data={agentNetwork} />}
</div> </div>
<div> <div>
<h2>Conversation State</h2> <h2>Conversation</h2>
<ConversationStateDiagram <ConversationDisplay
currentState={conversationState.currentState} messages={conversationMessages}
possibleTransitions={conversationState.possibleTransitions} participants={conversationParticipants}
/> />
</div> </div>
<div> <div>

View File

@ -0,0 +1,27 @@
// src/components/ConversationDisplay.js
import React from 'react';
const ConversationDisplay = ({ messages, participants }) => {
return (
<div className="conversation-display">
<h3>Conversation</h3>
<div className="participants">
<h4>Participants:</h4>
<ul>
{participants.map((participant, index) => (
<li key={index}>{participant.name}</li>
))}
</ul>
</div>
<div className="messages">
{messages.map((message, index) => (
<div key={index} className="message">
<strong>{message.sender}:</strong> {message.content}
</div>
))}
</div>
</div>
);
};
export default ConversationDisplay;

View File

@ -2,6 +2,7 @@ package com.ioa;
import com.ioa.agent.AgentInfo; import com.ioa.agent.AgentInfo;
import com.ioa.agent.AgentRegistry; import com.ioa.agent.AgentRegistry;
import com.ioa.conversation.ConversationManager;
import com.ioa.task.Task; import com.ioa.task.Task;
import com.ioa.task.TaskManager; import com.ioa.task.TaskManager;
import com.ioa.team.TeamFormation; import com.ioa.team.TeamFormation;
@ -29,6 +30,11 @@ public class IoASystem {
return new WebSocketService(messagingTemplate); return new WebSocketService(messagingTemplate);
} }
@Bean
public ConversationManager conversationManager(BedrockLanguageModel model, WebSocketService webSocketService) {
return new ConversationManager(model, webSocketService);
}
@Bean @Bean
public BedrockLanguageModel bedrockLanguageModel() { public BedrockLanguageModel bedrockLanguageModel() {
return new BedrockLanguageModel("anthropic.claude-3-sonnet-20240229-v1:0"); return new BedrockLanguageModel("anthropic.claude-3-sonnet-20240229-v1:0");
@ -40,17 +46,17 @@ public class IoASystem {
} }
@Bean @Bean
public AgentRegistry agentRegistry(ToolRegistry toolRegistry, TreeOfThought treeOfThought, WebSocketService webSocketService) { public AgentRegistry agentRegistry(ToolRegistry toolRegistry, TreeOfThought treeOfThought, WebSocketService webSocketService, ConversationManager conversationManager) {
AgentRegistry registry = new AgentRegistry(toolRegistry); AgentRegistry registry = new AgentRegistry(toolRegistry);
// Other agent creation code // Agent creation is now moved to processTasksAndAgents method
return registry; return registry;
} }
@Bean @Bean
public TaskManager taskManager(AgentRegistry agentRegistry, BedrockLanguageModel model, ToolRegistry toolRegistry, TreeOfThought treeOfThought) { public TaskManager taskManager(AgentRegistry agentRegistry, BedrockLanguageModel model, ToolRegistry toolRegistry, TreeOfThought treeOfThought, ConversationManager conversationManager) {
return new TaskManager(agentRegistry, model, toolRegistry, treeOfThought); return new TaskManager(agentRegistry, model, toolRegistry, treeOfThought, conversationManager);
} }
@Bean @Bean
@ -58,12 +64,6 @@ public class IoASystem {
return new TeamFormation(agentRegistry, treeOfThought, webSocketService, model); return new TeamFormation(agentRegistry, treeOfThought, webSocketService, model);
} }
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(IoASystem.class, args);
IoASystem system = context.getBean(IoASystem.class);
system.processTasksAndAgents(context);
}
@Bean @Bean
public ToolRegistry toolRegistry() { public ToolRegistry toolRegistry() {
ToolRegistry toolRegistry = new ToolRegistry(); ToolRegistry toolRegistry = new ToolRegistry();
@ -87,6 +87,12 @@ public class IoASystem {
return toolRegistry; return toolRegistry;
} }
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(IoASystem.class, args);
IoASystem system = context.getBean(IoASystem.class);
system.processTasksAndAgents(context);
}
public void processTasksAndAgents(ConfigurableApplicationContext context) { public void processTasksAndAgents(ConfigurableApplicationContext context) {
AgentRegistry agentRegistry = context.getBean(AgentRegistry.class); AgentRegistry agentRegistry = context.getBean(AgentRegistry.class);
TeamFormation teamFormation = context.getBean(TeamFormation.class); TeamFormation teamFormation = context.getBean(TeamFormation.class);
@ -94,36 +100,37 @@ public class IoASystem {
TreeOfThought treeOfThought = context.getBean(TreeOfThought.class); TreeOfThought treeOfThought = context.getBean(TreeOfThought.class);
WebSocketService webSocketService = context.getBean(WebSocketService.class); WebSocketService webSocketService = context.getBean(WebSocketService.class);
ToolRegistry toolRegistry = context.getBean(ToolRegistry.class); ToolRegistry toolRegistry = context.getBean(ToolRegistry.class);
ConversationManager conversationManager = context.getBean(ConversationManager.class);
// Register all agents // Register all agents
agentRegistry.registerAgent("agent1", new AgentInfo("agent1", "General Assistant", agentRegistry.registerAgent("agent1", new AgentInfo("agent1", "General Assistant",
Arrays.asList("general", "search"), Arrays.asList("general", "search"),
Arrays.asList("webSearch", "getWeather", "setReminder"), Arrays.asList("webSearch", "getWeather", "setReminder"),
treeOfThought, webSocketService, toolRegistry)); treeOfThought, webSocketService, toolRegistry, conversationManager));
agentRegistry.registerAgent("agent2", new AgentInfo("agent2", "Travel Expert", agentRegistry.registerAgent("agent2", new AgentInfo("agent2", "Travel Expert",
Arrays.asList("travel", "booking"), Arrays.asList("travel", "booking"),
Arrays.asList("bookTravel", "calculateDistance", "findRestaurants"), Arrays.asList("bookTravel", "calculateDistance", "findRestaurants"),
treeOfThought, webSocketService, toolRegistry)); treeOfThought, webSocketService, toolRegistry, conversationManager));
agentRegistry.registerAgent("agent3", new AgentInfo("agent3", "Event Planner Extraordinaire", agentRegistry.registerAgent("agent3", new AgentInfo("agent3", "Event Planner Extraordinaire",
Arrays.asList("event planning", "team management", "booking"), Arrays.asList("event planning", "team management", "booking"),
Arrays.asList("findRestaurants", "bookTravel", "scheduleAppointment", "getWeather"), Arrays.asList("findRestaurants", "bookTravel", "scheduleAppointment", "getWeather"),
treeOfThought, webSocketService, toolRegistry)); treeOfThought, webSocketService, toolRegistry, conversationManager));
agentRegistry.registerAgent("agent4", new AgentInfo("agent4", "Fitness Guru", agentRegistry.registerAgent("agent4", new AgentInfo("agent4", "Fitness Guru",
Arrays.asList("health", "nutrition", "motivation"), Arrays.asList("health", "nutrition", "motivation"),
Arrays.asList("findFitnessClasses", "getRecipe", "setReminder", "getWeather"), Arrays.asList("findFitnessClasses", "getRecipe", "setReminder", "getWeather"),
treeOfThought, webSocketService, toolRegistry)); treeOfThought, webSocketService, toolRegistry, conversationManager));
agentRegistry.registerAgent("agent5", new AgentInfo("agent5", "Research Specialist", agentRegistry.registerAgent("agent5", new AgentInfo("agent5", "Research Specialist",
Arrays.asList("research", "writing", "analysis"), Arrays.asList("research", "writing", "analysis"),
Arrays.asList("webSearch", "getNewsUpdates", "translate", "compareProductPrices"), Arrays.asList("webSearch", "getNewsUpdates", "translate", "compareProductPrices"),
treeOfThought, webSocketService, toolRegistry)); treeOfThought, webSocketService, toolRegistry, conversationManager));
agentRegistry.registerAgent("agent6", new AgentInfo("agent6", "Digital Marketing Expert", agentRegistry.registerAgent("agent6", new AgentInfo("agent6", "Digital Marketing Expert",
Arrays.asList("marketing", "social media", "content creation"), Arrays.asList("marketing", "social media", "content creation"),
Arrays.asList("webSearch", "getNewsUpdates", "scheduleAppointment", "getMovieRecommendations"), Arrays.asList("webSearch", "getNewsUpdates", "scheduleAppointment", "getMovieRecommendations"),
treeOfThought, webSocketService, toolRegistry)); treeOfThought, webSocketService, toolRegistry, conversationManager));
agentRegistry.registerAgent("agent7", new AgentInfo("agent7", "Family Travel Coordinator", agentRegistry.registerAgent("agent7", new AgentInfo("agent7", "Family Travel Coordinator",
Arrays.asList("travel", "family planning", "budgeting"), Arrays.asList("travel", "family planning", "budgeting"),
Arrays.asList("bookTravel", "calculateDistance", "getWeather", "findRestaurants", "getFinancialAdvice"), Arrays.asList("bookTravel", "calculateDistance", "getWeather", "findRestaurants", "getFinancialAdvice"),
treeOfThought, webSocketService, toolRegistry)); treeOfThought, webSocketService, toolRegistry, conversationManager));
// Create all tasks // Create all tasks
List<Task> tasks = Arrays.asList( List<Task> tasks = Arrays.asList(
@ -174,14 +181,35 @@ public class IoASystem {
System.out.println("Formed team: " + team); System.out.println("Formed team: " + team);
if (!team.isEmpty()) { if (!team.isEmpty()) {
// Create a conversation for the team
String conversationId = conversationManager.createConversation();
// Add team members to the conversation
for (AgentInfo agent : team) {
conversationManager.addParticipant(conversationId, agent);
}
// Assign the task to all team members // Assign the task to all team members
for (AgentInfo agent : team) { for (AgentInfo agent : team) {
Task agentTask = new Task(task.getId() + "_" + agent.getId(), task.getDescription(), task.getRequiredCapabilities(), task.getRequiredTools()); Task agentTask = new Task(task.getId() + "_" + agent.getId(), task.getDescription(), task.getRequiredCapabilities(), task.getRequiredTools());
agentTask.setAssignedAgent(agent); agentTask.setAssignedAgent(agent);
taskManager.addTask(agentTask); taskManager.addTask(agentTask);
taskManager.executeTask(agentTask.getId()); taskManager.executeTask(agentTask.getId(), conversationId);
System.out.println("Task result for " + agent.getId() + ": " + agentTask.getResult());
} }
// Start the conversation
conversationManager.startConversation(conversationId, "Let's work on the task: " + task.getDescription());
// Wait for the conversation to finish (you might want to implement a more sophisticated mechanism)
try {
Thread.sleep(30000); // Wait for 30 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
// Get the result
String result = conversationManager.getConversationResult(conversationId);
System.out.println("Task result: " + result);
} else { } else {
System.out.println("No suitable agents found for this task. Consider updating the agent pool or revising the task requirements."); System.out.println("No suitable agents found for this task. Consider updating the agent pool or revising the task requirements.");
} }

View File

@ -1,10 +1,15 @@
package com.ioa.agent; package com.ioa.agent;
import com.ioa.conversation.Message;
import com.ioa.util.TreeOfThought; import com.ioa.util.TreeOfThought;
import com.ioa.service.WebSocketService; import com.ioa.service.WebSocketService;
import com.ioa.tool.ToolRegistry; import com.ioa.tool.ToolRegistry;
import com.ioa.conversation.ConversationFSM;
import com.ioa.conversation.ConversationManager;
import java.util.*; import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class AgentInfo { public class AgentInfo {
private String id; private String id;
@ -14,9 +19,11 @@ public class AgentInfo {
private TreeOfThought treeOfThought; private TreeOfThought treeOfThought;
private WebSocketService webSocketService; private WebSocketService webSocketService;
private ToolRegistry toolRegistry; private ToolRegistry toolRegistry;
private final ConversationManager conversationManager;
public AgentInfo(String id, String name, List<String> capabilities, List<String> tools, public AgentInfo(String id, String name, List<String> capabilities, List<String> tools,
TreeOfThought treeOfThought, WebSocketService webSocketService, ToolRegistry toolRegistry) { TreeOfThought treeOfThought, WebSocketService webSocketService,
ToolRegistry toolRegistry, ConversationManager conversationManager) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.capabilities = capabilities; this.capabilities = capabilities;
@ -24,6 +31,19 @@ public AgentInfo(String id, String name, List<String> capabilities, List<String>
this.treeOfThought = treeOfThought; this.treeOfThought = treeOfThought;
this.webSocketService = webSocketService; this.webSocketService = webSocketService;
this.toolRegistry = toolRegistry; this.toolRegistry = toolRegistry;
this.conversationManager = conversationManager;
}
public void sendMessage(String conversationId, String content) {
conversationManager.postMessage(conversationId, this.id, content);
}
public void receiveMessage(Message message) {
// Process the received message
Map<String, Object> reasoningResult = treeOfThought.reason("Respond to message: " + message.getContent(), 2, 2);
String response = (String) reasoningResult.get("response"); // Assuming the response is stored under the key "response"
// Send the response back to the conversation
sendMessage(message.getConversationId(), response);
} }
public List<String> getCapabilities() { public List<String> getCapabilities() {
@ -98,4 +118,8 @@ public AgentInfo(String id, String name, List<String> capabilities, List<String>
return result; return result;
} }
public void voteToFinish(String conversationId) {
conversationManager.postMessage(conversationId, this.id, "/vote");
}
} }

View File

@ -1,26 +1,72 @@
package com.ioa.conversation; package com.ioa.conversation;
import java.util.stream.Collectors;
import com.ioa.agent.AgentInfo;
import com.ioa.model.BedrockLanguageModel; import com.ioa.model.BedrockLanguageModel;
import com.ioa.service.WebSocketService; import com.ioa.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
@Component @Component
public class ConversationFSM { public class ConversationFSM {
private ConversationState currentState; private ConversationState currentState;
private BedrockLanguageModel model; private final BedrockLanguageModel model;
private final WebSocketService webSocketService;
private final Queue<Message> messageQueue;
private final List<AgentInfo> participants;
private final Map<String, Boolean> votes;
private final AtomicBoolean finished;
private String result;
private final ScheduledExecutorService executorService;
@Autowired public ConversationFSM(BedrockLanguageModel model, WebSocketService webSocketService) {
private WebSocketService webSocketService; this.executorService = Executors.newScheduledThreadPool(1);
public ConversationFSM(BedrockLanguageModel model) {
this.currentState = ConversationState.DISCUSSION; this.currentState = ConversationState.DISCUSSION;
this.model = model; this.model = model;
this.webSocketService = webSocketService;
this.messageQueue = new ConcurrentLinkedQueue<>();
this.participants = new ArrayList<>();
this.votes = new HashMap<>();
this.finished = new AtomicBoolean(false);
this.result = "";
} }
public void handleMessage(Message message) { public void addParticipant(AgentInfo agent) {
participants.add(agent);
votes.put(agent.getId(), false);
webSocketService.sendUpdate("conversation_participants", participants);
}
public void removeParticipant(AgentInfo agent) {
participants.remove(agent);
votes.remove(agent.getId());
webSocketService.sendUpdate("conversation_participants", participants);
}
public void postMessage(Message message) {
messageQueue.offer(message);
processMessages();
}
private void processMessages() {
while (!messageQueue.isEmpty() && !finished.get()) {
Message message = messageQueue.poll();
handleMessage(message);
}
}
private void handleMessage(Message message) {
if (message.getContent().startsWith("/vote")) {
handleVote(message.getSender());
} else {
String stateTransitionTask = "Decide the next conversation state based on this message: " + message.getContent() + String stateTransitionTask = "Decide the next conversation state based on this message: " + message.getContent() +
"\nCurrent state: " + currentState; "\nCurrent state: " + currentState +
"\nParticipants: " + participants;
String reasoning = model.generate(stateTransitionTask, null); String reasoning = model.generate(stateTransitionTask, null);
@ -31,49 +77,64 @@ public class ConversationFSM {
ConversationState newState = ConversationState.valueOf(response.trim()); ConversationState newState = ConversationState.valueOf(response.trim());
transitionTo(newState); transitionTo(newState);
// Handle the message based on the new state // Broadcast the message to all participants
switch (newState) { for (AgentInfo agent : participants) {
case DISCUSSION: if (!agent.getId().equals(message.getSender())) {
handleDiscussionMessage(message); agent.receiveMessage(message);
break;
case TASK_ASSIGNMENT:
handleTaskAssignmentMessage(message);
break;
case EXECUTION:
handleExecutionMessage(message);
break;
case CONCLUSION:
handleConclusionMessage(message);
break;
} }
} }
webSocketService.sendUpdate("conversation_message", message);
}
}
private void handleVote(String agentId) {
votes.put(agentId, true);
checkVotes();
}
private void checkVotes() {
int totalVotes = (int) votes.values().stream().filter(v -> v).count();
if (totalVotes > participants.size() / 2) {
finish("Majority vote reached");
}
}
public void finish(String reason) {
if (finished.compareAndSet(false, true)) {
result = "Conversation finished. Reason: " + reason + "\nFinal state: " + currentState;
webSocketService.sendUpdate("conversation_finished", result);
}
}
public boolean isFinished() {
return finished.get();
}
public String getResult() {
return result;
}
private void transitionTo(ConversationState newState) { private void transitionTo(ConversationState newState) {
this.currentState = newState; this.currentState = newState;
webSocketService.sendUpdate("conversation_state", new ConversationStateUpdate(currentState)); webSocketService.sendUpdate("conversation_state", new ConversationStateUpdate(currentState, getPossibleTransitions()));
} }
private void handleDiscussionMessage(Message message) { private List<String> getPossibleTransitions() {
// Implement discussion logic // This is a simplified version. You might want to implement more complex logic.
} return Arrays.asList(ConversationState.values()).stream()
.map(Enum::name)
private void handleTaskAssignmentMessage(Message message) { .collect(Collectors.toList());
// Implement task assignment logic
}
private void handleExecutionMessage(Message message) {
// Implement execution logic
}
private void handleConclusionMessage(Message message) {
// Implement conclusion logic
} }
private class ConversationStateUpdate { private class ConversationStateUpdate {
public ConversationState state; public String currentState;
public List<String> possibleTransitions;
ConversationStateUpdate(ConversationState state) { ConversationStateUpdate(ConversationState state, List<String> transitions) {
this.state = state; this.currentState = state.name();
this.possibleTransitions = transitions;
} }
} }
} }

View File

@ -0,0 +1,74 @@
package com.ioa.conversation;
import com.ioa.agent.AgentInfo;
import com.ioa.model.BedrockLanguageModel;
import com.ioa.service.WebSocketService;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.*;
@Component
public class ConversationManager {
private final Map<String, ConversationFSM> conversations;
private final BedrockLanguageModel model;
private final WebSocketService webSocketService;
private final ScheduledExecutorService executorService;
public ConversationManager(BedrockLanguageModel model, WebSocketService webSocketService) {
this.conversations = new ConcurrentHashMap<>();
this.model = model;
this.webSocketService = webSocketService;
this.executorService = Executors.newScheduledThreadPool(1);
}
public String createConversation() {
String conversationId = UUID.randomUUID().toString();
ConversationFSM conversation = new ConversationFSM(model, webSocketService);
conversations.put(conversationId, conversation);
return conversationId;
}
public void addParticipant(String conversationId, AgentInfo agent) {
ConversationFSM conversation = conversations.get(conversationId);
if (conversation != null) {
conversation.addParticipant(agent);
}
}
public void removeParticipant(String conversationId, AgentInfo agent) {
ConversationFSM conversation = conversations.get(conversationId);
if (conversation != null) {
conversation.removeParticipant(agent);
}
}
public void postMessage(String conversationId, String senderId, String content) {
ConversationFSM conversation = conversations.get(conversationId);
if (conversation != null) {
conversation.postMessage(new Message(conversationId, senderId, content));
}
}
public void startConversation(String conversationId, String initialMessage) {
ConversationFSM conversation = conversations.get(conversationId);
if (conversation != null) {
conversation.postMessage(new Message(conversationId, "SYSTEM", initialMessage));
// Start a timer to end the conversation after 10 minutes
executorService.schedule(() -> {
if (!conversation.isFinished()) {
conversation.finish("Time limit reached");
}
}, 10, TimeUnit.MINUTES);
}
}
public String getConversationResult(String conversationId) {
ConversationFSM conversation = conversations.get(conversationId);
if (conversation != null) {
return conversation.getResult();
}
return "Conversation not found";
}
}

View File

@ -1,14 +1,25 @@
package com.ioa.conversation; package com.ioa.conversation;
import lombok.Data;
@Data
public class Message { public class Message {
private String sender; private final String conversationId;
private String content; private final String sender;
private final String content;
public Message(String sender, String content) { public Message(String conversationId, String sender, String content) {
this.conversationId = conversationId;
this.sender = sender; this.sender = sender;
this.content = content; this.content = content;
} }
public String getConversationId() {
return conversationId;
}
public String getSender() {
return sender;
}
public String getContent() {
return content;
}
} }

View File

@ -38,8 +38,8 @@ public class BedrockLanguageModel {
ArrayNode messages = requestBody.putArray("messages"); ArrayNode messages = requestBody.putArray("messages");
ObjectNode message = messages.addObject(); ObjectNode message = messages.addObject();
message.put("role", "user"); message.put("role", "user");
requestBody.put("max_tokens", 2000); requestBody.put("max_tokens", 20000);
requestBody.put("temperature", 0.7); requestBody.put("temperature", 0.4);
requestBody.put("top_p", 0.9); requestBody.put("top_p", 0.9);
ArrayNode content = message.putArray("content"); ArrayNode content = message.putArray("content");

View File

@ -6,13 +6,11 @@ import com.ioa.model.BedrockLanguageModel;
import com.ioa.service.WebSocketService; import com.ioa.service.WebSocketService;
import com.ioa.tool.ToolRegistry; import com.ioa.tool.ToolRegistry;
import com.ioa.util.TreeOfThought; import com.ioa.util.TreeOfThought;
import org.springframework.beans.factory.annotation.Autowired; import com.ioa.conversation.ConversationManager;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.List;
import java.util.ArrayList;
@Component @Component
public class TaskManager { public class TaskManager {
@ -21,90 +19,56 @@ public class TaskManager {
private BedrockLanguageModel model; private BedrockLanguageModel model;
private ToolRegistry toolRegistry; private ToolRegistry toolRegistry;
private TreeOfThought treeOfThought; private TreeOfThought treeOfThought;
private ConversationManager conversationManager;
@Autowired public TaskManager(AgentRegistry agentRegistry, BedrockLanguageModel model, ToolRegistry toolRegistry, TreeOfThought treeOfThought, ConversationManager conversationManager) {
private WebSocketService webSocketService;
public TaskManager(AgentRegistry agentRegistry, BedrockLanguageModel model, ToolRegistry toolRegistry, TreeOfThought treeOfThought) {
this.agentRegistry = agentRegistry; this.agentRegistry = agentRegistry;
this.model = model; this.model = model;
this.toolRegistry = toolRegistry; this.toolRegistry = toolRegistry;
this.treeOfThought = treeOfThought; this.treeOfThought = treeOfThought;
this.conversationManager = conversationManager;
} }
public void addTask(Task task) { public void addTask(Task task) {
tasks.put(task.getId(), task); tasks.put(task.getId(), task);
System.out.println("DEBUG: Task added: " + task.getId());
webSocketService.sendUpdate("task_added", Map.of("taskId", task.getId(), "description", task.getDescription()));
} }
public void executeTask(String taskId) { public void executeTask(String taskId, String conversationId) {
Task task = tasks.get(taskId); Task task = tasks.get(taskId);
AgentInfo agent = task.getAssignedAgent(); AgentInfo agent = task.getAssignedAgent();
updateTaskProgress(taskId, "STARTED", 0); conversationManager.postMessage(conversationId, agent.getId(), "Starting task: " + task.getDescription());
String executionPlanningTask = "Plan the execution of this task: " + task.getDescription() + String executionPlanningTask = "Plan the execution of this task: " + task.getDescription() +
"\nAssigned agent capabilities: " + agent.getCapabilities() + "\nAssigned agent capabilities: " + agent.getCapabilities() +
"\nAvailable tools: " + agent.getTools(); "\nAvailable tools: " + agent.getTools();
Map<String, Object> reasoningTree = treeOfThought.reason(executionPlanningTask, 3, 2); Map<String, Object> reasoningResult = treeOfThought.reason(executionPlanningTask, 3, 2);
String reasoning = formatReasoning(reasoningTree); String reasoning = (String) reasoningResult.get("reasoning"); // Assuming the reasoning is stored under the key "reasoning"
System.out.println("DEBUG: Task execution reasoning:\n" + reasoning); conversationManager.postMessage(conversationId, agent.getId(), "Task execution plan:\n" + reasoning);
webSocketService.sendUpdate("task_reasoning", Map.of("taskId", taskId, "reasoning", reasoning));
updateTaskProgress(taskId, "IN_PROGRESS", 25); String executionPrompt = "Based on this execution plan:\n" + reasoning +
"\nExecute the task using the available tools and provide the result.";
Map<String, Object> executionResult = treeOfThought.reason(executionPrompt, 1, 1);
String response = (String) executionResult.get("response"); // Assuming the response is stored under the key "response"
List<String> selectedTools = extractToolSelection(reasoning); String result = executeToolsFromResponse(response, agent);
System.out.println("DEBUG: Selected tools: " + selectedTools);
webSocketService.sendUpdate("tools_selected", Map.of("taskId", taskId, "tools", selectedTools));
updateTaskProgress(taskId, "IN_PROGRESS", 50);
String result = executeTools(selectedTools, task.getDescription(), agent);
task.setResult(result); task.setResult(result);
updateTaskProgress(taskId, "COMPLETED", 100);
System.out.println("DEBUG: Task completed: " + taskId + ", Result: " + result); conversationManager.postMessage(conversationId, agent.getId(), "Task result: " + result);
webSocketService.sendUpdate("task_completed", Map.of("taskId", taskId, "result", result));
} }
private void updateTaskProgress(String taskId, String status, int progressPercentage) { private String executeToolsFromResponse(String response, AgentInfo agent) {
Map<String, Object> progressUpdate = new HashMap<>();
progressUpdate.put("taskId", taskId);
progressUpdate.put("status", status);
progressUpdate.put("progressPercentage", progressPercentage);
webSocketService.sendUpdate("task_progress", progressUpdate);
}
private String formatReasoning(Map<String, Object> reasoningTree) {
// Implement a method to format the reasoning tree into a string
// This is a placeholder implementation
return reasoningTree.toString();
}
private List<String> extractToolSelection(String reasoning) {
// Implement a method to extract tool selection from reasoning
// This is a placeholder implementation that selects all available tools
return new ArrayList<>(toolRegistry.getAllTools().keySet());
}
private String executeTools(List<String> tools, String taskDescription, AgentInfo agent) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for (String tool : tools) { for (String tool : agent.getTools()) {
System.out.println("DEBUG: Executing tool: " + tool); if (response.contains(tool)) {
webSocketService.sendUpdate("tool_execution", Map.of("taskId", taskDescription, "tool", tool));
Object toolInstance = toolRegistry.getTool(tool); Object toolInstance = toolRegistry.getTool(tool);
// Execute the tool (this is a simplified representation) // Execute the tool (this is a simplified representation)
String toolResult = tool + " result: " + toolInstance.toString(); result.append(tool).append(" result: ").append(toolInstance.toString()).append("\n");
result.append(toolResult).append("\n"); }
}
System.out.println("DEBUG: Tool result: " + toolResult); return result.toString();
webSocketService.sendUpdate("tool_result", Map.of("taskId", taskDescription, "tool", tool, "result", toolResult));
}
return result.toString().trim();
} }
} }

View File

@ -35,7 +35,7 @@ public class TeamFormation {
"\nRequired tools: " + requiredTools + "\nRequired tools: " + requiredTools +
"\nAvailable agents and their tools: " + formatAgentTools(potentialAgents); "\nAvailable agents and their tools: " + formatAgentTools(potentialAgents);
Map<String, Object> reasoningTree = treeOfThought.reason(teamFormationTask, 3, 2); Map<String, Object> reasoningTree = treeOfThought.reason(teamFormationTask, 1, 2);
String reasoning = formatReasoning(reasoningTree); String reasoning = formatReasoning(reasoningTree);
// Send update about the reasoning process // Send update about the reasoning process

View File

@ -1,15 +1,15 @@
{ {
"files": { "files": {
"main.css": "/static/css/main.e6c13ad2.css", "main.css": "/static/css/main.e6c13ad2.css",
"main.js": "/static/js/main.720bb114.js", "main.js": "/static/js/main.a73628f2.js",
"static/js/453.d855a71b.chunk.js": "/static/js/453.d855a71b.chunk.js", "static/js/453.d855a71b.chunk.js": "/static/js/453.d855a71b.chunk.js",
"index.html": "/index.html", "index.html": "/index.html",
"main.e6c13ad2.css.map": "/static/css/main.e6c13ad2.css.map", "main.e6c13ad2.css.map": "/static/css/main.e6c13ad2.css.map",
"main.720bb114.js.map": "/static/js/main.720bb114.js.map", "main.a73628f2.js.map": "/static/js/main.a73628f2.js.map",
"453.d855a71b.chunk.js.map": "/static/js/453.d855a71b.chunk.js.map" "453.d855a71b.chunk.js.map": "/static/js/453.d855a71b.chunk.js.map"
}, },
"entrypoints": [ "entrypoints": [
"static/css/main.e6c13ad2.css", "static/css/main.e6c13ad2.css",
"static/js/main.720bb114.js" "static/js/main.a73628f2.js"
] ]
} }

View File

@ -1 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>React App</title><script defer="defer" src="/static/js/main.720bb114.js"></script><link href="/static/css/main.e6c13ad2.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html> <!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>React App</title><script defer="defer" src="/static/js/main.a73628f2.js"></script><link href="/static/css/main.e6c13ad2.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,39 @@
/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,3 @@
com/ioa/conversation/ConversationFSM$1.class
com/ioa/service/WebSocketService.class com/ioa/service/WebSocketService.class
com/ioa/tool/common/WebSearchTool.class com/ioa/tool/common/WebSearchTool.class
com/ioa/conversation/ConversationFSM.class com/ioa/conversation/ConversationFSM.class
@ -10,6 +9,7 @@ com/ioa/tool/common/FinancialAdviceTool.class
com/ioa/team/TeamFormation.class com/ioa/team/TeamFormation.class
com/ioa/tool/common/MovieRecommendationTool.class com/ioa/tool/common/MovieRecommendationTool.class
com/ioa/config/WebSocketConfig.class com/ioa/config/WebSocketConfig.class
com/ioa/conversation/ConversationManager.class
com/ioa/tool/common/WeatherTool.class com/ioa/tool/common/WeatherTool.class
com/ioa/tool/common/TravelBookingTool.class com/ioa/tool/common/TravelBookingTool.class
com/ioa/tool/common/FitnessClassFinderTool.class com/ioa/tool/common/FitnessClassFinderTool.class