| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | from typing import AsyncGenerator |
| 8 | |
| 9 | import httpx |
| 10 | |
| 11 | from llama_models.llama3.api.chat_format import ChatFormat |
| 12 | from llama_models.llama3.api.datatypes import Message, StopReason |
| 13 | from llama_models.llama3.api.tokenizer import Tokenizer |
| 14 | from llama_models.sku_list import resolve_model |
| 15 | |
| 16 | from ollama import AsyncClient |
| 17 | |
| 18 | from llama_stack.apis.inference import * # noqa: F403 |
| 19 | from llama_stack.providers.utils.inference.augment_messages import ( |
| 20 | augment_messages_for_tools, |
| 21 | ) |
| 22 | |
| 23 | # TODO: Eventually this will move to the llama cli model list command |
| 24 | # mapping of Model SKUs to ollama models |
| 25 | OLLAMA_SUPPORTED_SKUS = { |
| 26 | # "Llama3.1-8B-Instruct": "llama3.1", |
| 27 | "Llama3.1-8B-Instruct": "llama3.1:8b-instruct-fp16", |
| 28 | "Llama3.1-70B-Instruct": "llama3.1:70b-instruct-fp16", |
| 29 | } |
| 30 | |
| 31 | |
| 32 | class OllamaInferenceAdapter(Inference): |
| 33 | def __init__(self, url: str) -> None: |
| 34 | self.url = url |
| 35 | tokenizer = Tokenizer.get_instance() |
| 36 | self.formatter = ChatFormat(tokenizer) |
| 37 | |
| 38 | @property |
| 39 | def client(self) -> AsyncClient: |
| 40 | return AsyncClient(host=self.url) |
| 41 | |
| 42 | async def initialize(self) -> None: |
| 43 | print("Initializing Ollama, checking connectivity to server...") |
| 44 | try: |
| 45 | await self.client.ps() |
| 46 | except httpx.ConnectError as e: |
| 47 | raise RuntimeError( |
| 48 | "Ollama Server is not running, start it using `ollama serve` in a separate terminal" |
| 49 | ) from e |
| 50 | |
| 51 | async def shutdown(self) -> None: |
| 52 | pass |
| 53 | |
| 54 | async def completion( |
| 55 | self, |
| 56 | model: str, |
| 57 | content: InterleavedTextMedia, |
| 58 | sampling_params: Optional[SamplingParams] = SamplingParams(), |
| 59 | stream: Optional[bool] = False, |
| 60 | logprobs: Optional[LogProbConfig] = None, |
| 61 | ) -> AsyncGenerator: |
| 62 | raise NotImplementedError() |
| 63 | |
| 64 | def _messages_to_ollama_messages(self, messages: list[Message]) -> list: |
| 65 | ollama_messages = [] |
| 66 | for message in messages: |
| 67 | if message.role == "ipython": |
| 68 | role = "tool" |
| 69 | else: |
| 70 | role = message.role |
| 71 | ollama_messages.append({"role": role, "content": message.content}) |
| 72 | |
| 73 | return ollama_messages |
| 74 | |
| 75 | def resolve_ollama_model(self, model_name: str) -> str: |
| 76 | model = resolve_model(model_name) |
| 77 | assert ( |
| 78 | model is not None |
| 79 | and model.descriptor(shorten_default_variant=True) in OLLAMA_SUPPORTED_SKUS |
| 80 | ), f"Unsupported model: {model_name}, use one of the supported models: {','.join(OLLAMA_SUPPORTED_SKUS.keys())}" |
| 81 | |
| 82 | return OLLAMA_SUPPORTED_SKUS.get(model.descriptor(shorten_default_variant=True)) |
| 83 | |
| 84 | def get_ollama_chat_options(self, request: ChatCompletionRequest) -> dict: |
| 85 | options = {} |
| 86 | if request.sampling_params is not None: |
| 87 | for attr in {"temperature", "top_p", "top_k", "max_tokens"}: |
| 88 | if getattr(request.sampling_params, attr): |
| 89 | options[attr] = getattr(request.sampling_params, attr) |
| 90 | if ( |
| 91 | request.sampling_params.repetition_penalty is not None |
| 92 | and request.sampling_params.repetition_penalty != 1.0 |
| 93 | ): |
| 94 | options["repeat_penalty"] = request.sampling_params.repetition_penalty |
| 95 | |
| 96 | return options |
| 97 | |
| 98 | async def chat_completion( |
| 99 | self, |
| 100 | model: str, |
| 101 | messages: List[Message], |
| 102 | sampling_params: Optional[SamplingParams] = SamplingParams(), |
| 103 | tools: Optional[List[ToolDefinition]] = None, |
| 104 | tool_choice: Optional[ToolChoice] = ToolChoice.auto, |
| 105 | tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json, |
| 106 | stream: Optional[bool] = False, |
| 107 | logprobs: Optional[LogProbConfig] = None, |
| 108 | ) -> AsyncGenerator: |
| 109 | request = ChatCompletionRequest( |
| 110 | model=model, |
| 111 | messages=messages, |
| 112 | sampling_params=sampling_params, |
| 113 | tools=tools or [], |
| 114 | tool_choice=tool_choice, |
| 115 | tool_prompt_format=tool_prompt_format, |
| 116 | stream=stream, |
| 117 | logprobs=logprobs, |
| 118 | ) |
| 119 | |
| 120 | messages = augment_messages_for_tools(request) |
| 121 | # accumulate sampling params and other options to pass to ollama |
| 122 | options = self.get_ollama_chat_options(request) |
| 123 | ollama_model = self.resolve_ollama_model(request.model) |
| 124 | |
| 125 | res = await self.client.ps() |
| 126 | need_model_pull = True |
| 127 | for r in res["models"]: |
| 128 | if ollama_model == r["model"]: |
| 129 | need_model_pull = False |
| 130 | break |
| 131 | |
| 132 | if need_model_pull: |
| 133 | print(f"Pulling model: {ollama_model}") |
| 134 | status = await self.client.pull(ollama_model) |
| 135 | assert ( |
| 136 | status["status"] == "success" |
| 137 | ), f"Failed to pull model {self.model} in ollama" |
| 138 | |
| 139 | if not request.stream: |
| 140 | r = await self.client.chat( |
| 141 | model=ollama_model, |
| 142 | messages=self._messages_to_ollama_messages(messages), |
| 143 | stream=False, |
| 144 | options=options, |
| 145 | ) |
| 146 | stop_reason = None |
| 147 | if r["done"]: |
| 148 | if r["done_reason"] == "stop": |
| 149 | stop_reason = StopReason.end_of_turn |
| 150 | elif r["done_reason"] == "length": |
| 151 | stop_reason = StopReason.out_of_tokens |
| 152 | |
| 153 | completion_message = self.formatter.decode_assistant_message_from_content( |
| 154 | r["message"]["content"], stop_reason |
| 155 | ) |
| 156 | yield ChatCompletionResponse( |
| 157 | completion_message=completion_message, |
| 158 | logprobs=None, |
| 159 | ) |
| 160 | else: |
| 161 | yield ChatCompletionResponseStreamChunk( |
| 162 | event=ChatCompletionResponseEvent( |
| 163 | event_type=ChatCompletionResponseEventType.start, |
| 164 | delta="", |
| 165 | ) |
| 166 | ) |
| 167 | stream = await self.client.chat( |
| 168 | model=ollama_model, |
| 169 | messages=self._messages_to_ollama_messages(messages), |
| 170 | stream=True, |
| 171 | options=options, |
| 172 | ) |
| 173 | |
| 174 | buffer = "" |
| 175 | ipython = False |
| 176 | stop_reason = None |
| 177 | |
| 178 | async for chunk in stream: |
| 179 | if chunk["done"]: |
| 180 | if stop_reason is None and chunk["done_reason"] == "stop": |
| 181 | stop_reason = StopReason.end_of_turn |
| 182 | elif stop_reason is None and chunk["done_reason"] == "length": |
| 183 | stop_reason = StopReason.out_of_tokens |
| 184 | break |
| 185 | |
| 186 | text = chunk["message"]["content"] |
| 187 | |
| 188 | # check if its a tool call ( aka starts with <|python_tag|> ) |
| 189 | if not ipython and text.startswith("<|python_tag|>"): |
| 190 | ipython = True |
| 191 | yield ChatCompletionResponseStreamChunk( |
| 192 | event=ChatCompletionResponseEvent( |
| 193 | event_type=ChatCompletionResponseEventType.progress, |
| 194 | delta=ToolCallDelta( |
| 195 | content="", |
| 196 | parse_status=ToolCallParseStatus.started, |
| 197 | ), |
| 198 | ) |
| 199 | ) |
| 200 | buffer += text |
| 201 | continue |
| 202 | |
| 203 | if ipython: |
| 204 | if text == "<|eot_id|>": |
| 205 | stop_reason = StopReason.end_of_turn |
| 206 | text = "" |
| 207 | continue |
| 208 | elif text == "<|eom_id|>": |
| 209 | stop_reason = StopReason.end_of_message |
| 210 | text = "" |
| 211 | continue |
| 212 | |
| 213 | buffer += text |
| 214 | delta = ToolCallDelta( |
| 215 | content=text, |
| 216 | parse_status=ToolCallParseStatus.in_progress, |
| 217 | ) |
| 218 | |
| 219 | yield ChatCompletionResponseStreamChunk( |
| 220 | event=ChatCompletionResponseEvent( |
| 221 | event_type=ChatCompletionResponseEventType.progress, |
| 222 | delta=delta, |
| 223 | stop_reason=stop_reason, |
| 224 | ) |
| 225 | ) |
| 226 | else: |
| 227 | buffer += text |
| 228 | yield ChatCompletionResponseStreamChunk( |
| 229 | event=ChatCompletionResponseEvent( |
| 230 | event_type=ChatCompletionResponseEventType.progress, |
| 231 | delta=text, |
| 232 | stop_reason=stop_reason, |
| 233 | ) |
| 234 | ) |
| 235 | |
| 236 | # parse tool calls and report errors |
| 237 | message = self.formatter.decode_assistant_message_from_content( |
| 238 | buffer, stop_reason |
| 239 | ) |
| 240 | parsed_tool_calls = len(message.tool_calls) > 0 |
| 241 | if ipython and not parsed_tool_calls: |
| 242 | yield ChatCompletionResponseStreamChunk( |
| 243 | event=ChatCompletionResponseEvent( |
| 244 | event_type=ChatCompletionResponseEventType.progress, |
| 245 | delta=ToolCallDelta( |
| 246 | content="", |
| 247 | parse_status=ToolCallParseStatus.failure, |
| 248 | ), |
| 249 | stop_reason=stop_reason, |
| 250 | ) |
| 251 | ) |
| 252 | |
| 253 | for tool_call in message.tool_calls: |
| 254 | yield ChatCompletionResponseStreamChunk( |
| 255 | event=ChatCompletionResponseEvent( |
| 256 | event_type=ChatCompletionResponseEventType.progress, |
| 257 | delta=ToolCallDelta( |
| 258 | content=tool_call, |
| 259 | parse_status=ToolCallParseStatus.success, |
| 260 | ), |
| 261 | stop_reason=stop_reason, |
| 262 | ) |
| 263 | ) |
| 264 | |
| 265 | yield ChatCompletionResponseStreamChunk( |
| 266 | event=ChatCompletionResponseEvent( |
| 267 | event_type=ChatCompletionResponseEventType.complete, |
| 268 | delta="", |
| 269 | stop_reason=stop_reason, |
| 270 | ) |
| 271 | ) |