|
| 1 | +# Copyright 2025 Google Inc. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""A LLM provider for the Ollama server.""" |
| 15 | +from typing import Optional |
| 16 | +import json |
| 17 | +import requests |
| 18 | + |
| 19 | +from timesketch.lib.llms.providers import interface |
| 20 | +from timesketch.lib.llms.providers import manager |
| 21 | + |
| 22 | + |
| 23 | +class Ollama(interface.LLMProvider): |
| 24 | + """A LLM provider for the Ollama server.""" |
| 25 | + |
| 26 | + NAME = "ollama" |
| 27 | + |
| 28 | + def _post(self, request_body: str) -> requests.Response: |
| 29 | + """ |
| 30 | + Make a POST request to the Ollama server. |
| 31 | +
|
| 32 | + Args: |
| 33 | + request_body: The body of the request in JSON format. |
| 34 | +
|
| 35 | + Returns: |
| 36 | + The response from the server as a requests.Response object. |
| 37 | + """ |
| 38 | + api_resource = "/api/chat" |
| 39 | + url = self.config.get("server_url") + api_resource |
| 40 | + return requests.post( |
| 41 | + url, data=request_body, headers={"Content-Type": "application/json"} |
| 42 | + ) |
| 43 | + |
| 44 | + def generate(self, prompt: str, response_schema: Optional[dict] = None) -> str: |
| 45 | + """ |
| 46 | + Generate text using the Ollama server, optionally with a JSON schema. |
| 47 | +
|
| 48 | + Args: |
| 49 | + prompt: The prompt to use for the generation. |
| 50 | + response_schema: An optional JSON schema to define the expected |
| 51 | + response format. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + The generated text as a string (or parsed data if |
| 55 | + response_schema is provided). |
| 56 | +
|
| 57 | + Raises: |
| 58 | + ValueError: If the request fails or JSON parsing fails. |
| 59 | + """ |
| 60 | + request_body = { |
| 61 | + "messages": [{"role": "user", "content": prompt}], |
| 62 | + "model": self.config.get("model"), |
| 63 | + "stream": self.config.get("stream"), |
| 64 | + "options": { |
| 65 | + "temperature": self.config.get("temperature"), |
| 66 | + "num_predict": self.config.get("max_output_tokens"), |
| 67 | + "top_p": self.config.get("top_p"), |
| 68 | + "top_k": self.config.get("top_k"), |
| 69 | + }, |
| 70 | + } |
| 71 | + |
| 72 | + if response_schema: |
| 73 | + request_body["format"] = response_schema |
| 74 | + |
| 75 | + response = self._post(json.dumps(request_body)) |
| 76 | + |
| 77 | + if response.status_code != 200: |
| 78 | + raise ValueError(f"Error generating text: {response.text}") |
| 79 | + |
| 80 | + response_data = response.json() |
| 81 | + text_response = response_data.get("message", {}).get("content", "").strip() |
| 82 | + |
| 83 | + if response_schema: |
| 84 | + try: |
| 85 | + return json.loads(text_response) |
| 86 | + except json.JSONDecodeError as error: |
| 87 | + raise ValueError( |
| 88 | + f"Error JSON parsing text: {text_response}: {error}" |
| 89 | + ) from error |
| 90 | + |
| 91 | + return text_response |
| 92 | + |
| 93 | + |
| 94 | +manager.LLMManager.register_provider(Ollama) |
0 commit comments