| 1 | """ |
| 2 | For models other than those from OpenAI, use LiteLLM if possible. |
| 3 | Create all models managed by Ollama here, since they need to talk to ollama server. |
| 4 | """ |
| 5 | |
| 6 | import sys |
| 7 | from collections.abc import Mapping |
| 8 | from copy import deepcopy |
| 9 | from typing import Literal, cast |
| 10 | |
| 11 | import httpx |
| 12 | import ollama |
| 13 | import timeout_decorator |
| 14 | from ollama._types import Message, Options |
| 15 | from openai.types.chat import ChatCompletionMessage |
| 16 | |
| 17 | from app.model import common |
| 18 | from app.model.common import Model |
| 19 | |
| 20 | |
| 21 | class OllamaModel(Model): |
| 22 | """ |
| 23 | Base class for creating Singleton instances of Ollama models. |
| 24 | """ |
| 25 | |
| 26 | _instances = {} |
| 27 | |
| 28 | def __new__(cls): |
| 29 | if cls not in cls._instances: |
| 30 | cls._instances[cls] = super().__new__(cls) |
| 31 | cls._instances[cls]._initialized = False |
| 32 | return cls._instances[cls] |
| 33 | |
| 34 | def __init__(self, name: str): |
| 35 | if self._initialized: |
| 36 | return |
| 37 | # local models are free |
| 38 | super().__init__(name, 0.0, 0.0) |
| 39 | self.client: ollama.Client | None = None |
| 40 | self._initialized = True |
| 41 | |
| 42 | def setup(self) -> None: |
| 43 | """ |
| 44 | Check API key. |
| 45 | """ |
| 46 | self.check_api_key() |
| 47 | try: |
| 48 | self.send_empty_request() |
| 49 | print(f"Model {self.name} is up and running.") |
| 50 | except timeout_decorator.TimeoutError as e: |
| 51 | print( |
| 52 | "Ollama server is taking too long (more than 2 mins) to respond. Please check whether it's running.", |
| 53 | e, |
| 54 | ) |
| 55 | sys.exit(1) |
| 56 | except Exception as e: |
| 57 | print("Could not communicate with ollama server due to exception.", e) |
| 58 | sys.exit(1) |
| 59 | |
| 60 | @timeout_decorator.timeout(120) # 2 min |
| 61 | def send_empty_request(self): |
| 62 | """ |
| 63 | Send an empty request to the model, for two purposes |
| 64 | (1) check whether the model is up and running |
| 65 | (2) preload the model for faster response time (models will be kept in memory for 5 mins after loaded) |
| 66 | (see https://github.com/ollama/ollama/blob/main/docs/faq.md#how-can-i-pre-load-a-model-to-get-faster-response-times) |
| 67 | """ |
| 68 | # localhost is used when (1) running both ACR and ollama on host machine; and |
| 69 | # (2) running ollama in host, and ACR in container with --net=host |
| 70 | local_client = ollama.Client(host="http://localhost:11434") |
| 71 | # docker_host_client is used when running ollama in host and ACR in container, and |
| 72 | # Docker Desktop is installed |
| 73 | docker_host_client = ollama.Client(host="http://host.docker.internal:11434") |
| 74 | try: |
| 75 | local_client.chat(model=self.name, messages=[]) |
| 76 | self.client = local_client |
| 77 | return |
| 78 | except httpx.ConnectError: |
| 79 | # failed to connect to client at localhost |
| 80 | pass |
| 81 | |
| 82 | try: |
| 83 | docker_host_client.chat(model=self.name, messages=[]) |
| 84 | self.client = docker_host_client |
| 85 | except httpx.ConnectError: |
| 86 | # also failed to connect via host.docker.internal |
| 87 | print("Could not connect to ollama server.") |
| 88 | sys.exit(1) |
| 89 | |
| 90 | def check_api_key(self) -> str: |
| 91 | return "No key required for local models." |
| 92 | |
| 93 | def extract_resp_content( |
| 94 | self, chat_completion_message: ChatCompletionMessage |
| 95 | ) -> str: |
| 96 | """ |
| 97 | Given a chat completion message, extract the content from it. |
| 98 | """ |
| 99 | content = chat_completion_message.content |
| 100 | if content is None: |
| 101 | return "" |
| 102 | else: |
| 103 | return content |
| 104 | |
| 105 | def call( |
| 106 | self, |
| 107 | messages: list[dict], |
| 108 | top_p=1, |
| 109 | tools=None, |
| 110 | response_format: Literal["text", "json_object"] = "text", |
| 111 | **kwargs, |
| 112 | ): |
| 113 | stop_words = ["assistant", "\n\n \n\n"] |
| 114 | json_stop_words = deepcopy(stop_words) |
| 115 | json_stop_words.append("```") |
| 116 | json_stop_words.append(" " * 10) |
| 117 | # FIXME: ignore tools field since we don't use tools now |
| 118 | |
| 119 | assert self.client is not None |
| 120 | try: |
| 121 | # build up options for ollama |
| 122 | options = {"temperature": common.MODEL_TEMP, "top_p": top_p} |
| 123 | if response_format == "json_object": |
| 124 | # additional instructions for json mode |
| 125 | json_instruction = { |
| 126 | "role": "user", |
| 127 | "content": "Stop your response after a valid json is generated.", |
| 128 | } |
| 129 | messages.append(json_instruction) |
| 130 | # give more stop words and lower max_token for json mode |
| 131 | options.update({"stop": json_stop_words, "num_predict": 128}) |
| 132 | response = self.client.chat( |
| 133 | model=self.name, |
| 134 | messages=cast(list[Message], messages), |
| 135 | format="json", |
| 136 | options=cast(Options, options), |
| 137 | stream=False, |
| 138 | ) |
| 139 | else: |
| 140 | options.update({"stop": stop_words, "num_predict": 1024}) |
| 141 | response = self.client.chat( |
| 142 | model=self.name, |
| 143 | messages=cast(list[Message], messages), |
| 144 | options=cast(Options, options), |
| 145 | stream=False, |
| 146 | ) |
| 147 | |
| 148 | assert isinstance(response, Mapping) |
| 149 | resp_msg = response.get("message", None) |
| 150 | if resp_msg is None: |
| 151 | return "", 0, 0, 0 |
| 152 | |
| 153 | content: str = resp_msg.get("content", "") |
| 154 | return content, 0, 0, 0 |
| 155 | |
| 156 | except Exception as e: |
| 157 | # FIXME: catch appropriate exception from ollama |
| 158 | raise e |
| 159 | |
| 160 | |
| 161 | class Llama3_8B(OllamaModel): |
| 162 | def __init__(self): |
| 163 | super().__init__("llama3") |
| 164 | self.note = "Llama3 8B model." |
| 165 | |
| 166 | |
| 167 | class Llama3_70B(OllamaModel): |
| 168 | def __init__(self): |
| 169 | super().__init__("llama3:70b") |
| 170 | self.note = "Llama3 70B model." |