# AgentSafe + LangChain Integration Guide

Protect your LangChain agents from phishing, malicious redirects, scam sites, and prompt injection attacks before they interact with any external URL.

## Installation

```bash
pip install agentsafe-sdk langchain
```

## Quick Start

```python
import os
from agentsafe import AgentSafe

client = AgentSafe(api_key=os.environ["AGENTSAFE_API_KEY"])

# Check a URL before your agent visits it
result = client.check("https://example.com", action="browse")

if result.blocked:
    raise Exception(f"AgentSafe blocked unsafe destination: {result.url}")

print(f"Score: {result.score}/100")
print(f"Verdict: {result.recommendation}")
print(f"Reasoning: {result.summary}")
```

## LangChain Tool Integration

Add AgentSafe as a LangChain tool so your agent automatically checks URLs before interacting with them.

```python
import os
from langchain.tools import Tool
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from agentsafe import AgentSafe

client = AgentSafe(api_key=os.environ["AGENTSAFE_API_KEY"])

def check_url_safety(url: str) -> str:
    """Check if a URL is safe for the agent to interact with."""
    try:
        result = client.check(url, action="browse")
        return f"""
URL Safety Check Result:
- Score: {result.score}/100
- Verdict: {result.recommendation}
- Blocked: {result.blocked}
- Reasoning: {result.summary}
        """.strip()
    except Exception as e:
        return f"Safety check failed: {str(e)}"

agentsafe_tool = Tool(
    name="check_url_safety",
    func=check_url_safety,
    description=(
        "ALWAYS use this tool before visiting, clicking, or interacting with any URL. "
        "Returns a safety score and verdict. If blocked=True, do NOT proceed with the URL."
    )
)

# Add to your agent's tools
tools = [agentsafe_tool]  # add your other tools here

llm = ChatOpenAI(model="gpt-4o")
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant. Always check URL safety before interacting with any external link."),
    MessagesPlaceholder(variable_name="chat_history", optional=True),
    ("human", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])

agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Your agent now automatically checks URLs
response = agent_executor.invoke({
    "input": "Can you check if https://paypal-secure-account-verify.com is safe to use?"
})
```

## Payment Safety Integration

For agents that move money, pass transaction context for stricter payment-specific verdicts.

```python
from agentsafe import AgentSafe

client = AgentSafe(api_key=os.environ["AGENTSAFE_API_KEY"])

def safe_payment_check(url: str, amount: float, currency: str = "USD", recipient: str = None) -> dict:
    """
    Check if a payment destination is safe before sending funds.
    Returns a verdict with payment-specific risk analysis.
    """
    import requests

    response = requests.post(
        "https://api.agentsafe.app/api/check",
        headers={
            "Authorization": f"Bearer {os.environ['AGENTSAFE_API_KEY']}",
            "Content-Type": "application/json"
        },
        json={
            "url": url,
            "action": "send_payment",
            "amount": amount,
            "currency": currency,
            "recipient": recipient
        }
    )
    return response.json()

# Example usage
result = safe_payment_check(
    url="https://vendor.com/invoice",
    amount=4200,
    currency="USD",
    recipient="billing@vendor.com"
)

if result["recommended_action"] == "BLOCK":
    raise Exception(f"Payment blocked: {result['summary']}")

if result["recommended_action"] == "REQUIRE_HUMAN_APPROVAL":
    print(f"Human approval required: {result['summary']}")
    # trigger your approval workflow here

print(f"Payment destination approved: {result['summary']}")
```

## LangChain Callback Handler

Automatically scan every URL your agent encounters using a callback handler.

```python
from langchain.callbacks.base import BaseCallbackHandler
from agentsafe import AgentSafe
import re

class AgentSafeCallbackHandler(BaseCallbackHandler):
    """Automatically checks URLs in agent actions before execution."""

    def __init__(self, api_key: str, block_on_risky: bool = True):
        self.client = AgentSafe(api_key=api_key)
        self.block_on_risky = block_on_risky
        self.url_pattern = re.compile(r'https?://[^\s\'"]+')

    def on_agent_action(self, action, **kwargs):
        """Intercept agent actions and check any URLs found."""
        action_str = str(action)
        urls = self.url_pattern.findall(action_str)

        for url in urls:
            result = self.client.check(url, action="browse")
            if result.blocked and self.block_on_risky:
                raise ValueError(
                    f"AgentSafe blocked unsafe URL: {url}\n"
                    f"Score: {result.score}/100\n"
                    f"Reason: {result.summary}"
                )

# Usage
handler = AgentSafeCallbackHandler(
    api_key=os.environ["AGENTSAFE_API_KEY"],
    block_on_risky=True
)

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    callbacks=[handler],
    verbose=True
)
```

## CrewAI Integration

```python
from crewai import Agent, Task, Crew, Tool
from agentsafe import AgentSafe

client = AgentSafe(api_key=os.environ["AGENTSAFE_API_KEY"])

def check_url(url: str) -> str:
    result = client.check(url, action="browse")
    if result.blocked:
        return f"BLOCKED: {result.summary}"
    return f"SAFE (score: {result.score}/100): {result.summary}"

safety_tool = Tool(
    name="URL Safety Checker",
    func=check_url,
    description="Check if a URL is safe before visiting it. Always use before browsing."
)

researcher = Agent(
    role="Web Researcher",
    goal="Research topics safely without visiting malicious sites",
    tools=[safety_tool],
    backstory="You always verify URL safety before visiting any website."
)
```

## Environment Variables

```bash
export AGENTSAFE_API_KEY=your_api_key_here
```

Get your API key at: https://agentsafe.app

## Action Types

| Action | Use Case | Risk Multiplier |
|--------|----------|-----------------|
| `browse` | General web browsing | 1x |
| `login` | Authentication pages | 1.2x |
| `make_payment` | Payment pages | 1.5x |
| `send_payment` | Autonomous payments | 1.5x |
| `transfer_funds` | Fund transfers | 1.5x |
| `download` | File downloads | 1.2x |

## Response Fields

| Field | Type | Description |
|-------|------|-------------|
| `score` | 0-100 | Trust score (100 = fully trusted) |
| `recommendation` | string | `TRUSTED`, `RISKY`, or `UNKNOWN` |
| `recommended_action` | string | `ALLOW`, `BLOCK`, or `REQUIRE_HUMAN_APPROVAL` |
| `blocked` | bool | True if agent should not proceed |
| `summary` | string | Plain-English Claude reasoning |
| `risk_factors` | array | Specific threats detected |

## Links

- **Website:** https://agentsafe.app
- **API Docs:** https://api.agentsafe.app/api/docs
- **Python SDK:** https://pypi.org/project/agentsafe-sdk
- **JS/TS SDK:** https://www.npmjs.com/package/agentsafe-sdk
- **MCP Server:** `npx agentsafe-mcp-server`
- **Support:** support@agentsafe.app
