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.5.tar.gz (36.4 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.5-py3-none-any.whl (52.5 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for grasp_agents-0.2.5.tar.gz
Algorithm Hash digest
SHA256 892821ac216bb008f9f7a41da2d7bc0e45ab257bf1426edbafd470a5b9d07957
MD5 b78927c5e47af81fa9e257fb865e55b4
BLAKE2b-256 d5c5a54cf8237efa3c451be705e095731a9756d28339787cb923afb5532802c9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for grasp_agents-0.2.5-py3-none-any.whl
Algorithm Hash digest
SHA256 36283bbd5bda3bfd3a0d23dbbc41a9ae77cf33dc2108f6af80074931503df49a
MD5 b1664f237ddcefbd029b6c175873593f
BLAKE2b-256 f1cced62786f78c48318e335d0260ae615dac798276e0cc7aad2f4ea4bb23b5e

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