Skip to content

Commit

Permalink
game_moe
Browse files Browse the repository at this point in the history
  • Loading branch information
maeste committed Nov 14, 2024
1 parent 5d76309 commit 3e57eac
Show file tree
Hide file tree
Showing 15 changed files with 1,733 additions and 0 deletions.
64 changes: 64 additions & 0 deletions examples/create_a_game/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@

# Perceive and Act Example

This guide walks you through running a practical example of a multi-agent system using Wise Agents. In this example, four agents (a web interface agent, a sequential agent coordinator, and two intelligent agents) are started, allowing you to experiment with agent communication and interaction in a simulated environment, with a sequential coordination.


## Example Overview

The example consists of four agents:

1. **PerceivingAgent**: This is an agent that can perceive file changes. In case of changes it send a message with the list of books contained in books_read.txt to the SequentialCoordinator. This agent code is not part of wise-agents framework, but it's defined for this example use only in `custom_agent.py` present in the example directory.
2. **Literate Agent**: Handles requests and provides intelligent responses. Its system message says:
*"You are an english literature expert. The user will provide you with a list of books they have read. Suggest the next 3 books they should read."*
3. **ActionAgent**: This agent will write what received (the books suggested) in a file (books_suggested.txt). It will override the file each time. This agent code is not part of wise-agents framework, but it's defined for this example use only in `custom_agent.py` present in the example directory.
4. **SequentialCoordinator**: Take care of coordinating the request handling from the user delagating the work to other agents in a predetermined order.

These agents are defined in YAML configuration files located in the `examples/perceive_and_act` directory.

## Prerequisite For Running the Example
1. Clone the repository
2. Configure and start redis
3. Start artemis
4. Start Ollama

For detailed instructions on how to satisfy those prerequisite please refer to [prerequisites.md](../prerequisites.md)


### Step 1: Start the Intelligent Agent

In a console, run the intelligent agents and coordinator agent. Having custom creted agents in the directory of example you need to run the script from there after setting PYTHONPATH env variable. Here you have all the commands needed pretending you are in the project main directory:

```bash
cd examples/perceive_and_act
export PYTHONPATH="."
python ../../src/wiseagents/cli/wise_agent_cli.py ./intelligent-agents.yaml
```

This will initialize the intelligent agents and coordinator agent, which will be ready to watch `books_read.txt` for changes.


### Step 2: Interaction

