Metadata-Version: 2.4
Name: agentclear-fallback
Version: 0.1.0
Summary: Never let your AI agent fail again — automatic fallback to AgentClear's marketplace of 60+ API services.
Project-URL: Homepage, https://agentclear.dev
Project-URL: Documentation, https://docs.agentclear.dev/fallback
Project-URL: Repository, https://github.com/agentclear/agentclear-fallback
Project-URL: Issues, https://github.com/agentclear/agentclear-fallback/issues
Author-email: AgentClear <hello@agentclear.dev>
License-Expression: MIT
License-File: LICENSE
Keywords: agent,agentclear,ai,api,autogen,fallback,langchain,marketplace
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Requires-Dist: httpx>=0.24
Provides-Extra: all
Requires-Dist: langchain-core>=0.1; extra == 'all'
Requires-Dist: pyautogen>=0.2; extra == 'all'
Provides-Extra: autogen
Requires-Dist: pyautogen>=0.2; extra == 'autogen'
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: respx>=0.20; extra == 'dev'
Requires-Dist: ruff>=0.1; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.1; extra == 'langchain'
Description-Content-Type: text/markdown

# 🛡️ agentclear-fallback — Never Let Your Agent Fail Again

**Your agent crashes when it doesn't have the right tool.** This package catches those failures and automatically discovers, pays for, and calls the right API through [AgentClear's marketplace](https://agentclear.dev) of 60+ services.

One line of code turns every broken agent into a capable one.

```
pip install agentclear-fallback
```

---

## Quick Start

```python
from agentclear_fallback import agentclear_fallback

@agentclear_fallback(intent="get weather data")
def get_weather(city: str):
    raise NotImplementedError("No weather API configured")

# Instead of crashing, this discovers a weather API on AgentClear,
# calls it, and returns the data:
result = get_weather("London")
print(result)  # {"temperature": 15, "condition": "Cloudy", ...}
```

Set your API key:

```bash
export AGENTCLEAR_API_KEY="your-key-here"
```

Get your key → [agentclear.dev/settings/api-keys](https://agentclear.dev/settings/api-keys)

---

## How It Works

```
Your function raises an exception
         │
         ▼
   ┌─────────────┐
   │  Intercept   │  The decorator catches the error
   └──────┬──────┘
          ▼
   ┌─────────────┐
   │  Discover    │  POST /api/discover → finds the right service
   └──────┬──────┘
          ▼
   ┌─────────────┐
   │  Call        │  POST /api/proxy/{service_id} → invokes the API
   └──────┬──────┘
          ▼
   ┌─────────────┐
   │  Return      │  Response flows back as if the function worked
   └─────────────┘
```

No configuration. No manual API integration. Just describe what you need.

---

## Decorator Usage

### Explicit intent

```python
@agentclear_fallback(intent="translate text between languages")
def translate(text: str, target_language: str):
    raise NotImplementedError()

result = translate("Hello!", target_language="fr")
```

### Auto-inferred intent

The intent is derived from the function name and docstring:

```python
@agentclear_fallback
def fetch_stock_price(ticker: str):
    """Look up the current stock price for a given ticker symbol."""
    raise NotImplementedError()

result = fetch_stock_price("AAPL")
```

### Catch specific exceptions only

```python
@agentclear_fallback(catch=(NotImplementedError, ConnectionError))
def get_data(query: str):
    raise NotImplementedError()
```

### Async support

```python
@agentclear_fallback(intent="geocode address")
async def geocode(address: str):
    raise NotImplementedError()

result = await geocode("1600 Amphitheatre Parkway")
```

---

## LangChain Integration

Add `AgentClearFallbackTool` as the **last** tool in your agent. When the LLM can't find a matching tool, it falls through to AgentClear:

```bash
pip install "agentclear-fallback[langchain]"
```

```python
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
from agentclear_fallback import AgentClearFallbackTool

llm = ChatOpenAI(model="gpt-4o")

tools = [
    # ... your existing tools ...
    AgentClearFallbackTool(),  # ← always last
]

agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS)

# The calculator tool handles this:
agent.invoke({"input": "What is 42 * 17?"})

# No weather tool? AgentClear handles it:
agent.invoke({"input": "What's the weather in Tokyo?"})
```

The tool's description is carefully crafted so the LLM knows to use it as a last resort for any API-backed task.

---

## AutoGen Integration

```bash
pip install "agentclear-fallback[autogen]"
```

```python
from autogen import ConversableAgent
from agentclear_fallback import get_agentclear_autogen_tool

tool = get_agentclear_autogen_tool()

assistant = ConversableAgent("assistant", llm_config={...})
user_proxy = ConversableAgent("user_proxy", human_input_mode="NEVER")

# Register the tool
assistant.register_for_llm(
    name=tool["name"],
    description=tool["description"],
)(tool["func"])

user_proxy.register_for_execution(name=tool["name"])(tool["func"])

user_proxy.initiate_chat(assistant, message="What's the weather in Tokyo?")
```

---

## Core API

For direct usage without decorators or agent frameworks:

```python
from agentclear_fallback import AgentClearFallback

client = AgentClearFallback()

# Discover + call in one step
result = client.discover_and_call(
    intent="get weather data",
    payload={"city": "London"}
)
print(result)

# Or step by step
service = client.discover("get weather data")
result = client.call_service(service["id"], {"city": "London"})

# Async
result = await client.adiscover_and_call("get weather data", {"city": "London"})
```

---

## Configuration

| Setting | Environment Variable | Default |
|---|---|---|
| API Key | `AGENTCLEAR_API_KEY` | *(required)* |
| Base URL | *(constructor arg)* | `https://agentclear.dev` |
| Timeout | *(constructor arg)* | `30s` |

### Logging

Enable debug logging to see discovery and call details:

```python
import logging
logging.getLogger("agentclear_fallback").setLevel(logging.DEBUG)
```

### Error Handling

The package raises specific exceptions you can catch:

```python
from agentclear_fallback.core import (
    AgentClearError,            # Base exception
    AuthenticationError,        # Bad or missing API key
    InsufficientBalanceError,   # Account needs more funds
    DiscoveryError,             # No service matched the intent
    ServiceCallError,           # The API call itself failed
)
```

When your balance is low, the error message includes a direct link to [agentclear.dev/billing](https://agentclear.dev/billing) so you can add funds immediately.

---

## What Services Are Available?

AgentClear's marketplace includes 60+ API services across categories like:

- **Weather** — Current conditions, forecasts, historical data
- **Finance** — Stock prices, crypto, exchange rates, market data
- **Search** — Web search, news, image search
- **AI/ML** — Text generation, image recognition, embeddings
- **Documents** — PDF conversion, OCR, document parsing
- **Geocoding** — Address lookup, reverse geocoding, distance
- **Security** — IP reputation, domain scanning, SSL checks
- **Translation** — 100+ languages, text and document translation
- **Communication** — Email, SMS, push notifications

Browse all services → [agentclear.dev/marketplace](https://agentclear.dev/marketplace)

---

## License

MIT — see [LICENSE](LICENSE) for details.
