- Contents in this wiki are for entertainment purposes only
Simple Python Chat Agency with File Load/Save
Jump to navigation
Jump to search
Template:MenuSimplePythonChatAgency
import os
import json
class ChatAgent:
def __init__(self, name):
self.name = name
self.messages = []
def add_message(self, message):
self.messages.append(message)
def save_to_file(self, file_path):
with open(file_path, 'w') as file:
json.dump(self.__dict__, file)
@staticmethod
def load_from_file(file_path):
with open(file_path, 'r') as file:
data = json.load(file)
agent = ChatAgent(data['name'])
agent.messages = data['messages']
return agent
class ChatAgency:
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
def remove_agent(self, agent):
self.agents.remove(agent)
def find_agent_by_name(self, name):
for agent in self.agents:
if agent.name == name:
return agent
return None
def save_to_file(self, file_path):
with open(file_path, 'w') as file:
data = [agent.__dict__ for agent in self.agents]
json.dump(data, file)
@staticmethod
def load_from_file(file_path):
with open(file_path, 'r') as file:
data = json.load(file)
agency = ChatAgency()
for agent_data in data:
agent = ChatAgent(agent_data['name'])
agent.messages = agent_data['messages']
agency.add_agent(agent)
return agency
def main():
agency = ChatAgency()
while True:
print("1. Add agent")
print("2. Remove agent")
print("3. Add message to agent")
print("4. Display agent messages")
print("5. Save agency to file")
print("6. Load agency from file")
print("7. Exit")
choice = input("Enter your choice: ")
if choice == '1':
name = input("Enter agent name: ")
agent = ChatAgent(name)
agency.add_agent(agent)
print(f"Agent {name} added successfully.")
elif choice == '2':
name = input("Enter agent name: ")
agent = agency.find_agent_by_name(name)
if agent:
agency.remove_agent(agent)
print(f"Agent {name} removed successfully.")
else:
print(f"Agent {name} not found.")
elif choice == '3':
name = input("Enter agent name: ")
agent = agency.find_agent_by_name(name)
if agent:
message = input("Enter message: ")
agent.add_message(message)
print(f"Message added to agent {name} successfully.")
else:
print(f"Agent {name} not found.")
elif choice == '4':
name = input("Enter agent name: ")
agent = agency.find_agent_by_name(name)
if agent:
print(f"Messages for agent {name}:")
for message in agent.messages:
print(message)
else:
print(f"Agent {name} not found.")
elif choice == '5':
file_path = input("Enter file path: ")
agency.save_to_file(file_path)
print(f"Agency saved to {file_path} successfully.")
elif choice == '6':
file_path = input("Enter file path: ")
if os.path.exists(file_path):
agency = ChatAgency.load_from_file(file_path)
print(f"Agency loaded from {file_path} successfully.")
else:
print(f"File {file_path} not found.")
elif choice == '7':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()