LazyLLM

repository·main·Indexed 26 days ago

https://github.com/lazyagi/lazyllm

A low-code development tool for building and deploying multi-agent LLM applications. LazyLLM supports a workflow of prototype building, data feedback, and iterative optimization for both online and locally deployed models. It features a variety of code templates for chatbots, RAG systems, agents, and multimodal bots, as well as a CLI for model deployment via frameworks like vLLM and LightLLM, and the ability to launch Model Context Protocol (MCP) servers.

Tokens
144.6K
Snippets
336
Records
643
Agent score
87%

What's inside lazyllm

  1. Use the Graph class for complex DAG workflows

    main
    The Graph class allows you to create complex processing workflows based on a Directed Acyclic Graph (DAG). Nodes represent processing functions, and edges represent the data flow between them. It is designed for scenarios requiring complex data dependencies, such as machine learning pipelines or data processing workflows.
  2. Manage data streams with Flow

    main

    Flow defines the data stream, describing how data passes from one callable object to another. Flows allow you to organize complex applications using predefined patterns. Supported Flow types include:

    • Pipeline
    • Parallel
    • Diverter
    • Warp
    • IFS
    • Loop

    Flows enable easy combination of modules, reduce repetitive data transformation work, and support asynchronous/parallel execution for performance.

  3. Orchestrate data flows with LazyLLM Flow components

    main

    LazyLLM uses Flow components to build complex data processing pipelines. You can choose from several patterns depending on your requirements:

    • Pipeline: Sequential execution where the output of one stage is the input to the next.
    • Parallel: Executes multiple tasks in parallel; all components share the same input and their results are merged into a single output.
    • Diverter: Routes a single input through multiple modules in parallel, returning the outputs as a tuple.
    • Warp: Applies a single function to a group of inputs in parallel. Note: This is for synchronous tasks and cannot be used for asynchronous tasks like training or deployment.
    • IFS: An if-else structure that executes either a 'true path' or a 'false path' based on a condition.
    • Switch: A control flow mechanism that selects different paths based on an expression's value or truthiness.
    • Loop: Repeats a series of functions on an input until a stop condition is met or a maximum number of iterations is reached.
    • Graph: A Directed Acyclic Graph (DAG) for complex dependencies, supporting topological sorting and multi-input/multi-output nodes.
    • Bind: Used to pass parameters freely from upstream to downstream nodes.
  4. Understand the LazyLLM Registration Mechanism

    main

    LazyLLM uses an inheritance-as-registration mechanism to manage extensible components like Flows, Nodes, Tools, Models, and Launchers. Instead of manual registration calls (e.g., registry.register(...)), registration happens automatically at class definition time by parsing inheritance relationships and naming conventions.

    Key Principles:

    • Inheritance-driven: Inheriting a Base class explicitly declares which capability system the class belongs to.
    • Automatic: Registration occurs during class definition, not via manual triggers.
    • Hierarchical: Supports multi-level capability structures (e.g., group.subgroup.xxx).
    • Unified Access: Components are accessed via a stable, dot-notation interface (e.g., lazyllm.online.chat(...)) regardless of internal file structures.
  5. Understand Data Processing Conventions and Modes

    main

    LazyLLM unifies all datasets as List[dict]. The dataset size is the length of the list, and each dictionary represents a single data element.

    There are two primary processing modes:

    1. Single Data Processing Operator: Processes one dict at a time. The framework handles concurrency automatically. The return type determines the behavior:
      • Returns dict: Replaces the original data.
      • Returns List[dict]: Adds multiple new entries.
      • Returns None: Keeps the original data reference.
      • Returns List (empty): Deletes the data.
    2. Full Data Processing Operator: Processes the entire List[dict] at once. The framework calls these sequentially without automatic concurrency; users must implement their own concurrency if needed (e.g., for deduplication).
  6. Understand LazyLLM Application Architecture

    main

    LazyLLM applications are not static graphs. They are built using standard Python syntax, allowing for high flexibility and dynamic behavior. Key architectural characteristics include:

    • Traditional Programming Style: Applications are constructed using basic Python syntax, making them feel like traditional programming rather than rigid graph definitions.
    • Runtime Topology Changes: You can use Python's features to modify the application's topology (the structure of how modules connect) during runtime. Subsequent executions will follow the newly modified structure.
    • Dynamic Hook Injection: You can inject hook functions at the connection points between modules. These hooks can even be defined at runtime to intercept or modify data flow.
  7. Use the Reranker for fine-grained document ranking

    main

    The Reranker component performs a re-ranking process to refine the order of retrieved documents, ensuring that the most relevant documents appear at the top of the returned list. This is typically used in Retrieval-Augmented Generation (RAG) workflows to improve retrieval quality.

    reranker = lazyllm.Reranker(
        name='ModuleReranker',
        model=lazyllm.OnlineEmbeddingModule(type="rerank"),
        topk=1
    )
    
    # Re-rank multiple retrieved results
    doc_node_list = reranker(
        nodes=doc_node_list_1 + doc_node_list_2,
        query="用户问题"
    )
  8. Iterate over streaming output using StreamCallHelper

    main

    To consume streaming outputs, wrap your model or pipeline with lazyllm.StreamCallHelper. This allows you to iterate over the model's output using a for loop.

    If the model is part of a pipeline (Flow), wrap the outermost pipeline object instead of the model itself.

    # For a standalone model
    model = lazyllm.TrainableModule('qwen2-1.5b', stream=True)
    model = lazyllm.StreamCallHelper(model)
    for msg in model('hello'):
        print(msg)
    
    # For a model within a pipeline (Flow)
    model = lazyllm.TrainableModule('qwen2-1.5b', stream=True)
    ppl = lazyllm.pipeline(model)
    ppl = lazyllm.StreamCallHelper(ppl)
    for msg in ppl('hello'):
        print(msg)
  9. Build a data processing pipeline using registered operators

    main

    You can use the pipeline context manager from lazyllm to chain registered operators for data processing. Each operator in the pipeline can specify an input_key to identify the data field to process and an output_key to define where the result should be stored. You can also use .set_output('path/to/output') on an operator to export the final result as a .jsonl file at the specified path.

    from lazyllm import pipeline
    from lazyllm.tools.data import demo
    
    # Prepare data
    data = [
        {'text': 'hello world'},
        {'text': 'hello lazyllm'},
        {'text': 'hello world'},
    ]
    
    # Build data processing pipeline
    with pipeline() as ppl:
        ppl.upper = demo.process_uppercase(input_key='text')
        ppl.dedup = demo.process_deduplicate(input_key='text')
        ppl.add_suffix = demo.process_add_suffix(
            input_key='text',
            output_key='text_with_suffix',
        ).set_output('path/to/output')
    
    # Execute data processing pipeline
    result = ppl(data)  # Returns the absolute path to the exported .jsonl file
  10. Build a Multi-Agent Dialogue System with a Director

    main

    You can build a multi-agent dialogue system using a 'director-style scheduling' pattern. This involves using a DirectorDialogueAgent to control speaking order and conversation termination, while other DialogueAgent instances participate as controlled roles.

    Key components include:

    • DialogueAgent: Defines individual roles with independent memory (message_history) and persona (system_message).
    • DirectorDialogueAgent: Acts as the central controller to select the next speaker and decide when to end the conversation.
    • ChatPrompter: Used to build reusable prompt templates for different stages (e.g., continuing discussion, selecting speakers, or summarizing).
    • OnlineChatModule: Used to simulate the multi-agent conversation flow.
    from lazyllm import OnlineChatModule, ChatPrompter