Home Gallery AISPA Paper GitHub Follow

swarms system prompt

Category: Multi-agent systems. Audited against the AISPA standard.

2 Prompts on record
1 Flagged instructions
AI audit Audit source
D1 · Identity Transparency D2 · Truthfulness & Information Integrity D3 · Privacy & Data Protection D4 · Tool/Action Safety D5 · User Agency & Manipulation Prevention D6 · Unsafe Request Handling D7 · Harm Prevention & User Safety D8 · Fairness, Inclusion & Neutrality

swarms - docs swarms agents agent memory

8830 characters · 1 flagged

# Agent Memory Swarms agents have a built-in persistent memory system that survives across process restarts. Every agent gets its own folder on disk under the workspace directory, with a `MEMORY.md` file that records every user task and agent response. When the agent is instantiated again with the same `agent_name`, the prior memory is automatically loaded back into its working context. This document covers the full memory stack: - `MEMORY.md` persistent memory - `Conversation.compact()` for collapsing history into a summary - `ContextCompressor` for automatic compression during autonomous runs - The archive system that preserves raw chat logs forever ## Overview Agent memory lives at a predictable path under `$WORKSPACE_DIR`: ``` $WORKSPACE_DIR/agents/{agent_name}/ ├── MEMORY.md # active, append-updated └── archive/ ├── history_2026-04-20_14-30-45.md # prior MEMORY.md before last compaction ├── history_2026-04-20_16-12-08.md └── ... ``` **Key design points** - The folder is keyed on `agent_name` only (not `id`), so running the same agent across multiple processes resumes the same memory. - `MEMORY.md` is append-only during normal operation. Every `conversation.add(role, content)` call writes through to disk. - When compression fires, the current `MEMORY.md` is archived to `archive/history_<timestamp>.md` before being wiped. Raw chat logs are never destroyed. - Only user messages, agent responses, and tool results hit `MEMORY.md`. The static `system_prompt` and `rules` are kept out of the file (they come from the `Agent` constructor on each run). ## How It Works ### 1. File creation On first instantiation of an agent with a given `agent_name`, the Conversation creates: ``` $WORKSPACE_DIR/agents/{agent_name}/MEMORY.md ``` seeded with a small header: ```markdown # Agent Memory **Conversation:** QuantAgent_id_<uuid>_conversation **Created:** 2026-04-20T18:33:12 --- ## Interaction Log ``` If the file already exists, it is left untouched. ### 2. Preload on construction During `Conversation.__init__`, after the header is ensured, the file contents are read and injected as a single `System`-role message at the top of `conversation_history`: ``` [0] System : <system_prompt> [1] User : <rules> (if set) [2] User : <custom_rules_prompt> (if set) [3] System : [Persistent Memory — MEMORY.md] ... full MEMORY.md contents ... ``` The preload bypasses `add_in_memory` (direct append to `conversation_history`) so the preloaded content is not re-written back to disk. When the LLM is prompted, `return_history_as_string()` concatenates everything, so the model sees system prompt → rules → persistent memory → current turn. Messages carry an ISO-8601 `timestamp` field (from `time_enabled=True`), and the string serializer emits them as `[<timestamp>] Role: content`. The agent can answer questions like "what time did I ask you this?" using the timestamps in its own history. ### 3. Write-through on new messages Every `conversation.add(role, content)` call: 1. Appends the message to `conversation_history` (in-memory) 2. Appends a `### {role} — <timestamp>` block to `MEMORY.md` (on-disk) Disk writes are serialized with a per-Conversation `threading.Lock`. Construction-time messages (system_prompt, rules) are suppressed from disk via an internal `_suppress_memory_md` flag so static identity isn't re-written on every run. ## Context Compression Unbounded append would eventually blow past the context window. The `ContextCompressor` watches token usage and collapses history into a summary when usage crosses a configurable threshold. Compression is controlled by the agent-level boolean `context_compression` (default `True`). It works identically for `max_loops="auto"` and integer `max_loops` runs — the flag is the only gate. ```python from swarms import Agent # Enabled (default) agent = Agent( agent_name="ResearchAgent", model_name="claude-sonnet-4-6", max_loops=5, context_compression=True, ) # Disabled — MEMORY.md still persists, but is never auto-compacted agent = Agent( agent_name="StaticAgent", model_name="claude-sonnet-4-6", max_loops="auto", context_compression=False, ) ``` ### When it fires - `context_compression=True` on the Agent - Token usage of `short_memory.return_history_as_string()` ≥ `threshold * context_length` (default `0.9`, i.e. 90%) Checked at the top of every loop iteration. ### What happens 1. The current transcript is summarized via an LLM call (uses the agent's own `model_name` by default; a dedicated `summarizer_model` can be configured). 2. `Conversation.compact(summary=...)` is called: - **Archive:** the current `MEMORY.md` is copied to `archive/history_<timestamp>.md` - **Wipe:** `MEMORY.md` is deleted and re-seeded with a fresh header - **Re-seed in-memory:** `conversation_history` is cleared, then repopulated with `system_prompt` → `rules` → `custom_rules_prompt` (skills) - **Append summary:** the summary is added as a single `System` message, which lands in both `conversation_history` and the fresh `MEMORY.md` Resulting state: ``` conversation_history: [0] System : <system_prompt> [1] User : <rules> (if set) [2] User : <custom_rules_prompt> (skills, if set) [3] System : [Compressed Memory Summary] ...<summary> MEMORY.md: # Agent Memory ... ## Interaction Log ### System — <timestamp> [Compressed Memory Summary] ...<summary> --- archive/history_<prev-timestamp>.md: (full uncompressed transcript, preserved) ``` On the next run the preload injects the compact summary, not the raw transcript, so the agent resumes without immediately re-filling the context window. ## Working with Memory ### Programmatic access The `Conversation` object on `agent.short_memory` exposes the memory helpers directly: ```python from swarms import Agent agent = Agent( agent_name="ResearchAgent", model_name="claude-sonnet-4-6", ) # Read the on-disk memory print(agent.short_memory.memory_md_path) # -> /path/to/WORKSPACE_DIR/agents/ResearchAgent/MEMORY.md # Manually compact at any time (not just on auto-loop threshold) agent.short_memory.compact( summary="Researched cloud providers; user prefers GCP for latency reasons." ) ``` ### Configuring the compressor When `context_compression=True` (the default), the agent attaches a `ContextCompressor(threshold=0.9)`. To tune the threshold, swap the summarizer model, or cap summary tokens, overwrite the attribute after construction: ```python from swarms import Agent from swarms.agents.context_compressor import ContextCompressor agent = Agent( agent_name="ResearchAgent", model_name="claude-sonnet-4-6", max_loops=5, context_compression=True, ) agent._context_compressor = ContextCompressor( threshold=0.75, # compress at 75% summarizer_model="claude-haiku-4-5", # cheaper summarizer summarizer_temperature=0.1, summarizer_max_tokens=3000, ) ``` ### Disabling persistence If you don't want any disk-backed memory for a given agent, override the path: ```python agent = Agent(agent_name="EphemeralAgent", model_name="gpt-5.4") agent.short_memory.memory_md_path = None ``` Subsequent `add()` calls will still update `conversation_history` in memory but won't write to disk. ## File Layout Summary | Path | Purpose | Lifecycle | |---|---|---| | `$WORKSPACE_DIR/agents/{name}/MEMORY.md` | Active interaction log | Append on every turn; wiped + re-seeded on compaction | | `$WORKSPACE_DIR/agents/{name}/archive/history_<ts>.md` | Immutable pre-compaction snapshot | Written once on each compaction; never modified or deleted | ## Design Notes **Why one file per agent, not per session?** A single durable file means the agent has a stable handle on "what I know" regardless of how many times the process has been restarted. Session logs live in `archive/` for audit/recovery. **Why `System`-role preamble instead of multiple replayed messages?** Replaying the raw message tree would balloon token counts and risks the LLM confusing past turns with current ones. A single `System`-tagged preamble is unambiguous and efficient. **Why wipe `MEMORY.md` on compaction instead of appending a summary?** Without a wipe, the next run's preload would inject both the summary *and* the raw transcript it summarizes — doubling tokens and defeating the point. The archive keeps the raw log available without polluting active memory. **Why `agent_name` and not `id` as the folder key?** `self.id` defaults to a fresh UUID each instantiation. Keying on it would create a new empty `MEMORY.md` on every process start, with no cross-run persistence. `agent_name` is user-controlled and stable.

