| 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 together import Together |
| 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 TogetherImplConfig |
| 23 | |
| 24 | TOGETHER_SUPPORTED_MODELS = { |
| 25 | "Llama3.1-8B-Instruct": "meta-llama/Llama-3.1-8B-Instruct-Turbo", |
| 26 | "Llama3.1-70B-Instruct": "meta-llama/Llama-3.1-70B-Instruct-Turbo", |
| 27 | "Llama3.1-405B-Instruct": "meta-llama/Llama-3.1-405B-Instruct-Turbo", |
| 28 | } |
| 29 | |
| 30 | |
| 31 | class TogetherInferenceAdapter(Inference): |
| 32 | def __init__(self, config: TogetherImplConfig) -> None: |
| 33 | self.config = config |
| 34 | tokenizer = Tokenizer.get_instance() |
| 35 | self.formatter = ChatFormat(tokenizer) |
| 36 | |
| 37 | @property |
| 38 | def client(self) -> Together: |
| 39 | return Together(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_together_messages(self, messages: list[Message]) -> list: |
| 58 | together_messages = [] |
| 59 | for message in messages: |
| 60 | if message.role == "ipython": |
| 61 | role = "tool" |
| 62 | else: |
| 63 | role = message.role |
| 64 | together_messages.append({"role": role, "content": message.content}) |
| 65 | |
| 66 | return together_messages |
| 67 | |
| 68 | def resolve_together_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 TOGETHER_SUPPORTED_MODELS |
| 74 | ), f"Unsupported model: {model_name}, use one of the supported models: {','.join(TOGETHER_SUPPORTED_MODELS.keys())}" |
| 75 | |
| 76 | return TOGETHER_SUPPORTED_MODELS.get( |
| 77 | model.descriptor(shorten_default_variant=True) |
| 78 | ) |
| 79 | |
| 80 | def get_together_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 | # wrapper request to make it easier to pass around (internal only, not exposed to API) |
| 101 | request = ChatCompletionRequest( |
| 102 | model=model, |
| 103 | messages=messages, |
| 104 | sampling_params=sampling_params, |
| 105 | tools=tools or [], |
| 106 | tool_choice=tool_choice, |
| 107 | tool_prompt_format=tool_prompt_format, |
| 108 | stream=stream, |
| 109 | logprobs=logprobs, |
| 110 | ) |
| 111 | |
| 112 | # accumulate sampling params and other options to pass to together |
| 113 | options = self.get_together_chat_options(request) |
| 114 | together_model = self.resolve_together_model(request.model) |
| 115 | messages = augment_messages_for_tools(request) |
| 116 | |
| 117 | if not request.stream: |
| 118 | # TODO: might need to add back an async here |
| 119 | r = self.client.chat.completions.create( |
| 120 | model=together_model, |
| 121 | messages=self._messages_to_together_messages(messages), |
| 122 | stream=False, |
| 123 | **options, |
| 124 | ) |
| 125 | stop_reason = None |
| 126 | if r.choices[0].finish_reason: |
| 127 | if ( |
| 128 | r.choices[0].finish_reason == "stop" |
| 129 | or r.choices[0].finish_reason == "eos" |
| 130 | ): |
| 131 | stop_reason = StopReason.end_of_turn |
| 132 | elif r.choices[0].finish_reason == "length": |
| 133 | stop_reason = StopReason.out_of_tokens |
| 134 | |
| 135 | completion_message = self.formatter.decode_assistant_message_from_content( |
| 136 | r.choices[0].message.content, stop_reason |
| 137 | ) |
| 138 | yield ChatCompletionResponse( |
| 139 | completion_message=completion_message, |
| 140 | logprobs=None, |
| 141 | ) |
| 142 | else: |
| 143 | yield ChatCompletionResponseStreamChunk( |
| 144 | event=ChatCompletionResponseEvent( |
| 145 | event_type=ChatCompletionResponseEventType.start, |
| 146 | delta="", |
| 147 | ) |
| 148 | ) |
| 149 | |
| 150 | buffer = "" |
| 151 | ipython = False |
| 152 | stop_reason = None |
| 153 | |
| 154 | for chunk in self.client.chat.completions.create( |
| 155 | model=together_model, |
| 156 | messages=self._messages_to_together_messages(messages), |
| 157 | stream=True, |
| 158 | **options, |
| 159 | ): |
| 160 | if chunk.choices[0].finish_reason: |
| 161 | if ( |
| 162 | stop_reason is None and chunk.choices[0].finish_reason == "stop" |
| 163 | ) or ( |
| 164 | stop_reason is None and chunk.choices[0].finish_reason == "eos" |
| 165 | ): |
| 166 | stop_reason = StopReason.end_of_turn |
| 167 | elif ( |
| 168 | stop_reason is None |
| 169 | and chunk.choices[0].finish_reason == "length" |
| 170 | ): |
| 171 | stop_reason = StopReason.out_of_tokens |
| 172 | break |
| 173 | |
| 174 | text = chunk.choices[0].delta.content |
| 175 | if text is None: |
| 176 | continue |
| 177 | |
| 178 | # check if its a tool call ( aka starts with <|python_tag|> ) |
| 179 | if not ipython and text.startswith("<|python_tag|>"): |
| 180 | ipython = True |
| 181 | yield ChatCompletionResponseStreamChunk( |
| 182 | event=ChatCompletionResponseEvent( |
| 183 | event_type=ChatCompletionResponseEventType.progress, |
| 184 | delta=ToolCallDelta( |
| 185 | content="", |
| 186 | parse_status=ToolCallParseStatus.started, |
| 187 | ), |
| 188 | ) |
| 189 | ) |
| 190 | buffer += text |
| 191 | continue |
| 192 | |
| 193 | if ipython: |
| 194 | if text == "<|eot_id|>": |
| 195 | stop_reason = StopReason.end_of_turn |
| 196 | text = "" |
| 197 | continue |
| 198 | elif text == "<|eom_id|>": |
| 199 | stop_reason = StopReason.end_of_message |
| 200 | text = "" |
| 201 | continue |
| 202 | |
| 203 | buffer += text |
| 204 | delta = ToolCallDelta( |
| 205 | content=text, |
| 206 | parse_status=ToolCallParseStatus.in_progress, |
| 207 | ) |
| 208 | |
| 209 | yield ChatCompletionResponseStreamChunk( |
| 210 | event=ChatCompletionResponseEvent( |
| 211 | event_type=ChatCompletionResponseEventType.progress, |
| 212 | delta=delta, |
| 213 | stop_reason=stop_reason, |
| 214 | ) |
| 215 | ) |
| 216 | else: |
| 217 | buffer += text |
| 218 | yield ChatCompletionResponseStreamChunk( |
| 219 | event=ChatCompletionResponseEvent( |
| 220 | event_type=ChatCompletionResponseEventType.progress, |
| 221 | delta=text, |
| 222 | stop_reason=stop_reason, |
| 223 | ) |
| 224 | ) |
| 225 | |
| 226 | # parse tool calls and report errors |
| 227 | message = self.formatter.decode_assistant_message_from_content( |
| 228 | buffer, stop_reason |
| 229 | ) |
| 230 | parsed_tool_calls = len(message.tool_calls) > 0 |
| 231 | if ipython and not parsed_tool_calls: |
| 232 | yield ChatCompletionResponseStreamChunk( |
| 233 | event=ChatCompletionResponseEvent( |
| 234 | event_type=ChatCompletionResponseEventType.progress, |
| 235 | delta=ToolCallDelta( |
| 236 | content="", |
| 237 | parse_status=ToolCallParseStatus.failure, |
| 238 | ), |
| 239 | stop_reason=stop_reason, |
| 240 | ) |
| 241 | ) |
| 242 | |
| 243 | for tool_call in message.tool_calls: |
| 244 | yield ChatCompletionResponseStreamChunk( |
| 245 | event=ChatCompletionResponseEvent( |
| 246 | event_type=ChatCompletionResponseEventType.progress, |
| 247 | delta=ToolCallDelta( |
| 248 | content=tool_call, |
| 249 | parse_status=ToolCallParseStatus.success, |
| 250 | ), |
| 251 | stop_reason=stop_reason, |
| 252 | ) |
| 253 | ) |
| 254 | |
| 255 | yield ChatCompletionResponseStreamChunk( |
| 256 | event=ChatCompletionResponseEvent( |
| 257 | event_type=ChatCompletionResponseEventType.complete, |
| 258 | delta="", |
| 259 | stop_reason=stop_reason, |
| 260 | ) |
| 261 | ) |