AgentFlow

repository·main·Indexed 24 days ago

https://github.com/lupantech/agentflow

A trainable, modular agentic framework (v0.1.2) designed for long-horizon reasoning and reliable tool use. It optimizes a specialized 'Planner' agent using Flow-based Group Refined Policy Optimization (Flow-GRPO) and coordinates specialized modules including Planner, Executor, Verifier, and Generator.

Tokens
12.3K
Snippets
20
Records
81
Agent score
84%

What's inside agentflow

  1. Analyze Rollout Data and JSON Fields

    main

    Rollout trajectories are saved during training for analysis. These are organized by public IP and experiment name/timestamp. Note that step numbers restart from 0 whenever training is restarted.

    Directory Structure:

    rollout_data/
    └── {PUBLIC_IP}/
        └── {EXPERIMENT_NAME}_{TIMESTAMP}/
            ├── .init.lock
            ├── .run_info
            └── {MODEL_NAME}_{TIMESTAMP}/
                ├── train/
                └── validation/
                    ├── .val.lock
                    └── step_0/
                        ├── idx_0/
                        │   └── rollout_{uuid}.json
                        └── ...

    Rollout JSON Schema: Each rollout_{uuid}.json file contains the following fields:

    • prompt: The original problem or query.
    • groundtruth: The expected answer.
    • answer_extracted: The model's predicted answer.
    • reward: The score (0.0 for incorrect, positive value for correct).
    • total_result: A full execution trace containing:
      • query_analysis: Problem breakdown.
      • memory: Tool execution history.
      • direct_output: The final response.
      • Tool prompts and responses.
    • timestamp: The time of generation.
  2. Understand benchmark results organization

    main

    After a benchmark completes, results are stored in the test/ directory organized by task and model label.

    Directory Structure:

    test/
    └── {TASK_NAME}/              # e.g., aime24, bamboogle
        ├── logs/
        │   └── {MODEL_LABEL}/     # e.g., AgentFlow-7B
        │       ├── 0.log          # Per-problem execution logs
        │       └── ...
        ├── results/
        │   └── {MODEL_LABEL}/
        │       ├── final_results_direct_output.json    # Per-problem analysis
        │       ├── final_scores_direct_output.json     # Aggregate metrics
        │       ├── final_score_direct_output.log       # Scoring process log
        │       ├── output_0.json                      # Individual outputs
        │       └── ...
        └── cache/                 # Cached intermediate results
  3. Configure benchmark settings in `run.sh`

    main

    Each benchmark task's run.sh script (e.g., test/bamboogle/run.sh) can be customized by editing several key variables:

    1. Set Parallelism

    Adjust THREADS to control data parallelism for inference. Setting this too high may exceed API rate limits.

    THREADS=20  # Number of parallel workers

    2. Select Tasks

    Enable or disable specific benchmarks by commenting or uncommenting them in the TASKS array:

    TASKS=(
        "aime24"
        "gameof24"
        "bamboogle"
        # "gpqa"
    )

    3. Define Models

    Specify the models and their configurations using the MODELS array. Each entry follows a specific pipe-separated format.

    # Example configuration in test/bamboogle/run.sh
    TASK="bamboogle"
    THREADS=20
    DATA_FILE_NAME="data.json"
    
    MODELS=(
        "8000:vllm-AgentFlow/agentflow-planner-7b,AgentFlow-7B,\nBase_Generator_Tool|Python_Coder_Tool|Google_Search_Tool|Wikipedia_Search_Tool,\ngpt-4o-mini|gpt-4o-mini|Default|Default,\ntrainable|gpt-4o|gpt-4o|gpt-4o"
    )
  4. Monitor Training Logs

    main

    AgentFlow automatically organizes training output logs by your public IP address. Logs are split into 1MB chunks to facilitate easier management. By default, the system retains a maximum of 5000 log files.

    Log Directory Structure:

    task_logs/
    └── {PUBLIC_IP}/
        └── train_log/
            ├── training_output_0000  # First 1MB
            ├── training_output_0001  # Next 1MB
            └── ...

    To monitor the most recent logs in real-time, use the tail command on the log files within your IP directory.

    tail -f task_logs/{YOUR_IP}/train_log/training_output_*
  5. Manage Model Checkpoints

    main

    Model checkpoints are stored in a hierarchical directory structure based on your config.yaml settings. Checkpoints include both the model weights in HuggingFace format and the training state.

    Directory Structure:

    checkpoints/
    └── {PROJECT_NAME}/
        └── {EXPERIMENT_NAME}/
            ├── global_step_2/
            │   ├── actor/
            │   │   └── huggingface/  # HuggingFace format (ready for inference)
            │   └── data.pt           # Training state
            ├── global_step_4/
            └── latest_checkpointed_iteration.txt  # Points to latest checkpoint

    Configuration (train/config.yaml):

    • trainer.save_freq: Interval for saving checkpoints (default: every 2 epochs).
    • trainer.test_freq: Interval for validation (default: every 2 epochs).
    • trainer.total_epochs: Total training epochs (default: 5).

    How to use checkpoints:

    • For VLLM inference: Configure the paths in scripts/serve_vllm.sh.
    • For direct loading with Transformers: Use the path to the huggingface subdirectory within a specific global step.
  6. Obtain a Together AI API Key

    main

    Use a Together AI API key to access open-source models like Qwen, Llama, and Mixtral. This is the recommended method for international users to access Qwen/Qwen2.5-7B-Instruct with better connectivity.

    Steps to obtain:

    1. Visit Together.ai.
    2. Sign up or log in.
    3. Navigate to Settings > API Keys.
    4. Create a new API key.

    Common model names:

    • Qwen models: Qwen/Qwen2.5-7B-Instruct, Qwen/Qwen2.5-72B-Instruct (Note: Use non-quantized versions for best performance/accuracy over -Turbo versions).
    • Other models: meta-llama/Llama-3-70b-chat-hf, mistralai/Mixtral-8x7B-Instruct-v0.1.
  7. Test LLM engine connectivity

    main

    To ensure your configured LLM engines (e.g., OpenAI, DashScope, Gemini) are accessible and can be instantiated, run the LLM engine test script from the project root. The script performs a fault-tolerant test across multiple engines and provides a summary of passed and failed connections.

    cd PROJECT_ROOT
    python agentflow/scripts/test_llm_engine.py
  8. Obtain a DashScope API Key (Alibaba Cloud)

    main

    Use a DashScope API key to access Alibaba Cloud's Qwen (Tongyi Qianwen) model series. AgentFlow uses DashScope to call qwen2.5-7b-instruct as the LLM engine for agents and tools.

    Steps to obtain:

    1. Visit the Alibaba Cloud DashScope Console.
    2. Log in with your Alibaba Cloud account.
    3. Navigate to API-KEY Management.
    4. Create a new API key.

    Common model names: qwen-turbo, qwen-plus, qwen-max, qwen2.5-7b-instruct, qwen2.5-72b-instruct.

    Note: For international users, Together AI is recommended instead of DashScope for accessing Qwen models.

  9. Quick Start: AgentFlow Inference

    main

    To run a quick inference test using the modular agentic system (Planner, Executor, Verifier, Generator), execute the quick_start.py script. Ensure your API keys are set in .env first.

    python quick_start.py
    python quick_start.py
  10. Configure AgentFlow to use local vLLM

    main

    To integrate your local vLLM server into AgentFlow, modify the LLM engine configuration in the code.

    In agentflow/agentflow/models/planner.py, update the create_llm_engine call to use your local base_url and the specific model string:

    self.llm_engine_fixed = create_llm_engine(
        model_string="vllm-Qwen/Qwen2.5-7B-Instruct",
        base_url="http://localhost:8001/v1/",
        is_multimodal=False,
        temperature=temperature
    )
    self.llm_engine_fixed = create_llm_engine(
        model_string="vllm-Qwen/Qwen2.5-7B-Instruct",
        base_url="http://localhost:8001/v1/",
        is_multimodal=False,
        temperature=temperature
    )
  11. Use your own LLM model in AgentFlow

    main

    AgentFlow allows you to customize the LLM engine for different agent modules. The configuration depends on which agent you are modifying:

    Planner Agent

    To change the model for the Planner, modify the llm_engine_name parameter in the corresponding shell script used to run the agent (for example, test/bamboogle/run.sh).

    Other Agents (Executor, Verifier, Generator)

    By default, these agents use a fixed engine (Qwen-2.5-7B-Instruct via DashScope). To use a custom model, you must modify the source code:

    1. Modify the Planner's fixed engine: In agentflow/agentflow/models/planner.py, update self.llm_engine_fixed using create_llm_engine with your desired model_string.
    2. Modify the Executor: In agentflow/agentflow/solver.py, update the llm_engine_name parameter during the Executor instantiation.

    For a list of supported engines and the specific model_string formats required, refer to the llm_engine.md documentation.

    # Example: Modifying the Planner's fixed engine in agentflow/agentflow/models/planner.py
    self.llm_engine_fixed = create_llm_engine(model_string="your-engine", is_multimodal=False, temperature=temperature)
    
    # Example: Modifying the Executor in agentflow/agentflow/solver.py
    executor = Executor(
        llm_engine_name="dashscope",
        root_cache_dir=root_cache_dir,
        verbose=verbose,
        temperature=temperature
    )
  12. Configure AgentFlow environment variables

    main

    AgentFlow requires an .env file located in the agentflow/ folder for API keys. Copy the template and update it with your credentials.

    Required/Optional variables:

    • OPENAI_API_KEY: Used for judging responses.
    • GOOGLE_API_KEY: Used for the Google Search tool.
    • DASHSCOPE_API_KEY: [Optional] For calling Qwen-2.5-7B-Instruct as an engine for agents and tools.
    • TOGETHER_API_KEY: [Optional] Alternative for calling Qwen-2.5-7B-Instruct (recommended for international users).

    Alternatively, you can serve the Qwen2.5-7B-instruct model locally using vLLM.

    cp agentflow/.env.template agentflow/.env
    # Then edit agentflow/.env with your API keys
    cp agentflow/.env.template agentflow/.env