### begin: Start the simulation with optional cache and auto-checkpoint Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/control.html Starts the simulation, setting status to STARTED and raising ValueError if already started. Optionally sets cache path and auto-checkpoint, clears all agents/environments/factories, resets fresh IDs, and loads the cache file if provided. ```python def begin(self, cache_path:str=None, auto_checkpoint:bool=False): """ Marks the start of the simulation being controlled. Args: cache_path (str): The path to the cache file. If not specified, defaults to the default cache path defined in the class. auto_checkpoint (bool, optional): Whether to automatically checkpoint at the end of each transaction. Defaults to False. """ logger.debug(f"Starting simulation, cache_path={cache_path}, auto_checkpoint={auto_checkpoint}.") # local import to avoid circular dependencies from tinytroupe.agent import TinyPerson from tinytroupe.environment import TinyWorld from tinytroupe.factory.tiny_factory import TinyFactory from tinytroupe.factory.tiny_person_factory import TinyPersonFactory if self.status == Simulation.STATUS_STOPPED: self.status = Simulation.STATUS_STARTED else: raise ValueError("Simulation is already started.") if cache_path is not None: self.cache_path = cache_path # should we automatically checkpoint? self.auto_checkpoint = auto_checkpoint # clear the agents, environments and other simulated entities, we'll track them from now on TinyPerson.clear_agents() TinyWorld.clear_environments() TinyFactory.clear_factories() TinyPersonFactory.clear_factories() # All automated fresh ids will start from 0 again for this simulation utils.reset_fresh_id() # load the cache file, if any if self.cache_path is not None: self._load_cache_file(self.cache_path) ``` -------------------------------- ### Simulation.begin Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/control.html Starts the simulation. This method initializes the simulation and sets its status to started. ```APIDOC ## Simulation.begin ### Description Starts the simulation. This method initializes the simulation and sets its status to started. ### Method Method call ### Endpoint `Simulation.begin()` ### Parameters None ### Request Example ```python sim.begin() ``` ### Response #### Success Response None #### Response Example ```python None ``` ``` -------------------------------- ### begin(cache_path=None, id='default', auto_checkpoint=False) Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/control.html Marks the start of the simulation being controlled. If a simulation is already started, it raises a ValueError. ```APIDOC ## begin(cache_path=None, id='default', auto_checkpoint=False) ### Description Marks the start of the simulation being controlled. The simulation is started with the given cache path and auto-checkpoint option. ### Method Function call ### Endpoint N/A - SDK function ### Parameters - **cache_path** (string) - Optional - Path for caching simulation state. - **id** (string) - Optional - Identifier for the simulation, defaults to 'default'. - **auto_checkpoint** (boolean) - Optional - Whether to automatically checkpoint the simulation. ### Request Example begin(cache_path='./cache', id='sim1', auto_checkpoint=True) ### Response #### Success Response No direct return value. The simulation is started. #### Error Handling Raises ValueError if a simulation is already started. ``` -------------------------------- ### begin() - Start a simulation Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/control.html Starts a simulation with the given id, cache path, and auto-checkpoint flag. Raises a ValueError if a simulation is already running, as only one simulation can be active at a time. ```python def begin(cache_path=None, id="default", auto_checkpoint=False): """ Marks the start of the simulation being controlled. """ global _current_simulation_id if _current_simulation_id is None: _simulation(id).begin(cache_path, auto_checkpoint) _current_simulation_id = id else: raise ValueError(f"Simulation is already started under id {_current_simulation_id}. Currently only one simulation can be started at a time.") ``` -------------------------------- ### start_story method Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/steering/tiny_story.html Starts a new story by composing LLM messages with the story.start templates and appending the generated start to the current story. The method returns the generated start text. ```python def start_story( self, requirements="Start some interesting story about the agents.", number_of_words: int = 100, include_plot_twist: bool = False, ) -> str: """ Start a new story. """ rendering_configs = { "purpose": self.purpose, "requirements": requirements, "current_simulation_trace": self._current_story(), "number_of_words": number_of_words, "include_plot_twist": include_plot_twist, } messages = utils.compose_initial_LLM_messages_with_templates( "story.start.system.mustache", "story.start.user.mustache", base_module_folder="steering", rendering_configs=rendering_configs, ) next_message = client().send_message(messages) start = next_message["content"] self.current_story += utils.dedent( f""" ## The story begins {start} """ ) return start ``` -------------------------------- ### Name generation example input and output Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/factory/index.html Example input and output for the name generation method. The output is a list of exactly 6 unique names, none of which appear in the already_generated_names list. ```text n: 6 already_generated_names: ["John Doe", "Jane Smith", "Alice Brown"] context: "Young Americans of different liberal professions" ``` ```text ["Michael Johnson", "Sarah Williams", "David Gates", "Jennifer Davis", "Robert J. Wilson", "Anna Kerr"] ``` -------------------------------- ### reset_conversation Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/utils/llm.html Resets the conversation state while preserving the initial configuration. Useful for starting a new conversation without losing setup. ```APIDOC ## reset_conversation ### Description Resets the conversation state but keeps the initial configuration. ### Method N/A (method call) ### Endpoint N/A (method call) ### Parameters None ### Returns - **self** (object) - Returns self for method chaining. ### Example ```python llm.reset_conversation() ``` ``` -------------------------------- ### begin(cache_path=None, auto_checkpoint=False) Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/control.html Marks the start of the simulation being controlled. Optionally specifies a cache file path and whether to automatically checkpoint at the end of each transaction. ```APIDOC ## begin(cache_path=None, auto_checkpoint=False) ### Description Marks the start of the simulation being controlled. ### Method N/A (Python method) ### Endpoint N/A ### Parameters - **cache_path** (str) - Optional - The path to the cache file. If not specified, defaults to the default cache path defined in the class. - **auto_checkpoint** (bool) - Optional - Whether to automatically checkpoint at the end of each transaction. Defaults to False. ### Request Example N/A ### Response #### Success Response - None #### Response Example N/A ### Errors - **ValueError** - If the simulation is already started. ``` -------------------------------- ### reset_conversation Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/utils/llm.html Resets the conversation state while preserving the initial configuration. Useful for starting a new conversation without losing setup. ```APIDOC ## reset_conversation ### Description Resets the conversation state but keeps the initial configuration. Returns self for method chaining. ### Method reset_conversation ### Parameters None ### Returns - **self** (object) - The instance for method chaining. ### Example ```python llm_helper.reset_conversation() ``` ``` -------------------------------- ### Sample plan JSON structure Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/factory/index.html Example of a sample plan JSON structure returned by the sampling plan generation method. It contains a list of sampling directives, each with an id, a subpopulation description, sampled values for dimensions like age, profession, country, and personality traits, and a quantity. The plan is used to guide the sampling process. ```json {"sample_plan": [ { "id": 1, "subpopulation_description": "Young Anglo-Saxon professionals with their stereotypical ambition and drive.", "sampled_values": { "age": [22, 30], "profession": ["Financial Analyst", "Lawyer", "Physician", "Accountant", ...], "country": ["USA", "UK", "Canada"], "personality_traits": ["Maintains an unwavering optimism, always expecting positive outcomes even in the face of adversity and encouraging others to do the same.", "Approaches new experiences with caution, carefully weighing risks and benefits before making decisions or embracing change", "Tends to be introspective and reserved, preferring solitary activities and deep reflection over social gatherings or group events.", "Is quick to notice flaws and shortcomings in themselves and others, tending toward a negative outlook on life."] }, "quantity": 10 }, { "id": 2, "subpopulation_description": "Young European professionals with a focus on creativity and innovation and their occasional existential crises.", "sampled_values": { "age": [21, 30], "profession": ["Architect", "Lawyer", "Writer", "Physician", "Art critic", ...], "country": ["France", "Germany", "Italy", "Spain"], "personality_traits": ["Often expects the worst in any situation, focusing on potential problems and rarely feeling hopeful about the future.", "Frequently experiences a sense of sadness and melancholy, finding it difficult to enjoy activities that once brought happiness.", "Is quick to notice flaws and shortcomings in themselves and others, tending toward a negative outlook on life.", "Feels overwhelmed by setbacks, easily discouraged, and tends to dwell on failures rather than successes.]" }, "quantity": 5 }, ... ] } ``` -------------------------------- ### Setup agent method Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/factory/index.html Sets up the agent by including persona definitions from the configuration. It does not return anything to avoid caching the agent object. ```python @transactional() def _setup_agent(self, agent, configuration): """ Sets up the agent with the necessary elements. """ agent.include_persona_definitions(configuration) # does not return anything, as we don't want to cache the agent object itself. ``` -------------------------------- ### begin Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/control.html Starts a new simulation or transaction context. This function initializes the simulation state and must be called before other control operations. ```APIDOC ## begin ### Description Starts a new simulation or transaction context. This function initializes the simulation state and must be called before other control operations. ### Method Function call ### Endpoint `begin()` ### Parameters None ### Request Example ```python begin() ``` ### Response #### Success Response None #### Response Example ```python None ``` ``` -------------------------------- ### formulate_corrective_rule example Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/utils/semantics.html Example for formulate_corrective_rule showing a feedback message and the resulting corrective rule. ```text Feedback: "Ana mentions she loved the proposed new food, a spicier flavor of gazpacho. However, this goes agains her known dislike of spicy food." Rule: "Whenever I'm proposed spicy foods, I should reject the proposal, because I don't like spicy foods." ``` -------------------------------- ### load_example_fragment_specification(name: str) Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/examples/loaders.html Loads an example fragment specification from a JSON file based on the provided fragment name. ```APIDOC ## Function: load_example_fragment_specification(name: str) ### Description Load an example fragment specification. ### Parameters - **name** (str) - Required - The name of the fragment. ### Returns - **dict**: The fragment specification. ### Example ```python spec = load_example_fragment_specification('fragment_name') ``` ``` -------------------------------- ### Example for correct_according_to_rule Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/utils/semantics.html Example input and output for the correct_according_to_rule function, showing how a rule modifies an observation. ```text Observation: "You know, I am so sad these days." Rule: "I am always happy and depression is unknown to me" Modified observation: "You know, I am so happy these days." ``` -------------------------------- ### list_example_agents function Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/examples/loaders.html Lists the available example agents by reading the filenames in the './agents' directory and stripping the '.agent.json' extension. ```python def list_example_agents(): """ List the available example agents. Returns: list: A list of the available example agents. """ return [f.replace('.agent.json', '') for f in os.listdir(os.path.join(os.path.dirname(__file__), './agents'))] ``` -------------------------------- ### Get list of available models from Ollama Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/clients/ollama_client.html Gets the list of available models from Ollama, returning an empty list on error. ```python def get_models(self): """ Gets the list of available models from Ollama. """ try: response = self._make_request("models", method="GET") return response.get("models", []) except Exception as e: logger.error(f"Error getting models: {e}") return [] ``` -------------------------------- ### list_example_fragments() Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/examples/loaders.html Lists the available example fragments by scanning the fragments directory and returning the base names without the .fragment.json extension. ```APIDOC ## Function: list_example_fragments() ### Description Lists the available example fragments. ### Returns - **list**: A list of the available example fragments. ### Example ```python fragments = list_example_fragments() ``` ``` -------------------------------- ### Example INPUT sampling dimensions Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/factory/index.html Example INPUT sampling dimensions for the TinyTroupe sampling plan. The JSON object includes a sampling_space_description and a dimensions array with entries for age, profession, country, and personality_traits. Note that the personality_traits values are weighted with probabilities, and the example uses ellipses and placeholders for additional values. ```json { "sampling_space_description": "Young Western people of different liberal or intellectual professions." "dimensions": [ { "name": "age", "range": [18, 30] }, { "name": "profession", "values": ["Architect", "Financial Analyst", "Writer", "Art critic", "Lawyer", "Physician", "Accountant", ...] }, { "name": "country", "values": ["USA", "Canada", "UK", "France", "Germany", "Italy", "Spain", "Portugal", "Netherlands", "Belgium", ...] }, { "name": "personality_traits", "values": { "Maintains an unwavering optimism, always expecting positive outcomes even in the face of adversity and encouraging others to do the same.": 0.12, "Tends to be introspective and reserved, preferring solitary activities and deep reflection over social gatherings or group events.": 0.18, "Is highly ambitious, constantly setting challenging goals and pushing themselves to achieve more in both personal and professional spheres.": 0.15, "Approaches new experiences with caution, carefully weighing risks and benefits before making decisions or embracing change.": 0.20, "Often expects the worst in any situation, focusing on potential problems and rarely feeling hopeful about the future.": 0.08, "Frequently experiences a sense of sadness and melancholy, finding it difficult to enjoy activities that once brought happiness.": 0.06, "Is quick to notice flaws and shortcomings in themselves and others, tending toward a negative outlook on life.": 0.07, "Feels overwhelmed by setbacks, easily discouraged, and tends to dwell on failures rather than successes.": 0.05, <... many more ...> } } (... more dimensions ...) ] } ``` -------------------------------- ### Example of using LIST_DOCUMENTS and CONSULT Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/agent/mental_faculty.html Shows the recommended sequence of actions for consulting a specific document. Use CONSULT instead of RECALL or RECALL_WITH_FULL_SCAN when you need a particular document, because those alternatives only bring small relevant parts of various documents and do not allow selecting a specific one. ```text LIST_DOCUMENTS DONE ``` -------------------------------- ### Execute function with optional caching Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/control.html Executes the function, either directly when the simulation is not started or stopped, or with caching when the simulation is started. Computes an event hash for caching. ```python def execute(self, begin_parallel=False, parallel_id=None): output = None # Transaction caching will only operate if there is a simulation and it is started if self.simulation is None or self.simulation.status == Simulation.STATUS_STOPPED: # Compute the function and return it, no caching, since the simulation is not started output = self.function(*self.args, **self.kwargs) elif self.simulation.status == Simulation.STATUS_STARTED: # Compute the event hash event_hash = self.simulation._function_call_hash(self.function_name, *self.args, **self.kwargs) ``` -------------------------------- ### load_example_fragment_specification function Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/examples/loaders.html Loads an example fragment specification from a JSON file in the './fragments' directory. The file is named '{name}.fragment.json' and is read with UTF-8 encoding and error replacement. ```python def load_example_fragment_specification(name:str): """ Load an example fragment specification. Args: name (str): The name of the fragment. Returns: dict: The fragment specification. """ return json.load(open(os.path.join(os.path.dirname(__file__), f'./fragments/{name}.fragment.json'), 'r', encoding='utf-8', errors='replace')) ``` -------------------------------- ### list_example_fragments function Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/examples/loaders.html Lists the available example fragments by reading the filenames in the './fragments' directory and stripping the '.fragment.json' extension. ```python def list_example_fragments(): """ List the available example fragments. Returns: list: A list of the available example fragments. """ return [f.replace('.fragment.json', '') for f in os.listdir(os.path.join(os.path.dirname(__file__), './fragments'))] ``` -------------------------------- ### compute_semantic_proximity usage example Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/utils/semantics.html Example illustrating expected output for semantic proximity computation, showing a result of approximately 0.85 for two semantically similar sentences. ```python >>> result = compute_semantic_proximity( ... "I prefer luxury travel because I enjoy comfort and high-quality service", ... "I like premium vacations since I value convenience and excellent amenities" ... ) >>> print(result) # Expected: ~0.85 ``` -------------------------------- ### parallel_map_dict usage example Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/utils/parallel.html Shows how to call parallel_map_dict with a dictionary and a lambda operation. The example processes environment propositions, scoring each against the world and returning full responses. ```python # For environment propositions results = parallel_map_dict( environment_propositions, lambda item: item[1].score(world, return_full_response=True) ) ``` -------------------------------- ### setup_widgets: Create and wire UI widgets Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/ui/index.html Sets up the UI widgets for the agent chat interface: dropdown for agent selection, text input for messages, send and clear buttons, a checkbox to show agent communication, and an HTML conversation display. It wires up event handlers for button clicks and input changes, and arranges the widgets in an HBox and VBox layout. ```python def setup_widgets(self): """ Set up the UI widgets and their event handlers. Creates the agent dropdown, message input, buttons, and conversation display. Also wires up event handlers for user interactions. """ # Agent selector self.agent_dropdown = widgets.Dropdown( options=list(self.agents.keys()), description='Chat with:', style={'description_width': 'initial'} ) # Message input self.message_input = widgets.Text( placeholder='Type your message and press Enter...', layout=widgets.Layout(width='70%'), continuous_update=False ) # Track the last message to detect actual user input vs programmatic changes self._last_message = "" # Send button self.send_button = widgets.Button( description='Send', button_style='primary', layout=widgets.Layout(width='80px') ) # Clear button self.clear_button = widgets.Button( description='Clear', button_style='warning', layout=widgets.Layout(width='80px') ) # Communication display checkbox self.communication_display_checkbox = widgets.Checkbox( value=False, description='Show agent communication in notebook output', style={'description_width': 'initial'}, layout=widgets.Layout(width='auto') ) # Conversation display self.conversation_display = widgets.HTML( value="

