| 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 | |
| 8 | import logging |
| 9 | from typing import AsyncGenerator |
| 10 | |
| 11 | from huggingface_hub import AsyncInferenceClient, HfApi |
| 12 | from llama_models.llama3.api.chat_format import ChatFormat |
| 13 | from llama_models.llama3.api.datatypes import StopReason |
| 14 | from llama_models.llama3.api.tokenizer import Tokenizer |
| 15 | |
| 16 | from llama_stack.apis.inference import * # noqa: F403 |
| 17 | from llama_stack.providers.utils.inference.augment_messages import ( |
| 18 | augment_messages_for_tools, |
| 19 | ) |
| 20 | |
| 21 | from .config import InferenceAPIImplConfig, InferenceEndpointImplConfig, TGIImplConfig |
| 22 | |
| 23 | logger = logging.getLogger(__name__) |
| 24 | |
| 25 | |
| 26 | class _HfAdapter(Inference): |
| 27 | client: AsyncInferenceClient |
| 28 | max_tokens: int |
| 29 | model_id: str |
| 30 | |
| 31 | def __init__(self) -> None: |
| 32 | self.tokenizer = Tokenizer.get_instance() |
| 33 | self.formatter = ChatFormat(self.tokenizer) |
| 34 | |
| 35 | async def shutdown(self) -> None: |
| 36 | pass |
| 37 | |
| 38 | async def completion( |
| 39 | self, |
| 40 | model: str, |
| 41 | content: InterleavedTextMedia, |
| 42 | sampling_params: Optional[SamplingParams] = SamplingParams(), |
| 43 | stream: Optional[bool] = False, |
| 44 | logprobs: Optional[LogProbConfig] = None, |
| 45 | ) -> AsyncGenerator: |
| 46 | raise NotImplementedError() |
| 47 | |
| 48 | def get_chat_options(self, request: ChatCompletionRequest) -> dict: |
| 49 | options = {} |
| 50 | if request.sampling_params is not None: |
| 51 | for attr in {"temperature", "top_p", "top_k", "max_tokens"}: |
| 52 | if getattr(request.sampling_params, attr): |
| 53 | options[attr] = getattr(request.sampling_params, attr) |
| 54 | |
| 55 | return options |
| 56 | |
| 57 | async def chat_completion( |
| 58 | self, |
| 59 | model: str, |
| 60 | messages: List[Message], |
| 61 | sampling_params: Optional[SamplingParams] = SamplingParams(), |
| 62 | tools: Optional[List[ToolDefinition]] = None, |
| 63 | tool_choice: Optional[ToolChoice] = ToolChoice.auto, |
| 64 | tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json, |
| 65 | stream: Optional[bool] = False, |
| 66 | logprobs: Optional[LogProbConfig] = None, |
| 67 | ) -> AsyncGenerator: |
| 68 | request = ChatCompletionRequest( |
| 69 | model=model, |
| 70 | messages=messages, |
| 71 | sampling_params=sampling_params, |
| 72 | tools=tools or [], |
| 73 | tool_choice=tool_choice, |
| 74 | tool_prompt_format=tool_prompt_format, |
| 75 | stream=stream, |
| 76 | logprobs=logprobs, |
| 77 | ) |
| 78 | |
| 79 | messages = augment_messages_for_tools(request) |
| 80 | model_input = self.formatter.encode_dialog_prompt(messages) |
| 81 | prompt = self.tokenizer.decode(model_input.tokens) |
| 82 | |
| 83 | input_tokens = len(model_input.tokens) |
| 84 | max_new_tokens = min( |
| 85 | request.sampling_params.max_tokens or (self.max_tokens - input_tokens), |
| 86 | self.max_tokens - input_tokens - 1, |
| 87 | ) |
| 88 | |
| 89 | print(f"Calculated max_new_tokens: {max_new_tokens}") |
| 90 | |
| 91 | options = self.get_chat_options(request) |
| 92 | if not request.stream: |
| 93 | response = await self.client.text_generation( |
| 94 | prompt=prompt, |
| 95 | stream=False, |
| 96 | details=True, |
| 97 | max_new_tokens=max_new_tokens, |
| 98 | stop_sequences=["<|eom_id|>", "<|eot_id|>"], |
| 99 | **options, |
| 100 | ) |
| 101 | stop_reason = None |
| 102 | if response.details.finish_reason: |
| 103 | if response.details.finish_reason in ["stop", "eos_token"]: |
| 104 | stop_reason = StopReason.end_of_turn |
| 105 | elif response.details.finish_reason == "length": |
| 106 | stop_reason = StopReason.out_of_tokens |
| 107 | |
| 108 | completion_message = self.formatter.decode_assistant_message_from_content( |
| 109 | response.generated_text, |
| 110 | stop_reason, |
| 111 | ) |
| 112 | yield ChatCompletionResponse( |
| 113 | completion_message=completion_message, |
| 114 | logprobs=None, |
| 115 | ) |
| 116 | |
| 117 | else: |
| 118 | yield ChatCompletionResponseStreamChunk( |
| 119 | event=ChatCompletionResponseEvent( |
| 120 | event_type=ChatCompletionResponseEventType.start, |
| 121 | delta="", |
| 122 | ) |
| 123 | ) |
| 124 | buffer = "" |
| 125 | ipython = False |
| 126 | stop_reason = None |
| 127 | tokens = [] |
| 128 | |
| 129 | async for response in await self.client.text_generation( |
| 130 | prompt=prompt, |
| 131 | stream=True, |
| 132 | details=True, |
| 133 | max_new_tokens=max_new_tokens, |
| 134 | stop_sequences=["<|eom_id|>", "<|eot_id|>"], |
| 135 | **options, |
| 136 | ): |
| 137 | token_result = response.token |
| 138 | |
| 139 | buffer += token_result.text |
| 140 | tokens.append(token_result.id) |
| 141 | |
| 142 | if not ipython and buffer.startswith("<|python_tag|>"): |
| 143 | ipython = True |
| 144 | yield ChatCompletionResponseStreamChunk( |
| 145 | event=ChatCompletionResponseEvent( |
| 146 | event_type=ChatCompletionResponseEventType.progress, |
| 147 | delta=ToolCallDelta( |
| 148 | content="", |
| 149 | parse_status=ToolCallParseStatus.started, |
| 150 | ), |
| 151 | ) |
| 152 | ) |
| 153 | buffer = buffer[len("<|python_tag|>") :] |
| 154 | continue |
| 155 | |
| 156 | if token_result.text == "<|eot_id|>": |
| 157 | stop_reason = StopReason.end_of_turn |
| 158 | text = "" |
| 159 | elif token_result.text == "<|eom_id|>": |
| 160 | stop_reason = StopReason.end_of_message |
| 161 | text = "" |
| 162 | else: |
| 163 | text = token_result.text |
| 164 | |
| 165 | if ipython: |
| 166 | delta = ToolCallDelta( |
| 167 | content=text, |
| 168 | parse_status=ToolCallParseStatus.in_progress, |
| 169 | ) |
| 170 | else: |
| 171 | delta = text |
| 172 | |
| 173 | if stop_reason is None: |
| 174 | yield ChatCompletionResponseStreamChunk( |
| 175 | event=ChatCompletionResponseEvent( |
| 176 | event_type=ChatCompletionResponseEventType.progress, |
| 177 | delta=delta, |
| 178 | stop_reason=stop_reason, |
| 179 | ) |
| 180 | ) |
| 181 | |
| 182 | if stop_reason is None: |
| 183 | stop_reason = StopReason.out_of_tokens |
| 184 | |
| 185 | # parse tool calls and report errors |
| 186 | message = self.formatter.decode_assistant_message(tokens, stop_reason) |
| 187 | parsed_tool_calls = len(message.tool_calls) > 0 |
| 188 | if ipython and not parsed_tool_calls: |
| 189 | yield ChatCompletionResponseStreamChunk( |
| 190 | event=ChatCompletionResponseEvent( |
| 191 | event_type=ChatCompletionResponseEventType.progress, |
| 192 | delta=ToolCallDelta( |
| 193 | content="", |
| 194 | parse_status=ToolCallParseStatus.failure, |
| 195 | ), |
| 196 | stop_reason=stop_reason, |
| 197 | ) |
| 198 | ) |
| 199 | |
| 200 | for tool_call in message.tool_calls: |
| 201 | yield ChatCompletionResponseStreamChunk( |
| 202 | event=ChatCompletionResponseEvent( |
| 203 | event_type=ChatCompletionResponseEventType.progress, |
| 204 | delta=ToolCallDelta( |
| 205 | content=tool_call, |
| 206 | parse_status=ToolCallParseStatus.success, |
| 207 | ), |
| 208 | stop_reason=stop_reason, |
| 209 | ) |
| 210 | ) |
| 211 | |
| 212 | yield ChatCompletionResponseStreamChunk( |
| 213 | event=ChatCompletionResponseEvent( |
| 214 | event_type=ChatCompletionResponseEventType.complete, |
| 215 | delta="", |
| 216 | stop_reason=stop_reason, |
| 217 | ) |
| 218 | ) |
| 219 | |
| 220 | |
| 221 | class TGIAdapter(_HfAdapter): |
| 222 | async def initialize(self, config: TGIImplConfig) -> None: |
| 223 | self.client = AsyncInferenceClient(model=config.url, token=config.api_token) |
| 224 | endpoint_info = await self.client.get_endpoint_info() |
| 225 | self.max_tokens = endpoint_info["max_total_tokens"] |
| 226 | self.model_id = endpoint_info["model_id"] |
| 227 | |
| 228 | |
| 229 | class InferenceAPIAdapter(_HfAdapter): |
| 230 | async def initialize(self, config: InferenceAPIImplConfig) -> None: |
| 231 | self.client = AsyncInferenceClient( |
| 232 | model=config.model_id, token=config.api_token |
| 233 | ) |
| 234 | endpoint_info = await self.client.get_endpoint_info() |
| 235 | self.max_tokens = endpoint_info["max_total_tokens"] |
| 236 | self.model_id = endpoint_info["model_id"] |
| 237 | |
| 238 | |
| 239 | class InferenceEndpointAdapter(_HfAdapter): |
| 240 | async def initialize(self, config: InferenceEndpointImplConfig) -> None: |
| 241 | # Get the inference endpoint details |
| 242 | api = HfApi(token=config.api_token) |
| 243 | endpoint = api.get_inference_endpoint(config.endpoint_name) |
| 244 | |
| 245 | # Wait for the endpoint to be ready (if not already) |
| 246 | endpoint.wait(timeout=60) |
| 247 | |
| 248 | # Initialize the adapter |
| 249 | self.client = endpoint.async_client |
| 250 | self.model_id = endpoint.repository |
| 251 | self.max_tokens = int( |
| 252 | endpoint.raw["model"]["image"]["custom"]["env"]["MAX_TOTAL_TOKENS"] |
| 253 | ) |