Skip to main content

A lightweight library for building graph-driven AI agents with tool integration.

Project description

LWAgents Logo

By RapidEpoch, Learn More Here

LWAgents: A Library for Graph-Driven AI Agents with Tool Integration

LWAgents is a flexible and extensible Python library designed for building graph-driven workflows powered by AI agents. It provides a robust framework for creating, managing, and executing workflows where nodes represent states or tasks, edges represent transitions, and AI agents or deterministic logic decide the next steps.

Whether you're designing task-oriented AI systems, probabilistic workflows, or integrating external tools into your decision-making processes, LWAgents offers the structure and flexibility to get started quickly.


Key Features

  • Graph-Based Workflow Execution:

    • Represent workflows as graphs with nodes (tasks) and edges (transitions).
    • Seamlessly execute workflows step-by-step.
  • AI Agent Integration:

    • Integrate language models (like OpenAI's GPT) as decision-making agents.
    • Use agents for routing, decision-making, or task execution.
  • Tooling Support:

    • Extend functionality by defining custom tools and decorators.
    • Easily integrate tools for calculations, API calls, or other tasks.
  • Dynamic Transitions:

    • Support for conditional transitions via edge logic.
    • Direct traversal capabilities allow agents or nodes to dynamically decide the next step.
  • State Management:

    • Built-in support for maintaining and updating both local graph state and global agent state during execution.
    • Global agent state allows tracking all agent actions across the entire workflow.
    • Record detailed histories of execution for debugging and analysis.
  • Extensibility:

    • Modular architecture enables easy customization and scaling.
    • Add new nodes, tools, or agents with minimal setup.

Installation

Using pip

To install the library, run:

pip install lwagents

From Source

To install the library from source:

Clone the repository:

git clone https://github.com/HenningGC/lwagents.git

Navigate to the project directory:

cd lwagents

Install the package in editable mode:

pip install -e .

Basic Usage

Define a Simple Workflow

Define Nodes and Edges: Nodes represent tasks, and edges define transitions between them.

from lwagents import Graph, Node, Edge

def print_task(val):
    print(val)
    return

start_node = Node(node_name="start", kind="START", command=print_task, parameters={"val": "Starting..."})
task_node = Node(node_name="task", kind="STATE", command=print_task, parameters={"val": "Performing a task..."})
end_node = Node(node_name="end", kind="TERMINAL")

edge1 = Edge(edge_name="to_task")
edge2 = Edge(edge_name="to_end")

Create a Graph: Connect nodes with edges to define transitions.

with Graph(state=YourGlobalState) as graph:
    start_node.connect(to_node=task_node, edge=edge1)
    task_node.connect(to_node=end_node, edge=edge1)

Run the Workflow: Execute the graph starting from the START node.

graph.run(start_node=start_node, streaming=True)

Advanced Features

AI Agents for Decision-Making

Integrate AI agents (like OpenAI's GPT) to dynamically route or execute tasks:

from lwagents import LLMAgent, create_model

# Initialize an LLM model
llm_model = create_model("openai", instance_params={"api_key": "your_openai_api_key"})
agent = LLMAgent(name="my_agent", llm_model=llm_model)

# Use the agent in a node with model_params
def decision_task(agent):
    model_params = {
        "model": "gpt-4o-mini",
        "instructions": "You are a helpful decision-making assistant",
        "input": [{"role": "user", "content": "Which task should I perform next?"}]
    }
    return agent.action(model_params=model_params)

decision_node = Node(
    node_name="decision",
    kind="STATE",
    command=decision_task,
    parameters={"agent": agent}
)

Global Agent State Management

Access and manage global agent state across your workflow:

from lwagents.state import get_global_agent_state, reset_global_agent_state

# Reset global state at the beginning (optional, good for testing)
reset_global_agent_state()

# Access global state to see all agent activities
global_state = get_global_agent_state()
print(f"Total agent actions performed: {len(global_state.history)}")

# Print the global agent state history
global_state.print_history()

Tools for Task Execution

Define custom tools for your agents to use:

from lwagents import Tool

@Tool
def calculate_sum(a: int, b: int) -> int:
    return a + b

# Use the tool in a node
agent = LLMAgent(name="tool_agent", llm_model=llm_model, tools=[calculate_sum])

Custom Model Integration

Integrate custom models (e.g., HuggingFace) by extending BaseLLMModel:

from lwagents.models import BaseLLMModel, create_model
from lwagents.messages import LLMResponse, GPTResponse
from transformers import pipeline

class HuggingFaceModel(BaseLLMModel):
    def generate(self, prompt):
        result = self._model(prompt)
        return LLMResponse(response=result)

# Initialize and use
hf_pipeline = pipeline("text-generation", model="gpt2")
custom_model = create_model(
    model_type="custom",
    instance_params={},
    custom_model=HuggingFaceModel,
    custom_implementation=hf_pipeline
)
agent = LLMAgent(name="hf_agent", llm_model=custom_model)

Dynamic Node Routing

Define router nodes that use global agent state to make intelligent routing decisions:

from lwagents import GraphRequest
from lwagents.state import get_global_agent_state

def intelligent_router(agent):
    global_state = get_global_agent_state()
    
    model_params = {
        "model": "gpt-4o-mini",
        "instructions": "You are a helpful assistant that uses the tools at your disposal",
        "input": [{"role": "user", "content": "Use the get_result_sum tool to sum 300+140"}]
    }
    result = agent.action(model_params=model_params)
    
    return GraphRequest(result=result.content, traversal=result.content)

Project Structure

lwagents/
├── lwagents/               # Library code
│   ├── __init__.py         # Initialize the package
│   ├── graph.py            # Graph-related functionality
│   ├── state.py            # State management
│   ├── agent.py            # Agent implementation
│   ├── tools.py            # Tooling and decorators
│   ├── models.py           # Model-related code
│   ├── messages.py         # Message classes for agent communication
│   └── logs.py             # Logging utilities
├── tests/                  # Test cases
├── examples/               # Example scripts
├── .github/workflows/      # CI/CD automation
├── README.md               # Project documentation
├── pyproject.toml          # Build system requirements
└── LICENSE                 # License for the library

Contributing

Contributions are welcome! To contribute:

  1. Fork the repository
  2. Create a new branch for your feature or bug fix
  3. Submit a pull request

For more details, see our contribution guidelines.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Author

HenningGC - GitHub Profile


⭐ Star this repository if you find it useful!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lwagents-2.1.0.tar.gz (17.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lwagents-2.1.0-py3-none-any.whl (17.0 kB view details)

Uploaded Python 3

File details

Details for the file lwagents-2.1.0.tar.gz.

File metadata

  • Download URL: lwagents-2.1.0.tar.gz
  • Upload date:
  • Size: 17.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for lwagents-2.1.0.tar.gz
Algorithm Hash digest
SHA256 8c2a3b850df0020479f82c4574de2e779316116752cca167e142650b02577cad
MD5 720e57d0e810c1ec81592d964f6bb9a8
BLAKE2b-256 e8a8cbac8732c12478309b0bf5590c0859e46ec7fa39717b47b36f264de12aab

See more details on using hashes here.

File details

Details for the file lwagents-2.1.0-py3-none-any.whl.

File metadata

  • Download URL: lwagents-2.1.0-py3-none-any.whl
  • Upload date:
  • Size: 17.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.14

File hashes

Hashes for lwagents-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 583d1e247bfcd94da4ed4b2133721c19fa21fd3810ab643b691c8e99e2700ea8
MD5 47b01abd8ab95e34db8883232c11d8c8
BLAKE2b-256 4850db189ff462e12635cb1ad041d196a2896a21a80cb30d8eef885c89b5afdc

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page