Elffuss BraidHub

kikocis/llama-stack public

3fc339af16ee · 9.6 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
7from typing import AsyncGenerator
8
9from llama_models.llama3.api.chat_format import ChatFormat
10
11from llama_models.llama3.api.datatypes import Message, StopReason
12from llama_models.llama3.api.tokenizer import Tokenizer
13from llama_models.sku_list import resolve_model
14
15from together import Together
16
17from llama_stack.apis.inference import * # noqa: F403
18from llama_stack.providers.utils.inference.prepare_messages import prepare_messages
19
20from .config import TogetherImplConfig
21
22TOGETHER_SUPPORTED_MODELS = {
23 "Meta-Llama3.1-8B-Instruct": "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
24 "Meta-Llama3.1-70B-Instruct": "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
25 "Meta-Llama3.1-405B-Instruct": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",
26}
27
28
29class TogetherInferenceAdapter(Inference):
30 def __init__(self, config: TogetherImplConfig) -> None:
31 self.config = config
32 tokenizer = Tokenizer.get_instance()
33 self.formatter = ChatFormat(tokenizer)
34
35 @property
36 def client(self) -> Together:
37 return Together(api_key=self.config.api_key)
38
39 async def initialize(self) -> None:
40 return
41
42 async def shutdown(self) -> None:
43 pass
44
45 async def completion(self, request: CompletionRequest) -> AsyncGenerator:
46 raise NotImplementedError()
47
48 def _messages_to_together_messages(self, messages: list[Message]) -> list:
49 together_messages = []
50 for message in messages:
51 if message.role == "ipython":
52 role = "tool"
53 else:
54 role = message.role
55 together_messages.append({"role": role, "content": message.content})
56
57 return together_messages
58
59 def resolve_together_model(self, model_name: str) -> str:
60 model = resolve_model(model_name)
61 assert (
62 model is not None
63 and model.descriptor(shorten_default_variant=True)
64 in TOGETHER_SUPPORTED_MODELS
65 ), f"Unsupported model: {model_name}, use one of the supported models: {','.join(TOGETHER_SUPPORTED_MODELS.keys())}"
66
67 return TOGETHER_SUPPORTED_MODELS.get(
68 model.descriptor(shorten_default_variant=True)
69 )
70
71 def get_together_chat_options(self, request: ChatCompletionRequest) -> dict:
72 options = {}
73 if request.sampling_params is not None:
74 for attr in {"temperature", "top_p", "top_k", "max_tokens"}:
75 if getattr(request.sampling_params, attr):
76 options[attr] = getattr(request.sampling_params, attr)
77
78 return options
79
80 async def chat_completion(
81 self,
82 model: str,
83 messages: List[Message],
84 sampling_params: Optional[SamplingParams] = SamplingParams(),
85 tools: Optional[List[ToolDefinition]] = None,
86 tool_choice: Optional[ToolChoice] = ToolChoice.auto,
87 tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json,
88 stream: Optional[bool] = False,
89 logprobs: Optional[LogProbConfig] = None,
90 ) -> AsyncGenerator:
91 # wrapper request to make it easier to pass around (internal only, not exposed to API)
92 request = ChatCompletionRequest(
93 model=model,
94 messages=messages,
95 sampling_params=sampling_params,
96 tools=tools or [],
97 tool_choice=tool_choice,
98 tool_prompt_format=tool_prompt_format,
99 stream=stream,
100 logprobs=logprobs,
101 )
102
103 # accumulate sampling params and other options to pass to together
104 options = self.get_together_chat_options(request)
105 together_model = self.resolve_together_model(request.model)
106 messages = prepare_messages(request)
107
108 if not request.stream:
109 # TODO: might need to add back an async here
110 r = self.client.chat.completions.create(
111 model=together_model,
112 messages=self._messages_to_together_messages(messages),
113 stream=False,
114 **options,
115 )
116 stop_reason = None
117 if r.choices[0].finish_reason:
118 if (
119 r.choices[0].finish_reason == "stop"
120 or r.choices[0].finish_reason == "eos"
121 ):
122 stop_reason = StopReason.end_of_turn
123 elif r.choices[0].finish_reason == "length":
124 stop_reason = StopReason.out_of_tokens
125
126 completion_message = self.formatter.decode_assistant_message_from_content(
127 r.choices[0].message.content, stop_reason
128 )
129 yield ChatCompletionResponse(
130 completion_message=completion_message,
131 logprobs=None,
132 )
133 else:
134 yield ChatCompletionResponseStreamChunk(
135 event=ChatCompletionResponseEvent(
136 event_type=ChatCompletionResponseEventType.start,
137 delta="",
138 )
139 )
140
141 buffer = ""
142 ipython = False
143 stop_reason = None
144
145 for chunk in self.client.chat.completions.create(
146 model=together_model,
147 messages=self._messages_to_together_messages(messages),
148 stream=True,
149 **options,
150 ):
151 if chunk.choices[0].finish_reason:
152 if (
153 stop_reason is None and chunk.choices[0].finish_reason == "stop"
154 ) or (
155 stop_reason is None and chunk.choices[0].finish_reason == "eos"
156 ):
157 stop_reason = StopReason.end_of_turn
158 elif (
159 stop_reason is None
160 and chunk.choices[0].finish_reason == "length"
161 ):
162 stop_reason = StopReason.out_of_tokens
163 break
164
165 text = chunk.choices[0].delta.content
166 if text is None:
167 continue
168
169 # check if its a tool call ( aka starts with <|python_tag|> )
170 if not ipython and text.startswith("<|python_tag|>"):
171 ipython = True
172 yield ChatCompletionResponseStreamChunk(
173 event=ChatCompletionResponseEvent(
174 event_type=ChatCompletionResponseEventType.progress,
175 delta=ToolCallDelta(
176 content="",
177 parse_status=ToolCallParseStatus.started,
178 ),
179 )
180 )
181 buffer += text
182 continue
183
184 if ipython:
185 if text == "<|eot_id|>":
186 stop_reason = StopReason.end_of_turn
187 text = ""
188 continue
189 elif text == "<|eom_id|>":
190 stop_reason = StopReason.end_of_message
191 text = ""
192 continue
193
194 buffer += text
195 delta = ToolCallDelta(
196 content=text,
197 parse_status=ToolCallParseStatus.in_progress,
198 )
199
200 yield ChatCompletionResponseStreamChunk(
201 event=ChatCompletionResponseEvent(
202 event_type=ChatCompletionResponseEventType.progress,
203 delta=delta,
204 stop_reason=stop_reason,
205 )
206 )
207 else:
208 buffer += text
209 yield ChatCompletionResponseStreamChunk(
210 event=ChatCompletionResponseEvent(
211 event_type=ChatCompletionResponseEventType.progress,
212 delta=text,
213 stop_reason=stop_reason,
214 )
215 )
216
217 # parse tool calls and report errors
218 message = self.formatter.decode_assistant_message_from_content(
219 buffer, stop_reason
220 )
221 parsed_tool_calls = len(message.tool_calls) > 0
222 if ipython and not parsed_tool_calls:
223 yield ChatCompletionResponseStreamChunk(
224 event=ChatCompletionResponseEvent(
225 event_type=ChatCompletionResponseEventType.progress,
226 delta=ToolCallDelta(
227 content="",
228 parse_status=ToolCallParseStatus.failure,
229 ),
230 stop_reason=stop_reason,
231 )
232 )
233
234 for tool_call in message.tool_calls:
235 yield ChatCompletionResponseStreamChunk(
236 event=ChatCompletionResponseEvent(
237 event_type=ChatCompletionResponseEventType.progress,
238 delta=ToolCallDelta(
239 content=tool_call,
240 parse_status=ToolCallParseStatus.success,
241 ),
242 stop_reason=stop_reason,
243 )
244 )
245
246 yield ChatCompletionResponseStreamChunk(
247 event=ChatCompletionResponseEvent(
248 event_type=ChatCompletionResponseEventType.complete,
249 delta="",
250 stop_reason=stop_reason,
251 )
252 )