adaptive-memory-multi-model-router 2.15.3 → 2.15.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/adapters-ci.yml +142 -0
- package/.github/workflows/ci.yml +2 -5
- package/.github/workflows/pypi-publish.yml +102 -0
- package/CHANGELOG.md +7 -1
- package/README.md +260 -137
- package/README_ja.md +2 -2
- package/README_zh.md +1 -1
- package/adapters/README.md +36 -0
- package/adapters/__init__.py +25 -0
- package/adapters/a3m_adapter/__init__.py +51 -0
- package/adapters/a3m_adapter/adapter/__init__.py +22 -0
- package/adapters/a3m_adapter/adapter/autogen.py +169 -0
- package/adapters/a3m_adapter/adapter/config.py +100 -0
- package/adapters/a3m_adapter/adapter/haystack.py +197 -0
- package/adapters/a3m_adapter/adapter/langchain.py +155 -0
- package/adapters/a3m_adapter/adapter/langgraph.py +196 -0
- package/adapters/a3m_adapter/adapter/llamaindex.py +162 -0
- package/adapters/a3m_adapter/adapter/pinecone.py +217 -0
- package/adapters/a3m_adapter/adapter/vercel.py +188 -0
- package/adapters/a3m_adapter/tests/__init__.py +1 -0
- package/adapters/a3m_adapter/tests/test_adapters.py +118 -0
- package/adapters/a3m_adapter/tests/test_integration.py +80 -0
- package/adapters/requirements-dev.txt +6 -0
- package/adapters/requirements.txt +4 -0
- package/adapters/setup.py +23 -0
- package/apps/cost-calculator/README.md +72 -0
- package/apps/cost-calculator/calculator.css +280 -0
- package/apps/cost-calculator/calculator.js +150 -0
- package/apps/cost-calculator/index.html +321 -0
- package/apps/cost-calculator/package.json +13 -0
- package/articles/ANNOUNCEMENT_reddit_ml.md +76 -0
- package/articles/ANNOUNCEMENT_vc/347/244/276/345/214/272.md +71 -0
- package/articles/ANNOUNCEMENT_vercel.md +85 -0
- package/demo.py +251 -0
- package/dist/providers/providerConfig.d.ts +5 -1
- package/dist/providers/providerConfig.js +1006 -1
- package/dist/providers/providerConfig.js.map +1 -1
- package/docker-compose.yml +84 -60
- package/docs/comparison.md +2 -2
- package/docs/llms-full.txt +360 -138
- package/docs/llms.txt +70 -71
- package/docs-site/index.html +9 -9
- package/llms.txt +70 -62
- package/package.json +41 -91
- package/packages/a3m-vercel-ai/README.md +161 -0
- package/packages/a3m-vercel-ai/dist/a3m-language-model.d.ts +12 -0
- package/packages/a3m-vercel-ai/dist/a3m-language-model.d.ts.map +1 -0
- package/packages/a3m-vercel-ai/dist/a3m-language-model.js +289 -0
- package/packages/a3m-vercel-ai/dist/a3m-language-model.js.map +1 -0
- package/packages/a3m-vercel-ai/dist/index.d.ts +82 -0
- package/packages/a3m-vercel-ai/dist/index.d.ts.map +1 -0
- package/packages/a3m-vercel-ai/dist/index.js +79 -0
- package/packages/a3m-vercel-ai/dist/index.js.map +1 -0
- package/packages/a3m-vercel-ai/dist/types.d.ts +97 -0
- package/packages/a3m-vercel-ai/dist/types.d.ts.map +1 -0
- package/packages/a3m-vercel-ai/dist/types.js +5 -0
- package/packages/a3m-vercel-ai/dist/types.js.map +1 -0
- package/packages/a3m-vercel-ai/package-lock.json +969 -0
- package/packages/a3m-vercel-ai/package.json +46 -0
- package/packages/a3m-vercel-ai/src/a3m-language-model.ts +381 -0
- package/packages/a3m-vercel-ai/src/index.ts +104 -0
- package/packages/a3m-vercel-ai/src/types.ts +116 -0
- package/packages/a3m-vercel-ai/tsconfig.json +20 -0
- package/packages/agentkit-adapter/LICENSE +21 -0
- package/packages/agentkit-adapter/README.md +126 -0
- package/packages/agentkit-adapter/examples/agentkit-example.ts +139 -0
- package/packages/agentkit-adapter/package.json +57 -0
- package/packages/agentkit-adapter/src/adapter.ts +381 -0
- package/packages/agentkit-adapter/src/index.ts +36 -0
- package/packages/agentkit-adapter/src/types.ts +105 -0
- package/packages/agentkit-adapter/src/util.ts +13 -0
- package/packages/agentkit-adapter/tsconfig.json +22 -0
- package/prometheus.yml +8 -0
- package/python/README.md +92 -65
- package/python/a3m/__init__.py +32 -3
- package/python/a3m/adapters/__init__.py +21 -0
- package/python/a3m/adapters/langchain.py +190 -0
- package/python/a3m/adapters/llamaindex.py +249 -0
- package/python/a3m/adapters/qdrant.py +240 -0
- package/python/a3m/adapters/weaviate.py +263 -0
- package/python/a3m/client.py +5 -0
- package/python/a3m_router.egg-info/PKG-INFO +172 -0
- package/python/a3m_router.egg-info/SOURCES.txt +17 -0
- package/python/a3m_router.egg-info/dependency_links.txt +1 -0
- package/python/a3m_router.egg-info/requires.txt +24 -0
- package/python/a3m_router.egg-info/top_level.txt +1 -0
- package/python/build_verify.sh +32 -0
- package/python/dist/a3m_router-2.2.1-py3-none-any.whl +0 -0
- package/python/dist/a3m_router-2.2.1.tar.gz +0 -0
- package/python/dist/a3m_router-2.2.2-py3-none-any.whl +0 -0
- package/python/dist/a3m_router-2.2.2.tar.gz +0 -0
- package/python/mcp-server/README.md +172 -0
- package/python/mcp-server/a3m_mcp/__init__.py +15 -0
- package/python/mcp-server/a3m_mcp/__main__.py +15 -0
- package/python/mcp-server/a3m_mcp/server.py +339 -0
- package/python/mcp-server/pyproject.toml +24 -0
- package/python/pyproject.toml +56 -5
- package/python/setup.py +3 -28
- package/src/providers/providerConfig.ts +1053 -1
- package/summary.txt +38 -0
- package/tsconfig.build.json +1 -2
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""
|
|
2
|
+
A3M Router Adapter for AutoGen (Microsoft).
|
|
3
|
+
|
|
4
|
+
Drop-in replacement for AutoGen's LLMAgent that routes through A3M Router
|
|
5
|
+
for intelligent, cost-optimized multi-agent conversations.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
from autogen import ConversableAgent
|
|
9
|
+
from a3m_adapter import A3MAutoGenAdapter
|
|
10
|
+
|
|
11
|
+
llm_config = {
|
|
12
|
+
"model": "auto",
|
|
13
|
+
"temperature": 0.7,
|
|
14
|
+
"parallel_ensemble": 2,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
assistant = ConversableAgent(
|
|
18
|
+
name="assistant",
|
|
19
|
+
llm_config=llm_config,
|
|
20
|
+
)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import logging
|
|
26
|
+
from typing import Any, Dict, List, Optional, Union
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
A3M_AVAILABLE = False
|
|
31
|
+
try:
|
|
32
|
+
from a3m.router import A3MRouter, RouteResponse
|
|
33
|
+
A3M_AVAILABLE = True
|
|
34
|
+
except ImportError:
|
|
35
|
+
logger.warning(
|
|
36
|
+
"A3M Router not installed. Install with: pip install adaptive-memory-multi-model-router"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class A3MAutoGenAdapter:
|
|
41
|
+
"""
|
|
42
|
+
A3M Router adapter for AutoGen's ConversableAgent.
|
|
43
|
+
|
|
44
|
+
Enables AutoGen agents to use A3M Router for automatic model selection
|
|
45
|
+
across 47+ providers with cost optimization.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
model: str = "auto",
|
|
51
|
+
temperature: float = 0.7,
|
|
52
|
+
max_tokens: Optional[int] = 4096,
|
|
53
|
+
parallel_ensemble: int = 1,
|
|
54
|
+
api_key: Optional[str] = None,
|
|
55
|
+
**kwargs: Any,
|
|
56
|
+
) -> None:
|
|
57
|
+
"""
|
|
58
|
+
Initialize A3M Router adapter for AutoGen.
|
|
59
|
+
"""
|
|
60
|
+
self.model = model
|
|
61
|
+
self.temperature = temperature
|
|
62
|
+
self.max_tokens = max_tokens
|
|
63
|
+
self.parallel_ensemble = parallel_ensemble
|
|
64
|
+
self.api_key = api_key
|
|
65
|
+
self._a3m_router = None
|
|
66
|
+
self._initialized = False
|
|
67
|
+
|
|
68
|
+
def _ensure_router(self) -> None:
|
|
69
|
+
"""Lazily initialize the A3M router."""
|
|
70
|
+
if self._initialized:
|
|
71
|
+
return
|
|
72
|
+
|
|
73
|
+
if not A3M_AVAILABLE:
|
|
74
|
+
raise ImportError(
|
|
75
|
+
"A3M Router is not installed. "
|
|
76
|
+
"Install with: pip install adaptive-memory-multi-model-router"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
self._a3m_router = A3MRouter(
|
|
80
|
+
model=self.model,
|
|
81
|
+
temperature=self.temperature,
|
|
82
|
+
parallel_ensemble=self.parallel_ensemble,
|
|
83
|
+
)
|
|
84
|
+
self._initialized = True
|
|
85
|
+
logger.info(
|
|
86
|
+
"A3M Router initialized for AutoGen: model=%s, ensemble=%d",
|
|
87
|
+
self.model,
|
|
88
|
+
self.parallel_ensemble,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def create_agent_config(self) -> Dict[str, Any]:
|
|
92
|
+
"""
|
|
93
|
+
Create AutoGen-compatible agent config.
|
|
94
|
+
|
|
95
|
+
Returns a config dict that can be passed to ConversableAgent.
|
|
96
|
+
"""
|
|
97
|
+
return {
|
|
98
|
+
"model": self.model,
|
|
99
|
+
"temperature": self.temperature,
|
|
100
|
+
"max_tokens": self.max_tokens,
|
|
101
|
+
"parallel_ensemble": self.parallel_ensemble,
|
|
102
|
+
"a3m_router": self, # Pass self as the router
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
def chat(
|
|
106
|
+
self,
|
|
107
|
+
messages: List[Dict[str, str]],
|
|
108
|
+
**kwargs: Any,
|
|
109
|
+
) -> Dict[str, Any]:
|
|
110
|
+
"""
|
|
111
|
+
Generate a response using A3M Router.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
messages: List of message dicts with 'role' and 'content'
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
Response dict with 'content', 'provider', 'cost'
|
|
118
|
+
"""
|
|
119
|
+
self._ensure_router()
|
|
120
|
+
|
|
121
|
+
import asyncio
|
|
122
|
+
loop = asyncio.get_event_loop()
|
|
123
|
+
route_result = loop.run_in_executor(
|
|
124
|
+
None,
|
|
125
|
+
lambda: self._a3m_router.route(
|
|
126
|
+
messages=messages,
|
|
127
|
+
temperature=self.temperature,
|
|
128
|
+
max_tokens=self.max_tokens,
|
|
129
|
+
**kwargs,
|
|
130
|
+
),
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
"content": route_result.content,
|
|
135
|
+
"provider": getattr(route_result, 'provider', 'unknown'),
|
|
136
|
+
"cost": getattr(route_result, 'cost', 0.0),
|
|
137
|
+
"finish_reason": getattr(route_result, 'finish_reason', 'stop'),
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async def achat(
|
|
141
|
+
self,
|
|
142
|
+
messages: List[Dict[str, str]],
|
|
143
|
+
**kwargs: Any,
|
|
144
|
+
) -> Dict[str, Any]:
|
|
145
|
+
"""Async version of chat."""
|
|
146
|
+
self._ensure_router()
|
|
147
|
+
|
|
148
|
+
route_result = await self._a3m_router.aroute(
|
|
149
|
+
messages=messages,
|
|
150
|
+
temperature=self.temperature,
|
|
151
|
+
max_tokens=self.max_tokens,
|
|
152
|
+
**kwargs,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
"content": route_result.content,
|
|
157
|
+
"provider": getattr(route_result, 'provider', 'unknown'),
|
|
158
|
+
"cost": getattr(route_result, 'cost', 0.0),
|
|
159
|
+
"finish_reason": getattr(route_result, 'finish_reason', 'stop'),
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
def __repr__(self) -> str:
|
|
163
|
+
return (
|
|
164
|
+
f"A3MAutoGenAdapter("
|
|
165
|
+
f"model={self.model!r}, "
|
|
166
|
+
f"temperature={self.temperature}, "
|
|
167
|
+
f"max_tokens={self.max_tokens}, "
|
|
168
|
+
f"ensemble={self.parallel_ensemble})"
|
|
169
|
+
)
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration management for A3M Router adapters.
|
|
3
|
+
|
|
4
|
+
Provides settings for:
|
|
5
|
+
- Default model selection strategy
|
|
6
|
+
- Cost optimization thresholds
|
|
7
|
+
- Parallel ensemble settings
|
|
8
|
+
- Provider priority lists
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
from a3m_adapter_config import A3MConfig
|
|
12
|
+
|
|
13
|
+
config = A3MConfig.from_file("a3m_config.yaml")
|
|
14
|
+
llm = A3MChatModel(**config.to_dict())
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
from dataclasses import dataclass, field, asdict
|
|
22
|
+
from typing import Any, Dict, List, Optional, Union
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class A3MConfig:
|
|
29
|
+
"""Configuration for A3M Router adapters."""
|
|
30
|
+
|
|
31
|
+
# Model selection
|
|
32
|
+
model: str = "auto"
|
|
33
|
+
|
|
34
|
+
# Sampling parameters
|
|
35
|
+
temperature: float = 0.0
|
|
36
|
+
max_tokens: Optional[int] = 4096
|
|
37
|
+
top_p: float = 1.0
|
|
38
|
+
frequency_penalty: float = 0.0
|
|
39
|
+
presence_penalty: float = 0.0
|
|
40
|
+
|
|
41
|
+
# Routing strategy
|
|
42
|
+
parallel_ensemble: int = 1
|
|
43
|
+
fallback_enabled: bool = True
|
|
44
|
+
cost_threshold: float = 0.05 # Max $ per 1k tokens
|
|
45
|
+
|
|
46
|
+
# Provider preferences (highest priority first)
|
|
47
|
+
preferred_providers: List[str] = field(default_factory=lambda: [
|
|
48
|
+
"openai", "anthropic", "google", "azure_openai",
|
|
49
|
+
"azure_ais", "litellm", "groq", "together"
|
|
50
|
+
])
|
|
51
|
+
|
|
52
|
+
# Excluded providers (never use)
|
|
53
|
+
excluded_providers: List[str] = field(default_factory=lambda: [])
|
|
54
|
+
|
|
55
|
+
# API configuration
|
|
56
|
+
api_endpoint: str = "http://localhost:8787/v1"
|
|
57
|
+
api_key: Optional[str] = None
|
|
58
|
+
|
|
59
|
+
# Budget controls
|
|
60
|
+
monthly_budget_usd: Optional[float] = None
|
|
61
|
+
daily_budget_usd: Optional[float] = None
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def from_file(cls, path: str) -> "A3MConfig":
|
|
65
|
+
"""Load configuration from YAML file."""
|
|
66
|
+
try:
|
|
67
|
+
import yaml
|
|
68
|
+
with open(path, 'r') as f:
|
|
69
|
+
data = yaml.safe_load(f)
|
|
70
|
+
return cls(**data)
|
|
71
|
+
except ImportError:
|
|
72
|
+
logger.warning("PyYAML not installed, using JSON")
|
|
73
|
+
return cls.from_json(path)
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def from_json(cls, path: str) -> "A3MConfig":
|
|
77
|
+
"""Load configuration from JSON file."""
|
|
78
|
+
with open(path, 'r') as f:
|
|
79
|
+
data = json.load(f)
|
|
80
|
+
return cls(**data)
|
|
81
|
+
|
|
82
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
83
|
+
"""Convert to dictionary."""
|
|
84
|
+
return asdict(self)
|
|
85
|
+
|
|
86
|
+
def to_json(self, path: Optional[str] = None) -> Optional[str]:
|
|
87
|
+
"""Convert to JSON string or save to file."""
|
|
88
|
+
data = json.dumps(self.to_dict(), indent=2)
|
|
89
|
+
if path:
|
|
90
|
+
with open(path, 'w') as f:
|
|
91
|
+
f.write(data)
|
|
92
|
+
return data
|
|
93
|
+
|
|
94
|
+
def update_budget_limits(self, remaining_usd: float) -> None:
|
|
95
|
+
"""Update budget limits based on remaining funds."""
|
|
96
|
+
if self.daily_budget_usd is not None:
|
|
97
|
+
remaining_pct = remaining_usd / self.daily_budget_usd
|
|
98
|
+
if remaining_pct < 0.1:
|
|
99
|
+
logger.warning("Low daily budget: %s remaining", remaining_usd)
|
|
100
|
+
self.parallel_ensemble = 1 # Reduce to single-provider
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""
|
|
2
|
+
A3M Router Adapter for Haystack (Deepset's RAG framework).
|
|
3
|
+
|
|
4
|
+
Drop-in replacement for Haystack's OpenAIGenerator that routes through A3M Router
|
|
5
|
+
for intelligent, cost-optimized RAG pipelines.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
from haystack import Pipeline
|
|
9
|
+
from haystack.nodes import Retriever, PromptNode
|
|
10
|
+
from a3m_adapter import A3MHaystackAdapter
|
|
11
|
+
|
|
12
|
+
prompt_node = PromptNode(
|
|
13
|
+
"auto",
|
|
14
|
+
api_key=None,
|
|
15
|
+
generator_type='openai',
|
|
16
|
+
model_adapter=A3MHaystackAdapter(model='auto', parallel_ensemble=2),
|
|
17
|
+
)
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import logging
|
|
23
|
+
from typing import Any, Dict, List, Optional
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
HAYSTACK_AVAILABLE = False
|
|
28
|
+
try:
|
|
29
|
+
from haystack.nodes.base import BaseGenerator
|
|
30
|
+
HAYSTACK_AVAILABLE = True
|
|
31
|
+
except ImportError:
|
|
32
|
+
logger.warning("Haystack not installed. Install with: pip install farm-haystack")
|
|
33
|
+
|
|
34
|
+
A3M_AVAILABLE = False
|
|
35
|
+
try:
|
|
36
|
+
from a3m.router import A3MRouter, RouteResponse
|
|
37
|
+
A3M_AVAILABLE = True
|
|
38
|
+
except ImportError:
|
|
39
|
+
logger.warning(
|
|
40
|
+
"A3M Router not installed. Install with: pip install adaptive-memory-multi-model-router"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class A3MHaystackAdapter:
|
|
45
|
+
"""
|
|
46
|
+
A3M Router adapter for Haystack's PromptNode.
|
|
47
|
+
|
|
48
|
+
Enables Haystack RAG pipelines to use A3M Router for automatic model selection
|
|
49
|
+
across 47+ providers with cost optimization.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
model: str = "auto",
|
|
55
|
+
temperature: float = 0.7,
|
|
56
|
+
max_tokens: int = 4096,
|
|
57
|
+
parallel_ensemble: int = 1,
|
|
58
|
+
api_key: Optional[str] = None,
|
|
59
|
+
**kwargs: Any,
|
|
60
|
+
) -> None:
|
|
61
|
+
"""
|
|
62
|
+
Initialize A3M Router adapter for Haystack.
|
|
63
|
+
"""
|
|
64
|
+
self.model = model
|
|
65
|
+
self.temperature = temperature
|
|
66
|
+
self.max_tokens = max_tokens
|
|
67
|
+
self.parallel_ensemble = parallel_ensemble
|
|
68
|
+
self.api_key = api_key
|
|
69
|
+
self._a3m_router = None
|
|
70
|
+
self._initialized = False
|
|
71
|
+
self._kwargs = kwargs
|
|
72
|
+
|
|
73
|
+
def _ensure_router(self) -> None:
|
|
74
|
+
"""Lazily initialize the A3M router."""
|
|
75
|
+
if self._initialized:
|
|
76
|
+
return
|
|
77
|
+
|
|
78
|
+
if not A3M_AVAILABLE:
|
|
79
|
+
raise ImportError(
|
|
80
|
+
"A3M Router is not installed. "
|
|
81
|
+
"Install with: pip install adaptive-memory-multi-model-router"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
self._a3m_router = A3MRouter(
|
|
85
|
+
model=self.model,
|
|
86
|
+
temperature=self.temperature,
|
|
87
|
+
parallel_ensemble=self.parallel_ensemble,
|
|
88
|
+
)
|
|
89
|
+
self._initialized = True
|
|
90
|
+
logger.info(
|
|
91
|
+
"A3M Router initialized for Haystack: model=%s",
|
|
92
|
+
self.model,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def predict(
|
|
96
|
+
self,
|
|
97
|
+
query: str,
|
|
98
|
+
documents: Optional[List[Any]] = None,
|
|
99
|
+
**kwargs: Any,
|
|
100
|
+
) -> Dict[str, Any]:
|
|
101
|
+
"""
|
|
102
|
+
Generate answer from query and optional retrieved documents.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
query: The search query
|
|
106
|
+
documents: Optional list of retrieved documents for RAG
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
Dict with 'answers', 'provider', 'cost'
|
|
110
|
+
"""
|
|
111
|
+
self._ensure_router()
|
|
112
|
+
|
|
113
|
+
# Build context from documents if provided
|
|
114
|
+
if documents:
|
|
115
|
+
context = "\n\n".join([
|
|
116
|
+
f"Document {i+1}: {getattr(doc, 'content', str(doc))}"
|
|
117
|
+
for i, doc in enumerate(documents[:5]) # Limit to 5 docs
|
|
118
|
+
])
|
|
119
|
+
prompt = f"Context:\n{context}\n\nQuestion: {query}\n\nAnswer:"
|
|
120
|
+
else:
|
|
121
|
+
prompt = query
|
|
122
|
+
|
|
123
|
+
messages = [{"role": "user", "content": prompt}]
|
|
124
|
+
|
|
125
|
+
import asyncio
|
|
126
|
+
loop = asyncio.get_event_loop()
|
|
127
|
+
route_result = loop.run_in_executor(
|
|
128
|
+
None,
|
|
129
|
+
lambda: self._a3m_router.route(
|
|
130
|
+
messages=messages,
|
|
131
|
+
temperature=kwargs.get("temperature", self.temperature),
|
|
132
|
+
max_tokens=kwargs.get("max_tokens", self.max_tokens),
|
|
133
|
+
**kwargs,
|
|
134
|
+
),
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
"answers": [{"answer": route_result.content, "score": 1.0}],
|
|
139
|
+
"provider": getattr(route_result, 'provider', 'a3m'),
|
|
140
|
+
"cost": getattr(route_result, 'cost', 0.0),
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async def apredict(
|
|
144
|
+
self,
|
|
145
|
+
query: str,
|
|
146
|
+
documents: Optional[List[Any]] = None,
|
|
147
|
+
**kwargs: Any,
|
|
148
|
+
) -> Dict[str, Any]:
|
|
149
|
+
"""Async predict for Haystack."""
|
|
150
|
+
self._ensure_router()
|
|
151
|
+
|
|
152
|
+
if documents:
|
|
153
|
+
context = "\n\n".join([
|
|
154
|
+
f"Document {i+1}: {getattr(doc, 'content', str(doc))}"
|
|
155
|
+
for i, doc in enumerate(documents[:5])
|
|
156
|
+
])
|
|
157
|
+
prompt = f"Context:\n{context}\n\nQuestion: {query}\n\nAnswer:"
|
|
158
|
+
else:
|
|
159
|
+
prompt = query
|
|
160
|
+
|
|
161
|
+
messages = [{"role": "user", "content": prompt}]
|
|
162
|
+
|
|
163
|
+
route_result = await self._a3m_router.aroute(
|
|
164
|
+
messages=messages,
|
|
165
|
+
temperature=kwargs.get("temperature", self.temperature),
|
|
166
|
+
max_tokens=kwargs.get("max_tokens", self.max_tokens),
|
|
167
|
+
**kwargs,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
"answers": [{"answer": route_result.content, "score": 1.0}],
|
|
172
|
+
"provider": getattr(route_result, 'provider', 'a3m'),
|
|
173
|
+
"cost": getattr(route_result, 'cost', 0.0),
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
def run(
|
|
177
|
+
self,
|
|
178
|
+
query: str,
|
|
179
|
+
documents: Optional[List[Any]] = None,
|
|
180
|
+
**kwargs: Any,
|
|
181
|
+
) -> tuple[Dict[str, Any], str]:
|
|
182
|
+
"""
|
|
183
|
+
Haystack-compatible run method.
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
Tuple of (results dict, pipeline run metadata)
|
|
187
|
+
"""
|
|
188
|
+
result = self.predict(query, documents, **kwargs)
|
|
189
|
+
return (result, "a3m-haystack")
|
|
190
|
+
|
|
191
|
+
def __repr__(self) -> str:
|
|
192
|
+
return (
|
|
193
|
+
f"A3MHaystackAdapter("
|
|
194
|
+
f"model={self.model!r}, "
|
|
195
|
+
f"temperature={self.temperature}, "
|
|
196
|
+
f"max_tokens={self.max_tokens})"
|
|
197
|
+
)
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""
|
|
2
|
+
A3M Router Adapter for LangChain.
|
|
3
|
+
|
|
4
|
+
Drop-in replacement for LangChain's ChatOpenAI that routes through A3M Router
|
|
5
|
+
for intelligent, cost-optimized model selection across 47+ providers.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from typing import Any, Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
# Check availability
|
|
16
|
+
LANGCHAIN_AVAILABLE = False
|
|
17
|
+
try:
|
|
18
|
+
from langchain_core.language_models import BaseChatModel
|
|
19
|
+
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage
|
|
20
|
+
from langchain_core.outputs import ChatGeneration, ChatResult, LLMResult
|
|
21
|
+
LANGCHAIN_AVAILABLE = True
|
|
22
|
+
except ImportError:
|
|
23
|
+
logger.warning("LangChain not installed. Install with: pip install langchain langchain-core")
|
|
24
|
+
|
|
25
|
+
A3M_AVAILABLE = False
|
|
26
|
+
try:
|
|
27
|
+
from a3m.router import A3MRouter, RouteResponse
|
|
28
|
+
A3M_AVAILABLE = True
|
|
29
|
+
except ImportError:
|
|
30
|
+
logger.warning("A3M Router not installed. Install with: pip install adaptive-memory-multi-model-router")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class A3MLangChainAdapter:
|
|
34
|
+
"""
|
|
35
|
+
A3M Router adapter for LangChain's ChatOpenAI interface.
|
|
36
|
+
|
|
37
|
+
Routes prompts through A3M Router to automatically select the cheapest
|
|
38
|
+
capable model across 47+ LLM providers.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
model: str = "auto",
|
|
44
|
+
temperature: float = 0.0,
|
|
45
|
+
max_tokens: Optional[int] = 4096,
|
|
46
|
+
parallel_ensemble: int = 1,
|
|
47
|
+
api_key: Optional[str] = None,
|
|
48
|
+
**kwargs: Any,
|
|
49
|
+
) -> None:
|
|
50
|
+
"""
|
|
51
|
+
Initialize A3M Router adapter.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
model: Model name or "auto" for automatic routing
|
|
55
|
+
temperature: Sampling temperature
|
|
56
|
+
max_tokens: Maximum tokens to generate
|
|
57
|
+
parallel_ensemble: Number of providers to run in parallel
|
|
58
|
+
api_key: A3M API key (optional)
|
|
59
|
+
"""
|
|
60
|
+
self.model = model
|
|
61
|
+
self.temperature = temperature
|
|
62
|
+
self.max_tokens = max_tokens
|
|
63
|
+
self.parallel_ensemble = parallel_ensemble
|
|
64
|
+
self.api_key = api_key
|
|
65
|
+
self._a3m_router = None
|
|
66
|
+
self._initialized = False
|
|
67
|
+
|
|
68
|
+
def _ensure_router(self) -> None:
|
|
69
|
+
"""Lazily initialize the A3M router."""
|
|
70
|
+
if self._initialized:
|
|
71
|
+
return
|
|
72
|
+
|
|
73
|
+
if not A3M_AVAILABLE:
|
|
74
|
+
raise ImportError(
|
|
75
|
+
"A3M Router is not installed. "
|
|
76
|
+
"Install with: pip install adaptive-memory-multi-model-router"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
self._a3m_router = A3MRouter(
|
|
80
|
+
model=self.model,
|
|
81
|
+
temperature=self.temperature,
|
|
82
|
+
parallel_ensemble=self.parallel_ensemble,
|
|
83
|
+
)
|
|
84
|
+
self._initialized = True
|
|
85
|
+
logger.info(
|
|
86
|
+
"A3M Router initialized: model=%s, ensemble=%d",
|
|
87
|
+
self.model,
|
|
88
|
+
self.parallel_ensemble,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def _llm_type(self) -> str:
|
|
93
|
+
return "a3m_router"
|
|
94
|
+
|
|
95
|
+
def _generate(
|
|
96
|
+
self,
|
|
97
|
+
messages: List[BaseMessage],
|
|
98
|
+
stop: Optional[List[str]] = None,
|
|
99
|
+
run_manager: Any = None,
|
|
100
|
+
**kwargs: Any,
|
|
101
|
+
) -> LLMResult:
|
|
102
|
+
"""Generate a response using A3M Router."""
|
|
103
|
+
self._ensure_router()
|
|
104
|
+
|
|
105
|
+
# Convert messages
|
|
106
|
+
a3m_messages = self._convert_messages(messages)
|
|
107
|
+
|
|
108
|
+
# Route through A3M
|
|
109
|
+
import asyncio
|
|
110
|
+
loop = asyncio.get_event_loop()
|
|
111
|
+
route_result = loop.run_in_executor(
|
|
112
|
+
None,
|
|
113
|
+
lambda: self._a3m_router.route(
|
|
114
|
+
messages=a3m_messages,
|
|
115
|
+
temperature=self.temperature,
|
|
116
|
+
max_tokens=self.max_tokens,
|
|
117
|
+
stop=stop,
|
|
118
|
+
**kwargs,
|
|
119
|
+
),
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
ai_message = AIMessage(content=route_result.content)
|
|
123
|
+
generation = ChatGeneration(message=ai_message)
|
|
124
|
+
return LLMResult(generations=[[generation]])
|
|
125
|
+
|
|
126
|
+
def _convert_messages(self, messages: List[BaseMessage]) -> List[Dict[str, Any]]:
|
|
127
|
+
"""Convert LangChain messages to A3M format."""
|
|
128
|
+
a3m_messages = []
|
|
129
|
+
for msg in messages:
|
|
130
|
+
if isinstance(msg, SystemMessage):
|
|
131
|
+
a3m_messages.append({"role": "system", "content": msg.content})
|
|
132
|
+
elif isinstance(msg, HumanMessage):
|
|
133
|
+
a3m_messages.append({"role": "user", "content": msg.content})
|
|
134
|
+
elif isinstance(msg, AIMessage):
|
|
135
|
+
a3m_messages.append({"role": "assistant", "content": msg.content})
|
|
136
|
+
elif isinstance(msg, ToolMessage):
|
|
137
|
+
a3m_messages.append(
|
|
138
|
+
{"role": "tool", "content": msg.content, "tool_call_id": msg.tool_call_id}
|
|
139
|
+
)
|
|
140
|
+
else:
|
|
141
|
+
a3m_messages.append({"role": "user", "content": str(msg)})
|
|
142
|
+
return a3m_messages
|
|
143
|
+
|
|
144
|
+
def bind_tools(self, tools: List[Dict[str, Any]], **kwargs: Any) -> "A3MLangChainAdapter":
|
|
145
|
+
"""Bind tools for function calling."""
|
|
146
|
+
return self
|
|
147
|
+
|
|
148
|
+
def __repr__(self) -> str:
|
|
149
|
+
return (
|
|
150
|
+
f"A3MLangChainAdapter("
|
|
151
|
+
f"model={self.model!r}, "
|
|
152
|
+
f"temperature={self.temperature}, "
|
|
153
|
+
f"max_tokens={self.max_tokens}, "
|
|
154
|
+
f"ensemble={self.parallel_ensemble})"
|
|
155
|
+
)
|