Once all agents are up and running, you can edit `books_read.txt` file and `PerceivingAgent` will start sending requests to the coordinator agent. The coordinator agent will take care to interact to the `LiterateAgent` passing its response to the `ActionAgent` which will write the results to `books_suggested.txt. You will be able to see the interaction between the agents through the logs in both consoles.


### Step 3: Experiment

You can experiment with different agent configurations or modify the agent behaviors by editing the YAML files located in the `examples/perceive_and_act` directory. These configuration files define the agents' properties, including memory, communication methods, and response patterns. You can do that without restarting everything, just edit the yaml file(s) and use CLI's /reload command (see our documentation for more details on how to use CLI)

## Understanding the YAML Configuration

- **intelligent-agents.yaml**: Defines all the agents discussed in this document and needed to run the example

These YAML files include the specific `WiseAgent` classes and configuration needed to run the agents. Feel free to explore and modify these files to customize the agents' behavior.

## Additional Resources

For more information about the architecture and advanced configurations of wise-agents, refer to the [Wise Agents Architecture Document](wise_agents_architecture.md), which provides insights into how the system can be scaled and deployed in distributed environments.

## Conclusion

By following these steps, you have successfully run a simple sequential coordinated multi-agent chatbot using Wise Agents. You can now explore further by modifying agent behaviors, adding new agents, or experimenting with different message flows.

For any further assistance, feel free to refer to the official Wise Agents documentation or reach out to the repository maintainers.
Empty file.
114 changes: 114 additions & 0 deletions examples/create_a_game/custom_agents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import os
import threading
import time
import uuid
from openai.types.chat import ChatCompletionToolParam, ChatCompletionMessageParam
from typing import List, Optional
from wiseagents import WiseAgent, WiseAgentEvent, WiseAgentMessage, WiseAgentMetaData, WiseAgentTransport
from wiseagents.core import WiseAgentRegistry
from wiseagents.yaml import WiseAgentsLoader

class PerceivingAgent(WiseAgent):
yaml_tag = u'!custom_agents.PerceivingAgent'
yaml_loader = WiseAgentsLoader

stop_event = threading.Event()

def __init__(self, name: str, metadata: WiseAgentMetaData, transport: WiseAgentTransport, file_path: str, check_interval: float, destination_agent_name: str):
self._file_path = file_path
self._check_interval = check_interval
self._destination_agent_name = destination_agent_name
super().__init__(name=name, metadata=metadata, transport=transport)

def start_agent(self):
super().start_agent()
self.stop_event.clear()
self.perceive(self._file_path, self.on_file_change, self._check_interval)
self.context_name = self.name + str(uuid.uuid4())
WiseAgentRegistry.create_context(context_name=self.context_name)

def stop_agent(self):
self.stop_event.set()
super().stop_agent()
WiseAgentRegistry.remove_context(context_name=self.context_name)

def process_request(self, request: WiseAgentMessage,
conversation_history: List[ChatCompletionMessageParam]) -> Optional[str]:
pass

def process_response(self, response: WiseAgentMessage):
pass

def process_event(self, event: WiseAgentEvent):
pass

def process_error(self, error: WiseAgentMessage):
pass

def perceive(self, file_path, callback, check_interval=1.0):
"""
Monitors a file for any changes and invokes a callback with the file's content upon modification.
Args:
file_path (str): The path to the file to monitor.
callback (callable): A function to call with the file's content when it changes.
check_interval (float, optional): Time in seconds between checks. Defaults to 1.0.
"""
def watch():
try:
last_mtime = os.path.getmtime(file_path)
except FileNotFoundError:
last_mtime = None

while not self.stop_event.is_set():
try:
print(f"Checking file {file_path}")
current_mtime = os.path.getmtime(file_path)
if last_mtime is None:
last_mtime = current_mtime
elif current_mtime != last_mtime:
print(f"File {file_path} has changed")
last_mtime = current_mtime
with open(file_path, 'r') as f:
content = f.read()
callback(content)
except FileNotFoundError:
if last_mtime is not None:
last_mtime = None
except Exception as e:
print(f"Error monitoring file: {e}")
time.sleep(check_interval)

thread = threading.Thread(target=watch, daemon=True)
thread.start()

def on_file_change(self, content):
print(f"sending message: {content}, {self.name}, {self._destination_agent_name}")
self.send_request(WiseAgentMessage(message = content, sender=self.name, context_name=self.context_name), self._destination_agent_name)

class ActionAgent(WiseAgent):
yaml_tag = u'!custom_agents.ActionAgent'
yaml_loader = WiseAgentsLoader

def __init__(self, name: str, metadata: WiseAgentMetaData, transport: WiseAgentTransport, destination_file_path: str):
self._destination_file_path = destination_file_path
super().__init__(name=name, metadata=metadata, transport=transport)

def start_agent(self):
super().start_agent()

def process_request(self, request: WiseAgentMessage, conversation_history: List[ChatCompletionMessageParam]) -> str | None:
with open(self._destination_file_path, 'w') as f:
f.write(request.message)
self.send_response(WiseAgentMessage(message="File updated", sender=self.name, context_name=request.context_name), request.sender)


def process_response(self, response: WiseAgentMessage):
pass

def process_event(self, event: WiseAgentEvent):
pass

def process_error(self, error: WiseAgentMessage):
pass
1 change: 1 addition & 0 deletions examples/create_a_game/game.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
one or zero
99 changes: 99 additions & 0 deletions examples/create_a_game/intelligent-agents.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
---
!wiseagents.agents.LLMOnlyWiseAgent
metadata: !wiseagents.WiseAgentMetaData
description: This is an agent that can describe a game in full details
llm: !wiseagents.llm.OpenaiAPIWiseAgentLLM
model_name: granite3-moe:latest
remote_address: http://localhost:11434/v1
system_message: "You are an expert of games. You are able to describe all details of a game and its rule. Your description iaccurate enough to be used as set of specification for a programmer which want to implement it.
The user will provide you with a game name and you are describing it. If it's a well known game, please describe it in details. If it's a new game, crate new rules and please describe it in details as well. "
name: SpecificationAgent
transport: !wiseagents.transports.StompWiseAgentTransport
host: localhost
port: 61616
agent_name: SpecificationAgent
---
!wiseagents.agents.LLMOnlyWiseAgent
metadata: !wiseagents.WiseAgentMetaData
description: This is an agent that can write code to implement the game
llm: !wiseagents.llm.OpenaiAPIWiseAgentLLM
model_name: llama3.1
remote_address: http://localhost:11434/v1
system_message: You are an expert python programmer, considering the detailed description of a game in the conversation history, you are able to write the code to implement it. Write the code in python, object oriented, and provide it to the user.
name: CoderAgent
transport: !wiseagents.transports.StompWiseAgentTransport
host: localhost
port: 61616
agent_name: CoderAgent
---
!wiseagents.agents.LLMOnlyWiseAgent
metadata: !wiseagents.WiseAgentMetaData
description: This is an agent that can write code to test the game
llm: !wiseagents.llm.OpenaiAPIWiseAgentLLM
model_name: llama3.1
remote_address: http://localhost:11434/v1
system_message: You are an expert python programmer, considering the detailed description of a game in the conversation history, and the code implementing it you are able to write the code to test it. Write the code in python, and provide it to the user.
name: QEAgent
transport: !wiseagents.transports.StompWiseAgentTransport
host: localhost
port: 61616
agent_name: QEAgent
---
!wiseagents.agents.LLMOnlyWiseAgent
metadata: !wiseagents.WiseAgentMetaData
description: This is an agent that can write documentation for the game
llm: !wiseagents.llm.OpenaiAPIWiseAgentLLM
model_name: granite3-moe:latest
remote_address: http://localhost:11434/v1
system_message: "You are an expert content writer, understanding python code, and very good on writing usage manual of games. Considering the detailed description of a game in the conversation history, the code implementing it and the code testing it
you are able to write a detailed manual explaining how to use the program and play the game. Write the documentation in english, and provide it to the user."
name: DocAgent
transport: !wiseagents.transports.StompWiseAgentTransport
host: localhost
port: 61616
agent_name: DocAgent
---
!wiseagents.agents.LLMOnlyWiseAgent
metadata: !wiseagents.WiseAgentMetaData
description: This is an agent that can write transalte text from english to italian
llm: !wiseagents.llm.OpenaiAPIWiseAgentLLM
model_name: granite3-moe:latest
remote_address: http://localhost:11434/v1
system_message: "You are an expert language translator. Please translate the documentation provided in english to italian. The documentation is about a game, so you need to be able to understand the context and translate it properly."
name: TranslatorAgent
transport: !wiseagents.transports.StompWiseAgentTransport
host: localhost
port: 61616
agent_name: TranslatorAgent
---
!custom_agents.PerceivingAgent
metadata: !wiseagents.WiseAgentMetaData
description: This is an agent that can perceive file changes
name: PerceivingAgent
file_path: ./game.txt
check_interval: 5
destination_agent_name: SequentialCoordinator
transport: !wiseagents.transports.StompWiseAgentTransport
host: localhost
port: 61616
agent_name: PerceivingAgent
---
!custom_agents.ActionAgent
metadata: !wiseagents.WiseAgentMetaData
description: This is an agent that can write a file
name: ActionAgent
destination_file_path: ./books_suggested.txt
transport: !wiseagents.transports.StompWiseAgentTransport
host: localhost
port: 61616
agent_name: ActionAgent
---
!wiseagents.agents.SequentialMemoryCoordinatorWiseAgent
metadata: !wiseagents.WiseAgentMetaData
description: This is a coordinator agent
name: SequentialCoordinator
agents: ["SpecificationAgent", "CoderAgent", "QEAgent", "DocAgent", "TranslatorAgent"]
transport: !wiseagents.transports.StompWiseAgentTransport
host: localhost
port: 61616
agent_name: SequentialCoordinator
Loading

0 comments on commit 3e57eac

Please sign in to comment.