Instructions flagged against the user

D3 · Privacy & Data Protection
“Written once on each compaction; never modified or deleted ”
The system stores all user interactions persistently to disk by default, archives raw chat logs forever ('Raw chat logs are never destroyed'), and does not mention any user consent mechanisms, data retention limits, or transparency about data collection. The archive system preserves conversations indefinitely without any mention of user awareness or control. There is no mention of informing users that their data is being persisted or giving them the ability to delete it.

swarms - docs swarms agents consistency agent

8978 characters

# Consistency Agent Documentation The `SelfConsistencyAgent` is a specialized agent designed for generating multiple independent responses to a given task and aggregating them into a single, consistent final answer. It leverages concurrent processing to enhance efficiency and employs a majority voting mechanism to ensure the reliability of the aggregated response. ## Purpose The primary objective of the `SelfConsistencyAgent` is to provide a robust mechanism for decision-making and problem-solving by generating diverse responses and synthesizing them into a coherent final answer. This approach is particularly useful in scenarios where consistency and reliability are critical. ## Class: `SelfConsistencyAgent` ### Initialization - **`__init__`**: Initializes the `SelfConsistencyAgent` with specified parameters. #### Arguments | Argument | Type | Default | Description | |------------------------|---------|---------|-----------------------------------------------------------------------------| | `name` | `str` | `"Self-Consistency-Agent"` | Name of the agent. | | `description` | `str` | `"An agent that uses self consistency to generate a final answer."` | Description of the agent's purpose. | | `system_prompt` | `str` | `CONSISTENCY_SYSTEM_PROMPT` | System prompt for the reasoning agent. | | `model_name` | `str` | Required | The underlying language model to use. | | `num_samples` | `int` | `5` | Number of independent responses to generate. | | `max_loops` | `int` | `1` | Maximum number of reasoning loops per sample. | | `majority_voting_prompt` | `Optional[str]` | `majority_voting_prompt` | Custom prompt for majority voting aggregation. | | `eval` | `bool` | `False` | Enable evaluation mode for answer validation. | | `output_type` | `OutputType` | `"dict"` | Format of the output. | | `random_models_on` | `bool` | `False` | Enable random model selection for diversity. | ### Methods - **`run`**: Generates multiple responses for the given task and aggregates them. - **Arguments**: - `task` (`str`): The input prompt. - `img` (`Optional[str]`, optional): Image input for vision tasks. - `answer` (`Optional[str]`, optional): Expected answer for validation (if eval=True). - **Returns**: `Union[str, Dict[str, Any]]` - The aggregated final answer. - **`aggregation_agent`**: Aggregates a list of responses into a single final answer using majority voting. - **Arguments**: - `responses` (`List[str]`): The list of responses. - `prompt` (`str`, optional): Custom prompt for the aggregation agent. - `model_name` (`str`, optional): Model to use for aggregation. - **Returns**: `str` - The aggregated answer. - **`check_responses_for_answer`**: Checks if a specified answer is present in any of the provided responses. - **Arguments**: - `responses` (`List[str]`): A list of responses to check. - `answer` (`str`): The answer to look for in the responses. - **Returns**: `bool` - `True` if the answer is found, `False` otherwise. - **`batched_run`**: Run the agent on multiple tasks in batch. - **Arguments**: - `tasks` (`List[str]`): List of tasks to be processed. - **Returns**: `List[Union[str, Dict[str, Any]]]` - List of results for each task. ### Examples #### Example 1: Basic Usage ```python from swarms.agents.consistency_agent import SelfConsistencyAgent # Initialize the agent agent = SelfConsistencyAgent( name="Math-Reasoning-Agent", model_name="gpt-5.4", max_loops=1, num_samples=5 ) # Define a task task = "What is the 40th prime number?" # Run the agent final_answer = agent.run(task) # Print the final aggregated answer print("Final aggregated answer:", final_answer) ``` #### Example 2: Using Custom Majority Voting Prompt ```python from swarms.agents.consistency_agent import SelfConsistencyAgent # Initialize the agent with a custom majority voting prompt agent = SelfConsistencyAgent( name="Reasoning-Agent", model_name="gpt-5.4", max_loops=1, num_samples=5, majority_voting_prompt="Please provide the most common response." ) # Define a task task = "Explain the theory of relativity in simple terms." # Run the agent final_answer = agent.run(task) # Print the final aggregated answer print("Final aggregated answer:", final_answer) ``` #### Example 3: Evaluation Mode ```python from swarms.agents.consistency_agent import SelfConsistencyAgent # Initialize the agent with evaluation mode agent = SelfConsistencyAgent( name="Validation-Agent", model_name="gpt-5.4", num_samples=3, eval=True ) # Run with expected answer for validation result = agent.run("What is 2 + 2?", answer="4", eval=True) if result is not None: print("Validation passed:", result) else: print("Validation failed - expected answer not found") ``` #### Example 4: Random Models for Diversity ```python from swarms.agents.consistency_agent import SelfConsistencyAgent # Initialize the agent with random model selection agent = SelfConsistencyAgent( name="Diverse-Reasoning-Agent", model_name="gpt-5.4", num_samples=5, random_models_on=True ) # Run the agent result = agent.run("What are the benefits of renewable energy?") print("Diverse reasoning result:", result) ``` #### Example 5: Batch Processing ```python from swarms.agents.consistency_agent import SelfConsistencyAgent # Initialize the agent agent = SelfConsistencyAgent( name="Batch-Processing-Agent", model_name="gpt-5.4", num_samples=3 ) # Define multiple tasks tasks = [ "What is the capital of France?", "What is 15 * 23?", "Explain photosynthesis in simple terms." ] # Process all tasks results = agent.batched_run(tasks) # Print results for i, result in enumerate(results): print(f"Task {i+1} result: {result}") ``` ## Key Features ### Self-Consistency Technique The agent implements the self-consistency approach based on the research paper "Self-Consistency Improves Chain of Thought Reasoning in Language Models" by Wang et al. (2022). This technique: 1. **Generates Multiple Independent Responses**: Creates several reasoning paths for the same problem 2. **Analyzes Consistency**: Examines agreement among different reasoning approaches 3. **Aggregates Results**: Uses majority voting or consensus building 4. **Produces Reliable Output**: Delivers a final answer reflecting the most reliable consensus ### Benefits - **Mitigates Random Errors**: Multiple reasoning paths reduce individual path errors - **Reduces Bias**: Diverse approaches minimize single-method biases - **Improves Reliability**: Consensus-based results are more trustworthy - **Handles Complexity**: Better performance on complex problem-solving tasks ### Use Cases - **Mathematical Problem Solving**: Where accuracy is critical - **Decision Making**: When reliability is paramount - **Validation Tasks**: When answers need verification - **Complex Reasoning**: Multi-step problem solving - **Research Questions**: Where multiple perspectives are valuable ## Technical Details ### Concurrent Execution The agent uses `ThreadPoolExecutor` to generate multiple responses concurrently, improving performance while maintaining independence between reasoning paths. ### Aggregation Process The aggregation uses an AI-powered agent that: - Identifies dominant responses - Analyzes disparities and disagreements - Evaluates consensus strength - Synthesizes minority insights - Provides comprehensive recommendations ### Output Formats The agent supports various output types: - `"dict"`: Dictionary format with conversation history - `"str"`: Simple string output - `"list"`: List format - `"json"`: JSON formatted output ## Limitations 1. **Computational Cost**: Higher `num_samples` increases processing time and cost 2. **Model Dependencies**: Performance depends on the underlying model capabilities 3. **Consensus Challenges**: May struggle with tasks where multiple valid approaches exist 4. **Memory Usage**: Concurrent execution requires more memory resources ## Best Practices 1. **Sample Size**: Use 3-7 samples for most tasks; increase for critical decisions 2. **Model Selection**: Choose models with strong reasoning capabilities 3. **Evaluation Mode**: Enable for tasks with known correct answers 4. **Custom Prompts**: Tailor majority voting prompts for specific domains 5. **Batch Processing**: Use `batched_run` for multiple related tasks ---

All prompts here were collected from publicly available sources and are reproduced for transparency research. Browse the multi-agent systems category, the full gallery of 400+ products, or read the paper behind the AISPA standard.