Elffuss BraidHub

kikocis/llama-stack public

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