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