Grasp Agents Library
Project description
Grasp Agents
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 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 re
from typing import Any
from pathlib import Path
from pydantic import BaseModel, Field
from dotenv import load_dotenv
from grasp_agents.typing.tool import BaseTool
from grasp_agents.typing.io import AgentPayload
from grasp_agents.run_context import RunContextWrapper
from grasp_agents.openai.openai_llm import OpenAILLM, OpenAILLMSettings
from grasp_agents.llm_agent import LLMAgent
from grasp_agents.grasp_logging import setup_logging
from grasp_agents.typing.message import Conversation
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."
in_schema: type[TeacherQuestion] = TeacherQuestion
out_schema: type[StudentReply] = StudentReply
async def run(
self, inp: TeacherQuestion, ctx: RunContextWrapper[Any] | None = None
) -> StudentReply:
return input(inp.question)
class FinalResponse(AgentPayload):
problem: str
teacher = LLMAgent[Any, FinalResponse, None](
agent_id="teacher",
llm=OpenAILLM(
model_name="gpt-4.1",
api_provider="openai",
llm_settings=OpenAILLMSettings(temperature=0.1),
),
tools=[AskStudentTool()],
max_turns=20,
react_mode=True,
sys_prompt=sys_prompt_react,
out_schema=FinalResponse,
set_state_strategy="reset",
)
@teacher.tool_call_loop_exit_handler
def exit_tool_call_loop(conversation: Conversation, ctx, **kwargs) -> None:
message_text = conversation[-1].content
return re.search(r"<PROBLEM>", message_text)
@teacher.parse_output_handler
def parse_output(conversation: Conversation, ctx, **kwargs) -> FinalResponse:
message_text = conversation[-1].content
matches = re.findall(r"<PROBLEM>(.*?)</PROBLEM>", message_text, re.DOTALL)
return FinalResponse(problem=matches[0])
async def main():
ctx = RunContextWrapper(print_messages=True)
out = await teacher.run(ctx=ctx)
print(out.payloads[0].problem)
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file grasp_agents-0.1.18.tar.gz.
File metadata
- Download URL: grasp_agents-0.1.18.tar.gz
- Upload date:
- Size: 33.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.7.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3d12cca6b334dc9a32c3ebd27ded93b1745c03d68d57b9c1f325e3d3823e2919
|
|
| MD5 |
aeecf394fc830e2d47a8a14ad6be2ff8
|
|
| BLAKE2b-256 |
f12d9109640d668e0188445191fb4d745d00fd5ed202cc7703e4119e78fd27e5
|
File details
Details for the file grasp_agents-0.1.18-py3-none-any.whl.
File metadata
- Download URL: grasp_agents-0.1.18-py3-none-any.whl
- Upload date:
- Size: 48.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.7.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
63d27efd5826d866c5c674f9ee19bc3abb6a7ec1214a986bd4dcc03b871fe627
|
|
| MD5 |
35fc6d6222340c18436b8b4f0f2fd733
|
|
| BLAKE2b-256 |
3bdfc0b5dc237d054fd0cf1f9013f02079a6153607869cc2aaa252f8ea4205b9
|