The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(vertex_httpx.py): support functions param for gemini google ai studio + vertex ai
Krrish Dholakiad13d2e8a623b
diff --git a/litellm/llms/vertex_httpx.py b/litellm/llms/vertex_httpx.pyindex faecdd79026..1e842ce57ec 100644--- a/litellm/llms/vertex_httpx.py+++ b/litellm/llms/vertex_httpx.py@@ -30,6 +30,7 @@ from litellm.types.llms.openai import (ChatCompletionResponseMessage,ChatCompletionToolCallChunk,ChatCompletionToolCallFunctionChunk,+ ChatCompletionToolParamFunctionChunk,ChatCompletionUsageBlock,)from litellm.types.llms.vertex_ai import (@@ -296,11 +297,50 @@ class GoogleAIStudioGeminiConfig: # key diff from VertexAI - 'frequency_penalty"stream","tools","tool_choice",+ "functions","response_format","n","stop",]+ def _map_function(self, value: List[dict]) -> List[Tools]:+ gtool_func_declarations = []+ googleSearchRetrieval: Optional[dict] = None++ for tool in value:+ openai_function_object: Optional[ChatCompletionToolParamFunctionChunk] = (+ None+ )+ if "function" in tool: # tools list+ openai_function_object = ChatCompletionToolParamFunctionChunk( # type: ignore+ **tool["function"]+ )+ elif "name" in tool: # functions list+ openai_function_object = ChatCompletionToolParamFunctionChunk(**tool) # type: ignore++ # check if grounding+ if tool.get("googleSearchRetrieval", None) is not None:+ googleSearchRetrieval = tool["googleSearchRetrieval"]+ elif openai_function_object is not None:+ gtool_func_declaration = FunctionDeclaration(+ name=openai_function_object["name"],+ description=openai_function_object.get("description", ""),+ parameters=openai_function_object.get("parameters", {}),+ )+ gtool_func_declarations.append(gtool_func_declaration)+ else:+ # assume it's a provider-specific param+ verbose_logger.warning(+ "Invalid tool={}. Use `litellm.set_verbose` or `litellm --detailed_debug` to see raw request."+ )++ _tools = Tools(+ function_declarations=gtool_func_declarations,+ )+ if googleSearchRetrieval is not None:+ _tools["googleSearchRetrieval"] = googleSearchRetrieval+ return [_tools]+def map_tool_choice_values(self, model: str, tool_choice: Union[str, dict]) -> Optional[ToolConfig]:@@ -363,26 +403,11 @@ class GoogleAIStudioGeminiConfig: # key diff from VertexAI - 'frequency_penaltyif "json_schema" in value and "schema" in value["json_schema"]: # type: ignoreoptional_params["response_mime_type"] = "application/json"optional_params["response_schema"] = value["json_schema"]["schema"] # type: ignore- if param == "tools" and isinstance(value, list):- gtool_func_declarations = []- for tool in value:- _parameters = tool.get("function", {}).get("parameters", {})- _properties = _parameters.get("properties", {})- if isinstance(_properties, dict):- for _, _property in _properties.items():- if "enum" in _property and "format" not in _property:- _property["format"] = "enum"-- gtool_func_declaration = FunctionDeclaration(- name=tool["function"]["name"],- description=tool["function"].get("description", ""),- )- if len(_parameters.keys()) > 0:- gtool_func_declaration["parameters"] = _parameters- gtool_func_declarations.append(gtool_func_declaration)- optional_params["tools"] = [- Tools(function_declarations=gtool_func_declarations)- ]+ if (param == "tools" or param == "functions") and isinstance(value, list):+ optional_params["tools"] = self._map_function(value=value)+ optional_params["litellm_param_is_function_call"] = (+ True if param == "functions" else False+ )if param == "tool_choice" and (isinstance(value, str) or isinstance(value, dict)):@@ -506,6 +531,7 @@ class VertexGeminiConfig:"max_tokens","stream","tools",+ "functions","tool_choice","response_format","n",@@ -541,6 +567,44 @@ class VertexGeminiConfig:status_code=400,)+ def _map_function(self, value: List[dict]) -> List[Tools]:+ gtool_func_declarations = []+ googleSearchRetrieval: Optional[dict] = None++ for tool in value:+ openai_function_object: Optional[ChatCompletionToolParamFunctionChunk] = (+ None+ )+ if "function" in tool: # tools list+ openai_function_object = ChatCompletionToolParamFunctionChunk( # type: ignore+ **tool["function"]+ )+ elif "name" in tool: # functions list+ openai_function_object = ChatCompletionToolParamFunctionChunk(**tool) # type: ignore++ # check if grounding+ if tool.get("googleSearchRetrieval", None) is not None:+ googleSearchRetrieval = tool["googleSearchRetrieval"]+ elif openai_function_object is not None:+ gtool_func_declaration = FunctionDeclaration(+ name=openai_function_object["name"],+ description=openai_function_object.get("description", ""),+ parameters=openai_function_object.get("parameters", {}),+ )+ gtool_func_declarations.append(gtool_func_declaration)+ else:+ # assume it's a provider-specific param+ verbose_logger.warning(+ "Invalid tool={}. Use `litellm.set_verbose` or `litellm --detailed_debug` to see raw request."+ )++ _tools = Tools(+ function_declarations=gtool_func_declarations,+ )+ if googleSearchRetrieval is not None:+ _tools["googleSearchRetrieval"] = googleSearchRetrieval+ return [_tools]+def map_openai_params(self,model: str,@@ -582,33 +646,11 @@ class VertexGeminiConfig:optional_params["frequency_penalty"] = valueif param == "presence_penalty":optional_params["presence_penalty"] = value- if param == "tools" and isinstance(value, list):- gtool_func_declarations = []- googleSearchRetrieval: Optional[dict] = None- provider_specific_tools: List[dict] = []- for tool in value:- # check if grounding- try:- gtool_func_declaration = FunctionDeclaration(- name=tool["function"]["name"],- description=tool["function"].get("description", ""),- parameters=tool["function"].get("parameters", {}),- )- gtool_func_declarations.append(gtool_func_declaration)- except KeyError:- if tool.get("googleSearchRetrieval", None) is not None:- googleSearchRetrieval = tool["googleSearchRetrieval"]- else:- # assume it's a provider-specific param- verbose_logger.warning(- "Got KeyError parsing tool={}. Assuming it's a provider-specific param. Use `litellm.set_verbose` or `litellm --detailed_debug` to see raw request."- )- _tools = Tools(- function_declarations=gtool_func_declarations,+ if (param == "tools" or param == "functions") and isinstance(value, list):+ optional_params["tools"] = self._map_function(value=value)+ optional_params["is_function_call"] = (+ True if param == "functions" else False)- if googleSearchRetrieval is not None:- _tools["googleSearchRetrieval"] = googleSearchRetrieval- optional_params["tools"] = [_tools] + provider_specific_toolsif param == "tool_choice" and (isinstance(value, str) or isinstance(value, dict)):@@ -780,6 +822,7 @@ class VertexLLM(BaseLLM):model_response: ModelResponse,logging_obj: litellm.litellm_core_utils.litellm_logging.Logging,optional_params: dict,+ litellm_params: dict,api_key: str,data: Union[dict, str],messages: List,@@ -796,7 +839,6 @@ class VertexLLM(BaseLLM):)print_verbose(f"raw model_response: {response.text}")-## RESPONSE OBJECTtry:completion_response = GenerateContentResponseBody(**response.json()) # type: ignore@@ -904,6 +946,7 @@ class VertexLLM(BaseLLM):chat_completion_message = {"role": "assistant"}content_str = ""tools: List[ChatCompletionToolCallChunk] = []+ functions: Optional[ChatCompletionToolCallFunctionChunk] = Nonefor idx, candidate in enumerate(completion_response["candidates"]):if "content" not in candidate:continue@@ -926,18 +969,25 @@ class VertexLLM(BaseLLM):candidate["content"]["parts"][0]["functionCall"]["args"]),)- _tool_response_chunk = ChatCompletionToolCallChunk(- id=f"call_{str(uuid.uuid4())}",- type="function",- function=_function_chunk,- index=candidate.get("index", idx),- )- tools.append(_tool_response_chunk)+ if litellm_params.get("litellm_param_is_function_call") is True:+ functions = _function_chunk+ else:+ _tool_response_chunk = ChatCompletionToolCallChunk(+ id=f"call_{str(uuid.uuid4())}",+ type="function",+ function=_function_chunk,+ index=candidate.get("index", idx),+ )+ tools.append(_tool_response_chunk)chat_completion_message["content"] = (content_str if len(content_str) > 0 else None)- chat_completion_message["tool_calls"] = tools+ if len(tools) > 0:+ chat_completion_message["tool_calls"] = tools++ if functions is not None:+ chat_completion_message["function_call"] = functionschoice = litellm.Choices(finish_reason=candidate.get("finishReason", "stop"),@@ -1226,7 +1276,7 @@ class VertexLLM(BaseLLM):logging_obj,stream,optional_params: dict,- litellm_params=None,+ litellm_params: dict,logger_fn=None,headers={},client: Optional[AsyncHTTPHandler] = None,@@ -1260,6 +1310,7 @@ class VertexLLM(BaseLLM):messages=messages,print_verbose=print_verbose,optional_params=optional_params,+ litellm_params=litellm_params,encoding=encoding,)@@ -1281,7 +1332,7 @@ class VertexLLM(BaseLLM):vertex_location: Optional[str],vertex_credentials: Optional[str],gemini_api_key: Optional[str],- litellm_params=None,+ litellm_params: dict,logger_fn=None,extra_headers: Optional[dict] = None,client: Optional[Union[AsyncHTTPHandler, HTTPHandler]] = None,@@ -1293,7 +1344,6 @@ class VertexLLM(BaseLLM):optional_params=optional_params)- print_verbose("Incoming Vertex Args - {}".format(locals()))auth_header, url = self._get_token_and_url(model=model,gemini_api_key=gemini_api_key,@@ -1305,7 +1355,6 @@ class VertexLLM(BaseLLM):api_base=api_base,should_use_v1beta1_features=should_use_v1beta1_features,)- print_verbose("Updated URL - {}".format(url))## TRANSFORMATION ##try:@@ -1349,6 +1398,18 @@ class VertexLLM(BaseLLM):)optional_params.pop("response_schema")+ # Check for any 'litellm_param_*' set during optional param mapping++ remove_keys = []+ for k, v in optional_params.items():+ if k.startswith("litellm_param_"):+ litellm_params.update({k: v})+ remove_keys.append(k)++ optional_params = {+ k: v for k, v in optional_params.items() if k not in remove_keys+ }+try:content = _gemini_convert_messages_with_history(messages=messages)tools: Optional[Tools] = optional_params.pop("tools", None)@@ -1482,6 +1543,7 @@ class VertexLLM(BaseLLM):model_response=model_response,logging_obj=logging_obj,optional_params=optional_params,+ litellm_params=litellm_params,api_key="",data=data, # type: ignoremessages=messages,diff --git a/litellm/tests/test_completion.py b/litellm/tests/test_completion.pyindex 0e96f056bde..d5179da7a93 100644--- a/litellm/tests/test_completion.py+++ b/litellm/tests/test_completion.py@@ -2691,8 +2691,61 @@ def test_completion_hf_model_no_provider():# test_completion_hf_model_no_provider()[email protected](reason="anyscale stopped serving public api endpoints")-def test_completion_anyscale_with_functions():+def gemini_mock_post(*args, **kwargs):+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.headers = {"Content-Type": "application/json"}+ mock_response.json = MagicMock(+ return_value={+ "candidates": [+ {+ "content": {+ "parts": [+ {+ "functionCall": {+ "name": "get_current_weather",+ "args": {"location": "Boston, MA"},+ }+ }+ ],+ "role": "model",+ },+ "finishReason": "STOP",+ "index": 0,+ "safetyRatings": [+ {+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",+ "probability": "NEGLIGIBLE",+ },+ {+ "category": "HARM_CATEGORY_HARASSMENT",+ "probability": "NEGLIGIBLE",+ },+ {+ "category": "HARM_CATEGORY_HATE_SPEECH",+ "probability": "NEGLIGIBLE",+ },+ {+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",+ "probability": "NEGLIGIBLE",+ },+ ],+ }+ ],+ "usageMetadata": {+ "promptTokenCount": 86,+ "candidatesTokenCount": 19,+ "totalTokenCount": 105,+ },+ }+ )++ return mock_response+++async def test_completion_functions_param():+ litellm.set_verbose = Truefunction1 = [{"name": "get_current_weather",@@ -2711,18 +2764,33 @@ def test_completion_anyscale_with_functions():}]try:+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler+messages = [{"role": "user", "content": "What is the weather like in Boston?"}]- response = completion(- model="anyscale/mistralai/Mistral-7B-Instruct-v0.1",- messages=messages,- functions=function1,- )- # Add any assertions here to check the response- print(response)- cost = litellm.completion_cost(completion_response=response)- print("cost to make anyscale completion=", cost)- assert cost > 0.0+ client = AsyncHTTPHandler(concurrent_limit=1)++ with patch.object(client, "post", side_effect=gemini_mock_post) as mock_client:+ response: litellm.ModelResponse = await litellm.acompletion(+ model="gemini/gemini-1.5-pro",+ messages=messages,+ functions=function1,+ client=client,+ )+ print(response)+ # Add any assertions here to check the response+ mock_client.assert_called()+ print(f"mock_client.call_args.kwargs: {mock_client.call_args.kwargs}")+ assert "tools" in mock_client.call_args.kwargs["json"]+ assert (+ "litellm_param_is_function_call"+ not in mock_client.call_args.kwargs["json"]+ )+ assert (+ "litellm_param_is_function_call"+ not in mock_client.call_args.kwargs["json"]["generationConfig"]+ )+ assert response.choices[0].message.function_call is not Noneexcept Exception as e:pytest.fail(f"Error occurred: {e}")diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.pyindex 5d2c416f9cd..98ce3ae78cc 100644--- a/litellm/types/llms/openai.py+++ b/litellm/types/llms/openai.py@@ -448,6 +448,7 @@ class ChatCompletionResponseMessage(TypedDict, total=False):content: Optional[str]tool_calls: List[ChatCompletionToolCallChunk]role: Literal["assistant"]+ function_call: ChatCompletionToolCallFunctionChunkclass ChatCompletionUsageBlock(TypedDict):diff --git a/litellm/types/llms/vertex_ai.py b/litellm/types/llms/vertex_ai.pyindex 5586d4861c2..74acd4fec44 100644--- a/litellm/types/llms/vertex_ai.py+++ b/litellm/types/llms/vertex_ai.py@@ -90,7 +90,7 @@ class Schema(TypedDict, total=False):class FunctionDeclaration(TypedDict, total=False):name: Required[str]description: str- parameters: Schema+ parameters: Union[Schema, dict]response: Schema