Metadata-Version: 2.4
Name: clap-agents
Version: 0.2.2
Summary: A Python framework for building cognitive agentic patterns including ReAct agents, Multi-Agent Teams, native tool calling, and MCP client integration.
Project-URL: Homepage, https://github.com/MaitreyaM/CLAP-AGENTS.git
Project-URL: Repository, https://github.com/MaitreyaM/CLAP-AGENTS.git
Project-URL: Issues, https://github.com/MaitreyaM/CLAP-AGENTS.git/issues
Author-email: Maitreya Mishra <maitreyamishra04@gmail.com>
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: agent,agentic,agentic systems,ai,framework,llm,mcp,multi-agent,react,tool calling
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.10
Requires-Dist: anyio>=4.5
Requires-Dist: colorama
Requires-Dist: duckduckgo-search
Requires-Dist: groq
Requires-Dist: httpx-sse>=0.4
Requires-Dist: httpx>=0.27
Requires-Dist: jsonschema
Requires-Dist: mcp>=1.2.0
Requires-Dist: openai>=1.0.0
Requires-Dist: pydantic<3.0.0,>=2.7.2
Requires-Dist: requests
Provides-Extra: all
Requires-Dist: chromadb>=0.5.0; extra == 'all'
Requires-Dist: crawl4ai; extra == 'all'
Requires-Dist: fastembed>=0.2.0; extra == 'all'
Requires-Dist: graphviz; extra == 'all'
Requires-Dist: ollama>=0.2.0; extra == 'all'
Requires-Dist: pandas; extra == 'all'
Requires-Dist: pypdf; extra == 'all'
Requires-Dist: qdrant-client[fastembed]>=1.7.0; extra == 'all'
Requires-Dist: sentence-transformers; extra == 'all'
Provides-Extra: chromadb
Requires-Dist: chromadb>=0.5.0; extra == 'chromadb'
Provides-Extra: fastembed
Requires-Dist: fastembed>=0.2.0; extra == 'fastembed'
Provides-Extra: ollama
Requires-Dist: ollama>=0.2.0; extra == 'ollama'
Provides-Extra: pandas
Requires-Dist: pandas; extra == 'pandas'
Provides-Extra: pdf
Requires-Dist: pypdf; extra == 'pdf'
Provides-Extra: qdrant
Requires-Dist: qdrant-client[fastembed]>=1.7.0; extra == 'qdrant'
Provides-Extra: rag
Requires-Dist: chromadb>=0.5.0; extra == 'rag'
Requires-Dist: fastembed>=0.2.0; extra == 'rag'
Requires-Dist: ollama>=0.2.0; extra == 'rag'
Requires-Dist: pypdf; extra == 'rag'
Requires-Dist: qdrant-client[fastembed]>=1.7.0; extra == 'rag'
Requires-Dist: sentence-transformers; extra == 'rag'
Provides-Extra: sentence-transformers
Requires-Dist: sentence-transformers; extra == 'sentence-transformers'
Provides-Extra: standard-tools
Requires-Dist: crawl4ai; extra == 'standard-tools'
Provides-Extra: viz
Requires-Dist: graphviz; extra == 'viz'
Description-Content-Type: text/markdown

<p align="center">
  <img src="GITCLAP.png" alt="CLAP Logo" width="700" height="200"/>
</p>

# CLAP - Cognitive Layer Agent Package

