Skip to content

Commit

Permalink
streamlit gui
Browse files Browse the repository at this point in the history
  • Loading branch information
Luncenok committed Oct 20, 2024
1 parent e90ead9 commit 2b440ff
Show file tree
Hide file tree
Showing 26 changed files with 1,043 additions and 572 deletions.
632 changes: 553 additions & 79 deletions poetry.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ langchain = "^0.3.3"
langchain-community = "^0.3.2"
langchain-openai = "^0.2.2"
langchain-google-genai = "^2.0.1"
streamlit = "^1.39.0"
pytest = "^8.3.3"

[tool.pytest.ini_options]
pythonpath = ["src"]
Expand Down
7 changes: 4 additions & 3 deletions src/demo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from game.game_engine import GameEngine
from game.models.player import Player
from game.models.game_models import GamePhase, PlayerRole
from game.players.base_player import Player
from game.models.engine import GamePhase
from game.players.base_player import PlayerRole

game = GameEngine()

Expand All @@ -17,4 +18,4 @@
game.load_players(players, force_crewmate_to_impostor=False)
game.init_game()

game.main_game_loop()
game.enter_main_game_loop()
64 changes: 35 additions & 29 deletions src/demo_gui.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
import streamlit as st
import time
from game.game_engine import GameEngine
from game.models.player_human import HumanPlayer
from game.models.player_ai import AIPlayer
from game.models.game_models import PlayerRole
from game.gui.debug_gui import DebugGUI

game = GameEngine()

model_name = "gpt-4o-mini"
# model_name = "gemini-1.5-flash"

# impostor = HumanPlayer(name="Warcin")
impostor = AIPlayer(name="Warcin", llm_model_name=model_name, role=PlayerRole.IMPOSTOR)

players = [
# AIPlayer(name="Wateusz", llm_model_name=model_name),
# AIPlayer(name="Waciej", llm_model_name=model_name),
AIPlayer(name="Warek", llm_model_name=model_name),
AIPlayer(name="Wikolaj", llm_model_name=model_name),
impostor,
]
game.load_players(players, impostor_count=1)
game.init_game()

game.DEBUG = True
game.save_playthrough = f"whole_game_test__new_1.txt"
gui = DebugGUI(game)
game.gui = gui
game.main_game_loop()
gui.run()
from game.players.human import HumanPlayer
from game.players.ai import AIPlayer
from game.players.base_player import PlayerRole

def main():
st.title("Among Us Game - Streamlit")
game_engine = GameEngine()

model_name = "gpt-4o-mini" # Or any other suitable model name

player_names = ["Wateusz", "Waciej", "Warek"]
players = [AIPlayer(name=player_names[i], llm_model_name=model_name) for i in range(3)]
game_engine.load_players(players, impostor_count=1)
game_engine.init_game()

player_states_placeholder = st.empty()
game_log_placeholder = st.empty()

try:
game_engine.enter_main_game_loop()
while True:
# player_states = {player.name: player.to_dict() for player in game_engine.state.players}
game_state = game_engine.to_dict()
player_states_placeholder.json(game_state, expanded=False)
game_log_placeholder.text("\n".join(game_engine.state.playthrough))
time.sleep(0.1) # Update every 100 milliseconds

except Exception as e:
print(f"Error updating GUI: {e}")
st.error(f"An error occurred: {e}")


if __name__ == "__main__":
main()
17 changes: 14 additions & 3 deletions src/game/agents/adventure_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,15 @@
from llm_prompts import ADVENTURE_PLAN_TEMPLATE, ADVENTURE_ACTION_TEMPLATE
import re


class AdventureAgent(Agent):
def update_state(self, observations: str, tasks: List[str], actions: List[str], current_location: str):
def update_state(
self,
observations: str,
tasks: List[str],
actions: List[str],
current_location: str,
):
self.state.history = observations
self.state.current_tasks = tasks
self.state.available_actions = actions
Expand All @@ -20,7 +27,9 @@ def create_plan(self) -> str:
ASCII_MAP=ASCII_MAP,
history=self.state.history,
tasks=self.state.current_tasks,
actions="<action>"+"</action><action>".join(self.state.available_actions)+"</action>",
actions="<action>"
+ "</action><action>".join(self.state.available_actions)
+ "</action>",
current_location=self.state.current_location,
)
plan = self.llm.invoke([HumanMessage(content=plan_prompt)])
Expand Down Expand Up @@ -55,7 +64,9 @@ def check_action_valid(self, chosen_action: str) -> int:
def act(self) -> Any:
plan_prompt, plan = self.create_plan()
action_prompt, action = self.choose_action(plan)
self.responses.append(f"Based on plan: {plan}\n{self.player_name} chose action: {action} {self.state.available_actions[action]}")
self.responses.append(
f"Based on plan: {plan}\n{self.player_name} chose action: {action} {self.state.available_actions[action]}"
)
return f"Plan prompt:\n{plan_prompt}\n\nAction prompt:{action_prompt}", action

@staticmethod
Expand Down
38 changes: 35 additions & 3 deletions src/game/agents/base_agent.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from abc import ABC, abstractmethod
from typing import Any, List
from pydantic import BaseModel, Field, ConfigDict
from pydantic import BaseModel, Field


