Elffuss BraidHub

kikocis/llama-stack public

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