ais-langchain


Nameais-langchain JSON
Version 0.1.2 PyPI version JSON
download
home_pageNone
SummaryProduction-grade LangChain integration for AIS Protocol - Connect AIS agents to LangGraph workflows
upload_time2025-11-03 11:28:26
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseApache-2.0
keywords ais-protocol langchain langgraph ai-agents agent-communication multi-agent llm
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ais-langchain

**Production-grade LangChain integration for AIS Protocol**

Connect AIS agents to modern LangGraph workflows with enterprise resilience features.

[![PyPI version](https://img.shields.io/pypi/v/ais-langchain.svg)](https://pypi.org/project/ais-langchain/)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)

---

## 🎯 What is This?

This package enables **seamless integration** between [AIS Protocol](https://github.com/ais-protocol/ais-python) agents and [LangChain](https://python.langchain.com/)'s modern LangGraph framework.

**Think:** HTTP for AI agents + LangChain's powerful workflows = **Multi-Agent Nirvana** 🚀

---

## ✨ Features

### 🏗️ Production-Ready

- ✅ **Modern LangGraph** - Uses latest `langgraph` with `create_react_agent`
- ✅ **Automatic Retry** - Exponential backoff with configurable jitter
- ✅ **Circuit Breaker** - Prevents cascading failures
- ✅ **Response Caching** - Reduce latency up to 160x
- ✅ **Connection Pooling** - Efficient resource usage
- ✅ **Structured Logging** - Production-grade observability
- ✅ **Performance Metrics** - Track latency, success/failure rates
- ✅ **Health Checks** - Monitor agent availability
- ✅ **Type Safety** - Full Python type hints

### 🎭 Multi-Agent Orchestration

- ✅ **ManagedAISTools** - Coordinate multiple specialized agents
- ✅ **Dynamic Routing** - Route to agents based on capabilities
- ✅ **Capability Discovery** - Automatic tool generation
- ✅ **Session Management** - Stateful multi-turn conversations

---

## 🚀 Quick Start

### Installation

```bash
pip install ais-langchain ais-protocol langchain-core langgraph langchain-openai
```

### Basic Usage

```python
import asyncio
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from ais_protocol import AISClient
from ais_langchain import create_enhanced_ais_tool, EnhancedAISToolConfig, RetryConfig, CircuitBreakerConfig
from pydantic import BaseModel, Field

# 1. Connect to AIS agent
client = AISClient(
    agent_id='agent://example.com/my-client',
    agent_name='My Client'
)

await client.connect('http://localhost:8000')

# 2. Define schema
class CalculateArgs(BaseModel):
    operation: str = Field(description="Operation: add, subtract, multiply, divide")
    a: float = Field(description="First number")
    b: float = Field(description="Second number")

# 3. Create production-grade tool
calculator_tool = create_enhanced_ais_tool(EnhancedAISToolConfig(
    client=client,
    capability='calculate',
    args_schema=CalculateArgs,
    retry=RetryConfig(max_attempts=3),
    circuit_breaker=CircuitBreakerConfig(failure_threshold=5),
    cache=True
))

# 4. Use in LangGraph
model = ChatOpenAI(model='gpt-4o-mini')
agent = create_react_agent(model, [calculator_tool])

# 5. Run!
result = await agent.ainvoke({
    'messages': [{'role': 'user', 'content': 'What is 42 times 17?'}]
})
```

---

## 🎓 Examples

### Simple Tool

```python
from ais_langchain import create_ais_tool

# Basic tool (no resilience features)
simple_tool = create_ais_tool(
    client=client,
    capability='greet'
)
```

### Production-Grade Tool

```python
from ais_langchain import (
    create_enhanced_ais_tool,
    EnhancedAISToolConfig,
    Logger,
    LoggerConfig,
    LogLevel,
    MetricsCollector,
    RetryConfig,
    CircuitBreakerConfig,
)

logger = Logger.get_instance_sync(LoggerConfig(level=LogLevel.INFO, pretty=True))
metrics = MetricsCollector()

production_tool = create_enhanced_ais_tool(EnhancedAISToolConfig(
    client=client,
    capability='process_data',
    retry=RetryConfig(
        max_attempts=3,
        initial_delay=1.0,
        backoff_multiplier=2.0
    ),
    circuit_breaker=CircuitBreakerConfig(
        failure_threshold=5,
        reset_timeout=30.0
    ),
    cache=True,
    cache_ttl=60.0,
    logger=logger,
    metrics=metrics
))
```

### Multi-Agent Management

```python
from ais_langchain import ManagedAISTools

# Create managed tools for multiple agents
managed = ManagedAISTools(client)

tools = managed.create_all_tools(
    retry=RetryConfig(max_attempts=3),
    circuit_breaker=CircuitBreakerConfig(failure_threshold=5),
    cache=True,
    schemas={
        'calculate': CalculateArgs,
        'process_text': ProcessTextArgs
    }
)

# Get diagnostics
health = await managed.get_health()
metrics = managed.get_metrics()
diagnostics = await managed.get_diagnostics()
```

---

## 📊 Performance

### Caching Impact

```
Without caching:
- Average latency: ~800ms per call
- Network overhead: High

With caching (60s TTL):
- First call: ~800ms
- Cached calls: ~5ms
- Speedup: 160x ⚡
```

### Resilience Impact

```
Without retry/circuit breaker:
- Transient failures → errors
- Cascading failures possible
- Manual recovery needed

With retry + circuit breaker:
- 95%+ success rate with network issues
- Automatic recovery
- Prevents cascade failures
- Self-healing system ✨
```

---

## 🏗️ Architecture

### Tool Adapter

Converts AIS capabilities into LangChain tools:

```
AIS Agent                LangChain
   │                        │
   ├─ capability_1  ─→  Tool 1
   ├─ capability_2  ─→  Tool 2
   └─ capability_3  ─→  Tool 3
```

### Resilience Layers

```
LangGraph Request
    │
    ├─→ Response Cache (optional)
    │   ├─ Hit → Return cached
    │   └─ Miss → Continue
    │
    ├─→ Circuit Breaker
    │   ├─ OPEN → Fail fast
    │   ├─ HALF_OPEN → Test
    │   └─ CLOSED → Continue
    │
    ├─→ Retry Logic
    │   ├─ Success → Return
    │   └─ Failure → Retry with backoff
    │
    └─→ AIS Agent
        └─ Execute capability
```

---

## 📚 API Reference

### Core Functions

#### `create_ais_tool()`

Create a basic LangChain tool from an AIS capability.

```python
def create_ais_tool(
    client: AISClient,
    capability: str,
    name: Optional[str] = None,
    description: Optional[str] = None,
    args_schema: Optional[Type[BaseModel]] = None,
    timeout: Optional[float] = None,
) -> StructuredTool
```

#### `create_enhanced_ais_tool()`

Create a production-grade tool with resilience features.

```python
@dataclass
class EnhancedAISToolConfig:
    client: AISClient
    capability: str
    name: Optional[str] = None
    description: Optional[str] = None
    args_schema: Optional[Type[BaseModel]] = None
    timeout: Optional[float] = None
    retry: Optional[RetryConfig] = None
    circuit_breaker: Optional[CircuitBreakerConfig] = None
    cache: bool = False
    cache_ttl: float = 60.0
    logger: Optional[Logger] = None
    metrics: Optional[MetricsCollector] = None
```

#### `ManagedAISTools`

Manage multiple tools with shared infrastructure.

```python
managed = ManagedAISTools(
    client,
    logger=logger,
    metrics=metrics,
    cache=cache,
    cache_ttl=60.0
)

# Create all tools
tools = managed.create_all_tools(
    retry=RetryConfig(...),
    circuit_breaker=CircuitBreakerConfig(...),
    cache=True
)

# Get diagnostics
health = await managed.get_health()
metrics = managed.get_metrics()
diagnostics = await managed.get_diagnostics()
```

### Resilience Patterns

#### `with_retry()`

Execute function with retry logic.

```python
result = await with_retry(
    lambda: client.call('capability', params),
    RetryConfig(
        max_attempts=3,
        initial_delay=1.0,
        backoff_multiplier=2.0,
        jitter=0.1
    )
)
```

#### `CircuitBreaker`

Implement circuit breaker pattern.

```python
breaker = CircuitBreaker(CircuitBreakerConfig(
    failure_threshold=5,
    reset_timeout=30.0,
    on_open=lambda: print('Circuit OPEN'),
    on_close=lambda: print('Circuit CLOSED')
))

result = await breaker.execute(lambda: some_function())
```

#### `ResponseCache`

Cache responses.

```python
cache = ResponseCache(ttl=60.0)

cached = await cache.get('capability', params)
if not cached:
    result = await client.call('capability', params)
    await cache.set('capability', params, result)
```

### Observability

#### `Logger`

Structured logging.

```python
logger = Logger.get_instance_sync(LoggerConfig(
    level=LogLevel.INFO,
    pretty=True
))

logger.debug('Message', {'context': 'data'})
logger.info('Message', {'context': 'data'})
logger.warn('Message', {'context': 'data'})
logger.error('Message', error, {'context': 'data'})
```

#### `MetricsCollector`

Collect performance metrics.

```python
metrics = MetricsCollector()

metrics.increment_counter_sync('requests_total', 1, {'endpoint': '/api'})
metrics.record_histogram_sync('request_duration_ms', 245, {'endpoint': '/api'})
metrics.set_gauge_sync('active_connections', 10)

stats = metrics.get_histogram_stats('request_duration_ms')
print(stats['p95'])  # 95th percentile
```

#### `HealthChecker`

Monitor health.

```python
health = HealthChecker()

async def check_database():
    connected = await db.ping()
    return {
        'status': HealthStatus.HEALTHY if connected else HealthStatus.UNHEALTHY,
        'message': 'DB down' if not connected else 'DB connected'
    }

health.register('database', check_database)

result = await health.check()
print(result.status)  # HEALTHY | DEGRADED | UNHEALTHY
```

---

## 🎯 Use Cases

### 1. **Multi-Framework Integration**

LangChain agents calling AutoGPT, CrewAI, or custom agents:

```python
# LangChain → AIS → Any Agent Framework
autogpt_tool = create_enhanced_ais_tool(EnhancedAISToolConfig(
    client=autogpt_client,
    capability='research',
    retry=RetryConfig(max_attempts=3),
    cache=True
))

crewai_tool = create_enhanced_ais_tool(EnhancedAISToolConfig(
    client=crewai_client,
    capability='analyze',
    retry=RetryConfig(max_attempts=3),
    cache=True
))

agent = create_react_agent(model, [autogpt_tool, crewai_tool])
```

### 2. **Microservices for AI**

Each capability is an independent service:

```python
math_client = AISClient(...)
await math_client.connect('http://nlp-service:8001')

vision_client = AISClient(...)
await vision_client.connect('http://vision-service:8002')

speech_client = AISClient(...)
await speech_client.connect('http://speech-service:8003')
```

---

## 🏆 Production Checklist

Before deploying to production:

- ✅ Configure retry logic for your use case
- ✅ Set appropriate circuit breaker thresholds
- ✅ Enable caching for read-heavy workloads
- ✅ Set up health checks
- ✅ Monitor performance metrics
- ✅ Configure structured logging
- ✅ Set connection pool sizes
- ✅ Configure timeouts appropriately
- ✅ Test failure scenarios
- ✅ Set up alerting

---

## 🆘 Troubleshooting

### Common Issues

**"Cannot connect to AIS agent"**
```bash
# Make sure agent is running
curl http://localhost:8000/health
```

**"Circuit breaker is OPEN"**
```python
# Reset manually or wait for timeout
await managed_tools.reset_circuit_breakers()
```

**"Cache hit rate is low"**
```python
# Check stats
stats = cache.get_stats()
print(stats)
```

---

## 📝 License

Apache-2.0 - See [LICENSE](LICENSE) for details

---

## 🤝 Contributing

Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md)

---

## 🔗 Links

- **PyPI:** https://pypi.org/project/ais-langchain/
- **GitHub:** https://github.com/ais-protocol/ais-langchain-python
- **AIS Protocol:** https://github.com/ais-protocol/ais-python
- **LangChain:** https://python.langchain.com/

---

## 🎉 Built for LangChain

This integration was built with ❤️ as a gift to the LangChain community.

**Let's make multi-agent AI interoperable!** 🚀

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "ais-langchain",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": "Mercola Consulting Services <manishk@mercola.com>",
    "keywords": "ais-protocol, langchain, langgraph, ai-agents, agent-communication, multi-agent, llm",
    "author": null,
    "author_email": "Mercola Consulting Services <manishk@mercola.com>",
    "download_url": "https://files.pythonhosted.org/packages/e5/0d/29f8e5c69adf48f109bb993d2fd388070944fced1d4b2b6adb525ba8e3ee/ais_langchain-0.1.2.tar.gz",
    "platform": null,
    "description": "# ais-langchain\r\n\r\n**Production-grade LangChain integration for AIS Protocol**\r\n\r\nConnect AIS agents to modern LangGraph workflows with enterprise resilience features.\r\n\r\n[![PyPI version](https://img.shields.io/pypi/v/ais-langchain.svg)](https://pypi.org/project/ais-langchain/)\r\n[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)\r\n[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)\r\n\r\n---\r\n\r\n## \ud83c\udfaf What is This?\r\n\r\nThis package enables **seamless integration** between [AIS Protocol](https://github.com/ais-protocol/ais-python) agents and [LangChain](https://python.langchain.com/)'s modern LangGraph framework.\r\n\r\n**Think:** HTTP for AI agents + LangChain's powerful workflows = **Multi-Agent Nirvana** \ud83d\ude80\r\n\r\n---\r\n\r\n## \u2728 Features\r\n\r\n### \ud83c\udfd7\ufe0f Production-Ready\r\n\r\n- \u2705 **Modern LangGraph** - Uses latest `langgraph` with `create_react_agent`\r\n- \u2705 **Automatic Retry** - Exponential backoff with configurable jitter\r\n- \u2705 **Circuit Breaker** - Prevents cascading failures\r\n- \u2705 **Response Caching** - Reduce latency up to 160x\r\n- \u2705 **Connection Pooling** - Efficient resource usage\r\n- \u2705 **Structured Logging** - Production-grade observability\r\n- \u2705 **Performance Metrics** - Track latency, success/failure rates\r\n- \u2705 **Health Checks** - Monitor agent availability\r\n- \u2705 **Type Safety** - Full Python type hints\r\n\r\n### \ud83c\udfad Multi-Agent Orchestration\r\n\r\n- \u2705 **ManagedAISTools** - Coordinate multiple specialized agents\r\n- \u2705 **Dynamic Routing** - Route to agents based on capabilities\r\n- \u2705 **Capability Discovery** - Automatic tool generation\r\n- \u2705 **Session Management** - Stateful multi-turn conversations\r\n\r\n---\r\n\r\n## \ud83d\ude80 Quick Start\r\n\r\n### Installation\r\n\r\n```bash\r\npip install ais-langchain ais-protocol langchain-core langgraph langchain-openai\r\n```\r\n\r\n### Basic Usage\r\n\r\n```python\r\nimport asyncio\r\nfrom langchain_openai import ChatOpenAI\r\nfrom langgraph.prebuilt import create_react_agent\r\nfrom ais_protocol import AISClient\r\nfrom ais_langchain import create_enhanced_ais_tool, EnhancedAISToolConfig, RetryConfig, CircuitBreakerConfig\r\nfrom pydantic import BaseModel, Field\r\n\r\n# 1. Connect to AIS agent\r\nclient = AISClient(\r\n    agent_id='agent://example.com/my-client',\r\n    agent_name='My Client'\r\n)\r\n\r\nawait client.connect('http://localhost:8000')\r\n\r\n# 2. Define schema\r\nclass CalculateArgs(BaseModel):\r\n    operation: str = Field(description=\"Operation: add, subtract, multiply, divide\")\r\n    a: float = Field(description=\"First number\")\r\n    b: float = Field(description=\"Second number\")\r\n\r\n# 3. Create production-grade tool\r\ncalculator_tool = create_enhanced_ais_tool(EnhancedAISToolConfig(\r\n    client=client,\r\n    capability='calculate',\r\n    args_schema=CalculateArgs,\r\n    retry=RetryConfig(max_attempts=3),\r\n    circuit_breaker=CircuitBreakerConfig(failure_threshold=5),\r\n    cache=True\r\n))\r\n\r\n# 4. Use in LangGraph\r\nmodel = ChatOpenAI(model='gpt-4o-mini')\r\nagent = create_react_agent(model, [calculator_tool])\r\n\r\n# 5. Run!\r\nresult = await agent.ainvoke({\r\n    'messages': [{'role': 'user', 'content': 'What is 42 times 17?'}]\r\n})\r\n```\r\n\r\n---\r\n\r\n## \ud83c\udf93 Examples\r\n\r\n### Simple Tool\r\n\r\n```python\r\nfrom ais_langchain import create_ais_tool\r\n\r\n# Basic tool (no resilience features)\r\nsimple_tool = create_ais_tool(\r\n    client=client,\r\n    capability='greet'\r\n)\r\n```\r\n\r\n### Production-Grade Tool\r\n\r\n```python\r\nfrom ais_langchain import (\r\n    create_enhanced_ais_tool,\r\n    EnhancedAISToolConfig,\r\n    Logger,\r\n    LoggerConfig,\r\n    LogLevel,\r\n    MetricsCollector,\r\n    RetryConfig,\r\n    CircuitBreakerConfig,\r\n)\r\n\r\nlogger = Logger.get_instance_sync(LoggerConfig(level=LogLevel.INFO, pretty=True))\r\nmetrics = MetricsCollector()\r\n\r\nproduction_tool = create_enhanced_ais_tool(EnhancedAISToolConfig(\r\n    client=client,\r\n    capability='process_data',\r\n    retry=RetryConfig(\r\n        max_attempts=3,\r\n        initial_delay=1.0,\r\n        backoff_multiplier=2.0\r\n    ),\r\n    circuit_breaker=CircuitBreakerConfig(\r\n        failure_threshold=5,\r\n        reset_timeout=30.0\r\n    ),\r\n    cache=True,\r\n    cache_ttl=60.0,\r\n    logger=logger,\r\n    metrics=metrics\r\n))\r\n```\r\n\r\n### Multi-Agent Management\r\n\r\n```python\r\nfrom ais_langchain import ManagedAISTools\r\n\r\n# Create managed tools for multiple agents\r\nmanaged = ManagedAISTools(client)\r\n\r\ntools = managed.create_all_tools(\r\n    retry=RetryConfig(max_attempts=3),\r\n    circuit_breaker=CircuitBreakerConfig(failure_threshold=5),\r\n    cache=True,\r\n    schemas={\r\n        'calculate': CalculateArgs,\r\n        'process_text': ProcessTextArgs\r\n    }\r\n)\r\n\r\n# Get diagnostics\r\nhealth = await managed.get_health()\r\nmetrics = managed.get_metrics()\r\ndiagnostics = await managed.get_diagnostics()\r\n```\r\n\r\n---\r\n\r\n## \ud83d\udcca Performance\r\n\r\n### Caching Impact\r\n\r\n```\r\nWithout caching:\r\n- Average latency: ~800ms per call\r\n- Network overhead: High\r\n\r\nWith caching (60s TTL):\r\n- First call: ~800ms\r\n- Cached calls: ~5ms\r\n- Speedup: 160x \u26a1\r\n```\r\n\r\n### Resilience Impact\r\n\r\n```\r\nWithout retry/circuit breaker:\r\n- Transient failures \u2192 errors\r\n- Cascading failures possible\r\n- Manual recovery needed\r\n\r\nWith retry + circuit breaker:\r\n- 95%+ success rate with network issues\r\n- Automatic recovery\r\n- Prevents cascade failures\r\n- Self-healing system \u2728\r\n```\r\n\r\n---\r\n\r\n## \ud83c\udfd7\ufe0f Architecture\r\n\r\n### Tool Adapter\r\n\r\nConverts AIS capabilities into LangChain tools:\r\n\r\n```\r\nAIS Agent                LangChain\r\n   \u2502                        \u2502\r\n   \u251c\u2500 capability_1  \u2500\u2192  Tool 1\r\n   \u251c\u2500 capability_2  \u2500\u2192  Tool 2\r\n   \u2514\u2500 capability_3  \u2500\u2192  Tool 3\r\n```\r\n\r\n### Resilience Layers\r\n\r\n```\r\nLangGraph Request\r\n    \u2502\r\n    \u251c\u2500\u2192 Response Cache (optional)\r\n    \u2502   \u251c\u2500 Hit \u2192 Return cached\r\n    \u2502   \u2514\u2500 Miss \u2192 Continue\r\n    \u2502\r\n    \u251c\u2500\u2192 Circuit Breaker\r\n    \u2502   \u251c\u2500 OPEN \u2192 Fail fast\r\n    \u2502   \u251c\u2500 HALF_OPEN \u2192 Test\r\n    \u2502   \u2514\u2500 CLOSED \u2192 Continue\r\n    \u2502\r\n    \u251c\u2500\u2192 Retry Logic\r\n    \u2502   \u251c\u2500 Success \u2192 Return\r\n    \u2502   \u2514\u2500 Failure \u2192 Retry with backoff\r\n    \u2502\r\n    \u2514\u2500\u2192 AIS Agent\r\n        \u2514\u2500 Execute capability\r\n```\r\n\r\n---\r\n\r\n## \ud83d\udcda API Reference\r\n\r\n### Core Functions\r\n\r\n#### `create_ais_tool()`\r\n\r\nCreate a basic LangChain tool from an AIS capability.\r\n\r\n```python\r\ndef create_ais_tool(\r\n    client: AISClient,\r\n    capability: str,\r\n    name: Optional[str] = None,\r\n    description: Optional[str] = None,\r\n    args_schema: Optional[Type[BaseModel]] = None,\r\n    timeout: Optional[float] = None,\r\n) -> StructuredTool\r\n```\r\n\r\n#### `create_enhanced_ais_tool()`\r\n\r\nCreate a production-grade tool with resilience features.\r\n\r\n```python\r\n@dataclass\r\nclass EnhancedAISToolConfig:\r\n    client: AISClient\r\n    capability: str\r\n    name: Optional[str] = None\r\n    description: Optional[str] = None\r\n    args_schema: Optional[Type[BaseModel]] = None\r\n    timeout: Optional[float] = None\r\n    retry: Optional[RetryConfig] = None\r\n    circuit_breaker: Optional[CircuitBreakerConfig] = None\r\n    cache: bool = False\r\n    cache_ttl: float = 60.0\r\n    logger: Optional[Logger] = None\r\n    metrics: Optional[MetricsCollector] = None\r\n```\r\n\r\n#### `ManagedAISTools`\r\n\r\nManage multiple tools with shared infrastructure.\r\n\r\n```python\r\nmanaged = ManagedAISTools(\r\n    client,\r\n    logger=logger,\r\n    metrics=metrics,\r\n    cache=cache,\r\n    cache_ttl=60.0\r\n)\r\n\r\n# Create all tools\r\ntools = managed.create_all_tools(\r\n    retry=RetryConfig(...),\r\n    circuit_breaker=CircuitBreakerConfig(...),\r\n    cache=True\r\n)\r\n\r\n# Get diagnostics\r\nhealth = await managed.get_health()\r\nmetrics = managed.get_metrics()\r\ndiagnostics = await managed.get_diagnostics()\r\n```\r\n\r\n### Resilience Patterns\r\n\r\n#### `with_retry()`\r\n\r\nExecute function with retry logic.\r\n\r\n```python\r\nresult = await with_retry(\r\n    lambda: client.call('capability', params),\r\n    RetryConfig(\r\n        max_attempts=3,\r\n        initial_delay=1.0,\r\n        backoff_multiplier=2.0,\r\n        jitter=0.1\r\n    )\r\n)\r\n```\r\n\r\n#### `CircuitBreaker`\r\n\r\nImplement circuit breaker pattern.\r\n\r\n```python\r\nbreaker = CircuitBreaker(CircuitBreakerConfig(\r\n    failure_threshold=5,\r\n    reset_timeout=30.0,\r\n    on_open=lambda: print('Circuit OPEN'),\r\n    on_close=lambda: print('Circuit CLOSED')\r\n))\r\n\r\nresult = await breaker.execute(lambda: some_function())\r\n```\r\n\r\n#### `ResponseCache`\r\n\r\nCache responses.\r\n\r\n```python\r\ncache = ResponseCache(ttl=60.0)\r\n\r\ncached = await cache.get('capability', params)\r\nif not cached:\r\n    result = await client.call('capability', params)\r\n    await cache.set('capability', params, result)\r\n```\r\n\r\n### Observability\r\n\r\n#### `Logger`\r\n\r\nStructured logging.\r\n\r\n```python\r\nlogger = Logger.get_instance_sync(LoggerConfig(\r\n    level=LogLevel.INFO,\r\n    pretty=True\r\n))\r\n\r\nlogger.debug('Message', {'context': 'data'})\r\nlogger.info('Message', {'context': 'data'})\r\nlogger.warn('Message', {'context': 'data'})\r\nlogger.error('Message', error, {'context': 'data'})\r\n```\r\n\r\n#### `MetricsCollector`\r\n\r\nCollect performance metrics.\r\n\r\n```python\r\nmetrics = MetricsCollector()\r\n\r\nmetrics.increment_counter_sync('requests_total', 1, {'endpoint': '/api'})\r\nmetrics.record_histogram_sync('request_duration_ms', 245, {'endpoint': '/api'})\r\nmetrics.set_gauge_sync('active_connections', 10)\r\n\r\nstats = metrics.get_histogram_stats('request_duration_ms')\r\nprint(stats['p95'])  # 95th percentile\r\n```\r\n\r\n#### `HealthChecker`\r\n\r\nMonitor health.\r\n\r\n```python\r\nhealth = HealthChecker()\r\n\r\nasync def check_database():\r\n    connected = await db.ping()\r\n    return {\r\n        'status': HealthStatus.HEALTHY if connected else HealthStatus.UNHEALTHY,\r\n        'message': 'DB down' if not connected else 'DB connected'\r\n    }\r\n\r\nhealth.register('database', check_database)\r\n\r\nresult = await health.check()\r\nprint(result.status)  # HEALTHY | DEGRADED | UNHEALTHY\r\n```\r\n\r\n---\r\n\r\n## \ud83c\udfaf Use Cases\r\n\r\n### 1. **Multi-Framework Integration**\r\n\r\nLangChain agents calling AutoGPT, CrewAI, or custom agents:\r\n\r\n```python\r\n# LangChain \u2192 AIS \u2192 Any Agent Framework\r\nautogpt_tool = create_enhanced_ais_tool(EnhancedAISToolConfig(\r\n    client=autogpt_client,\r\n    capability='research',\r\n    retry=RetryConfig(max_attempts=3),\r\n    cache=True\r\n))\r\n\r\ncrewai_tool = create_enhanced_ais_tool(EnhancedAISToolConfig(\r\n    client=crewai_client,\r\n    capability='analyze',\r\n    retry=RetryConfig(max_attempts=3),\r\n    cache=True\r\n))\r\n\r\nagent = create_react_agent(model, [autogpt_tool, crewai_tool])\r\n```\r\n\r\n### 2. **Microservices for AI**\r\n\r\nEach capability is an independent service:\r\n\r\n```python\r\nmath_client = AISClient(...)\r\nawait math_client.connect('http://nlp-service:8001')\r\n\r\nvision_client = AISClient(...)\r\nawait vision_client.connect('http://vision-service:8002')\r\n\r\nspeech_client = AISClient(...)\r\nawait speech_client.connect('http://speech-service:8003')\r\n```\r\n\r\n---\r\n\r\n## \ud83c\udfc6 Production Checklist\r\n\r\nBefore deploying to production:\r\n\r\n- \u2705 Configure retry logic for your use case\r\n- \u2705 Set appropriate circuit breaker thresholds\r\n- \u2705 Enable caching for read-heavy workloads\r\n- \u2705 Set up health checks\r\n- \u2705 Monitor performance metrics\r\n- \u2705 Configure structured logging\r\n- \u2705 Set connection pool sizes\r\n- \u2705 Configure timeouts appropriately\r\n- \u2705 Test failure scenarios\r\n- \u2705 Set up alerting\r\n\r\n---\r\n\r\n## \ud83c\udd98 Troubleshooting\r\n\r\n### Common Issues\r\n\r\n**\"Cannot connect to AIS agent\"**\r\n```bash\r\n# Make sure agent is running\r\ncurl http://localhost:8000/health\r\n```\r\n\r\n**\"Circuit breaker is OPEN\"**\r\n```python\r\n# Reset manually or wait for timeout\r\nawait managed_tools.reset_circuit_breakers()\r\n```\r\n\r\n**\"Cache hit rate is low\"**\r\n```python\r\n# Check stats\r\nstats = cache.get_stats()\r\nprint(stats)\r\n```\r\n\r\n---\r\n\r\n## \ud83d\udcdd License\r\n\r\nApache-2.0 - See [LICENSE](LICENSE) for details\r\n\r\n---\r\n\r\n## \ud83e\udd1d Contributing\r\n\r\nContributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md)\r\n\r\n---\r\n\r\n## \ud83d\udd17 Links\r\n\r\n- **PyPI:** https://pypi.org/project/ais-langchain/\r\n- **GitHub:** https://github.com/ais-protocol/ais-langchain-python\r\n- **AIS Protocol:** https://github.com/ais-protocol/ais-python\r\n- **LangChain:** https://python.langchain.com/\r\n\r\n---\r\n\r\n## \ud83c\udf89 Built for LangChain\r\n\r\nThis integration was built with \u2764\ufe0f as a gift to the LangChain community.\r\n\r\n**Let's make multi-agent AI interoperable!** \ud83d\ude80\r\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Production-grade LangChain integration for AIS Protocol - Connect AIS agents to LangGraph workflows",
    "version": "0.1.2",
    "project_urls": {
        "Documentation": "https://github.com/ais-protocol/ais-langchain-python#readme",
        "Homepage": "https://github.com/ais-protocol/ais-langchain-python",
        "Issues": "https://github.com/ais-protocol/ais-langchain-python/issues",
        "Repository": "https://github.com/ais-protocol/ais-langchain-python"
    },
    "split_keywords": [
        "ais-protocol",
        " langchain",
        " langgraph",
        " ai-agents",
        " agent-communication",
        " multi-agent",
        " llm"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "d4c91dda2119031e14e3e0f33a1daca2859a39fab93e3efe83b6028d41eadd3b",
                "md5": "8f0b11db3db893b9973a7cf98aae5ca7",
                "sha256": "3af1cc6e82042d6e58710bdd800442e69f63c929cfd31036596ad1cf377e546b"
            },
            "downloads": -1,
            "filename": "ais_langchain-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "8f0b11db3db893b9973a7cf98aae5ca7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 24053,
            "upload_time": "2025-11-03T11:28:24",
            "upload_time_iso_8601": "2025-11-03T11:28:24.297938Z",
            "url": "https://files.pythonhosted.org/packages/d4/c9/1dda2119031e14e3e0f33a1daca2859a39fab93e3efe83b6028d41eadd3b/ais_langchain-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e50d29f8e5c69adf48f109bb993d2fd388070944fced1d4b2b6adb525ba8e3ee",
                "md5": "bd0be34decb4828c90e24e6333b86adc",
                "sha256": "0b783546f1f61ca02541cb66503d81cb639927d25f069e080f2206ed2a15f9cc"
            },
            "downloads": -1,
            "filename": "ais_langchain-0.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "bd0be34decb4828c90e24e6333b86adc",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 32121,
            "upload_time": "2025-11-03T11:28:26",
            "upload_time_iso_8601": "2025-11-03T11:28:26.275773Z",
            "url": "https://files.pythonhosted.org/packages/e5/0d/29f8e5c69adf48f109bb993d2fd388070944fced1d4b2b6adb525ba8e3ee/ais_langchain-0.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-11-03 11:28:26",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "ais-protocol",
    "github_project": "ais-langchain-python#readme",
    "github_not_found": true,
    "lcname": "ais-langchain"
}
        
Elapsed time: 3.77839s