MCPcopy Create free account
hub / github.com/Roy3838/Observer / handle_request

Method handle_request

api/gemini_pro_handler.py:71–229  ·  view source on GitHub ↗

Process a /v1/chat/completions request asynchronously for Gemini Pro models. Returns either dict (non-streaming) or StreamingResponse (streaming).

(self, request_data: dict)

Source from the content-addressed store, hash-verified

69 logger.info("GeminiProAPIHandler registered models: %s", [m["name"] for m in self.models])
70
71 async def handle_request(self, request_data: dict):
72 """
73 Process a /v1/chat/completions request asynchronously for Gemini Pro models.
74 Returns either dict (non-streaming) or StreamingResponse (streaming).
75 """
76 if not self.api_key:
77 raise ConfigError("GEMINI_PRO_API_KEY is not configured on the server.")
78
79 # --- Request Data Validation and Processing ---
80 model_name = request_data.get("model")
81 if not model_name:
82 raise ValueError("Request data must include a 'model' field.")
83
84 # Map display name to actual Gemini model ID
85 if model_name in self.model_map:
86 target_model = self.model_map[model_name]["model_id"]
87 else:
88 target_model = model_name # Fallback to direct name
89
90 messages = request_data.get("messages", [])
91 if not messages:
92 raise ValueError("Request body must contain a 'messages' array")
93
94 # Check for streaming
95 if request_data.get("stream", False):
96 return StreamingResponse(
97 self._stream_gemini_response(request_data, target_model),
98 media_type="text/event-stream"
99 )
100
101 # --- Convert OpenAI format messages to Gemini format ---
102 system_instruction, contents = self._convert_messages_to_gemini_format(messages)
103
104 if not contents:
105 raise ValueError("No valid content found to send to Gemini.")
106
107 # --- Prepare Gemini API Call ---
108 gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/{target_model}:generateContent"
109
110 # Build payload with converted contents
111 payload = {"contents": contents}
112
113 # Add system_instruction if present
114 if system_instruction:
115 payload["system_instruction"] = system_instruction
116
117 # Add generationConfig if needed from request_data (temperature, max_tokens etc.)
118 generation_config = {}
119 if "temperature" in request_data: generation_config["temperature"] = request_data["temperature"]
120 if "max_tokens" in request_data: generation_config["maxOutputTokens"] = request_data["max_tokens"]
121 if generation_config: payload["generationConfig"] = generation_config
122
123 headers = {
124 "Content-Type": "application/json",
125 "x-goog-api-key": self.api_key,
126 "User-Agent": "ObserverAI-FastAPI-Client/1.0"
127 }
128

Callers

nothing calls this directly

Calls 8

ConfigErrorClass · 0.90
get_http_clientFunction · 0.90
BackendAPIErrorClass · 0.90
HandlerErrorClass · 0.90
infoMethod · 0.80
errorMethod · 0.80

Tested by

no test coverage detected