Elffuss BraidHub

kikocis/llama-stack public

842c3e3bbdd0 · 9.4 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 fireworks.client import Fireworks
10
11from llama_models.llama3.api.chat_format import ChatFormat
12
13from llama_models.llama3.api.datatypes import Message, StopReason
14from llama_models.llama3.api.tokenizer import Tokenizer
15from llama_models.sku_list import resolve_model
16
17from llama_stack.apis.inference import * # noqa: F403
18from llama_stack.providers.utils.inference.prepare_messages import prepare_messages
19
20from .config import FireworksImplConfig
21
22FIREWORKS_SUPPORTED_MODELS = {
23 "Meta-Llama3.1-8B-Instruct": "fireworks/llama-v3p1-8b-instruct",
24 "Meta-Llama3.1-70B-Instruct": "fireworks/llama-v3p1-70b-instruct",
25 "Meta-Llama3.1-405B-Instruct": "fireworks/llama-v3p1-405b-instruct",
26}
27
28
29class FireworksInferenceAdapter(Inference):
30 def __init__(self, config: FireworksImplConfig) -> None:
31 self.config = config
32 tokenizer = Tokenizer.get_instance()
33 self.formatter = ChatFormat(tokenizer)
34
35 @property
36 def client(self) -> Fireworks:
37 return Fireworks(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(
46 self,
47 model: str,
48 content: InterleavedTextMedia,
49 sampling_params: Optional[SamplingParams] = SamplingParams(),
50 stream: Optional[bool] = False,
51 logprobs: Optional[LogProbConfig] = None,
52 ) -> AsyncGenerator:
53 raise NotImplementedError()
54
55 def _messages_to_fireworks_messages(self, messages: list[Message]) -> list:
56 fireworks_messages = []
57 for message in messages:
58 if message.role == "ipython":
59 role = "tool"
60 else:
61 role = message.role
62 fireworks_messages.append({"role": role, "content": message.content})
63
64 return fireworks_messages
65
66 def resolve_fireworks_model(self, model_name: str) -> str:
67 model = resolve_model(model_name)
68 assert (
69 model is not None
70 and model.descriptor(shorten_default_variant=True)
71 in FIREWORKS_SUPPORTED_MODELS
72 ), f"Unsupported model: {model_name}, use one of the supported models: {','.join(FIREWORKS_SUPPORTED_MODELS.keys())}"
73
74 return FIREWORKS_SUPPORTED_MODELS.get(
75 model.descriptor(shorten_default_variant=True)
76 )
77
78 def get_fireworks_chat_options(self, request: ChatCompletionRequest) -> dict:
79 options = {}
80 if request.sampling_params is not None:
81 for attr in {"temperature", "top_p", "top_k", "max_tokens"}:
82 if getattr(request.sampling_params, attr):
83 options[attr] = getattr(request.sampling_params, attr)
84
85 return options
86
87 async def chat_completion(
88 self,
89 model: str,
90 messages: List[Message],
91 sampling_params: Optional[SamplingParams] = SamplingParams(),
92 tools: Optional[List[ToolDefinition]] = None,
93 tool_choice: Optional[ToolChoice] = ToolChoice.auto,
94 tool_prompt_format: Optional[ToolPromptFormat] = ToolPromptFormat.json,
95 stream: Optional[bool] = False,
96 logprobs: Optional[LogProbConfig] = None,
97 ) -> AsyncGenerator:
98 request = ChatCompletionRequest(
99 model=model,
100 messages=messages,
101 sampling_params=sampling_params,
102 tools=tools or [],
103 tool_choice=tool_choice,
104 tool_prompt_format=tool_prompt_format,
105 stream=stream,
106 logprobs=logprobs,
107 )
108
109 messages = prepare_messages(request)
110
111 # accumulate sampling params and other options to pass to fireworks
112 options = self.get_fireworks_chat_options(request)
113 fireworks_model = self.resolve_fireworks_model(request.model)
114
115 if not request.stream:
116 r = await self.client.chat.completions.acreate(
117 model=fireworks_model,
118 messages=self._messages_to_fireworks_messages(messages),
119 stream=False,
120 **options,
121 )
122 stop_reason = None
123 if r.choices[0].finish_reason:
124 if r.choices[0].finish_reason == "stop":
125 stop_reason = StopReason.end_of_turn
126 elif r.choices[0].finish_reason == "length":
127 stop_reason = StopReason.out_of_tokens
128
129 completion_message = self.formatter.decode_assistant_message_from_content(
130 r.choices[0].message.content, stop_reason
131 )
132
133 yield ChatCompletionResponse(
134 completion_message=completion_message,
135 logprobs=None,
136 )
137 else:
138 yield ChatCompletionResponseStreamChunk(
139 event=ChatCompletionResponseEvent(
140 event_type=ChatCompletionResponseEventType.start,
141 delta="",
142 )
143 )
144
145 buffer = ""
146 ipython = False
147 stop_reason = None
148
149 async for chunk in self.client.chat.completions.acreate(
150 model=fireworks_model,
151 messages=self._messages_to_fireworks_messages(messages),
152 stream=True,
153 **options,
154 ):
155 if chunk.choices[0].finish_reason:
156 if stop_reason is None and chunk.choices[0].finish_reason == "stop":
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 )