Skip to main content

Grasp Agents Library

Project description

Grasp Agents


Grasp Agents

PyPI version License: MIT PyPI downloads GitHub Stars GitHub Forks

Overview

Grasp Agents is a modular Python framework for building agentic AI pipelines and applications. It is meant to be minimalistic but functional, allowing for rapid experimentation while keeping full and granular low-level control over prompting, LLM handling, and inter-agent communication by avoiding excessive higher-level abstractions.

Features

  • Clean formulation of agents as generic entities over:
    • I/O schemas
    • Agent state
    • Shared context
  • Transparent implementation of common agentic patterns:
    • Single-agent loops with an optional "ReAct mode" to enforce reasoning between the tool calls
    • Workflows (static communication topology), including loops
    • Agents-as-tools for task delegation
    • Freeform A2A communication via the in-process actor model
  • Batch processing support outside of agentic loops
  • Simple logging and usage/cost tracking

Project Structure

  • base_agent.py, llm_agent.py, comm_agent.py: Core agent class implementations.
  • agent_message.py, agent_message_pool.py: Messaging and message pool management.
  • llm_agent_state.py: State management for LLM agents.
  • tool_orchestrator.py: Orchestration of tools used by agents.
  • prompt_builder.py: Tools for constructing prompts.
  • workflow/: Modules for defining and managing agent workflows.
  • cloud_llm.py, llm.py: LLM integration and base LLM functionalities.
  • openai/: Modules specific to OpenAI API integration.
  • memory.py: Memory management for agents (currently only message history).
  • run_context.py: Context management for agent runs.
  • usage_tracker.py: Tracking of API usage and costs.
  • costs_dict.yaml: Dictionary for cost tracking (update if needed).
  • rate_limiting/: Basic rate limiting tools.

Quickstart & Installation Variants (UV Package manager)

Note: You can check this sample project code in the src/grasp_agents/examples/demo/uv folder. Feel free to copy and paste the code from there to a separate project. There are also examples for other package managers.

1. Prerequisites

Install the UV Package Manager:

curl -LsSf https://astral.sh/uv/install.sh | sh

2. Create Project & Install Dependencies

mkdir my-test-uv-app
cd my-test-uv-app
uv init .

Create and activate a virtual environment:

uv venv
source .venv/bin/activate

Add and sync dependencies:

uv add grasp_agents
uv sync

3. Example Usage

Ensure you have a .env file with your OpenAI and Google AI Studio API keys set

OPENAI_API_KEY=your_openai_api_key
GOOGLE_AI_STUDIO_API_KEY=your_google_ai_studio_api_key

Create a script, e.g., problem_recommender.py:

import asyncio
import re
from pathlib import Path
from typing import Any

from dotenv import load_dotenv
from pydantic import BaseModel, Field

from grasp_agents.grasp_logging import setup_logging
from grasp_agents.llm_agent import LLMAgent
from grasp_agents.openai.openai_llm import OpenAILLM, OpenAILLMSettings
from grasp_agents.run_context import RunContextWrapper
from grasp_agents.typing.message import Conversation
from grasp_agents.typing.tool import BaseTool

load_dotenv()


# Configure the logger to output to the console and/or a file
setup_logging(
    logs_file_path="grasp_agents_demo.log",
    logs_config_path=Path().cwd() / "configs/logging/default.yaml",
)

sys_prompt_react = """
Your task is to suggest an exciting stats problem to a student.
Ask the student about their education, interests, and preferences, then suggest a problem tailored to them.

# Instructions
* Ask questions one by one.
* Provide your thinking before asking a question and after receiving a reply.
* The problem must be enclosed in <PROBLEM> tags.
"""


class TeacherQuestion(BaseModel):
    question: str = Field(..., description="The question to ask the student.")


StudentReply = str


class AskStudentTool(BaseTool[TeacherQuestion, StudentReply, Any]):
    name: str = "ask_student_tool"
    description: str = "Ask the student a question and get their reply."

    async def run(
        self, inp: TeacherQuestion, ctx: RunContextWrapper[Any] | None = None
    ) -> StudentReply:
        return input(inp.question)


Problem = str


teacher = LLMAgent[Any, Problem, None](
    agent_id="teacher",
    llm=OpenAILLM(
        model_name="openai:gpt-4.1",
        llm_settings=OpenAILLMSettings(temperature=0.1)
    ),
    tools=[AskStudentTool()],
    max_turns=20,
    react_mode=True,
    sys_prompt=sys_prompt_react,
    set_state_strategy="reset",
)


@teacher.exit_tool_call_loop_handler
def exit_tool_call_loop(
    conversation: Conversation, ctx: RunContextWrapper[Any] | None, **kwargs: Any
) -> bool:
    return r"<PROBLEM>" in str(conversation[-1].content)


@teacher.parse_output_handler
def parse_output(
    conversation: Conversation, ctx: RunContextWrapper[Any] | None, **kwargs: Any
) -> Problem:
    message = str(conversation[-1].content)
    matches = re.findall(r"<PROBLEM>(.*?)</PROBLEM>", message, re.DOTALL)

    return matches[0]


async def main():
    ctx = RunContextWrapper[None](print_messages=True)
    out = await teacher.run(ctx=ctx)
    print(out.payloads[0])
    print(ctx.usage_tracker.total_usage)


asyncio.run(main())

Run your script:

uv run problem_recommender.py

You can find more examples in src/grasp_agents/examples/notebooks/agents_demo.ipynb.

Project details


Release history Release notifications | RSS feed

Download files

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

Source Distribution

grasp_agents-0.2.8.tar.gz (36.0 kB view details)

Uploaded Source

Built Distribution

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

grasp_agents-0.2.8-py3-none-any.whl (52.1 kB view details)

Uploaded Python 3

File details

Details for the file grasp_agents-0.2.8.tar.gz.

File metadata

  • Download URL: grasp_agents-0.2.8.tar.gz
  • Upload date:
  • Size: 36.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.7.7

File hashes

Hashes for grasp_agents-0.2.8.tar.gz
Algorithm Hash digest
SHA256 99bffddfa9da7a1eb82467d671bd0c8982603f12d7b26c7cecb0db0ff96fe891
MD5 ab83fc694b7d5cf74cbf5da502cb3417
BLAKE2b-256 8bb7e557e4acf9d133ca85eb77b863c99929577d7d403177da91025cf56c5391

See more details on using hashes here.

File details

Details for the file grasp_agents-0.2.8-py3-none-any.whl.

File metadata

File hashes

Hashes for grasp_agents-0.2.8-py3-none-any.whl
Algorithm Hash digest
SHA256 4fa1281c1726ddc38864d0b40c64915418708617f0c6d3706554611baecad125
MD5 ac513525d25fe359ab4d1468cde73d17
BLAKE2b-256 7c5f57b5e9e48d44b0221211a125144a51194f7076320b5f9a6be2d651581f31

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