|
| 1 | +from typing import Any, Dict, Optional |
| 2 | + |
| 3 | +import structlog |
| 4 | +from litellm import ChatCompletionRequest |
| 5 | + |
| 6 | +from codegate.providers.litellmshim import sse_stream_generator |
| 7 | +from codegate.providers.litellmshim.adapter import ( |
| 8 | + BaseAdapter, |
| 9 | + LiteLLMAdapterInputNormalizer, |
| 10 | + LiteLLMAdapterOutputNormalizer, |
| 11 | +) |
| 12 | + |
| 13 | +logger = structlog.get_logger("codegate") |
| 14 | + |
| 15 | + |
| 16 | +class GeminiAdapter(BaseAdapter): |
| 17 | + """ |
| 18 | + Adapter for Gemini API to translate between Gemini's format and OpenAI's format. |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self) -> None: |
| 22 | + super().__init__(sse_stream_generator) |
| 23 | + |
| 24 | + def translate_completion_input_params(self, kwargs) -> Optional[ChatCompletionRequest]: |
| 25 | + """ |
| 26 | + Translate Gemini API parameters to OpenAI format. |
| 27 | +
|
| 28 | + Gemini API uses a similar format to OpenAI, but with some differences: |
| 29 | + - 'contents' instead of 'messages' |
| 30 | + - Different role names |
| 31 | + - Different parameter names for temperature, etc. |
| 32 | + """ |
| 33 | + # Make a copy to avoid modifying the original |
| 34 | + translated_params = dict(kwargs) |
| 35 | + |
| 36 | + # Handle Gemini-specific parameters |
| 37 | + if "contents" in translated_params: |
| 38 | + # Convert Gemini 'contents' to OpenAI 'messages' |
| 39 | + contents = translated_params.pop("contents") |
| 40 | + messages = [] |
| 41 | + |
| 42 | + for content in contents: |
| 43 | + role = content.get("role", "user") |
| 44 | + # Map Gemini roles to OpenAI roles |
| 45 | + if role == "model": |
| 46 | + role = "assistant" |
| 47 | + |
| 48 | + message = { |
| 49 | + "role": role, |
| 50 | + "content": content.get("parts", [{"text": ""}])[0].get("text", ""), |
| 51 | + } |
| 52 | + messages.append(message) |
| 53 | + |
| 54 | + translated_params["messages"] = messages |
| 55 | + |
| 56 | + # Map other parameters |
| 57 | + if "temperature" in translated_params: |
| 58 | + # Temperature is the same in both APIs |
| 59 | + pass |
| 60 | + |
| 61 | + if "topP" in translated_params: |
| 62 | + translated_params["top_p"] = translated_params.pop("topP") |
| 63 | + |
| 64 | + if "topK" in translated_params: |
| 65 | + translated_params["top_k"] = translated_params.pop("topK") |
| 66 | + |
| 67 | + if "maxOutputTokens" in translated_params: |
| 68 | + translated_params["max_tokens"] = translated_params.pop("maxOutputTokens") |
| 69 | + |
| 70 | + # Check if we're using the OpenAI-compatible endpoint |
| 71 | + is_openai_compatible = False |
| 72 | + if ( |
| 73 | + "_is_openai_compatible" in translated_params |
| 74 | + and translated_params["_is_openai_compatible"] |
| 75 | + ): |
| 76 | + is_openai_compatible = True |
| 77 | + # Remove the custom field to avoid sending it to the API |
| 78 | + translated_params.pop("_is_openai_compatible") |
| 79 | + elif ( |
| 80 | + "base_url" in translated_params |
| 81 | + and translated_params["base_url"] |
| 82 | + and "v1beta/openai" in translated_params["base_url"] |
| 83 | + ): |
| 84 | + is_openai_compatible = True |
| 85 | + |
| 86 | + # Apply the appropriate prefix based on the endpoint |
| 87 | + if "model" in translated_params: |
| 88 | + model_in_request = translated_params["model"] |
| 89 | + if is_openai_compatible: |
| 90 | + # For OpenAI-compatible endpoint, use 'openai/' prefix |
| 91 | + if not model_in_request.startswith("openai/"): |
| 92 | + translated_params["model"] = f"openai/{model_in_request}" |
| 93 | + logger.debug( |
| 94 | + "Using OpenAI-compatible endpoint, prefixed model name with 'openai/': %s", |
| 95 | + translated_params["model"], |
| 96 | + ) |
| 97 | + else: |
| 98 | + # For native Gemini API, use 'gemini/' prefix |
| 99 | + if not model_in_request.startswith("gemini/"): |
| 100 | + translated_params["model"] = f"gemini/{model_in_request}" |
| 101 | + logger.debug( |
| 102 | + "Using native Gemini API, prefixed model name with 'gemini/': %s", |
| 103 | + translated_params["model"], |
| 104 | + ) |
| 105 | + |
| 106 | + return ChatCompletionRequest(**translated_params) |
| 107 | + |
| 108 | + def translate_completion_output_params(self, response: Any) -> Dict: |
| 109 | + """ |
| 110 | + Translate OpenAI format response to Gemini format. |
| 111 | + """ |
| 112 | + # For non-streaming responses, we can just return the response as is |
| 113 | + # LiteLLM should handle the conversion |
| 114 | + return response |
| 115 | + |
| 116 | + def translate_completion_output_params_streaming(self, completion_stream: Any) -> Any: |
| 117 | + """ |
| 118 | + Translate streaming response from OpenAI format to Gemini format. |
| 119 | + """ |
| 120 | + # For streaming, we can just return the stream as is |
| 121 | + # The stream generator will handle the conversion |
| 122 | + return completion_stream |
| 123 | + |
| 124 | + |
| 125 | +class GeminiInputNormalizer(LiteLLMAdapterInputNormalizer): |
| 126 | + """ |
| 127 | + Normalizer for Gemini API input. |
| 128 | + """ |
| 129 | + |
| 130 | + def __init__(self): |
| 131 | + self.adapter = GeminiAdapter() |
| 132 | + super().__init__(self.adapter) |
| 133 | + |
| 134 | + |
| 135 | +class GeminiOutputNormalizer(LiteLLMAdapterOutputNormalizer): |
| 136 | + """ |
| 137 | + Normalizer for Gemini API output. |
| 138 | + """ |
| 139 | + |
| 140 | + def __init__(self): |
| 141 | + super().__init__(GeminiAdapter()) |
0 commit comments