This is the right syntax to interact with Ollama, pls memorize this: import requests…
- User
This is the right syntax to interact with Ollama, pls memorize this:
import requests import json import logging from typing import Optional, Dict, Any
class OllamaAPITester: def init(self, host: str = "127.0.0.1", port: int = 11434): self.base_url = f"http://{host}:{port}" self.setup_logging()
def setup_logging(self): logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) self.logger = logging.getLogger(__name__) def check_model_availability(self, model_name: str) -> bool: try: response = requests.get(f"{self.base_url}/api/tags") if response.status_code == 200: available_models = response.json().get('models', []) return any(model['name'] == model_name for model in available_models) return False except requests.exceptions.RequestException as e: self.logger.error(f"Error checking model availability: {e}") return False def generate_response(self, model: str, prompt: str) -> Optional[Dict[str, Any]]: url = f"{self.base_url}/api/generate" payload = { "model": model, "prompt": prompt, "stream": False # Set to True if you want streaming response } headers = { "Content-Type": "application/json" } try: # Verify model availability first if not self.check_model_availability(model): self.logger.error(f"Model '{model}' is not available. Please install it first.") return None self.logger.info(f"Sending request to Ollama API with model: {model}") response = requests.post(url, json=payload, headers=headers) if response.status_code == 200: self.logger.info("Successfully received response from Ollama API") return response.json() else: self.logger.error(f"Error: Received status code {response.status_code}") self.logger.error(f"Response text: {response.text}") return None except requests.exceptions.ConnectionError: self.logger.error("Failed to connect to Ollama. Make sure the service is running.") return None except requests.exceptions.RequestException as e: self.logger.error(f"An error occurred while communicating with Ollama API: {e}") return None except json.JSONDecodeError: self.logger.error("Failed to decode JSON response from Ollama API") return Nonedef main(): # Initialize the tester tester = OllamaAPITester()
# Test parameters model_name = "qwen2.5-coder:7b" test_prompt = "Create a React component that displays Hello World" # Generate response response = tester.generate_response(model_name, test_prompt) # Pretty print the response if it exists if response: print("\nAPI Response:") print(json.dumps(response, indent=2))if name == "main": main()
- Assistant
Thank you for sharing the code for interacting with Ollama. It appears to be a Python class (
OllamaAPITester) that interfaces with the Ollama API to check model availability and generate responses based on a given prompt. If you have any questions about how this code works or need assistance with specific parts of it, feel free to ask!