diff --git a/.circleci/config.yml b/.circleci/config.yml index 779f302c94..8ad7e52683 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -931,7 +931,7 @@ jobs: command: | pwd ls - python -m pytest -vv tests/litellm --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit-litellm.xml --durations=10 -n 4 + python -m pytest -vv tests/test_litellm --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit-litellm.xml --durations=10 -n 4 no_output_timeout: 120m - run: name: Run enterprise tests diff --git a/.github/workflows/test-litellm.yml b/.github/workflows/test-litellm.yml index db2ebb3cba..6dbbe663ab 100644 --- a/.github/workflows/test-litellm.yml +++ b/.github/workflows/test-litellm.yml @@ -1,4 +1,4 @@ -name: LiteLLM Mock Tests (folder - tests/litellm) +name: LiteLLM Mock Tests (folder - tests/test_litellm) on: pull_request: diff --git a/Makefile b/Makefile index a06509312d..b25c95cd8f 100644 --- a/Makefile +++ b/Makefile @@ -26,10 +26,10 @@ test: poetry run pytest tests/ test-unit: - poetry run pytest tests/litellm/ + poetry run pytest tests/test_litellm/ test-integration: - poetry run pytest tests/ -k "not litellm" + poetry run pytest tests/ -k "not test_litellm" test-unit-helm: helm unittest -f 'tests/*.yaml' deploy/charts/litellm-helm \ No newline at end of file diff --git a/litellm/__init__.py b/litellm/__init__.py index 99127bec19..9b019daec7 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -929,11 +929,10 @@ from .llms.vertex_ai.vertex_ai_partner_models.llama3.transformation import ( from .llms.vertex_ai.vertex_ai_partner_models.ai21.transformation import ( VertexAIAi21Config, ) - +from .llms.ollama.chat.transformation import OllamaChatConfig from .llms.ollama.completion.transformation import OllamaConfig from .llms.sagemaker.completion.transformation import SagemakerConfig from .llms.sagemaker.chat.transformation import SagemakerChatConfig -from .llms.ollama_chat import OllamaChatConfig from .llms.bedrock.chat.invoke_handler import ( AmazonCohereChatConfig, bedrock_tool_name_mappings, diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py index 5ae1dcf988..a3f6bffa55 100644 --- a/litellm/litellm_core_utils/streaming_handler.py +++ b/litellm/litellm_core_utils/streaming_handler.py @@ -549,41 +549,6 @@ class CustomStreamWrapper: ) return "" - def handle_ollama_chat_stream(self, chunk): - # for ollama_chat/ provider - try: - if isinstance(chunk, dict): - json_chunk = chunk - else: - json_chunk = json.loads(chunk) - if "error" in json_chunk: - raise Exception(f"Ollama Error - {json_chunk}") - - text = "" - is_finished = False - finish_reason = None - if json_chunk["done"] is True: - text = "" - is_finished = True - finish_reason = "stop" - return { - "text": text, - "is_finished": is_finished, - "finish_reason": finish_reason, - } - elif "message" in json_chunk: - print_verbose(f"delta content: {json_chunk}") - text = json_chunk["message"]["content"] - return { - "text": text, - "is_finished": is_finished, - "finish_reason": finish_reason, - } - else: - raise Exception(f"Ollama Error - {json_chunk}") - except Exception as e: - raise e - def handle_triton_stream(self, chunk): try: if isinstance(chunk, dict): @@ -1142,12 +1107,6 @@ class CustomStreamWrapper: new_chunk = self.completion_stream[:chunk_size] completion_obj["content"] = new_chunk self.completion_stream = self.completion_stream[chunk_size:] - elif self.custom_llm_provider == "ollama_chat": - response_obj = self.handle_ollama_chat_stream(chunk) - completion_obj["content"] = response_obj["text"] - print_verbose(f"completion obj content: {completion_obj['content']}") - if response_obj["is_finished"]: - self.received_finish_reason = response_obj["finish_reason"] elif self.custom_llm_provider == "triton": response_obj = self.handle_triton_stream(chunk) completion_obj["content"] = response_obj["text"] @@ -1198,6 +1157,7 @@ class CustomStreamWrapper: if response_obj["is_finished"]: self.received_finish_reason = response_obj["finish_reason"] elif self.custom_llm_provider == "cached_response": + chunk = cast(ModelResponseStream, chunk) response_obj = { "text": chunk.choices[0].delta.content, "is_finished": True, @@ -1225,7 +1185,7 @@ class CustomStreamWrapper: if self.custom_llm_provider == "azure": if isinstance(chunk, BaseModel) and hasattr(chunk, "model"): # for azure, we need to pass the model from the orignal chunk - self.model = chunk.model + self.model = getattr(chunk, "model", self.model) response_obj = self.handle_openai_chat_completion_chunk(chunk) if response_obj is None: return diff --git a/litellm/llms/ollama/chat/transformation.py b/litellm/llms/ollama/chat/transformation.py new file mode 100644 index 0000000000..e415704a76 --- /dev/null +++ b/litellm/llms/ollama/chat/transformation.py @@ -0,0 +1,483 @@ +import json +import time +import uuid +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterator, + Iterator, + List, + Optional, + Union, + cast, +) + +from httpx._models import Headers, Response +from pydantic import BaseModel + +import litellm +from litellm.llms.base_llm.base_model_iterator import BaseModelResponseIterator +from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException +from litellm.types.llms.ollama import OllamaToolCall, OllamaToolCallFunction +from litellm.types.llms.openai import ( + AllMessageValues, + ChatCompletionAssistantToolCall, + ChatCompletionUsageBlock, +) +from litellm.types.utils import ModelResponse, ModelResponseStream + +from ..common_utils import OllamaError + +if TYPE_CHECKING: + from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj + + LiteLLMLoggingObj = _LiteLLMLoggingObj +else: + LiteLLMLoggingObj = Any + + +class OllamaChatConfig(BaseConfig): + """ + Reference: https://github.com/ollama/ollama/blob/main/docs/api.md#parameters + + The class `OllamaConfig` provides the configuration for the Ollama's API interface. Below are the parameters: + + - `mirostat` (int): Enable Mirostat sampling for controlling perplexity. Default is 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0. Example usage: mirostat 0 + + - `mirostat_eta` (float): Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. Default: 0.1. Example usage: mirostat_eta 0.1 + + - `mirostat_tau` (float): Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. Default: 5.0. Example usage: mirostat_tau 5.0 + + - `num_ctx` (int): Sets the size of the context window used to generate the next token. Default: 2048. Example usage: num_ctx 4096 + + - `num_gqa` (int): The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b. Example usage: num_gqa 1 + + - `num_gpu` (int): The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. Example usage: num_gpu 0 + + - `num_thread` (int): Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Example usage: num_thread 8 + + - `repeat_last_n` (int): Sets how far back for the model to look back to prevent repetition. Default: 64, 0 = disabled, -1 = num_ctx. Example usage: repeat_last_n 64 + + - `repeat_penalty` (float): Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. Default: 1.1. Example usage: repeat_penalty 1.1 + + - `temperature` (float): The temperature of the model. Increasing the temperature will make the model answer more creatively. Default: 0.8. Example usage: temperature 0.7 + + - `seed` (int): Sets the random number seed to use for generation. Setting this to a specific number will make the model generate the same text for the same prompt. Example usage: seed 42 + + - `stop` (string[]): Sets the stop sequences to use. Example usage: stop "AI assistant:" + + - `tfs_z` (float): Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. Default: 1. Example usage: tfs_z 1 + + - `num_predict` (int): Maximum number of tokens to predict when generating text. Default: 128, -1 = infinite generation, -2 = fill context. Example usage: num_predict 42 + + - `top_k` (int): Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. Default: 40. Example usage: top_k 40 + + - `top_p` (float): Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. Default: 0.9. Example usage: top_p 0.9 + + - `system` (string): system prompt for model (overrides what is defined in the Modelfile) + + - `template` (string): the full prompt or prompt template (overrides what is defined in the Modelfile) + """ + + mirostat: Optional[int] = None + mirostat_eta: Optional[float] = None + mirostat_tau: Optional[float] = None + num_ctx: Optional[int] = None + num_gqa: Optional[int] = None + num_thread: Optional[int] = None + repeat_last_n: Optional[int] = None + repeat_penalty: Optional[float] = None + seed: Optional[int] = None + tfs_z: Optional[float] = None + num_predict: Optional[int] = None + top_k: Optional[int] = None + system: Optional[str] = None + template: Optional[str] = None + + def __init__( + self, + mirostat: Optional[int] = None, + mirostat_eta: Optional[float] = None, + mirostat_tau: Optional[float] = None, + num_ctx: Optional[int] = None, + num_gqa: Optional[int] = None, + num_thread: Optional[int] = None, + repeat_last_n: Optional[int] = None, + repeat_penalty: Optional[float] = None, + temperature: Optional[float] = None, + seed: Optional[int] = None, + stop: Optional[list] = None, + tfs_z: Optional[float] = None, + num_predict: Optional[int] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + system: Optional[str] = None, + template: Optional[str] = None, + ) -> None: + locals_ = locals().copy() + for key, value in locals_.items(): + if key != "self" and value is not None: + setattr(self.__class__, key, value) + + @classmethod + def get_config(cls): + return super().get_config() + + def get_supported_openai_params(self, model: str): + return [ + "max_tokens", + "max_completion_tokens", + "stream", + "top_p", + "temperature", + "seed", + "frequency_penalty", + "stop", + "tools", + "tool_choice", + "functions", + "response_format", + ] + + def map_openai_params( + self, + non_default_params: dict, + optional_params: dict, + model: str, + drop_params: bool, + ) -> dict: + for param, value in non_default_params.items(): + if param == "max_tokens" or param == "max_completion_tokens": + optional_params["num_predict"] = value + if param == "stream": + optional_params["stream"] = value + if param == "temperature": + optional_params["temperature"] = value + if param == "seed": + optional_params["seed"] = value + if param == "top_p": + optional_params["top_p"] = value + if param == "frequency_penalty": + optional_params["repeat_penalty"] = value + if param == "stop": + optional_params["stop"] = value + if ( + param == "response_format" + and isinstance(value, dict) + and value.get("type") == "json_object" + ): + optional_params["format"] = "json" + if ( + param == "response_format" + and isinstance(value, dict) + and value.get("type") == "json_schema" + ): + if value.get("json_schema") and value["json_schema"].get("schema"): + optional_params["format"] = value["json_schema"]["schema"] + ### FUNCTION CALLING LOGIC ### + if param == "tools": + ## CHECK IF MODEL SUPPORTS TOOL CALLING ## + try: + model_info = litellm.get_model_info( + model=model, custom_llm_provider="ollama" + ) + if model_info.get("supports_function_calling") is True: + optional_params["tools"] = value + else: + raise Exception + except Exception: + optional_params["format"] = "json" + litellm.add_function_to_prompt = ( + True # so that main.py adds the function call to the prompt + ) + optional_params["functions_unsupported_model"] = value + + if len(optional_params["functions_unsupported_model"]) == 1: + optional_params["function_name"] = optional_params[ + "functions_unsupported_model" + ][0]["function"]["name"] + + if param == "functions": + ## CHECK IF MODEL SUPPORTS TOOL CALLING ## + try: + model_info = litellm.get_model_info( + model=model, custom_llm_provider="ollama" + ) + if model_info.get("supports_function_calling") is True: + optional_params["tools"] = value + else: + raise Exception + except Exception: + optional_params["format"] = "json" + litellm.add_function_to_prompt = ( + True # so that main.py adds the function call to the prompt + ) + optional_params[ + "functions_unsupported_model" + ] = non_default_params.get("functions") + non_default_params.pop("tool_choice", None) # causes ollama requests to hang + non_default_params.pop("functions", None) # causes ollama requests to hang + return optional_params + + def validate_environment( + self, + headers: dict, + model: str, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> dict: + return headers + + def get_complete_url( + self, + api_base: Optional[str], + api_key: Optional[str], + model: str, + optional_params: dict, + litellm_params: dict, + stream: Optional[bool] = None, + ) -> str: + """ + OPTIONAL + + Get the complete url for the request + + Some providers need `model` in `api_base` + """ + if api_base is None: + api_base = "http://localhost:11434" + if api_base.endswith("/api/chat"): + url = api_base + else: + url = f"{api_base}/api/chat" + + return url + + def transform_request( + self, + model: str, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + headers: dict, + ) -> dict: + stream = optional_params.pop("stream", False) + format = optional_params.pop("format", None) + keep_alive = optional_params.pop("keep_alive", None) + function_name = optional_params.pop("function_name", None) + litellm_params["function_name"] = function_name + tools = optional_params.pop("tools", None) + + new_messages = [] + for m in messages: + if isinstance( + m, BaseModel + ): # avoid message serialization issues - https://github.com/BerriAI/litellm/issues/5319 + m = m.model_dump(exclude_none=True) + tool_calls = m.get("tool_calls") + if tool_calls is not None and isinstance(tool_calls, list): + new_tools: List[OllamaToolCall] = [] + for tool in tool_calls: + typed_tool = ChatCompletionAssistantToolCall(**tool) # type: ignore + if typed_tool["type"] == "function": + arguments = {} + if "arguments" in typed_tool["function"]: + arguments = json.loads(typed_tool["function"]["arguments"]) + ollama_tool_call = OllamaToolCall( + function=OllamaToolCallFunction( + name=typed_tool["function"].get("name") or "", + arguments=arguments, + ) + ) + new_tools.append(ollama_tool_call) + cast(dict, m)["tool_calls"] = new_tools + new_messages.append(m) + + data = { + "model": model, + "messages": new_messages, + "options": optional_params, + "stream": stream, + } + if format is not None: + data["format"] = format + if tools is not None: + data["tools"] = tools + if keep_alive is not None: + data["keep_alive"] = keep_alive + + return data + + def transform_response( + self, + model: str, + raw_response: Response, + model_response: ModelResponse, + logging_obj: LiteLLMLoggingObj, + request_data: dict, + messages: List[AllMessageValues], + optional_params: dict, + litellm_params: dict, + encoding: str, + api_key: Optional[str] = None, + json_mode: Optional[bool] = None, + ) -> ModelResponse: + ## LOGGING + logging_obj.post_call( + input=messages, + api_key="", + original_response=raw_response.text, + additional_args={ + "headers": None, + "api_base": litellm_params.get("api_base"), + }, + ) + + response_json = raw_response.json() + + ## RESPONSE OBJECT + model_response.choices[0].finish_reason = "stop" + if ( + request_data.get("format", "") == "json" + and litellm_params.get("function_name") is not None + ): + function_call = json.loads(response_json["message"]["content"]) + message = litellm.Message( + content=None, + tool_calls=[ + { + "id": f"call_{str(uuid.uuid4())}", + "function": { + "name": function_call.get( + "name", litellm_params.get("function_name") + ), + "arguments": json.dumps( + function_call.get("arguments", function_call) + ), + }, + "type": "function", + } + ], + ) + model_response.choices[0].message = message # type: ignore + model_response.choices[0].finish_reason = "tool_calls" + else: + _message = litellm.Message(**response_json["message"]) + model_response.choices[0].message = _message # type: ignore + model_response.created = int(time.time()) + model_response.model = "ollama_chat/" + model + prompt_tokens = response_json.get("prompt_eval_count", litellm.token_counter(messages=messages)) # type: ignore + completion_tokens = response_json.get( + "eval_count", + litellm.token_counter(text=response_json["message"]["content"]), + ) + setattr( + model_response, + "usage", + litellm.Usage( + prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, + total_tokens=prompt_tokens + completion_tokens, + ), + ) + return model_response + + def get_error_class( + self, error_message: str, status_code: int, headers: Union[dict, Headers] + ) -> BaseLLMException: + return OllamaError( + status_code=status_code, message=error_message, headers=headers + ) + + def get_model_response_iterator( + self, + streaming_response: Union[Iterator[str], AsyncIterator[str], ModelResponse], + sync_stream: bool, + json_mode: Optional[bool] = False, + ): + return OllamaChatCompletionResponseIterator( + streaming_response=streaming_response, + sync_stream=sync_stream, + json_mode=json_mode, + ) + + +class OllamaChatCompletionResponseIterator(BaseModelResponseIterator): + def chunk_parser(self, chunk: dict) -> ModelResponseStream: + try: + """ + Expected chunk format: + { + "model": "llama3.1", + "created_at": "2025-05-24T02:12:05.859654Z", + "message": { + "role": "assistant", + "content": "", + "tool_calls": [{ + "function": { + "name": "get_latest_album_ratings", + "arguments": { + "artist_name": "Taylor Swift" + } + } + }] + }, + "done_reason": "stop", + "done": true, + ... + } + + Need to: + - convert 'message' to 'delta' + - return finish_reason when done is true + - return usage when done is true + + """ + from litellm.types.utils import Delta, StreamingChoices + + delta = Delta( + content=chunk["message"].get("content", ""), + tool_calls=chunk["message"].get("tool_calls"), + ) + + if chunk["done"] is True: + finish_reason = chunk.get("done_reason", "stop") + choices = [ + StreamingChoices( + delta=delta, + finish_reason=finish_reason, + ) + ] + else: + choices = [ + StreamingChoices( + delta=delta, + ) + ] + + usage = ChatCompletionUsageBlock( + prompt_tokens=chunk.get("prompt_eval_count", 0), + completion_tokens=chunk.get("eval_count", 0), + total_tokens=chunk.get("prompt_eval_count", 0) + + chunk.get("eval_count", 0), + ) + + return ModelResponseStream( + id=str(uuid.uuid4()), + object="chat.completion.chunk", + created=int(time.time()), # ollama created_at is in UTC + usage=usage, + model=chunk["model"], + choices=choices, + ) + except KeyError as e: + raise OllamaError( + message=f"KeyError: {e}, Got unexpected response from Ollama: {chunk}", + status_code=400, + headers={"Content-Type": "application/json"}, + ) + except Exception as e: + raise e diff --git a/litellm/llms/ollama_chat.py b/litellm/llms/ollama_chat.py index 22438eca08..d46e714519 100644 --- a/litellm/llms/ollama_chat.py +++ b/litellm/llms/ollama_chat.py @@ -14,7 +14,6 @@ from litellm.llms.custom_httpx.http_handler import ( HTTPHandler, get_async_httpx_client, ) -from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig from litellm.types.llms.ollama import OllamaToolCall, OllamaToolCallFunction from litellm.types.llms.openai import ChatCompletionAssistantToolCall from litellm.types.utils import ModelResponse, StreamingChoices @@ -31,190 +30,6 @@ class OllamaError(Exception): ) # Call the base class constructor with the parameters it needs -class OllamaChatConfig(OpenAIGPTConfig): - """ - Reference: https://github.com/ollama/ollama/blob/main/docs/api.md#parameters - - The class `OllamaConfig` provides the configuration for the Ollama's API interface. Below are the parameters: - - - `mirostat` (int): Enable Mirostat sampling for controlling perplexity. Default is 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0. Example usage: mirostat 0 - - - `mirostat_eta` (float): Influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. Default: 0.1. Example usage: mirostat_eta 0.1 - - - `mirostat_tau` (float): Controls the balance between coherence and diversity of the output. A lower value will result in more focused and coherent text. Default: 5.0. Example usage: mirostat_tau 5.0 - - - `num_ctx` (int): Sets the size of the context window used to generate the next token. Default: 2048. Example usage: num_ctx 4096 - - - `num_gqa` (int): The number of GQA groups in the transformer layer. Required for some models, for example it is 8 for llama2:70b. Example usage: num_gqa 1 - - - `num_gpu` (int): The number of layers to send to the GPU(s). On macOS it defaults to 1 to enable metal support, 0 to disable. Example usage: num_gpu 0 - - - `num_thread` (int): Sets the number of threads to use during computation. By default, Ollama will detect this for optimal performance. It is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Example usage: num_thread 8 - - - `repeat_last_n` (int): Sets how far back for the model to look back to prevent repetition. Default: 64, 0 = disabled, -1 = num_ctx. Example usage: repeat_last_n 64 - - - `repeat_penalty` (float): Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. Default: 1.1. Example usage: repeat_penalty 1.1 - - - `temperature` (float): The temperature of the model. Increasing the temperature will make the model answer more creatively. Default: 0.8. Example usage: temperature 0.7 - - - `seed` (int): Sets the random number seed to use for generation. Setting this to a specific number will make the model generate the same text for the same prompt. Example usage: seed 42 - - - `stop` (string[]): Sets the stop sequences to use. Example usage: stop "AI assistant:" - - - `tfs_z` (float): Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting. Default: 1. Example usage: tfs_z 1 - - - `num_predict` (int): Maximum number of tokens to predict when generating text. Default: 128, -1 = infinite generation, -2 = fill context. Example usage: num_predict 42 - - - `top_k` (int): Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. Default: 40. Example usage: top_k 40 - - - `top_p` (float): Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. Default: 0.9. Example usage: top_p 0.9 - - - `system` (string): system prompt for model (overrides what is defined in the Modelfile) - - - `template` (string): the full prompt or prompt template (overrides what is defined in the Modelfile) - """ - - mirostat: Optional[int] = None - mirostat_eta: Optional[float] = None - mirostat_tau: Optional[float] = None - num_ctx: Optional[int] = None - num_gqa: Optional[int] = None - num_thread: Optional[int] = None - repeat_last_n: Optional[int] = None - repeat_penalty: Optional[float] = None - seed: Optional[int] = None - tfs_z: Optional[float] = None - num_predict: Optional[int] = None - top_k: Optional[int] = None - system: Optional[str] = None - template: Optional[str] = None - - def __init__( - self, - mirostat: Optional[int] = None, - mirostat_eta: Optional[float] = None, - mirostat_tau: Optional[float] = None, - num_ctx: Optional[int] = None, - num_gqa: Optional[int] = None, - num_thread: Optional[int] = None, - repeat_last_n: Optional[int] = None, - repeat_penalty: Optional[float] = None, - temperature: Optional[float] = None, - seed: Optional[int] = None, - stop: Optional[list] = None, - tfs_z: Optional[float] = None, - num_predict: Optional[int] = None, - top_k: Optional[int] = None, - top_p: Optional[float] = None, - system: Optional[str] = None, - template: Optional[str] = None, - ) -> None: - locals_ = locals().copy() - for key, value in locals_.items(): - if key != "self" and value is not None: - setattr(self.__class__, key, value) - - @classmethod - def get_config(cls): - return super().get_config() - - def get_supported_openai_params(self, model: str): - return [ - "max_tokens", - "max_completion_tokens", - "stream", - "top_p", - "temperature", - "seed", - "frequency_penalty", - "stop", - "tools", - "tool_choice", - "functions", - "response_format", - ] - - def map_openai_params( - self, - non_default_params: dict, - optional_params: dict, - model: str, - drop_params: bool, - ) -> dict: - for param, value in non_default_params.items(): - if param == "max_tokens" or param == "max_completion_tokens": - optional_params["num_predict"] = value - if param == "stream": - optional_params["stream"] = value - if param == "temperature": - optional_params["temperature"] = value - if param == "seed": - optional_params["seed"] = value - if param == "top_p": - optional_params["top_p"] = value - if param == "frequency_penalty": - optional_params["repeat_penalty"] = value - if param == "stop": - optional_params["stop"] = value - if ( - param == "response_format" - and isinstance(value, dict) - and value.get("type") == "json_object" - ): - optional_params["format"] = "json" - if ( - param == "response_format" - and isinstance(value, dict) - and value.get("type") == "json_schema" - ): - if value.get("json_schema") and value["json_schema"].get("schema"): - optional_params["format"] = value["json_schema"]["schema"] - ### FUNCTION CALLING LOGIC ### - if param == "tools": - ## CHECK IF MODEL SUPPORTS TOOL CALLING ## - try: - model_info = litellm.get_model_info( - model=model, custom_llm_provider="ollama" - ) - if model_info.get("supports_function_calling") is True: - optional_params["tools"] = value - else: - raise Exception - except Exception: - optional_params["format"] = "json" - litellm.add_function_to_prompt = ( - True # so that main.py adds the function call to the prompt - ) - optional_params["functions_unsupported_model"] = value - - if len(optional_params["functions_unsupported_model"]) == 1: - optional_params["function_name"] = optional_params[ - "functions_unsupported_model" - ][0]["function"]["name"] - - if param == "functions": - ## CHECK IF MODEL SUPPORTS TOOL CALLING ## - try: - model_info = litellm.get_model_info( - model=model, custom_llm_provider="ollama" - ) - if model_info.get("supports_function_calling") is True: - optional_params["tools"] = value - else: - raise Exception - except Exception: - optional_params["format"] = "json" - litellm.add_function_to_prompt = ( - True # so that main.py adds the function call to the prompt - ) - optional_params["functions_unsupported_model"] = ( - non_default_params.get("functions") - ) - non_default_params.pop("tool_choice", None) # causes ollama requests to hang - non_default_params.pop("functions", None) # causes ollama requests to hang - return optional_params - - # ollama implementation def get_ollama_response( # noqa: PLR0915 model_response: ModelResponse, diff --git a/litellm/main.py b/litellm/main.py index 453560a6a7..a408148344 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -127,7 +127,7 @@ from .litellm_core_utils.prompt_templates.factory import ( stringify_json_tool_call_content, ) from .litellm_core_utils.streaming_chunk_builder_utils import ChunkProcessor -from .llms import baseten, maritalk, ollama_chat +from .llms import baseten from .llms.anthropic.chat import AnthropicChatCompletion from .llms.azure.audio_transcriptions import AzureAudioTranscription from .llms.azure.azure import AzureChatCompletion, _check_dynamic_azure_params @@ -2957,23 +2957,24 @@ def completion( # type: ignore # noqa: PLR0915 or os.environ.get("OLLAMA_API_KEY") or litellm.api_key ) - ## LOGGING - generator = ollama_chat.get_ollama_response( - api_base=api_base, - api_key=api_key, + + response = base_llm_http_handler.completion( model=model, + stream=stream, messages=messages, - optional_params=optional_params, - logging_obj=logging, acompletion=acompletion, + api_base=api_base, model_response=model_response, + optional_params=optional_params, + litellm_params=litellm_params, + custom_llm_provider="ollama_chat", + timeout=timeout, + headers=headers, encoding=encoding, + api_key=api_key, + logging_obj=logging, # model call logging done inside the class as we make need to modify I/O to fit aleph alpha's requirements client=client, ) - if acompletion is True or optional_params.get("stream", False) is True: - return generator - - response = generator elif custom_llm_provider == "triton": api_base = litellm.api_base or api_base diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yaml index 8b306ee82e..6358620bf8 100644 --- a/litellm/proxy/_new_secret_config.yaml +++ b/litellm/proxy/_new_secret_config.yaml @@ -4,8 +4,9 @@ model_list: model: openai/fake api_key: fake-key api_base: https://exampleopenaiendpoint-production.up.railway.app/ + litellm_settings: cache: true success_callback: ["langfuse"] failure_callback: ["langfuse"] - alerting: ["slack"] \ No newline at end of file + alerting: ["slack"] diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py index 31f8437d29..daf2112287 100644 --- a/litellm/proxy/auth/user_api_key_auth.py +++ b/litellm/proxy/auth/user_api_key_auth.py @@ -725,20 +725,6 @@ async def _user_api_key_auth_builder( # noqa: PLR0915 ) ## Check DB - if ( - isinstance(api_key, str) and valid_token is None - ): # if generated token, make sure it starts with sk-. - assert api_key.startswith( - "sk-" - ), "LiteLLM Virtual Key expected. Received={}, expected to start with 'sk-'.".format( - api_key - ) # prevent token hashes from being used - else: - verbose_logger.warning( - "litellm.proxy.proxy_server.user_api_key_auth(): Warning - Key={} is not a string.".format( - api_key - ) - ) if ( prisma_client is None @@ -752,11 +738,26 @@ async def _user_api_key_auth_builder( # noqa: PLR0915 ## check for cache hit (In-Memory Cache) _user_role = None - abbreviated_api_key = abbreviate_api_key(api_key=api_key) - if api_key.startswith("sk-"): - api_key = hash_token(token=api_key) if valid_token is None: + if isinstance( + api_key, str + ): # if generated token, make sure it starts with sk-. + assert api_key.startswith( + "sk-" + ), "LiteLLM Virtual Key expected. Received={}, expected to start with 'sk-'.".format( + api_key + ) # prevent token hashes from being used + else: + verbose_logger.warning( + "litellm.proxy.proxy_server.user_api_key_auth(): Warning - Key={} is not a string.".format( + api_key + ) + ) + abbreviated_api_key = abbreviate_api_key(api_key=api_key) + if api_key.startswith("sk-"): + api_key = hash_token(token=api_key) + try: valid_token = await get_key_object( hashed_token=api_key, diff --git a/litellm/proxy/hooks/__init__.py b/litellm/proxy/hooks/__init__.py index 1287513982..aef3cc0fcc 100644 --- a/litellm/proxy/hooks/__init__.py +++ b/litellm/proxy/hooks/__init__.py @@ -23,7 +23,7 @@ PROXY_HOOKS = { ## FEATURE FLAG HOOKS ## if os.getenv("EXPERIMENTAL_MULTI_INSTANCE_RATE_LIMITING", "false").lower() == "true": - PROXY_HOOKS["max_parallel_requests"] = _PROXY_MaxParallelRequestsHandler_v2 + PROXY_HOOKS["parallel_request_limiter"] = _PROXY_MaxParallelRequestsHandler_v2 ### update PROXY_HOOKS with ENTERPRISE_PROXY_HOOKS ### diff --git a/litellm/router_strategy/base_routing_strategy.py b/litellm/router_strategy/base_routing_strategy.py index 1c1909c9e3..37e2aded64 100644 --- a/litellm/router_strategy/base_routing_strategy.py +++ b/litellm/router_strategy/base_routing_strategy.py @@ -124,10 +124,10 @@ class BaseRoutingStrategy(ABC): if not self.dual_cache.redis_cache: return # Redis is not initialized - verbose_router_logger.debug( - "Pushing Redis Increment Pipeline for queue: %s", - self.redis_increment_operation_queue, - ) + # verbose_router_logger.debug( + # "Pushing Redis Increment Pipeline for queue: %s", + # self.redis_increment_operation_queue, + # ) if len(self.redis_increment_operation_queue) > 0: await self.dual_cache.redis_cache.async_increment_pipeline( increment_list=self.redis_increment_operation_queue, @@ -207,9 +207,9 @@ class BaseRoutingStrategy(ABC): await self.dual_cache.in_memory_cache.async_set_cache( key=key, value=float(value) ) - verbose_router_logger.debug( - f"Updated in-memory cache for {key}: {value}" - ) + # verbose_router_logger.debug( + # f"Updated in-memory cache for {key}: {value}" + # ) self.reset_in_memory_keys_to_update() except Exception as e: diff --git a/tests/code_coverage_tests/router_code_coverage.py b/tests/code_coverage_tests/router_code_coverage.py index 8b4622d9b8..d700e56a06 100644 --- a/tests/code_coverage_tests/router_code_coverage.py +++ b/tests/code_coverage_tests/router_code_coverage.py @@ -31,7 +31,7 @@ def get_all_functions_called_in_tests(base_dir): specifically in files containing the word 'router'. """ called_functions = set() - test_dirs = ["local_testing", "router_unit_tests", "litellm"] + test_dirs = ["local_testing", "router_unit_tests", "test_litellm"] for test_dir in test_dirs: dir_path = os.path.join(base_dir, test_dir) diff --git a/tests/test_fallbacks.py b/tests/test_fallbacks.py index aab8e985bd..bc9aa4c64c 100644 --- a/tests/test_fallbacks.py +++ b/tests/test_fallbacks.py @@ -3,7 +3,7 @@ import pytest import asyncio import aiohttp -from large_text import text +from tests.large_text import text import time from typing import Optional diff --git a/tests/test_litellm/llms/ollama/test_ollama_chat_transformation.py b/tests/test_litellm/llms/ollama/test_ollama_chat_transformation.py index 6be2a96d37..84d7d26dce 100644 --- a/tests/test_litellm/llms/ollama/test_ollama_chat_transformation.py +++ b/tests/test_litellm/llms/ollama/test_ollama_chat_transformation.py @@ -9,7 +9,7 @@ sys.path.insert( 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../..")) ) -from litellm.llms.ollama_chat import OllamaChatConfig +from litellm.llms.ollama.chat.transformation import OllamaChatConfig from litellm.utils import get_optional_params diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py index eccd5b798d..0d57da0ed2 100644 --- a/tests/test_litellm/test_utils.py +++ b/tests/test_litellm/test_utils.py @@ -85,7 +85,7 @@ def test_all_model_configs(): drop_params=False, ) == {"max_tokens": 10} - from litellm.llms.ollama_chat import OllamaChatConfig + from litellm.llms.ollama.chat.transformation import OllamaChatConfig assert "max_completion_tokens" in OllamaChatConfig().get_supported_openai_params( model="llama3" diff --git a/tests/test_models.py b/tests/test_models.py index eaad07052c..7d2fcce879 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -451,7 +451,7 @@ async def test_get_personal_models_for_user(): """ Test /models endpoint with team """ - from test_users import new_user + from tests.test_users import new_user async with aiohttp.ClientSession() as session: # Creat a user user_data = await new_user(session=session, i=0, models=["gpt-3.5-turbo"]) @@ -504,8 +504,8 @@ async def test_team_model_e2e(): - update model - delete model """ - from test_users import new_user - from test_team import new_team + from tests.test_users import new_user + from tests.test_team import new_team import uuid async with aiohttp.ClientSession() as session: # Creat a user