code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def parse_trigger_plugin(trigger_path, plugin_config, parse_only=False): """Parse plugin file and return the trigger config.""" # Open and exec plugin definitions with open(trigger_path, 'r') as f: trigger_code = f.read() trigger_vars = {} exec(trigger_code, trigger_vars) # Get trigger...
Parse plugin file and return the trigger config.
parse_trigger_plugin
python
calebmadrigal/trackerjacker
trackerjacker/plugin_parser.py
https://github.com/calebmadrigal/trackerjacker/blob/master/trackerjacker/plugin_parser.py
MIT
def parse_plugin_config(plugin_config_str): """Attempt to parse the config as ast or json.""" if not plugin_config_str: return {} try: return ast.literal_eval(plugin_config_str) except SyntaxError: pass try: return json.loads(plugin_config_str) except json.decod...
Attempt to parse the config as ast or json.
parse_plugin_config
python
calebmadrigal/trackerjacker
trackerjacker/plugin_parser.py
https://github.com/calebmadrigal/trackerjacker/blob/master/trackerjacker/plugin_parser.py
MIT
def __init__(self, **kwargs): """ Initialize an agent with given or generated characteristics. This method should not be called directly - use create_agent() instead. """ if not Agent._allow_init: raise RuntimeError("Agent instances should be created using Agent.crea...
Initialize an agent with given or generated characteristics. This method should not be called directly - use create_agent() instead.
__init__
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def create_agent( agent_id: str = DefaultValue.NOT_PROVIDED, gender: str = DefaultValue.NOT_PROVIDED, name: str = DefaultValue.NOT_PROVIDED, age: int = DefaultValue.NOT_PROVIDED, occupation: str = DefaultValue.NOT_PROVIDED, location: str = DefaultValue.NOT_PROVIDED, ...
Initialize an agent with given or generated characteristics. Creates a new agent instance with a unique identifier and a set of characteristics. If specific characteristics are not provided, they are automatically generated to create a complete and realistic agent profile. ...
create_agent
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def _generate_prompt_to_generate_bio(**kwargs) -> str: """ Generate a prompt for creating an agent's biography. Creates a prompt that will be used by the language model to generate a realistic biography for the agent. If characteristics are provided, they are incorporated into t...
Generate a prompt for creating an agent's biography. Creates a prompt that will be used by the language model to generate a realistic biography for the agent. If characteristics are provided, they are incorporated into the prompt to ensure the generated bio is consistent with t...
_generate_prompt_to_generate_bio
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def _generate_agent_bio(agent_informations: dict) -> str: """ Generate a biography for an agent using a language model. Uses the OpenAI API to generate a realistic and detailed biography based on the agent's characteristics. The biography is generated to be consistent with any e...
Generate a biography for an agent using a language model. Uses the OpenAI API to generate a realistic and detailed biography based on the agent's characteristics. The biography is generated to be consistent with any existing information about the agent. Args: agent...
_generate_agent_bio
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def act(self) -> str: """ Generate and execute the agent's next action based on their current state. This method: 1. Generates a self-introduction based on agent's characteristics and history 2. Creates a prompt combining the self-introduction and available actions 3. Us...
Generate and execute the agent's next action based on their current state. This method: 1. Generates a self-introduction based on agent's characteristics and history 2. Creates a prompt combining the self-introduction and available actions 3. Uses the language model to decide t...
act
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def dump(self) -> dict: """ Dump the agent's state to a dictionary. """ return { "agent_id": self.agent_id, "agent_informations": self.agent_informations, "interactions": [interaction.dump() for interaction in self._interaction_manager.get_agent_inter...
Dump the agent's state to a dictionary.
dump
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def ask(self, message: str) -> str: """ Ask the agent a question and receive a contextually aware response. The agent considers its characteristics and interaction history when formulating the response, maintaining consistency with its persona. Note: The agent will not save the...
Ask the agent a question and receive a contextually aware response. The agent considers its characteristics and interaction history when formulating the response, maintaining consistency with its persona. Note: The agent will not save the question nor the response in its interaction h...
ask
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def add_action(self, action: Action) -> None: """ Add a new action to the agent's capabilities. This method allows extending an agent's behavior by adding custom actions. Each action consists of: 1. A descriptor that tells the agent how to use the action 2. A function that imple...
Add a new action to the agent's capabilities. This method allows extending an agent's behavior by adding custom actions. Each action consists of: 1. A descriptor that tells the agent how to use the action 2. A function that implements the action's behavior Args: ac...
add_action
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def execute_action(self, action_name: str, *args, **kwargs) -> Dict[str, Any]: """ Manually execute an action by name. Args: name: Name of the action to execute *args, **kwargs: Arguments to pass to the action function Returns: Dict containing the ac...
Manually execute an action by name. Args: name: Name of the action to execute *args, **kwargs: Arguments to pass to the action function Returns: Dict containing the action results
execute_action
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def remove_action(self, action_name: str) -> None: """ Remove an action from the agent's action space. """ if action_name not in self._actions: raise RuntimeError(f"Invalid action: {action_name}, action does not exist in the agent's action space") del self._actions[a...
Remove an action from the agent's action space.
remove_action
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def talk_to(self, agent: Agent | list[Agent], message: str) -> Dict[str, Any]: """ Send a message from one agent to another and record the interaction. """ if "talk" not in self._actions: # Did you really removed the default "talk" action and expect the talk_to method to wor...
Send a message from one agent to another and record the interaction.
talk_to
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def think(self, message: str) -> None: """ Make the agent think about a message. """ if "think" not in self._actions: raise RuntimeError("Think action not found in the agent's action space.") self.execute_action("think", message)
Make the agent think about a message.
think
python
Thytu/Agentarium
agentarium/Agent.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Agent.py
Apache-2.0
def __new__(cls): """ Implements the singleton pattern to ensure only one instance exists. Returns: AgentInteractionManager: The single instance of the manager. """ if cls._instance is None: cls._instance = super(AgentInteractionManager, cls).__new__(cls)...
Implements the singleton pattern to ensure only one instance exists. Returns: AgentInteractionManager: The single instance of the manager.
__new__
python
Thytu/Agentarium
agentarium/AgentInteractionManager.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/AgentInteractionManager.py
Apache-2.0
def __init__(self): """ Initializes the interaction manager if not already initialized. Due to the singleton pattern, this will only execute once, even if multiple instances are created. """ if not self._initialized: self._agents: Dict[str, Agent] = {} ...
Initializes the interaction manager if not already initialized. Due to the singleton pattern, this will only execute once, even if multiple instances are created.
__init__
python
Thytu/Agentarium
agentarium/AgentInteractionManager.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/AgentInteractionManager.py
Apache-2.0
def register_agent(self, agent: Agent) -> None: """ Register a new agent with the interaction manager. This method adds the agent to the manager's registry and initializes their private interaction history. Args: agent (Agent): The agent to register with the manager...
Register a new agent with the interaction manager. This method adds the agent to the manager's registry and initializes their private interaction history. Args: agent (Agent): The agent to register with the manager.
register_agent
python
Thytu/Agentarium
agentarium/AgentInteractionManager.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/AgentInteractionManager.py
Apache-2.0
def record_interaction(self, sender: Agent, receiver: Agent | list[Agent], message: str) -> None: """ Record a new interaction between two agents. This method creates a new Interaction object and stores it in both the global interaction history and the private interaction histories of b...
Record a new interaction between two agents. This method creates a new Interaction object and stores it in both the global interaction history and the private interaction histories of both involved agents. Args: sender (Agent): The agent initiating the interaction. ...
record_interaction
python
Thytu/Agentarium
agentarium/AgentInteractionManager.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/AgentInteractionManager.py
Apache-2.0
def __new__(cls, name: str = None): """ Create or return the singleton instance of Checkpoint. Args: name (str): Name of the checkpoint """ if cls._instance is None: cls._instance = super(CheckpointManager, cls).__new__(cls) cls._instance._ini...
Create or return the singleton instance of Checkpoint. Args: name (str): Name of the checkpoint
__new__
python
Thytu/Agentarium
agentarium/CheckpointManager.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/CheckpointManager.py
Apache-2.0
def __init__(self, name: str = "default"): """ Initialize the checkpoint manager (only runs once for the singleton). Args: name (str): Name of the checkpoint """ if self._initialized: return self.name = name self.path = f"{self.name}.dil...
Initialize the checkpoint manager (only runs once for the singleton). Args: name (str): Name of the checkpoint
__init__
python
Thytu/Agentarium
agentarium/CheckpointManager.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/CheckpointManager.py
Apache-2.0
def __new__(cls): """ Implement the singleton pattern to ensure only one config instance exists. Returns: Config: The single instance of the Config class. """ if cls._instance is None: cls._instance = super(Config, cls).__new__(cls) return cls._in...
Implement the singleton pattern to ensure only one config instance exists. Returns: Config: The single instance of the Config class.
__new__
python
Thytu/Agentarium
agentarium/Config.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Config.py
Apache-2.0
def __init__(self): """ Initialize the configuration if not already initialized. Due to the singleton pattern, this will only execute once, even if multiple instances are created. """ if not self._initialized: self._config = {} self._load_config()...
Initialize the configuration if not already initialized. Due to the singleton pattern, this will only execute once, even if multiple instances are created.
__init__
python
Thytu/Agentarium
agentarium/Config.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Config.py
Apache-2.0
def _load_config(self) -> None: """ Load configuration from all sources in order of priority. The configuration is loaded in the following order: 1. Set default values 2. Override with values from config.yaml if it exists 3. Override with environment variables if they ex...
Load configuration from all sources in order of priority. The configuration is loaded in the following order: 1. Set default values 2. Override with values from config.yaml if it exists 3. Override with environment variables if they exist
_load_config
python
Thytu/Agentarium
agentarium/Config.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Config.py
Apache-2.0
def _deep_update(self, d: Dict, u: Dict) -> Dict: """ Recursively update a dictionary with values from another dictionary. Args: d (Dict): The base dictionary to update u (Dict): The dictionary containing update values Returns: Dict: The updated dict...
Recursively update a dictionary with values from another dictionary. Args: d (Dict): The base dictionary to update u (Dict): The dictionary containing update values Returns: Dict: The updated dictionary
_deep_update
python
Thytu/Agentarium
agentarium/Config.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Config.py
Apache-2.0
def dump(self) -> dict: """ Returns a dictionary representation of the interaction. """ return { "sender": self.sender.agent_id, "receiver": [receiver.agent_id for receiver in self.receiver], "message": self.message, }
Returns a dictionary representation of the interaction.
dump
python
Thytu/Agentarium
agentarium/Interaction.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Interaction.py
Apache-2.0
def __str__(self) -> str: """ Returns a human-readable string representation of the interaction. Returns: str: A formatted string showing sender, receiver, and the interaction message. """ if len(self.receiver) == 1: return f"{self.sender.name} ({self.se...
Returns a human-readable string representation of the interaction. Returns: str: A formatted string showing sender, receiver, and the interaction message.
__str__
python
Thytu/Agentarium
agentarium/Interaction.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/Interaction.py
Apache-2.0
def cache_w_checkpoint_manager(function): """ A decorator that checks if an action should be skipped based on recorded actions. If the action is found in the checkpoint manager's recorded actions, it will be skipped. This helps in replaying simulations without duplicating actions. Args: fu...
A decorator that checks if an action should be skipped based on recorded actions. If the action is found in the checkpoint manager's recorded actions, it will be skipped. This helps in replaying simulations without duplicating actions. Args: function (Callable[..., Any]): The function to deco...
cache_w_checkpoint_manager
python
Thytu/Agentarium
agentarium/utils.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/utils.py
Apache-2.0
def standardize_action_output(action): """ Decorator that standardizes the output format of action functions. This decorator ensures that all action functions return a dictionary with a consistent format, containing at minimum an 'action' key with the action name. If the original function returns a...
Decorator that standardizes the output format of action functions. This decorator ensures that all action functions return a dictionary with a consistent format, containing at minimum an 'action' key with the action name. If the original function returns a dictionary, its contents are preserved (e...
standardize_action_output
python
Thytu/Agentarium
agentarium/actions/Action.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/actions/Action.py
Apache-2.0
def verify_agent_in_kwargs(function): """ Decorator that verifies the presence of an 'agent' key in kwargs. This decorator ensures that any action function receives an agent instance through its kwargs. This is crucial for actions that need to interact with or modify the agent's state. Args: ...
Decorator that verifies the presence of an 'agent' key in kwargs. This decorator ensures that any action function receives an agent instance through its kwargs. This is crucial for actions that need to interact with or modify the agent's state. Args: function (Callable): The action functi...
verify_agent_in_kwargs
python
Thytu/Agentarium
agentarium/actions/Action.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/actions/Action.py
Apache-2.0
def talk_action_function(*args, **kwargs): """ Send a message from one agent to another and record the interaction. Args: *args: Variable length argument list where: - First argument (str): The ID of the agent to send the message to - Second argument (str): The content of th...
Send a message from one agent to another and record the interaction. Args: *args: Variable length argument list where: - First argument (str): The ID of the agent to send the message to - Second argument (str): The content of the message to send **kwargs: Arbitrary keyw...
talk_action_function
python
Thytu/Agentarium
agentarium/actions/default_actions.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/actions/default_actions.py
Apache-2.0
def think_action_function(*args, **kwargs): """ Record an agent's internal thought. Args: *params: Variable length argument list where the first argument is the thought content. **kwargs: Arbitrary keyword arguments. Must contain 'agent' key with the Agent instance. Returns: di...
Record an agent's internal thought. Args: *params: Variable length argument list where the first argument is the thought content. **kwargs: Arbitrary keyword arguments. Must contain 'agent' key with the Agent instance. Returns: dict: A dictionary containing: - sender (...
think_action_function
python
Thytu/Agentarium
agentarium/actions/default_actions.py
https://github.com/Thytu/Agentarium/blob/master/agentarium/actions/default_actions.py
Apache-2.0
def use_chatgpt(prompt: str, *args, **kwargs) -> Dict[str, str]: """ A custom action that allows an agent to interact with ChatGPT. This function demonstrates how to: 1. Maintain conversation history in agent's storage 2. Make API calls to external services 3. Update agent's memory with the inte...
A custom action that allows an agent to interact with ChatGPT. This function demonstrates how to: 1. Maintain conversation history in agent's storage 2. Make API calls to external services 3. Update agent's memory with the interaction The function follows the required format for custom actions...
use_chatgpt
python
Thytu/Agentarium
examples/3_adding_a_custom_action/demo.py
https://github.com/Thytu/Agentarium/blob/master/examples/3_adding_a_custom_action/demo.py
Apache-2.0
def print_agent_output(output: Dict[str, Any]) -> None: """ Helper function to format and print agent's action outputs. Args: output (Dict[str, Any]): The output dictionary from an agent's action """ print(f"=== Agent executed action '{output['action']}' with the following output ===", end=...
Helper function to format and print agent's action outputs. Args: output (Dict[str, Any]): The output dictionary from an agent's action
print_agent_output
python
Thytu/Agentarium
examples/3_adding_a_custom_action/demo.py
https://github.com/Thytu/Agentarium/blob/master/examples/3_adding_a_custom_action/demo.py
Apache-2.0
def main(): """ Main demo function showcasing: 1. Agent creation with personality 2. Adding a custom action 3. Direct action calls vs autonomous behavior """ # Create an agent with a defined personality agent = Agent.create_agent( agent_id="demo_agent", name="John", ...
Main demo function showcasing: 1. Agent creation with personality 2. Adding a custom action 3. Direct action calls vs autonomous behavior
main
python
Thytu/Agentarium
examples/3_adding_a_custom_action/demo.py
https://github.com/Thytu/Agentarium/blob/master/examples/3_adding_a_custom_action/demo.py
Apache-2.0
def cleanup_checkpoint_files(): """Automatically clean up any checkpoint files after each test.""" yield # Clean up any .dill files in the current directory for file in os.listdir(): if file.endswith('.dill'): os.remove(file)
Automatically clean up any checkpoint files after each test.
cleanup_checkpoint_files
python
Thytu/Agentarium
tests/conftest.py
https://github.com/Thytu/Agentarium/blob/master/tests/conftest.py
Apache-2.0
def agent_pair(): """Create a pair of agents for interaction testing.""" alice = Agent.create_agent(name="Alice", bio="Alice is a test agent") bob = Agent.create_agent(name="Bob", bio="Bob is a test agent") yield alice, bob # Reset both agents after each test that uses this fixture alice.reset()...
Create a pair of agents for interaction testing.
agent_pair
python
Thytu/Agentarium
tests/conftest.py
https://github.com/Thytu/Agentarium/blob/master/tests/conftest.py
Apache-2.0
def test_action_creation(): """Test creating an action with valid parameters.""" def test_function(*args, **kwargs): return {"result": "success"} action = Action( name="test", description="A test action", parameters=["param1", "param2"], function=test_function ) ...
Test creating an action with valid parameters.
test_action_creation
python
Thytu/Agentarium
tests/test_action.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_action.py
Apache-2.0
def test_action_single_parameter(): """Test creating an action with a single parameter string.""" def test_function(*args, **kwargs): return {"result": "success"} # Test with a single parameter string action = Action( name="test", description="A test action", parameters=...
Test creating an action with a single parameter string.
test_action_single_parameter
python
Thytu/Agentarium
tests/test_action.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_action.py
Apache-2.0
def test_invalid_action_name(): """Test that action creation fails with invalid name.""" def test_function(*args, **kwargs): return {"result": "success"} with pytest.raises(ValueError): Action( name="", description="A test action", parameters=["param1"], ...
Test that action creation fails with invalid name.
test_invalid_action_name
python
Thytu/Agentarium
tests/test_action.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_action.py
Apache-2.0
def test_invalid_parameters(): """Test that action creation fails with invalid parameters.""" def test_function(*args, **kwargs): return {"result": "success"} # Test empty parameter name with pytest.raises(ValueError): Action( name="test", description="A test act...
Test that action creation fails with invalid parameters.
test_invalid_parameters
python
Thytu/Agentarium
tests/test_action.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_action.py
Apache-2.0
def test_action_format(): """Test the action format string generation.""" def test_function(*args, **kwargs): return {"result": "success"} action = Action( name="test", description="A test action", parameters=["param1", "param2"], function=test_function ) ex...
Test the action format string generation.
test_action_format
python
Thytu/Agentarium
tests/test_action.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_action.py
Apache-2.0
def test_action_execution(base_agent): """Test executing an action with an agent.""" def test_function(*args, **kwargs): agent = kwargs["agent"] return {"message": f"Action executed by {agent.name}"} action = Action( name="test", description="A test action", paramet...
Test executing an action with an agent.
test_action_execution
python
Thytu/Agentarium
tests/test_action.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_action.py
Apache-2.0
def test_agent_creation(base_agent): """Test basic agent creation with default and custom values.""" # Test with default values assert base_agent.agent_id is not None assert base_agent.name is not None assert base_agent.age is not None assert base_agent.occupation is not None assert base_age...
Test basic agent creation with default and custom values.
test_agent_creation
python
Thytu/Agentarium
tests/test_agent.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_agent.py
Apache-2.0
def test_agent_default_actions(agent_pair): """Test that agents are created with default actions.""" alice, _ = agent_pair assert "talk" in alice._actions assert "think" in alice._actions
Test that agents are created with default actions.
test_agent_default_actions
python
Thytu/Agentarium
tests/test_agent.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_agent.py
Apache-2.0
def test_agent_custom_actions(base_agent): """Test adding and using custom actions.""" def custom_action(*args, **kwargs): agent = kwargs["agent"] return {"message": f"Custom action by {agent.name}"} custom_action_obj = Action( name="custom", description="A custom action", ...
Test adding and using custom actions.
test_agent_custom_actions
python
Thytu/Agentarium
tests/test_agent.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_agent.py
Apache-2.0
def test_checkpoint_save_load(checkpoint_manager, agent_pair): """Test saving and loading checkpoint data.""" # Create agents and perform actions alice, bob = agent_pair alice.talk_to(bob, "Hello Bob!") bob.talk_to(alice, "Hi Alice!") # Save checkpoint checkpoint_manager.save() # Crea...
Test saving and loading checkpoint data.
test_checkpoint_save_load
python
Thytu/Agentarium
tests/test_checkpoint_manager.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_checkpoint_manager.py
Apache-2.0
def test_checkpoint_recording(checkpoint_manager, agent_pair): """Test that actions are properly recorded.""" alice, bob = agent_pair # Check that actions were recorded assert len(checkpoint_manager.recorded_actions) == 2 # two agents created # Perform some actions alice.talk_to(bob, "Hello!")...
Test that actions are properly recorded.
test_checkpoint_recording
python
Thytu/Agentarium
tests/test_checkpoint_manager.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_checkpoint_manager.py
Apache-2.0
def test_singleton_behavior(): """Test that CheckpointManager behaves like a singleton.""" manager1 = CheckpointManager() manager2 = CheckpointManager() # Both instances should reference the same object assert manager1 is manager2 # Clean up if os.path.exists(manager1.path): os.rem...
Test that CheckpointManager behaves like a singleton.
test_singleton_behavior
python
Thytu/Agentarium
tests/test_checkpoint_manager.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_checkpoint_manager.py
Apache-2.0
def test_agent_registration(interaction_manager, agent_pair): """Test registering agents with the interaction manager.""" alice, bob = agent_pair # Verify agents are registered assert alice.agent_id in interaction_manager._agents assert bob.agent_id in interaction_manager._agents # Verify corr...
Test registering agents with the interaction manager.
test_agent_registration
python
Thytu/Agentarium
tests/test_interaction_manager.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_interaction_manager.py
Apache-2.0
def test_interaction_order(interaction_manager, agent_pair): """Test that interactions are recorded in order.""" alice, bob = agent_pair messages = ["First", "Second", "Third"] for msg in messages: interaction_manager.record_interaction(alice, bob, msg) # Verify interactions are in order ...
Test that interactions are recorded in order.
test_interaction_order
python
Thytu/Agentarium
tests/test_interaction_manager.py
https://github.com/Thytu/Agentarium/blob/master/tests/test_interaction_manager.py
Apache-2.0
def is_debug_environment(): """Check if the InvenTree environment is running in a debug environment.""" return is_true(os.environ.get('INVENTREE_DEBUG', 'False')) or is_true( os.environ.get('RUNNER_DEBUG', 'False') )
Check if the InvenTree environment is running in a debug environment.
is_debug_environment
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def get_version_vals(): """Get values from the VERSION file.""" version_file = local_dir().joinpath('VERSION') if not version_file.exists(): return {} try: from dotenv import dotenv_values return dotenv_values(version_file) except ImportError: error( 'ERR...
Get values from the VERSION file.
get_version_vals
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def is_pkg_installer(content: Optional[dict] = None, load_content: bool = False): """Check if the current environment is a package installer by VERSION/environment.""" if load_content: content = get_version_vals() return get_installer(content) == 'PKG'
Check if the current environment is a package installer by VERSION/environment.
is_pkg_installer
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def get_installer(content: Optional[dict] = None): """Get the installer for the current environment or a content dict.""" if content is None: content = os.environ return content.get('INVENTREE_PKG_INSTALLER', None)
Get the installer for the current environment or a content dict.
get_installer
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def task_exception_handler(t, v, tb): """Handle exceptions raised by tasks. The intent here is to provide more 'useful' error messages when tasks fail. """ sys.__excepthook__(t, v, tb) if t is ModuleNotFoundError: mod_name = str(v).split(' ')[-1].strip("'") error(f'Error importing...
Handle exceptions raised by tasks. The intent here is to provide more 'useful' error messages when tasks fail.
task_exception_handler
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def state_logger(fn=None, method_name=None): """Decorator to log state markers before/after function execution, optionally accepting arguments.""" def decorator(func): func.method_name = method_name or f'invoke task named `{func.__name__}`' @wraps(func) def wrapped(c, *args, **kwargs):...
Decorator to log state markers before/after function execution, optionally accepting arguments.
state_logger
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def envcheck_invoke_version(): """Check that the installed invoke version meets minimum requirements.""" MIN_INVOKE_VERSION: str = '2.0.0' min_version = tuple(map(int, MIN_INVOKE_VERSION.split('.'))) invoke_version = tuple(map(int, invoke.__version__.split('.'))) # noqa: RUF048 if invoke_version ...
Check that the installed invoke version meets minimum requirements.
envcheck_invoke_version
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def envcheck_invoke_path(): """Check that the path of the used invoke is correct.""" if is_docker_environment() or is_rtd_environment(): return invoke_path: Path = Path(invoke.__file__) env_path: Path = Path(sys.prefix).resolve() loc_path: Path = Path(__file__).parent.resolve() if not i...
Check that the path of the used invoke is correct.
envcheck_invoke_path
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def envcheck_python_version(): """Check that the installed python version meets minimum requirements. If the python version is not sufficient, exits with a non-zero exit code. """ REQ_MAJOR: int = 3 REQ_MINOR: int = 9 version = sys.version.split(' ')[0] valid: bool = True if sys.vers...
Check that the installed python version meets minimum requirements. If the python version is not sufficient, exits with a non-zero exit code.
envcheck_python_version
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def envcheck_invoke_cmd(): """Checks if the rights invoke command for the current environment is used.""" first_cmd = sys.argv[0].replace(sys.prefix, '') intendded = ['/bin/invoke', '/bin/inv'] correct_cmd: Optional[str] = None if is_rtd_environment() or is_docker_environment(): pass el...
Checks if the rights invoke command for the current environment is used.
envcheck_invoke_cmd
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def main(): """Main function to check the execution environment.""" envcheck_invoke_version() envcheck_python_version() envcheck_invoke_path() envcheck_invoke_cmd()
Main function to check the execution environment.
main
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def content_excludes( allow_auth: bool = True, allow_tokens: bool = True, allow_plugins: bool = True, allow_sso: bool = True, ): """Returns a list of content types to exclude from import / export. Arguments: allow_auth (bool): Allow user authentication data to be exported / imported ...
Returns a list of content types to exclude from import / export. Arguments: allow_auth (bool): Allow user authentication data to be exported / imported allow_tokens (bool): Allow tokens to be exported / imported allow_plugins (bool): Allow plugin information to be exported / imported ...
content_excludes
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def run(c, cmd, path: Optional[Path] = None, pty=False, env=None): """Runs a given command a given path. Args: c: Command line context. cmd: Command to run. path: Path to run the command in. pty (bool, optional): Run an interactive session. Defaults to False. env (dict, ...
Runs a given command a given path. Args: c: Command line context. cmd: Command to run. path: Path to run the command in. pty (bool, optional): Run an interactive session. Defaults to False. env (dict, optional): Environment variables to pass to the command. Defaults to None....
run
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def yarn(c, cmd): """Runs a given command against the yarn package manager. Args: c: Command line context. cmd: Yarn command to run. """ path = local_dir().joinpath('src', 'frontend') run(c, cmd, path, False)
Runs a given command against the yarn package manager. Args: c: Command line context. cmd: Yarn command to run.
yarn
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def node_available(versions: bool = False, bypass_yarn: bool = False): """Checks if the frontend environment (ie node and yarn in bash) is available.""" def ret(val, val0=None, val1=None): if versions: return val, val0, val1 return val def check(cmd): try: r...
Checks if the frontend environment (ie node and yarn in bash) is available.
node_available
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def check_file_existence(filename: Path, overwrite: bool = False): """Checks if a file exists and asks the user if it should be overwritten. Args: filename (str): Name of the file to check. overwrite (bool, optional): Overwrite the file without asking. Defaults to False. """ if filename...
Checks if a file exists and asks the user if it should be overwritten. Args: filename (str): Name of the file to check. overwrite (bool, optional): Overwrite the file without asking. Defaults to False.
check_file_existence
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def plugins(c, uv=False): """Installs all plugins as specified in 'plugins.txt'.""" from src.backend.InvenTree.InvenTree.config import get_plugin_file plugin_file = get_plugin_file() info(f"Installing plugin packages from '{plugin_file}'") # Install the plugins if not uv: run(c, f"pip...
Installs all plugins as specified in 'plugins.txt'.
plugins
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def setup_dev(c, tests=False): """Sets up everything needed for the dev environment.""" info("Installing required python packages from 'src/backend/requirements-dev.txt'") # Install required Python packages with PIP run(c, 'pip3 install -U --require-hashes -r src/backend/requirements-dev.txt') # I...
Sets up everything needed for the dev environment.
setup_dev
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def rebuild_models(c): """Rebuild database models with MPTT structures.""" info('Rebuilding internal database structures') manage(c, 'rebuild_models', pty=True)
Rebuild database models with MPTT structures.
rebuild_models
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def clean_settings(c): """Clean the setting tables of old settings.""" info('Cleaning old settings from the database') manage(c, 'clean_settings') success('Settings cleaned successfully')
Clean the setting tables of old settings.
clean_settings
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def static(c, frontend=False, clear=True, skip_plugins=False): """Copies required static files to the STATIC_ROOT directory, as per Django requirements.""" if frontend and node_available(): frontend_compile(c) info('Collecting static files...') cmd = 'collectstatic --no-input --verbosity 0' ...
Copies required static files to the STATIC_ROOT directory, as per Django requirements.
static
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def translate(c, ignore_static=False, no_frontend=False): """Rebuild translation source files. Advanced use only! Note: This command should not be used on a local install, it is performed as part of the InvenTree translation toolchain. """ info('Building translation files') # Translate applica...
Rebuild translation source files. Advanced use only! Note: This command should not be used on a local install, it is performed as part of the InvenTree translation toolchain.
translate
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def backup(c, clean=False, path=None): """Backup the database and media files.""" info('Backing up InvenTree database...') cmd = '--noinput --compress -v 2' if path: # Resolve the provided path path = Path(path) if not os.path.isabs(path): path = local_dir().joinpat...
Backup the database and media files.
backup
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def restore( c, path=None, db_file=None, media_file=None, ignore_media=False, ignore_database=False, ): """Restore the database and media files.""" base_cmd = '--noinput --uncompress -v 2' if path: # Resolve the provided path path = Path(path) if not os.path....
Restore the database and media files.
restore
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def migrate(c): """Performs database migrations. This is a critical step if the database schema have been altered! """ info('Running InvenTree database migrations...') # Run custom management command which wraps migrations in "maintenance mode" manage(c, 'makemigrations') manage(c, 'runmig...
Performs database migrations. This is a critical step if the database schema have been altered!
migrate
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def update( c, skip_backup: bool = False, frontend: bool = False, no_frontend: bool = False, skip_static: bool = False, uv: bool = False, ): """Update InvenTree installation. This command should be invoked after source code has been updated, e.g. downloading new code from GitHub. ...
Update InvenTree installation. This command should be invoked after source code has been updated, e.g. downloading new code from GitHub. The following tasks are performed, in order: - install - backup (optional) - migrate - frontend_compile or frontend_download (optional) - static (op...
update
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def export_records( c, filename='data.json', overwrite=False, include_permissions=False, include_tokens=False, exclude_plugins=False, include_sso=False, retain_temp=False, ): """Export all database records to a file. Write data to the file defined by filename. If --overwrite...
Export all database records to a file. Write data to the file defined by filename. If --overwrite is not set, the user will be prompted about overwriting an existing files. If --include-permissions is not set, the file defined by filename will have permissions specified for a user or group removed. If ...
export_records
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def delete_data(c, force=False): """Delete all database records! Warning: This will REALLY delete all records in the database!! """ info('Deleting all data from InvenTree database...') if force: manage(c, 'flush --noinput') else: manage(c, 'flush')
Delete all database records! Warning: This will REALLY delete all records in the database!!
delete_data
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def import_fixtures(c): """Import fixture data into the database. This command imports all existing test fixture data into the database. Warning: - Intended for testing / development only! - Running this command may overwrite existing database data!! - Don't say you were not warned...
Import fixture data into the database. This command imports all existing test fixture data into the database. Warning: - Intended for testing / development only! - Running this command may overwrite existing database data!! - Don't say you were not warned...
import_fixtures
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def wait(c): """Wait until the database connection is ready.""" info('Waiting for database connection...') return manage(c, 'wait_for_db')
Wait until the database connection is ready.
wait
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def gunicorn(c, address='0.0.0.0:8000', workers=None): """Launch a gunicorn webserver. Note: This server will not auto-reload in response to code changes. """ config_file = local_dir().joinpath('contrib', 'container', 'gunicorn.conf.py') cmd = f'gunicorn -c {config_file} InvenTree.wsgi -b {address}...
Launch a gunicorn webserver. Note: This server will not auto-reload in response to code changes.
gunicorn
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def server(c, address='127.0.0.1:8000', no_reload=False, no_threading=False): """Launch a (development) server using Django's in-built webserver. Note: This is *not* sufficient for a production installation. """ cmd = f'runserver {address}' if no_reload: cmd += ' --noreload' if no_thr...
Launch a (development) server using Django's in-built webserver. Note: This is *not* sufficient for a production installation.
server
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def test_translations(c): """Add a fictional language to test if each component is ready for translations.""" import django from django.conf import settings # setup django base_path = Path.cwd() new_base_path = pathlib.Path('InvenTree').resolve() sys.path.append(str(new_base_path)) os.c...
Add a fictional language to test if each component is ready for translations.
test_translations
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def test( c, disable_pty=False, runtest='', migrations=False, report=False, coverage=False, translations=False, ): """Run unit-tests for InvenTree codebase. Args: c: Command line context. disable_pty (bool): Disable PTY (default = False) runtest (str): Specif...
Run unit-tests for InvenTree codebase. Args: c: Command line context. disable_pty (bool): Disable PTY (default = False) runtest (str): Specify which tests to run, in format <module>.<file>.<class>.<method> (default = '') migrations (bool): Run migration unit tests (default = False) ...
test
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def export_settings_definitions(c, filename='inventree_settings.json', overwrite=False): """Export settings definition to a JSON file.""" filename = Path(filename).resolve() check_file_existence(filename, overwrite) info(f"Exporting settings definition to '{filename}'...") manage(c, f'export_settin...
Export settings definition to a JSON file.
export_settings_definitions
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def version(c): """Show the current version of InvenTree.""" import src.backend.InvenTree.InvenTree.version as InvenTreeVersion from src.backend.InvenTree.InvenTree.config import ( get_backup_dir, get_config_file, get_media_dir, get_plugin_file, get_static_dir, ) ...
Show the current version of InvenTree.
version
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def frontend_compile(c): """Generate react frontend. Args: c: Context variable """ info('Compiling frontend code...') frontend_install(c) frontend_trans(c, extract=False) frontend_build(c) success('Frontend compilation complete')
Generate react frontend. Args: c: Context variable
frontend_compile
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def frontend_install(c): """Install frontend requirements. Args: c: Context variable """ info('Installing frontend dependencies') yarn(c, 'yarn install')
Install frontend requirements. Args: c: Context variable
frontend_install
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def frontend_trans(c, extract: bool = True): """Compile frontend translations. Args: c: Context variable extract (bool): Whether to extract translations from source code. Defaults to True. """ info('Compiling frontend translations') if extract: yarn(c, 'yarn run extract') ...
Compile frontend translations. Args: c: Context variable extract (bool): Whether to extract translations from source code. Defaults to True.
frontend_trans
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def frontend_server(c): """Start frontend development server. Args: c: Context variable """ info('Starting frontend development server') yarn(c, 'yarn run compile') yarn(c, 'yarn run dev --host')
Start frontend development server. Args: c: Context variable
frontend_server
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def check_already_current(tag=None, sha=None): """Check if the currently available frontend is already the requested one.""" ref = 'tag' if tag else 'commit' if tag: current = manage_py_dir().joinpath( 'web', 'static', 'web', '.vite', 'tag.txt' ) ...
Check if the currently available frontend is already the requested one.
check_already_current
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def doc_schema(c): """Generate schema documentation for the API.""" schema( c, ignore_warnings=True, overwrite=True, filename='docs/generated/schema.yml' ) run(c, 'python docs/extract_schema.py docs/generated/schema.yml')
Generate schema documentation for the API.
doc_schema
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def docs_server(c, address='localhost:8080', compile_schema=False): """Start a local mkdocs server to view the documentation.""" # Extract settings definitions export_definitions(c, basedir='docs') if compile_schema: doc_schema(c) run(c, f'mkdocs serve -a {address} -f docs/mkdocs.yml')
Start a local mkdocs server to view the documentation.
docs_server
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def build_docs(c, mkdocs=False): """Build the required documents for building the docs. Optionally build the documentation using mkdocs.""" migrate(c) export_definitions(c, basedir='docs') doc_schema(c) if mkdocs: run(c, 'mkdocs build -f docs/mkdocs.yml') info('Documentation build ...
Build the required documents for building the docs. Optionally build the documentation using mkdocs.
build_docs
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def clear_generated(c): """Clear generated files from `invoke update`.""" # pyc/pyo files run(c, 'find src -name "*.pyc" -exec rm -f {} +') run(c, 'find src -name "*.pyo" -exec rm -f {} +') # cache folders run(c, 'find src -name "__pycache__" -exec rm -rf {} +') # Generated translations ...
Clear generated files from `invoke update`.
clear_generated
python
inventree/InvenTree
tasks.py
https://github.com/inventree/InvenTree/blob/master/tasks.py
MIT
def extract_source_strings(file_path): """Extract source strings from the provided file.""" here = os.path.abspath(os.path.dirname(__file__)) abs_file_path = os.path.abspath(os.path.join(here, *file_path)) sources = [] with open(abs_file_path, encoding='utf-8') as f: for line in f: ...
Extract source strings from the provided file.
extract_source_strings
python
inventree/InvenTree
.github/scripts/check_source_strings.py
https://github.com/inventree/InvenTree/blob/master/.github/scripts/check_source_strings.py
MIT
def compare_source_strings(sources, threshold): """Compare source strings to find duplicates (or close matches).""" issues = 0 for i, source in enumerate(sources): for other in sources[i + 1 :]: if other.lower() == source.lower(): print(f'- Duplicate: {source} ~ {other}'...
Compare source strings to find duplicates (or close matches).
compare_source_strings
python
inventree/InvenTree
.github/scripts/check_source_strings.py
https://github.com/inventree/InvenTree/blob/master/.github/scripts/check_source_strings.py
MIT
def get_existing_release_tags(include_prerelease=True): """Request information on existing releases via the GitHub API.""" # Check for github token token = os.getenv('GITHUB_TOKEN', None) headers = None if token: headers = {'Authorization': f'Bearer {token}'} response = requests.get(f'...
Request information on existing releases via the GitHub API.
get_existing_release_tags
python
inventree/InvenTree
.github/scripts/version_check.py
https://github.com/inventree/InvenTree/blob/master/.github/scripts/version_check.py
MIT
def check_version_number(version_string, allow_duplicate=False): """Check the provided version number. Returns True if the provided version is the 'newest' InvenTree release """ print(f"Checking version '{version_string}'") # Check that the version string matches the required format match = re...
Check the provided version number. Returns True if the provided version is the 'newest' InvenTree release
check_version_number
python
inventree/InvenTree
.github/scripts/version_check.py
https://github.com/inventree/InvenTree/blob/master/.github/scripts/version_check.py
MIT
def top_level_path(path: str) -> str: """Return the top level path of the input path.""" path = path.strip() if path.startswith('/'): path = path[1:] if path.endswith('/'): path = path[:-1] path = path.strip() parts = path.split('/') key = parts[1] if len(parts) > 1 else ...
Return the top level path of the input path.
top_level_path
python
inventree/InvenTree
docs/extract_schema.py
https://github.com/inventree/InvenTree/blob/master/docs/extract_schema.py
MIT