Spaces:
Running
Running
Commit
·
8b7abe5
1
Parent(s):
e0b9c59
huggingface support
Browse files- Dockerfile +2 -1
- README.md +107 -83
- app/main.py +35 -18
- docker-compose.yml +2 -1
Dockerfile
CHANGED
@@ -16,4 +16,5 @@ RUN mkdir -p /app/credentials
|
|
16 |
EXPOSE 8050
|
17 |
|
18 |
# Command to run the application
|
19 |
-
|
|
|
|
16 |
EXPOSE 8050
|
17 |
|
18 |
# Command to run the application
|
19 |
+
# Use the default Hugging Face port 7860
|
20 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
@@ -1,85 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# OpenAI to Gemini Adapter
|
2 |
|
3 |
-
This service provides an OpenAI-compatible API that translates requests to Google's Vertex AI Gemini models.
|
4 |
|
5 |
## Features
|
6 |
|
7 |
-
-
|
8 |
-
-
|
9 |
-
-
|
10 |
-
-
|
|
|
11 |
|
12 |
-
##
|
13 |
|
14 |
-
|
15 |
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
|
20 |
|
21 |
-
|
22 |
|
23 |
-
|
24 |
-
```
|
25 |
-
mkdir -p credentials
|
26 |
-
```
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
# Example with multiple credential files
|
31 |
-
cp /path/to/your/service-account1.json credentials/service-account1.json
|
32 |
-
cp /path/to/your/service-account2.json credentials/service-account2.json
|
33 |
-
cp /path/to/your/service-account3.json credentials/service-account3.json
|
34 |
-
```
|
35 |
|
36 |
-
|
37 |
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
|
44 |
|
45 |
Start the service using Docker Compose:
|
46 |
|
47 |
-
```
|
48 |
docker-compose up -d
|
49 |
```
|
50 |
|
51 |
-
The service will be available at http://localhost:8050.
|
52 |
|
53 |
## API Usage
|
54 |
|
55 |
The service implements OpenAI-compatible endpoints:
|
56 |
|
57 |
-
-
|
58 |
-
-
|
59 |
-
-
|
60 |
|
61 |
All endpoints require authentication using an API key in the Authorization header.
|
62 |
|
63 |
### Authentication
|
64 |
|
65 |
-
The service requires an API key for authentication.
|
66 |
|
67 |
-
To authenticate, include the API key in the Authorization header using the Bearer token format:
|
68 |
|
69 |
```
|
70 |
-
Authorization: Bearer
|
71 |
```
|
72 |
|
73 |
-
|
74 |
|
75 |
### Example Requests
|
76 |
|
|
|
|
|
77 |
#### Basic Request
|
78 |
|
79 |
```bash
|
80 |
-
curl -X POST
|
81 |
-H "Content-Type: application/json" \
|
82 |
-
-H "Authorization: Bearer
|
83 |
-d '{
|
84 |
"model": "gemini-1.5-pro",
|
85 |
"messages": [
|
@@ -93,9 +109,9 @@ curl -X POST http://localhost:8050/v1/chat/completions \
|
|
93 |
#### Grounded Search Request
|
94 |
|
95 |
```bash
|
96 |
-
curl -X POST
|
97 |
-H "Content-Type: application/json" \
|
98 |
-
-H "Authorization: Bearer
|
99 |
-d '{
|
100 |
"model": "gemini-2.5-pro-exp-03-25-search",
|
101 |
"messages": [
|
@@ -110,70 +126,78 @@ curl -X POST http://localhost:8050/v1/chat/completions \
|
|
110 |
|
111 |
The API supports the following Vertex AI Gemini models:
|
112 |
|
113 |
-
| Model ID
|
114 |
-
|
115 |
-
| `gemini-2.5-pro-exp-03-25`
|
116 |
| `gemini-2.5-pro-exp-03-25-search` | Gemini 2.5 Pro with Google Search grounding |
|
117 |
-
| `gemini-2.0-flash`
|
118 |
-
| `gemini-2.0-flash-search`
|
119 |
-
| `gemini-2.0-flash-lite`
|
120 |
| `gemini-2.0-flash-lite-search` | Gemini 2.0 Flash Lite with Google Search grounding |
|
121 |
-
| `gemini-2.0-pro-exp-02-05`
|
122 |
-
| `gemini-1.5-flash`
|
123 |
-
| `gemini-1.5-flash-8b`
|
124 |
-
| `gemini-1.5-pro`
|
125 |
-
| `gemini-1.0-pro-002`
|
126 |
-
| `gemini-1.0-pro-vision-001`
|
127 |
-
| `gemini-embedding-exp`
|
128 |
|
129 |
-
Models with the `-search` suffix enable grounding with Google Search using dynamic retrieval
|
130 |
|
131 |
### Supported Parameters
|
132 |
|
133 |
-
The API supports
|
134 |
|
135 |
-
| OpenAI Parameter
|
136 |
-
|
137 |
-
| `temperature`
|
138 |
-
| `max_tokens`
|
139 |
-
| `top_p`
|
140 |
-
| `top_k`
|
141 |
-
| `stop`
|
142 |
-
| `presence_penalty`
|
143 |
-
| `frequency_penalty` | `frequency_penalty`
|
144 |
-
| `seed`
|
145 |
-
| `logprobs`
|
146 |
-
| `n`
|
147 |
|
148 |
-
## Credential
|
149 |
|
150 |
-
The
|
151 |
|
152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
|
154 |
```bash
|
155 |
-
curl
|
156 |
```
|
157 |
|
158 |
-
This
|
159 |
|
160 |
```json
|
161 |
{
|
162 |
"status": "ok",
|
163 |
"credentials": {
|
164 |
-
"available":
|
165 |
-
"files": [
|
166 |
-
"current_index":
|
167 |
}
|
168 |
}
|
169 |
```
|
170 |
|
171 |
-
## Environment Variables
|
172 |
-
|
173 |
-
- `CREDENTIALS_DIR`: Directory containing credential files (default: `/app/credentials`)
|
174 |
-
- `GOOGLE_APPLICATION_CREDENTIALS`: Path to a specific credential file (used as fallback)
|
175 |
-
- `API_KEY`: API key for authentication (default: `123456`)
|
176 |
-
|
177 |
## License
|
178 |
|
179 |
-
This project is licensed under the MIT License
|
|
|
1 |
+
---
|
2 |
+
title: OpenAI to Gemini Adapter
|
3 |
+
emoji: 🔄☁️
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: green
|
6 |
+
sdk: docker
|
7 |
+
app_port: 7860
|
8 |
+
---
|
9 |
+
|
10 |
# OpenAI to Gemini Adapter
|
11 |
|
12 |
+
This service provides an OpenAI-compatible API that translates requests to Google's Vertex AI Gemini models, allowing you to use Gemini models with tools expecting an OpenAI interface.
|
13 |
|
14 |
## Features
|
15 |
|
16 |
+
- OpenAI-compatible API endpoints (`/v1/chat/completions`, `/v1/models`).
|
17 |
+
- Supports Google Cloud credentials via `GOOGLE_CREDENTIALS_JSON` secret (recommended for Spaces) or local file methods.
|
18 |
+
- Supports credential rotation when using local files.
|
19 |
+
- Handles streaming and non-streaming responses.
|
20 |
+
- Configured for easy deployment on Hugging Face Spaces using Docker (port 7860) or locally via Docker Compose (port 8050).
|
21 |
|
22 |
+
## Hugging Face Spaces Deployment (Recommended)
|
23 |
|
24 |
+
This application is ready for deployment on Hugging Face Spaces using Docker.
|
25 |
|
26 |
+
1. **Create a new Space:** Go to Hugging Face Spaces and create a new Space, choosing "Docker" as the Space SDK.
|
27 |
+
2. **Upload Files:** Upload the `app/` directory, `Dockerfile`, and `app/requirements.txt` to your Space repository. You can do this via the web interface or using Git.
|
28 |
+
3. **Configure Secrets:** In your Space settings, navigate to the **Secrets** section and add the following secrets:
|
29 |
+
* `API_KEY`: Your desired API key for authenticating requests to this adapter service. If not set, it defaults to `123456`.
|
30 |
+
* `GOOGLE_CREDENTIALS_JSON`: The **entire content** of your Google Cloud service account JSON key file. Copy and paste the JSON content directly into the secret value field. **This is the required method for providing credentials on Hugging Face.**
|
31 |
+
4. **Deployment:** Hugging Face will automatically build and deploy the Docker container. The application will run on port 7860 as defined in the `Dockerfile` and this README's metadata.
|
32 |
|
33 |
+
Your adapter service will be available at the URL provided by your Hugging Face Space (e.g., `https://your-user-name-your-space-name.hf.space`).
|
34 |
|
35 |
+
## Local Docker Setup (for Development/Testing)
|
36 |
|
37 |
+
### Prerequisites
|
|
|
|
|
|
|
38 |
|
39 |
+
- Docker and Docker Compose
|
40 |
+
- Google Cloud service account credentials with Vertex AI access
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
+
### Credential Setup (Local Docker)
|
43 |
|
44 |
+
1. Create a `credentials` directory in the project root:
|
45 |
+
```bash
|
46 |
+
mkdir -p credentials
|
47 |
+
```
|
48 |
+
2. Add your service account JSON files to the `credentials` directory:
|
49 |
+
```bash
|
50 |
+
# Example with multiple credential files
|
51 |
+
cp /path/to/your/service-account1.json credentials/service-account1.json
|
52 |
+
cp /path/to/your/service-account2.json credentials/service-account2.json
|
53 |
+
```
|
54 |
+
The service will automatically detect and rotate through all `.json` files in this directory if the `GOOGLE_CREDENTIALS_JSON` environment variable is *not* set.
|
55 |
+
3. Alternatively, set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable *in your local environment or `docker-compose.yml`* to the *path* of a single credential file (used as a fallback if the other methods fail).
|
56 |
|
57 |
+
### Running Locally
|
58 |
|
59 |
Start the service using Docker Compose:
|
60 |
|
61 |
+
```bash
|
62 |
docker-compose up -d
|
63 |
```
|
64 |
|
65 |
+
The service will be available at `http://localhost:8050` (as defined in `docker-compose.yml`).
|
66 |
|
67 |
## API Usage
|
68 |
|
69 |
The service implements OpenAI-compatible endpoints:
|
70 |
|
71 |
+
- `GET /v1/models` - List available models
|
72 |
+
- `POST /v1/chat/completions` - Create a chat completion
|
73 |
+
- `GET /health` - Health check endpoint (includes credential status)
|
74 |
|
75 |
All endpoints require authentication using an API key in the Authorization header.
|
76 |
|
77 |
### Authentication
|
78 |
|
79 |
+
The service requires an API key for authentication.
|
80 |
|
81 |
+
To authenticate, include the API key in the `Authorization` header using the `Bearer` token format:
|
82 |
|
83 |
```
|
84 |
+
Authorization: Bearer YOUR_API_KEY
|
85 |
```
|
86 |
|
87 |
+
Replace `YOUR_API_KEY` with the key you configured (either via the `API_KEY` secret/environment variable or the default `123456`).
|
88 |
|
89 |
### Example Requests
|
90 |
|
91 |
+
*(Replace `YOUR_ADAPTER_URL` with your Hugging Face Space URL or `http://localhost:8050` if running locally)*
|
92 |
+
|
93 |
#### Basic Request
|
94 |
|
95 |
```bash
|
96 |
+
curl -X POST YOUR_ADAPTER_URL/v1/chat/completions \
|
97 |
-H "Content-Type: application/json" \
|
98 |
+
-H "Authorization: Bearer YOUR_API_KEY" \
|
99 |
-d '{
|
100 |
"model": "gemini-1.5-pro",
|
101 |
"messages": [
|
|
|
109 |
#### Grounded Search Request
|
110 |
|
111 |
```bash
|
112 |
+
curl -X POST YOUR_ADAPTER_URL/v1/chat/completions \
|
113 |
-H "Content-Type: application/json" \
|
114 |
+
-H "Authorization: Bearer YOUR_API_KEY" \
|
115 |
-d '{
|
116 |
"model": "gemini-2.5-pro-exp-03-25-search",
|
117 |
"messages": [
|
|
|
126 |
|
127 |
The API supports the following Vertex AI Gemini models:
|
128 |
|
129 |
+
| Model ID | Description |
|
130 |
+
| ------------------------------ | ---------------------------------------------- |
|
131 |
+
| `gemini-2.5-pro-exp-03-25` | Gemini 2.5 Pro Experimental (March 25) |
|
132 |
| `gemini-2.5-pro-exp-03-25-search` | Gemini 2.5 Pro with Google Search grounding |
|
133 |
+
| `gemini-2.0-flash` | Gemini 2.0 Flash |
|
134 |
+
| `gemini-2.0-flash-search` | Gemini 2.0 Flash with Google Search grounding |
|
135 |
+
| `gemini-2.0-flash-lite` | Gemini 2.0 Flash Lite |
|
136 |
| `gemini-2.0-flash-lite-search` | Gemini 2.0 Flash Lite with Google Search grounding |
|
137 |
+
| `gemini-2.0-pro-exp-02-05` | Gemini 2.0 Pro Experimental (February 5) |
|
138 |
+
| `gemini-1.5-flash` | Gemini 1.5 Flash |
|
139 |
+
| `gemini-1.5-flash-8b` | Gemini 1.5 Flash 8B |
|
140 |
+
| `gemini-1.5-pro` | Gemini 1.5 Pro |
|
141 |
+
| `gemini-1.0-pro-002` | Gemini 1.0 Pro |
|
142 |
+
| `gemini-1.0-pro-vision-001` | Gemini 1.0 Pro Vision |
|
143 |
+
| `gemini-embedding-exp` | Gemini Embedding Experimental |
|
144 |
|
145 |
+
Models with the `-search` suffix enable grounding with Google Search using dynamic retrieval.
|
146 |
|
147 |
### Supported Parameters
|
148 |
|
149 |
+
The API supports common OpenAI-compatible parameters, mapping them to Vertex AI where possible:
|
150 |
|
151 |
+
| OpenAI Parameter | Vertex AI Parameter | Description |
|
152 |
+
| ------------------- | --------------------- | ------------------------------------------------- |
|
153 |
+
| `temperature` | `temperature` | Controls randomness (0.0 to 1.0) |
|
154 |
+
| `max_tokens` | `max_output_tokens` | Maximum number of tokens to generate |
|
155 |
+
| `top_p` | `top_p` | Nucleus sampling parameter (0.0 to 1.0) |
|
156 |
+
| `top_k` | `top_k` | Top-k sampling parameter |
|
157 |
+
| `stop` | `stop_sequences` | List of strings that stop generation when encountered |
|
158 |
+
| `presence_penalty` | `presence_penalty` | Penalizes repeated tokens |
|
159 |
+
| `frequency_penalty` | `frequency_penalty` | Penalizes frequent tokens |
|
160 |
+
| `seed` | `seed` | Random seed for deterministic generation |
|
161 |
+
| `logprobs` | `logprobs` | Number of log probabilities to return |
|
162 |
+
| `n` | `candidate_count` | Number of completions to generate |
|
163 |
|
164 |
+
## Credential Handling Priority
|
165 |
|
166 |
+
The application loads Google Cloud credentials in the following order:
|
167 |
|
168 |
+
1. **`GOOGLE_CREDENTIALS_JSON` Environment Variable / Secret:** Checks for the JSON *content* directly in this variable (Required for Hugging Face).
|
169 |
+
2. **`credentials/` Directory (Local Only):** Looks for `.json` files in the directory specified by `CREDENTIALS_DIR` (Default: `/app/credentials` inside the container). Rotates through found files. Used if `GOOGLE_CREDENTIALS_JSON` is not set.
|
170 |
+
3. **`GOOGLE_APPLICATION_CREDENTIALS` Environment Variable (Local Only):** Checks for a *file path* specified by this variable. Used as a fallback if the above methods fail.
|
171 |
+
|
172 |
+
## Environment Variables / Secrets
|
173 |
+
|
174 |
+
- `API_KEY`: API key for authentication (Default: `123456`). **Required as Secret on Hugging Face.**
|
175 |
+
- `GOOGLE_CREDENTIALS_JSON`: **(Required Secret on Hugging Face)** The full JSON content of your service account key. Takes priority over other methods.
|
176 |
+
- `CREDENTIALS_DIR` (Local Only): Directory containing credential files (Default: `/app/credentials` in the container). Used if `GOOGLE_CREDENTIALS_JSON` is not set.
|
177 |
+
- `GOOGLE_APPLICATION_CREDENTIALS` (Local Only): Path to a *specific* credential file. Used as a fallback if the above methods fail.
|
178 |
+
- `PORT`: Not needed for `CMD` config (uses 7860). Hugging Face provides this automatically, `docker-compose.yml` maps 8050 locally.
|
179 |
+
|
180 |
+
## Health Check
|
181 |
+
|
182 |
+
You can check the status of the service using the health endpoint:
|
183 |
|
184 |
```bash
|
185 |
+
curl YOUR_ADAPTER_URL/health -H "Authorization: Bearer YOUR_API_KEY"
|
186 |
```
|
187 |
|
188 |
+
This returns information about the credential status:
|
189 |
|
190 |
```json
|
191 |
{
|
192 |
"status": "ok",
|
193 |
"credentials": {
|
194 |
+
"available": 1, // Example: 1 if loaded via JSON secret, or count if loaded from files
|
195 |
+
"files": [], // Lists files only if using CREDENTIALS_DIR method
|
196 |
+
"current_index": 0
|
197 |
}
|
198 |
}
|
199 |
```
|
200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
## License
|
202 |
|
203 |
+
This project is licensed under the MIT License.
|
app/main.py
CHANGED
@@ -173,28 +173,45 @@ class OpenAIRequest(BaseModel):
|
|
173 |
|
174 |
# Configure authentication
|
175 |
def init_vertex_ai():
|
|
|
176 |
try:
|
177 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
credentials, project_id = credential_manager.get_next_credentials()
|
179 |
-
|
180 |
if credentials and project_id:
|
181 |
-
client = genai.Client(vertexai=True,credentials=credentials, project=project_id, location="us-central1")
|
182 |
-
|
183 |
-
print(f"Initialized Vertex AI with project: {project_id}")
|
184 |
return True
|
185 |
|
186 |
-
# Fall back to environment variable
|
187 |
file_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
|
188 |
if file_path and os.path.exists(file_path):
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
|
|
|
|
|
|
198 |
except Exception as e:
|
199 |
print(f"Error initializing authentication: {e}")
|
200 |
return False
|
@@ -645,9 +662,9 @@ async def chat_completions(request: OpenAIRequest, api_key: str = Depends(get_ap
|
|
645 |
|
646 |
# Initialize Vertex AI with the rotated credentials
|
647 |
try:
|
648 |
-
client
|
649 |
-
|
650 |
-
print(f"Using credentials for project: {project_id}")
|
651 |
except Exception as auth_error:
|
652 |
error_response = create_openai_error_response(
|
653 |
500, f"Failed to initialize authentication: {str(auth_error)}", "server_error"
|
|
|
173 |
|
174 |
# Configure authentication
|
175 |
def init_vertex_ai():
|
176 |
+
global client # Ensure we modify the global client variable
|
177 |
try:
|
178 |
+
# Priority 1: Check for credentials JSON content in environment variable (Hugging Face)
|
179 |
+
credentials_json_str = os.environ.get("GOOGLE_CREDENTIALS_JSON")
|
180 |
+
if credentials_json_str:
|
181 |
+
try:
|
182 |
+
credentials_info = json.loads(credentials_json_str)
|
183 |
+
credentials = service_account.Credentials.from_service_account_info(credentials_info, scopes=['https://www.googleapis.com/auth/cloud-platform'])
|
184 |
+
project_id = credentials.project_id
|
185 |
+
client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
|
186 |
+
print(f"Initialized Vertex AI using GOOGLE_CREDENTIALS_JSON env var for project: {project_id}")
|
187 |
+
return True
|
188 |
+
except Exception as e:
|
189 |
+
print(f"Error loading credentials from GOOGLE_CREDENTIALS_JSON: {e}")
|
190 |
+
# Fall through to other methods if this fails
|
191 |
+
|
192 |
+
# Priority 2: Try to use the credential manager to get credentials from files
|
193 |
credentials, project_id = credential_manager.get_next_credentials()
|
194 |
+
|
195 |
if credentials and project_id:
|
196 |
+
client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
|
197 |
+
print(f"Initialized Vertex AI using Credential Manager for project: {project_id}")
|
|
|
198 |
return True
|
199 |
|
200 |
+
# Priority 3: Fall back to GOOGLE_APPLICATION_CREDENTIALS environment variable (file path)
|
201 |
file_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
|
202 |
if file_path and os.path.exists(file_path):
|
203 |
+
try:
|
204 |
+
credentials = service_account.Credentials.from_service_account_file(file_path, scopes=['https://www.googleapis.com/auth/cloud-platform'])
|
205 |
+
project_id = credentials.project_id
|
206 |
+
client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
|
207 |
+
print(f"Initialized Vertex AI using GOOGLE_APPLICATION_CREDENTIALS file path for project: {project_id}")
|
208 |
+
return True
|
209 |
+
except Exception as e:
|
210 |
+
print(f"Error loading credentials from GOOGLE_APPLICATION_CREDENTIALS path {file_path}: {e}")
|
211 |
+
|
212 |
+
# If none of the methods worked
|
213 |
+
print(f"Error: No valid credentials found. Tried GOOGLE_CREDENTIALS_JSON, Credential Manager ({credential_manager.credentials_dir}), and GOOGLE_APPLICATION_CREDENTIALS.")
|
214 |
+
return False
|
215 |
except Exception as e:
|
216 |
print(f"Error initializing authentication: {e}")
|
217 |
return False
|
|
|
662 |
|
663 |
# Initialize Vertex AI with the rotated credentials
|
664 |
try:
|
665 |
+
# Re-initialize client for this request - credentials might have rotated
|
666 |
+
client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
|
667 |
+
print(f"Using credentials for project: {project_id} for this request")
|
668 |
except Exception as auth_error:
|
669 |
error_response = create_openai_error_response(
|
670 |
500, f"Failed to initialize authentication: {str(auth_error)}", "server_error"
|
docker-compose.yml
CHANGED
@@ -6,7 +6,8 @@ services:
|
|
6 |
context: .
|
7 |
dockerfile: Dockerfile
|
8 |
ports:
|
9 |
-
|
|
|
10 |
volumes:
|
11 |
- ./credentials:/app/credentials
|
12 |
environment:
|
|
|
6 |
context: .
|
7 |
dockerfile: Dockerfile
|
8 |
ports:
|
9 |
+
# Map host port 8050 to container port 7860 (for Hugging Face compatibility)
|
10 |
+
- "8050:7860"
|
11 |
volumes:
|
12 |
- ./credentials:/app/credentials
|
13 |
environment:
|