| 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 llama_models.llama3.api.chat_format import ChatFormat |
| 10 | |
| 11 | from llama_models.llama3.api.datatypes import Message, StopReason |
| 12 | from llama_models.llama3.api.tokenizer import Tokenizer |
| 13 | from llama_models.sku_list import resolve_model |
| 14 | |
| 15 | from fireworks.client import Fireworks |
| 16 | |
| 17 | from llama_stack.apis.inference import * # noqa: F403 |
| 18 | from llama_stack.providers.utils.inference.prepare_messages import prepare_messages |
| 19 | |
| 20 | from .config import FireworksImplConfig |
| 21 | |
| 22 | FIREWORKS_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 | |
| 29 | class 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(self, request: CompletionRequest) -> AsyncGenerator: |
| 46 | raise NotImplementedError() |
| 47 | |
| 48 | def _messages_to_fireworks_messages(self, messages: list[Message]) -> list: |
| 49 | fireworks_messages = [] |
| 50 | for message in messages: |
| 51 | if message.role == "ipython": |
| 52 | role = "tool" |
| 53 | else: |
| 54 | role = message.role |
| 55 | fireworks_messages.append({"role": role, "content": message.content}) |
| 56 | |
| 57 | return fireworks_messages |
| 58 | |
| 59 | def resolve_fireworks_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 FIREWORKS_SUPPORTED_MODELS |
| 65 | ), f"Unsupported model: {model_name}, use one of the supported models: {','.join(FIREWORKS_SUPPORTED_MODELS.keys())}" |
| 66 | |
| 67 | return FIREWORKS_SUPPORTED_MODELS.get( |
| 68 | model.descriptor(shorten_default_variant=True) |
| 69 | ) |
| 70 | |
| 71 | def get_fireworks_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 | request = ChatCompletionRequest( |
| 92 | model=model, |
| 93 | messages=messages, |
| 94 | sampling_params=sampling_params, |
| 95 | tools=tools or [], |
| 96 | tool_choice=tool_choice, |
| 97 | tool_prompt_format=tool_prompt_format, |
| 98 | stream=stream, |
| 99 | logprobs=logprobs, |
| 100 | ) |
| 101 | |
| 102 | messages = prepare_messages(request) |
| 103 | |
| 104 | # accumulate sampling params and other options to pass to fireworks |
| 105 | options = self.get_fireworks_chat_options(request) |
| 106 | fireworks_model = self.resolve_fireworks_model(request.model) |
| 107 | |
| 108 | if not request.stream: |
| 109 | r = await self.client.chat.completions.acreate( |
| 110 | model=fireworks_model, |
| 111 | messages=self._messages_to_fireworks_messages(messages), |
| 112 | stream=False, |
| 113 | **options, |
| 114 | ) |
| 115 | stop_reason = None |
| 116 | if r.choices[0].finish_reason: |
| 117 | if r.choices[0].finish_reason == "stop": |
| 118 | stop_reason = StopReason.end_of_turn |
| 119 | elif r.choices[0].finish_reason == "length": |
| 120 | stop_reason = StopReason.out_of_tokens |
| 121 | |
| 122 | completion_message = self.formatter.decode_assistant_message_from_content( |
| 123 | r.choices[0].message.content, stop_reason |
| 124 | ) |
| 125 | |
| 126 | yield ChatCompletionResponse( |
| 127 | completion_message=completion_message, |
| 128 | logprobs=None, |
| 129 | ) |
| 130 | else: |
| 131 | yield ChatCompletionResponseStreamChunk( |
| 132 | event=ChatCompletionResponseEvent( |
| 133 | event_type=ChatCompletionResponseEventType.start, |
| 134 | delta="", |
| 135 | ) |
| 136 | ) |
| 137 | |
| 138 | buffer = "" |
| 139 | ipython = False |
| 140 | stop_reason = None |
| 141 | |
| 142 | async for chunk in self.client.chat.completions.acreate( |
| 143 | model=fireworks_model, |
| 144 | messages=self._messages_to_fireworks_messages(messages), |
| 145 | stream=True, |
| 146 | **options, |
| 147 | ): |
| 148 | if chunk.choices[0].finish_reason: |
| 149 | if stop_reason is None and chunk.choices[0].finish_reason == "stop": |
| 150 | stop_reason = StopReason.end_of_turn |
| 151 | elif ( |
| 152 | stop_reason is None |
| 153 | and chunk.choices[0].finish_reason == "length" |
| 154 | ): |
| 155 | stop_reason = StopReason.out_of_tokens |
| 156 | break |
| 157 | |
| 158 | text = chunk.choices[0].delta.content |
| 159 | if text is None: |
| 160 | continue |
| 161 | |
| 162 | # check if its a tool call ( aka starts with <|python_tag|> ) |
| 163 | if not ipython and text.startswith("<|python_tag|>"): |
| 164 | ipython = True |
| 165 | yield ChatCompletionResponseStreamChunk( |
| 166 | event=ChatCompletionResponseEvent( |
| 167 | event_type=ChatCompletionResponseEventType.progress, |
| 168 | delta=ToolCallDelta( |
| 169 | content="", |
| 170 | parse_status=ToolCallParseStatus.started, |
| 171 | ), |
| 172 | ) |
| 173 | ) |
| 174 | buffer += text |
| 175 | continue |
| 176 | |
| 177 | if ipython: |
| 178 | if text == "<|eot_id|>": |
| 179 | stop_reason = StopReason.end_of_turn |
| 180 | text = "" |
| 181 | continue |
| 182 | elif text == "<|eom_id|>": |
| 183 | stop_reason = StopReason.end_of_message |
| 184 | text = "" |
| 185 | continue |
| 186 | |
| 187 | buffer += text |
| 188 | delta = ToolCallDelta( |
| 189 | content=text, |
| 190 | parse_status=ToolCallParseStatus.in_progress, |
| 191 | ) |
| 192 | |
| 193 | yield ChatCompletionResponseStreamChunk( |
| 194 | event=ChatCompletionResponseEvent( |
| 195 | event_type=ChatCompletionResponseEventType.progress, |
| 196 | delta=delta, |
| 197 | stop_reason=stop_reason, |
| 198 | ) |
| 199 | ) |
| 200 | else: |
| 201 | buffer += text |
| 202 | yield ChatCompletionResponseStreamChunk( |
| 203 | event=ChatCompletionResponseEvent( |
| 204 | event_type=ChatCompletionResponseEventType.progress, |
| 205 | delta=text, |
| 206 | stop_reason=stop_reason, |
| 207 | ) |
| 208 | ) |
| 209 | |
| 210 | # parse tool calls and report errors |
| 211 | message = self.formatter.decode_assistant_message_from_content( |
| 212 | buffer, stop_reason |
| 213 | ) |
| 214 | parsed_tool_calls = len(message.tool_calls) > 0 |
| 215 | if ipython and not parsed_tool_calls: |
| 216 | yield ChatCompletionResponseStreamChunk( |
| 217 | event=ChatCompletionResponseEvent( |
| 218 | event_type=ChatCompletionResponseEventType.progress, |
| 219 | delta=ToolCallDelta( |
| 220 | content="", |
| 221 | parse_status=ToolCallParseStatus.failure, |
| 222 | ), |
| 223 | stop_reason=stop_reason, |
| 224 | ) |
| 225 | ) |
| 226 | |
| 227 | for tool_call in message.tool_calls: |
| 228 | yield ChatCompletionResponseStreamChunk( |
| 229 | event=ChatCompletionResponseEvent( |
| 230 | event_type=ChatCompletionResponseEventType.progress, |
| 231 | delta=ToolCallDelta( |
| 232 | content=tool_call, |
| 233 | parse_status=ToolCallParseStatus.success, |
| 234 | ), |
| 235 | stop_reason=stop_reason, |
| 236 | ) |
| 237 | ) |
| 238 | |
| 239 | yield ChatCompletionResponseStreamChunk( |
| 240 | event=ChatCompletionResponseEvent( |
| 241 | event_type=ChatCompletionResponseEventType.complete, |
| 242 | delta="", |
| 243 | stop_reason=stop_reason, |
| 244 | ) |
| 245 | ) |