Check if an Ollama model exists before attempting to use it. Args: model_name: Name of the model to check ollama_host: Ollama host URL, defaults to localhost:11434 Returns: bool: True if model exists, False otherwise
(model_name: str, ollama_host: str = None)
| 19 | pass |
| 20 | |
| 21 | def check_ollama_model_exists(model_name: str, ollama_host: str = None) -> bool: |
| 22 | """ |
| 23 | Check if an Ollama model exists before attempting to use it. |
| 24 | |
| 25 | Args: |
| 26 | model_name: Name of the model to check |
| 27 | ollama_host: Ollama host URL, defaults to localhost:11434 |
| 28 | |
| 29 | Returns: |
| 30 | bool: True if model exists, False otherwise |
| 31 | """ |
| 32 | if ollama_host is None: |
| 33 | ollama_host = os.getenv("OLLAMA_HOST", "http://localhost:11434") |
| 34 | |
| 35 | try: |
| 36 | # Remove /api prefix if present and add it back |
| 37 | if ollama_host.endswith('/api'): |
| 38 | ollama_host = ollama_host[:-4] |
| 39 | |
| 40 | response = requests.get(f"{ollama_host}/api/tags", timeout=5) |
| 41 | if response.status_code == 200: |
| 42 | models_data = response.json() |
| 43 | available_models = [model.get('name', '').split(':')[0] for model in models_data.get('models', [])] |
| 44 | model_base_name = model_name.split(':')[0] # Remove tag if present |
| 45 | |
| 46 | is_available = model_base_name in available_models |
| 47 | if is_available: |
| 48 | logger.info(f"Ollama model '{model_name}' is available") |
| 49 | else: |
| 50 | logger.warning(f"Ollama model '{model_name}' is not available. Available models: {available_models}") |
| 51 | return is_available |
| 52 | else: |
| 53 | logger.warning(f"Could not check Ollama models, status code: {response.status_code}") |
| 54 | return False |
| 55 | except requests.exceptions.RequestException as e: |
| 56 | logger.warning(f"Could not connect to Ollama to check models: {e}") |
| 57 | return False |
| 58 | except Exception as e: |
| 59 | logger.warning(f"Error checking Ollama model availability: {e}") |
| 60 | return False |
| 61 | |
| 62 | class OllamaDocumentProcessor(DataComponent): |
| 63 | """ |