class AgentState(BaseModel):
history: str = Field(default_factory=str)
Expand All @@ -9,17 +10,48 @@ class AgentState(BaseModel):
messages: List[str] = Field(default_factory=list)
current_location: str = Field(default_factory=str)

def to_dict(self):
return {
"history": self.history,
"current_tasks": self.current_tasks,
"available_actions": self.available_actions,
"messages": self.messages,
"current_location": self.current_location,
}


class Agent(ABC, BaseModel):
llm: Any
# has to be Any because of MagicMock. TODO: Fix test integration with pydanitc
llm: Any # Optional[ChatOpenAI | ChatGoogleGenerativeAI] = None
state: AgentState = Field(default_factory=AgentState)
responses: List[str] = Field(default_factory=list)
player_name: str = ""
role: str = ""

@abstractmethod
def update_state(self, observations: str, tasks: List[str] = None, actions: List[str] = None):
def update_state(
self, observations: str, tasks: List[str] = None, actions: List[str] = None
):
pass

@abstractmethod
def act(self) -> Any:
pass

def to_dict(self):
llm_data = "human"
if self.llm:
if hasattr(self.llm, "model_name"):
llm_data = self.llm.model_name
elif hasattr(self.llm, "model"):
llm_data = self.llm.model
else:
llm_data = "unknown"

return {
"llm": llm_data,
"state": self.state.to_dict(),
"responses": self.responses,
"player_name": self.player_name,
"role": self.role,
}
19 changes: 15 additions & 4 deletions src/game/agents/discussion_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@
from .base_agent import Agent
from langchain.schema import HumanMessage
from llm_prompts import DISCUSSION_TEMPLATE, DISCUSSION_RESPONSE_TEMPLATE
import datetime


class DiscussionAgent(Agent):
def update_state(self, observations: str, tasks: List[str] = None, actions: List[str] = None, messages: List[str] = None):
def update_state(
self,
observations: str,
tasks: List[str] = None,
actions: List[str] = None,
messages: List[str] = None,
):
self.state.history = observations
self.state.messages = messages

Expand Down Expand Up @@ -34,5 +40,10 @@ def respond_to_statements(self, statements: str, points: str) -> str:

def act(self) -> Any:
points_prompt, points = self.create_discussion_points()
response_prompt, response = self.respond_to_statements(statements='\n'.join(self.state.messages), points=points)
return f"Points prompt: {points_prompt}\n\nResponse prompt: {response_prompt}", response
response_prompt, response = self.respond_to_statements(
statements="\n".join(self.state.messages), points=points
)
return (
f"Points prompt: {points_prompt}\n\nResponse prompt: {response_prompt}",
response,
)
10 changes: 7 additions & 3 deletions src/game/agents/voting_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
from llm_prompts import VOTING_TEMPLATE
import re


class VotingAgent(Agent):
def update_state(self, observations: str, tasks: List[str] = None, actions: List[str] = None):
def update_state(
self, observations: str, tasks: List[str] = None, actions: List[str] = None
):
self.state.history = observations
self.state.available_actions = actions

Expand All @@ -16,7 +19,8 @@ def choose_action(self, discussion_log: str) -> int:
discussion=discussion_log,
history=self.state.history,
actions="\n".join(
f"{i+1}. {action}" for i, action in enumerate(self.state.available_actions)
f"{i+1}. {action}"
for i, action in enumerate(self.state.available_actions)
),
)
chosen_action = self.llm.invoke([HumanMessage(content=action_prompt)])
Expand All @@ -36,7 +40,7 @@ def check_action_valid(self, chosen_action: str) -> int:
warning_str = f"{self.player_name} LLM did not conform to output format. Expected one of {normalized_available_actions}, but got {chosen_action} ({normalized_chosen_action} normalized)"
print(warning_str)
self.responses.append(warning_str)
return 0 # Default to first action if invalid
return 0 # Default to first action if invalid

def act(self) -> Any:
# choose_action is used
Expand Down
14 changes: 7 additions & 7 deletions src/game/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,21 @@
"lime",
]
ASCII_MAP = """
|\\----------------|--------------|----------------|--------------\\
|\\----------------|--------------|----------------|-------------\\
| \\
| UPPER ENGINE CAFETERIA WEAPONS \\
| |- --------| | \\
|/--------| |--| MEDBAY | | \\
| | | | \\------\\
/---------| |-------\\ | |----------| | \\
| | | \\ |---| |------| | |
| \\ | | |
| | | | \\-----\\
/---------| |-------\\ | |----------| | \\
| | | \\ |---| |------| | |
| \\ | | |
| REACTOR SECURITY | | ADMIN OFFICE | O2 NAVIGATION |
| | | | | |
| | | | |---| |----|-|----------| |
\\---------| |----------|------| | | /
\\--------| |----------|------| | | /
| | | /------/
|\\--------| |--| | /
|\\-------| |--| | /
| | | |-- --| /
| LOWER ENGINE ELECTRICAL STORAGE | COMMS | SHIELDS /
| | | /
Expand Down
Loading

0 comments on commit 2b440ff

Please sign in to comment.