[![PyPI version](https://img.shields.io/pypi/v/clap-agents.svg)](https://pypi.org/project/clap-agents/) 
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Python Version](https://img.shields.io/pypi/pyversions/clap-agents.svg)](https://pypi.org/project/clap-agents/) 

**CLAP (Cognitive Layer Agent Package)** is a Python framework providing building blocks for creating sophisticated AI agents based on modern agentic patterns. It enables developers to easily construct agents capable of reasoning, planning, and interacting with external tools, systems, and knowledge bases.

Built with an asynchronous core (`asyncio`), CLAP offers flexibility and performance for complex agentic workflows.

<p align="center">
  <img src="PIP CLAP.png" alt="CLAP Pip Install" width="700" height="200"/> <!-- Updated alt text -->
</p>

## Key Features

*   **Modular Agent Patterns:**
    *   **ReAct Agent:** Implements the Reason-Act loop with robust thought-prompting and native tool calling. Ideal for complex reasoning and RAG.
    *   **Tool Agent:** A straightforward agent for single-step tool usage, including simple RAG.
    *   **Multi-Agent Teams:** Define teams of specialized agents with dependencies, enabling collaborative task execution (sequential or parallel).
*   **Advanced Tool Integration:**
    *   **Native LLM Tool Calling:** Leverages modern LLM APIs for reliable tool execution.
    *   **Local Tools:** Easily define and use local Python functions (both synchronous and asynchronous) as tools using the `@tool` decorator.
    *   **Remote Tools (MCP):** Integrates with [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers via the included `MCPClientManager`, allowing agents to discover and use tools exposed by external systems (currently supports SSE transport).
    *   **Robust Validation & Coercion:** Uses `jsonschema` for strict validation of tool arguments and attempts type coercion for common LLM outputs (e.g., string numbers to integers).
*   **Retrieval Augmented Generation (RAG) Capabilities:**
    *   **`VectorStoreInterface`:** An abstraction for interacting with various vector databases.
    *   **Supported Vector Stores:**
        *   **ChromaDB:** (`ChromaStore`) For local or self-hosted vector storage.
        *   **Qdrant:** (`QdrantStore`) For local (in-memory or file-based) vector storage.
    *   **`EmbeddingFunctionInterface`:** A protocol for consistent interaction with different embedding models.
    *   **Supported Embedding Function Wrappers:**
        *   `SentenceTransformerEmbeddings`: Uses models from the `sentence-transformers` library.
        *   `OllamaEmbeddings`: Generates embeddings using models running locally via Ollama.
        *   `FastEmbedEmbeddings`: Utilizes the `fastembed` library for CPU-optimized embeddings. (Note: Performance for very large batch ingestions via the async wrapper might vary based on CPU and may be slower than SentenceTransformers for initial bulk loads.)
    *   **RAG-Aware Agents:** Both `Agent` (via `ReactAgent`) and `ToolAgent` can be equipped with a `vector_store` to perform `vector_query` tool calls, enabling them to retrieve context before responding.
    *   **Utilities:** Includes basic PDF and CSV text loaders and chunking strategies in `clap.utils.rag_utils`.
*   **Pluggable LLM Backends:**
    *   Uses a **Strategy Pattern** (`LLMServiceInterface`) to abstract LLM interactions.
    *   Includes ready-to-use service implementations for:
        *   **Groq:** (`GroqService`)
        *   **Google Generative AI (Gemini):** (`GoogleOpenAICompatService` via OpenAI compatibility layer)
        *   **Ollama (Local LLMs):** (`OllamaOpenAICompatService` also known as `OllamaService` via OpenAI compatibility layer, allowing use of locally run models like Llama 3, Mistral, etc.)
    *   Easily extensible to support other LLM providers.
*   **Asynchronous Core:** Built entirely on `asyncio` for efficient I/O operations and potential concurrency.
*   **Structured Context Passing:** Enables clear and organized information flow between agents in a team.
*   **Built-in Tools:** Includes helpers for web search (`duckduckgo_search`). More available via optional dependencies.

## Installation

Ensure you have Python 3.10 or later installed.

```bash
pip install clap-agents
```

Ensure you have Python 3.10 or later installed.

```bash
pip install clap-agents


To use specific features, you might need to install optional dependencies:
# For Qdrant support (includes fastembed)
pip install "clap-agents[qdrant]"

# For ChromaDB support
pip install "clap-agents[chromadb]"

# For Ollama (LLM and/or Embeddings)
pip install "clap-agents[ollama]"

# For other tools like web crawling or visualization
pip install "clap-agents[standard_tools,viz]"

# To install all major optional dependencies
pip install "clap-agents[all]"
```


Check the pyproject.toml for the full list of [project.optional-dependencies]. You will also need to have external services like Ollama or Qdrant (if used locally) running.
Depending on the tools or LLM backends you intend to use, you might need additional dependencies listed in the pyproject.toml (e.g., groq, openai, mcp, jsonschema, requests, duckduckgo-search, graphviz). Check the [project.dependencies] and [project.optional-dependencies] sections.


## Quick Start: Simple Tool calling Agent with a Local Tool
This example demonstrates creating a Tool calling agent using the Groq backend and a local tool

```
from dotenv import load_dotenv
from clap import ToolAgent
from clap import duckduckgo_search

load_dotenv()

async def main():
    agent = ToolAgent(tools=duckduckgo_search, model="meta-llama/llama-4-scout-17b-16e-instruct")
    user_query = "Search the web for recent news about AI advancements."
    response = await agent.run(user_msg=user_query)
    print(f"Response:\n{response}")

asyncio.run(main())
```


## Quick Start: Simple ReAct Agent with a Local Tool
This example demonstrates creating a ReAct agent using the Groq backend and a local tool.

```
import asyncio
import os
from dotenv import load_dotenv
from clap import ReactAgent, tool, GroqService

load_dotenv() 
@tool
def get_word_length(word: str) -> int:
    """Calculates the length of a word."""
    print(f"[Local Tool] Calculating length of: {word}")
    return len(word)

async def main():
    groq_service = GroqService() # Your service of choice (either groq or Google)
    agent = ReactAgent(
        llm_service=groq_service,
        model="llama-3.3-70b-versatile", # Or another Groq model
        tools=[get_word_length], # Provide the local tool
        # system_prompt="You are a helpful assistant." # Optional base prompt
    )

    user_query = "How many letters are in the word 'framework'?"
    response = await agent.run(user_msg=user_query)
    
    print(response)
    
asyncio.run(main())
```

## Quick Start: Simple Tool-Calling Agent with Ollama
This example demonstrates a ToolAgent using a local Ollama model and a local tool.
Ensure Ollama is running and you have pulled the model (e.g., ollama pull llama3).

```
import asyncio
from dotenv import load_dotenv
from clap import ToolAgent, tool, OllamaService # Assuming OllamaService is your OllamaOpenAICompatService

load_dotenv()

@tool
def get_capital(country: str) -> str:
    """Returns the capital of a country."""
    if country.lower() == "france": return "Paris"
    return f"I don't know the capital of {country}."

async def main():
    # Initialize the Ollama service
    ollama_llm_service = OllamaService(default_model="llama3") # Specify your Ollama model

    agent = ToolAgent(
        llm_service=ollama_llm_service,
        model="llama3", # Model name for this agent
        tools=[get_capital]
    )
    user_query = "What is the capital of France?"
    response = await agent.run(user_msg=user_query)
    print(f"Query: {user_query}\nResponse:\n{response}")

    await ollama_llm_service.close() # Important for OllamaService

if __name__ == "__main__":
    asyncio.run(main())

```

## Quick Start: RAG Agent with Qdrant and Ollama Embeddings
This example shows an Agent performing RAG using Ollama for embeddings and Qdrant as the vector store.
Ensure Ollama is running (with nomic-embed-text and llama3 pulled) and Qdrant is running (e.g., via Docker).
```
import asyncio
import os
import shutil
from dotenv import load_dotenv
from clap import Agent, QdrantStore, OllamaEmbeddings, OllamaService
from clap.utils.rag_utils import chunk_text_by_fixed_size
from qdrant_client import models as qdrant_models # If needed for distance

load_dotenv()

OLLAMA_HOST = "http://localhost:11434"
EMBED_MODEL = "nomic-embed-text"
LLM_MODEL = "llama3"
DB_PATH = "./temp_rag_db_ollama_qdrant"
COLLECTION = "my_rag_docs"

async def main():
    if os.path.exists(DB_PATH): shutil.rmtree(DB_PATH)

    ollama_ef = OllamaEmbeddings(model_name=EMBED_MODEL, ollama_host=OLLAMA_HOST)
    vector_store = await QdrantStore.create(
        collection_name=COLLECTION,
        embedding_function=ollama_ef,
        path=DB_PATH, # For local file-based Qdrant
        recreate_collection_if_exists=True
    )

    sample_texts = ["The sky is blue due to Rayleigh scattering.", "Large language models are powerful."]
    chunks = [chunk for text in sample_texts for chunk in chunk_text_by_fixed_size(text, 100, 10)]
    ids = [str(i) for i in range(len(chunks))] # Qdrant needs UUIDs; QdrantStore handles this
    
    if chunks:
        await vector_store.add_documents(documents=chunks, ids=ids)
    print(f"Ingested {len(chunks)} chunks.")

    ollama_llm_service = OllamaService(default_model=LLM_MODEL, base_url=f"{OLLAMA_HOST}/v1")
    rag_agent = Agent(
        name="RAGMaster",
        backstory="I answer questions using provided documents.",
        task_description="Why is the sky blue according to the documents?", # This becomes the User Query
        llm_service=ollama_llm_service,
        model=LLM_MODEL,
        vector_store=vector_store
    )

    response = await rag_agent.run()
    print(f"Query: {rag_agent.task_description}\nResponse:\n{response.get('output')}")

    await vector_store.close()
    await ollama_llm_service.close()
    if os.path.exists(DB_PATH): shutil.rmtree(DB_PATH)

asyncio.run(main())
```

## Exploring Further


# Multi-Agent Teams: See examples/test_clap_comprehensive_suite.py and other team examples for setting up sequential or parallel agent workflows.

# MCP Integration: Check examples/test_clap_comprehensive_suite.py (ensure corresponding MCP servers from examples/simple_mcp.py etc. are running).

# Other LLM Services (Groq, Google Gemini , Ollama): Modify the Quick Starts to use GroqService or GoogleOpenAICompatService (ensure API keys are set).

# Different Vector Stores & Embedding Functions: Experiment with ChromaStore, QdrantStore, SentenceTransformerEmbeddings, FastEmbedEmbeddings, and OllamaEmbeddings as shown in the comprehensive test suite.

License
This project is licensed under the terms of the Apache License 2.0. See the LICENSE file for details.



