|
| 1 | +from typing import Optional |
| 2 | +from langflow import CustomComponent |
| 3 | +from langchain.chat_models.anthropic import ChatAnthropic |
| 4 | +from langchain.llms.base import BaseLLM |
| 5 | + |
| 6 | + |
| 7 | +class AnthropicLLM(CustomComponent): |
| 8 | + display_name: str = "AnthropicLLM" |
| 9 | + description: str = "Anthropic Chat&Completion large language models." |
| 10 | + |
| 11 | + def build_config(self): |
| 12 | + return { |
| 13 | + "model": { |
| 14 | + "display_name": "Model Name", |
| 15 | + "options": [ |
| 16 | + "claude-2.1", |
| 17 | + "claude-2.0", |
| 18 | + "claude-instant-1.2", |
| 19 | + "claude-instant-1" |
| 20 | + # Add more models as needed |
| 21 | + ], |
| 22 | + "info": "https://python.langchain.com/docs/integrations/chat/anthropic", |
| 23 | + "required": True, |
| 24 | + "value": "claude-2.1", |
| 25 | + }, |
| 26 | + "anthropic_api_key": { |
| 27 | + "display_name": "Anthropic API Key", |
| 28 | + "required": True, |
| 29 | + "password": True, |
| 30 | + "info": "Your Anthropic API key.", |
| 31 | + }, |
| 32 | + "max_tokens": { |
| 33 | + "display_name": "Max Tokens", |
| 34 | + "field_type": "int", |
| 35 | + "value": 256, |
| 36 | + }, |
| 37 | + "temperature": { |
| 38 | + "display_name": "Temperature", |
| 39 | + "field_type": "float", |
| 40 | + "value": 0.7, |
| 41 | + }, |
| 42 | + "api_endpoint": { |
| 43 | + "display_name": "API Endpoint", |
| 44 | + "info": "Endpoint of the Anthropic API. Defaults to 'https://api.anthropic.com' if not specified.", |
| 45 | + }, |
| 46 | + "code": {"show": False}, |
| 47 | + } |
| 48 | + |
| 49 | + def build( |
| 50 | + self, |
| 51 | + model: str, |
| 52 | + anthropic_api_key: Optional[str] = None, |
| 53 | + max_tokens: Optional[int] = None, |
| 54 | + temperature: Optional[float] = None, |
| 55 | + api_endpoint: Optional[str] = None, |
| 56 | + ) -> BaseLLM: |
| 57 | + # Set default API endpoint if not provided |
| 58 | + if not api_endpoint: |
| 59 | + api_endpoint = "https://api.anthropic.com" |
| 60 | + |
| 61 | + try: |
| 62 | + output = ChatAnthropic( |
| 63 | + model=model, |
| 64 | + anthropic_api_key=anthropic_api_key, |
| 65 | + max_tokens_to_sample=max_tokens, |
| 66 | + temperature=temperature, |
| 67 | + anthropic_api_url=api_endpoint, |
| 68 | + ) |
| 69 | + except Exception as e: |
| 70 | + raise ValueError("Could not connect to Anthropic API.") from e |
| 71 | + return output |
0 commit comments