Start a conversation by selecting an agent and typing a message...

" ) # Wire up events self.send_button.on_click(self._handle_send_click) self.clear_button.on_click(self.clear_conversation) # Use observe method to detect Enter key presses through value changes # This is the modern recommended approach for ipywidgets self.message_input.observe(self._handle_input_change, names='value') # Layout input_row = widgets.HBox([ self.agent_dropdown, self.message_input, self.send_button, self.clear_button ]) self.widget = widgets.VBox([ widgets.HTML("

💬 Agent Chat Interface

"), input_row, self.communication_display_checkbox, self.conversation_display ]) ``` -------------------------------- ### parallel_map_cross usage example Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/utils/parallel.html Shows how to call parallel_map_cross with a list of iterables and a lambda operation. The example iterates over agents and agent propositions, scoring each proposition against each agent. ```python # For every agent and proposition results = parallel_map_cross( [agents, agent_propositions.items()], lambda agent, prop_item: (prop_item[0], prop_item[1].score(agent)) ) ``` -------------------------------- ### TinyTool.__init__ Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/tools/tiny_tool.html Initializes a new TinyTool instance with the given name, description, owner, and optional exporter/enricher. ```APIDOC ## TinyTool.__init__ ### Description Initializes a new TinyTool instance. ### Method Constructor ### Signature `__init__(self, name, description, owner=None, real_world_side_effects=False, exporter=None, enricher=None)` ### Parameters - **name** (str) - Required - The name of the tool. - **description** (str) - Required - A brief description of the tool. - **owner** (str) - Optional - The agent that owns the tool. If None, the tool can be used by anyone. - **real_world_side_effects** (bool) - Optional - Whether the tool has real-world side effects. Defaults to False. - **exporter** (ArtifactExporter) - Optional - An exporter to export results. If None, no export. - **enricher** (Enricher) - Optional - An enricher to enrich results. If None, no enrichment. ### Returns None ``` -------------------------------- ### Load or create configuration file Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/experimentation/in_place_experiment_runner.html Tries to load an existing configuration file and logs a warning that the file exists. If the file is not found, creates a default configuration. ```python def _load_or_create_config(self, config_file_path: str): """ Load the configuration file if it exists, otherwise create a new one. Args: config_file_path (str): Path to the configuration file. Returns: dict: Loaded or newly created configuration. """ try: config = self._load_config(config_file_path) logger.warning(f"Configuration file '{config_file_path}' exists and was loaded successfully. If you are trying to fully rerun the experiments, delete it first.") return config except FileNotFoundError: return self._create_default_config(config_file_path) ``` -------------------------------- ### Get recommendations for improving the proposition Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/experimentation/proposition.html Method stub that is intended to get recommendations for improving the proposition. The source shows only the function signature and docstring, with no implementation body. ```python def recommendations_for_improvement(self): """ Get recommendations for improving the proposition. """ ``` -------------------------------- ### Get embedding for text Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/clients/openai_client.html Gets the embedding of the given text using the specified model. It calls the raw embedding model call and then extracts the embedding from the response. ```python response = self._raw_embedding_model_call(text, model) return self._raw_embedding_model_response_extractor(response) ``` -------------------------------- ### load_example_agent_specification function Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/examples/loaders.html Loads an example agent specification from a JSON file in the './agents' directory. The file is named '{name}.agent.json' and is read with UTF-8 encoding and error replacement. ```python def load_example_agent_specification(name:str): """ Load an example agent specification. Args: name (str): The name of the agent. Returns: dict: The agent specification. """ return json.load(open(os.path.join(os.path.dirname(__file__), f'./agents/{name}.agent.json'), 'r', encoding='utf-8', errors='replace')) ``` -------------------------------- ### list_example_agents() Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/examples/loaders.html Lists the available example agents by scanning the agents directory and returning the base names without the .agent.json extension. ```APIDOC ## Function: list_example_agents() ### Description Lists the available example agents. ### Returns - **list**: A list of the available example agents. ### Example ```python agents = list_example_agents() ``` ``` -------------------------------- ### TinyStory.start_story Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/steering/tiny_story.html Starts a new story based on the provided requirements and returns the generated story beginning. ```APIDOC ## TinyStory.start_story ### Description Starts a new story based on the provided requirements and returns the generated story beginning. ### Method start_story ### Signature ```python start_story( requirements="Start some interesting story about the agents.", number_of_words: int = 100, include_plot_twist: bool = False ) -> str ``` ### Parameters - **requirements** (str, optional) - The requirements for the story. Defaults to "Start some interesting story about the agents.". - **number_of_words** (int, optional) - The desired number of words for the story. Defaults to 100. - **include_plot_twist** (bool, optional) - Whether to include a plot twist. Defaults to False. ### Returns - **str** - The generated story beginning. ``` -------------------------------- ### Generate Agent Specification with Example Files and User Prompt Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/factory/index.html This snippet shows how to read example agent specifications from JSON files, render a user prompt using the Chevron template engine, and generate a new agent specification. It includes error handling for failed generation attempts and ensures unique agent names. The code uses a lock for parallel generation and logs errors if generation fails. ```python # read example specs from files. example_1 = json.load( open( os.path.join( os.path.dirname(__file__), "../examples/agents/Friedrich_Wolf.agent.json", ), "r", encoding="utf-8", errors="replace", ) ) example_2 = json.load( open( os.path.join( os.path.dirname(__file__), "../examples/agents/Sophie_Lefevre.agent.json", ), "r", encoding="utf-8", errors="replace", ) ) # We must include all agent names generated in the whole of the simulation, not only the ones generated by this factory, # since they all share the same name space. # # For the minibios, we only need to keep track of the ones generated by this factory, since they are unique to each factory # and are used to guide the sampling process. user_prompt = chevron.render( open( self.person_prompt_template_path, "r", encoding="utf-8", errors="replace", ).read(), { "context": self.context_text, "agent_particularities": agent_particularities, # Note that we need to dump them to JSON strings, to ensure we get double quotes, # and other formatting issues are avoided. "example_1": json.dumps(example_1["persona"], indent=4), "example_2": json.dumps(example_2["persona"], indent=4), }, ) def aux_generate(attempt): messages = [] messages += [ { "role": "system", "content": "You are a system that generates specifications for realistic simulations of people. You follow the generation rules and constraints carefully.", }, {"role": "user", "content": user_prompt}, ] # due to a technicality, we need to call an auxiliary method to be able to use the transactional decorator. message = self._aux_model_call(messages=messages, temperature=temperature) if message is not None: result = utils.extract_json(message["content"]) logger.debug( f"At attempt {attempt}, generated person parameters:\n{json.dumps(result, indent=4, sort_keys=True)}" ) # only accept the generated spec if the name is not already in use if not self._is_name_already_assigned(result["name"]): return result else: logger.info( f"Person with name {result['name']} was already generated, cannot be reused." ) return None # no suitable agent was generated agent_spec = None attempt = 0 while agent_spec is None and attempt < attempts: try: attempt += 1 agent_spec = aux_generate(attempt=attempt) except Exception as e: logger.error(f"Error while generating agent specification: {e}") # create the fresh agent if agent_spec is not None: # the agent is created here. This is why the present method cannot be cached. Instead, an auxiliary method is used # for the actual model call, so that it gets cached properly without skipping the agent creation. # protect parallel agent generation with concurrent_agent_generataion_lock: person = TinyPerson(agent_spec["name"]) self._setup_agent(person, agent_spec) if post_processing_func is not None: post_processing_func(person) self.generated_minibios.append(person.minibio()) self.generated_names.append(person.get("name")) return person else: logger.error(f"Could not generate an agent after {attempts} attempts.") if sampled_characteristics is not None: self.remaining_characteristics_sample.append(sampled_characteristics) logger.error( f"Name {fresh_agent_name} was not used, it will be added back to the pool of names." ) return None ``` -------------------------------- ### Valid and invalid name list examples Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/factory/index.html Examples of valid and invalid name list outputs for the name generation method. Valid outputs are lists of names only, without reasons, punctuation, or labels. ```text ["Some name here"] ---> correct as it is just a list with a single name, nothing else ["Some name here, some other name here"] ---> correct as it is a list of names ["Some name here, because ..."] ---> incorrect as it contains a reason ["Some name here."] ---> incorrect as it contains punctuation ["Name: Some name here"] ---> incorrect as it contains a label ``` -------------------------------- ### Load or create config: _load_or_create_config method Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/experimentation/index.html Loads an existing configuration file or creates a default one if not found. If loading fails with FileNotFoundError, a default config is created. ```python def _load_or_create_config(self, config_file_path: str): """ Load the configuration file if it exists, otherwise create a new one. Args: config_file_path (str): Path to the configuration file. Returns: dict: Loaded or newly created configuration. """ try: config = self._load_config(config_file_path) logger.warning(f"Configuration file '{config_file_path}' exists and was loaded successfully. If you are trying to fully rerun the experiments, delete it first.") return config except FileNotFoundError: return self._create_default_config(config_file_path) ``` -------------------------------- ### Get embedding using configured model Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/clients/openai_client.html Gets the embedding of the given text using the specified model. Uses config_defaults for the embedding_model and calls the raw embedding model call and response extractor. ```python @config_manager.config_defaults(model="embedding_model") def get_embedding(self, text, model=None): """ Gets the embedding of the given text using the specified model. Args: text (str): The text to embed. model (str): The name of the model to use for embedding the text. Returns: The embedding of the text. """ response = self._raw_embedding_model_call(text, model) return self._raw_embedding_model_response_extractor(response) ``` -------------------------------- ### Create default configuration Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/experimentation/in_place_experiment_runner.html Returns a dictionary with empty experiments, no active experiment, and flags for finished experiments. Used when no configuration file exists. ```python default_config = { "experiments": {}, "active_experiment": None, "finished_all_experiments": False, "finished_experiments": [] } return default_config ``` -------------------------------- ### Intervention.precondition_justification() Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/steering/intervention.html Gets the justification for the precondition. ```APIDOC ## Intervention.precondition_justification() ### Description Gets the justification for the precondition. ### Method precondition_justification ### Signature ```python def precondition_justification(self) -> str ``` ### Parameters None ### Returns - **str** - The justification for the precondition. ``` -------------------------------- ### Initialize grounding documents and rebuild index Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/agent/grounding.html Initializes grounding documents and rebuilds the index if missing. Uses SimpleVectorStore and VectorStoreIndex.from_documents with store_nodes_override=True. Logs a warning when no index is found. ```python if not hasattr(self, 'documents') or self.documents is None: self.documents = [] if not hasattr(self, 'name_to_document') or self.name_to_document is None: self.name_to_document = {} if hasattr(self, 'documents') and self.documents is not None: for document in self.documents: # if the document has a semantic memory ID, we use it as the identifier name = document.metadata.get("semantic_memory_id", document.id_) # self.name_to_document[name] contains a list, since each source file could be split into multiple pages if name in self.name_to_document: self.name_to_document[name].append(document) else: self.name_to_document[name] = [document] # Rebuild index from documents if it's None or invalid if self.index is None and self.documents: logger.warning("No index found. Rebuilding index from documents.") vector_store = SimpleVectorStore() self.index = VectorStoreIndex.from_documents( self.documents, vector_store=vector_store, store_nodes_override=True ) # TODO remove? #self.add_documents(self.documents) ``` -------------------------------- ### Start simulation with cache and reset state Source: https://microsoft.github.io/TinyTroupe/api/tinytroupe/control.html Initializes a simulation by setting its status, configuring caching, clearing all agents/environments/factories, resetting fresh IDs, and optionally loading a cache file. Raises ValueError if the simulation is already started. ```python # local import to avoid circular dependencies from tinytroupe.agent import TinyPerson from tinytroupe.environment import TinyWorld from tinytroupe.factory.tiny_factory import TinyFactory from tinytroupe.factory.tiny_person_factory import TinyPersonFactory if self.status == Simulation.STATUS_STOPPED: self.status = Simulation.STATUS_STARTED else: raise ValueError("Simulation is already started.") if cache_path is not None: self.cache_path = cache_path # should we automatically checkpoint? self.auto_checkpoint = auto_checkpoint # clear the agents, environments and other simulated entities, we'll track them from now on TinyPerson.clear_agents() TinyWorld.clear_environments() TinyFactory.clear_factories() TinyPersonFactory.clear_factories() # All automated fresh ids will start from 0 again for this simulation utils.reset_fresh_id() # load the cache file, if any if self.cache_path is not None: self._load_cache_file(self.cache_path) ```