5b484c9226
Refactored LLM provider infrastructure to support sustainable additions of new providers with both embedding and text generation capabilities.
## Major Changes
### Unified Provider Architecture (ADR-015)
- Created `nextcloud_mcp_server/providers/` with unified Provider ABC
- Providers now support optional capabilities (embeddings and/or generation)
- Auto-detection registry with priority: Bedrock → Ollama → Simple
- Backward compatible - existing code continues to work
### New Providers
- **BedrockProvider**: Full Amazon Bedrock integration
- Embeddings: Titan Embed, Cohere Embed models
- Generation: Claude, Llama, Titan Text, Mistral models
- Model-specific request/response handling
- AWS credential chain integration
- **OllamaProvider**: Migrated with both capabilities support
- **AnthropicProvider**: Moved from test code to production providers
- **SimpleProvider**: Migrated in-memory fallback provider
### Breaking Changes
None - full backward compatibility maintained:
- `embedding.get_embedding_service()` still works
- RAG evaluation tests updated to use unified providers
- All existing tests pass (127 unit tests)
### Testing
- Added 9 comprehensive Bedrock unit tests with mocked boto3
- All existing unit tests pass
- Type checking (ty) and linting (ruff) pass
- Verified backward compatibility
### Documentation
- `docs/ADR-015-unified-provider-architecture.md`: Comprehensive ADR
- `docs/bedrock-setup.md`: AWS setup guide with IAM permissions
- `CLAUDE.md`: Updated with provider architecture section
### Dependencies
- Added `boto3>=1.35.0` to dev dependencies (optional)
## Environment Variables
### Bedrock
- `AWS_REGION`: AWS region (e.g., "us-east-1")
- `BEDROCK_EMBEDDING_MODEL`: Model ID for embeddings
- `BEDROCK_GENERATION_MODEL`: Model ID for generation
- `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`: Optional credentials
### Ollama
- `OLLAMA_BASE_URL`: API URL
- `OLLAMA_EMBEDDING_MODEL`: Embedding model (default: "nomic-embed-text")
- `OLLAMA_GENERATION_MODEL`: Generation model
## AWS Bedrock Permissions Required
Minimal IAM policy:
```json
{
"Effect": "Allow",
"Action": ["bedrock:InvokeModel"],
"Resource": ["arn:aws:bedrock:*::foundation-model/*"]
}
```
See `docs/bedrock-setup.md` for detailed setup instructions.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
98 lines
2.7 KiB
Python
98 lines
2.7 KiB
Python
"""Unified Anthropic provider for text generation."""
|
|
|
|
import logging
|
|
|
|
from anthropic import AsyncAnthropic
|
|
|
|
from .base import Provider
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class AnthropicProvider(Provider):
|
|
"""
|
|
Anthropic provider for text generation.
|
|
|
|
Supports Claude models via the Anthropic API.
|
|
Note: Anthropic doesn't provide embedding models, only text generation.
|
|
"""
|
|
|
|
def __init__(self, api_key: str, model: str = "claude-3-5-sonnet-20241022"):
|
|
"""
|
|
Initialize Anthropic provider.
|
|
|
|
Args:
|
|
api_key: Anthropic API key
|
|
model: Model name (e.g., "claude-3-5-sonnet-20241022")
|
|
"""
|
|
self.client = AsyncAnthropic(api_key=api_key)
|
|
self.model = model
|
|
|
|
logger.info(f"Initialized Anthropic provider (model={model})")
|
|
|
|
@property
|
|
def supports_embeddings(self) -> bool:
|
|
"""Whether this provider supports embedding generation."""
|
|
return False
|
|
|
|
@property
|
|
def supports_generation(self) -> bool:
|
|
"""Whether this provider supports text generation."""
|
|
return True
|
|
|
|
async def embed(self, text: str) -> list[float]:
|
|
"""
|
|
Generate embedding vector for text.
|
|
|
|
Raises:
|
|
NotImplementedError: Anthropic doesn't provide embedding models
|
|
"""
|
|
raise NotImplementedError(
|
|
"Embedding not supported by Anthropic - use Ollama or Bedrock for embeddings"
|
|
)
|
|
|
|
async def embed_batch(self, texts: list[str]) -> list[list[float]]:
|
|
"""
|
|
Generate embeddings for multiple texts.
|
|
|
|
Raises:
|
|
NotImplementedError: Anthropic doesn't provide embedding models
|
|
"""
|
|
raise NotImplementedError(
|
|
"Embedding not supported by Anthropic - use Ollama or Bedrock for embeddings"
|
|
)
|
|
|
|
def get_dimension(self) -> int:
|
|
"""
|
|
Get embedding dimension.
|
|
|
|
Raises:
|
|
NotImplementedError: Anthropic doesn't provide embedding models
|
|
"""
|
|
raise NotImplementedError(
|
|
"Embedding not supported by Anthropic - use Ollama or Bedrock for embeddings"
|
|
)
|
|
|
|
async def generate(self, prompt: str, max_tokens: int = 500) -> str:
|
|
"""
|
|
Generate text using Anthropic API.
|
|
|
|
Args:
|
|
prompt: The prompt to generate from
|
|
max_tokens: Maximum tokens to generate
|
|
|
|
Returns:
|
|
Generated text
|
|
"""
|
|
message = await self.client.messages.create(
|
|
model=self.model,
|
|
max_tokens=max_tokens,
|
|
temperature=0.7,
|
|
messages=[{"role": "user", "content": prompt}],
|
|
)
|
|
return message.content[0].text
|
|
|
|
async def close(self) -> None:
|
|
"""Close the client (no-op for Anthropic SDK)."""
|
|
pass
|