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