thisFasih commited on
Commit
de6f587
·
verified ·
1 Parent(s): e8bfd4d

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +126 -12
  2. app.py +83 -0
  3. requirements.txt +2 -0
README.md CHANGED
@@ -1,12 +1,126 @@
1
- ---
2
- title: API Key Tester
3
- emoji: 🐠
4
- colorFrom: green
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 6.0.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # API Key Validator for OpenAI & Gemini
2
+
3
+ A lightweight Gradio web app that lets you quickly validate API keys for both OpenAI and Google Gemini (Generative Language API) and view the list of available models for each provider.
4
+
5
+ ## Features
6
+ - Validate OpenAI API key (calls `GET /v1/models`).
7
+ - Validate Gemini API key (calls `GET /v1beta/models`).
8
+ - Secure password-style input fields (keys never echoed in plain text).
9
+ - Immediate feedback: success, failure, and raw error payload when invalid.
10
+ - Displays available model IDs / names returned by each provider.
11
+ - Zero persistence: keys are not stored, logged, or transmitted elsewhere.
12
+
13
+ ## Tech Stack
14
+ - **Python** (>=3.9 recommended)
15
+ - **Gradio** for the UI
16
+ - **Requests** for outbound HTTPS calls
17
+
18
+ ## Getting Started
19
+ ### 1. Clone / Download
20
+ ```bash
21
+ git clone <your-repo-url>
22
+ cd api-key-tester-app
23
+ ```
24
+ (Replace folder name if different.)
25
+
26
+ ### 2. Create Virtual Environment (Optional but Recommended)
27
+ ```bash
28
+ python -m venv .venv
29
+ # Windows
30
+ .venv\Scripts\activate
31
+ # macOS / Linux
32
+ source .venv/bin/activate
33
+ ```
34
+
35
+ ### 3. Install Dependencies
36
+ ```bash
37
+ pip install -r requirements.txt
38
+ ```
39
+
40
+ ### 4. Run the App
41
+ ```bash
42
+ python app.py
43
+ ```
44
+ Gradio will print a local URL (e.g., `http://127.0.0.1:7860`) and, if enabled, a public share URL.
45
+
46
+ ## Usage
47
+ 1. Enter your OpenAI API key (format typically starts with `sk-...`).
48
+ 2. Enter your Gemini API key (Google AI Studio issued key).
49
+ 3. Click **"Test Keys"**.
50
+ 4. View validation results and model lists.
51
+
52
+ If a key is invalid, the raw response body (error JSON / message) is shown in the results panel for troubleshooting.
53
+
54
+ ## Security & Privacy
55
+ - Inputs use `type="password"` in Gradio (no on-screen echo).
56
+ - Keys are only transmitted directly to official provider endpoints.
57
+ - No server-side storage, caching, or logging of keys.
58
+ - Avoid sharing screenshots that contain sensitive error payloads.
59
+
60
+ ## Environment Variables (Optional Enhancement)
61
+ Currently keys are entered manually. You could extend the app to pre-fill from environment variables (example shown for convenience):
62
+ Add to your shell:
63
+ ```bash
64
+ # Windows PowerShell
65
+ $Env:OPENAI_API_KEY="sk-your-key"
66
+ $Env:GEMINI_API_KEY="your-gemini-key"
67
+ ```
68
+
69
+ ## Error Handling
70
+ - Network errors captured and surfaced as exception strings.
71
+ - Non-200 status codes display provider error payload (`resp.text`).
72
+ - Rate limits or expired keys will return provider-specific error JSON.
73
+
74
+ ## Roadmap / Ideas
75
+ - Add support for additional providers (Anthropic, Mistral, etc.).
76
+ - Show quota usage (if endpoint available).
77
+ - Dark mode toggle.
78
+ - Simple caching of last successful model list.
79
+ - Downloadable validation report.
80
+
81
+ ## Testing
82
+ There are no automated tests yet. Suggested next steps:
83
+ - Unit test helper functions `test_openai_key` and `test_gemini_key` using mocked `requests.get`.
84
+ - Add a smoke test ensuring the Gradio interface launches without exceptions.
85
+
86
+ ## Contributing
87
+ 1. Fork the repository.
88
+ 2. Create a feature branch: `git checkout -b feature/<name>`.
89
+ 3. Commit changes: `git commit -m "Add <feature>"`.
90
+ 4. Push: `git push origin feature/<name>`.
91
+ 5. Open a Pull Request.
92
+
93
+ Please keep changes minimal and focused. For significant UI or provider additions, open an issue first to discuss.
94
+
95
+ ## Configuration Notes
96
+ | Provider | Endpoint Used | Purpose |
97
+ |----------|---------------|---------|
98
+ | OpenAI | `GET https://api.openai.com/v1/models` | Validates key + lists models |
99
+ | Gemini | `GET https://generativelanguage.googleapis.com/v1beta/models?key=...` | Validates key + lists models |
100
+
101
+ ## Limitations
102
+ - Does not test key against every possible endpoint.
103
+ - Model lists may differ if access is restricted or in preview.
104
+ - No persistent audit trail by design.
105
+
106
+ ## License
107
+ Specify a license (e.g., MIT, Apache-2.0). If none provided, all rights reserved by default.
108
+
109
+ ## Disclaimer
110
+ This tool is for quick manual validation. Always follow provider security best practices and rotate credentials regularly.
111
+
112
+ ## FAQ
113
+ **Q: Are my keys stored anywhere?**
114
+ A: No. They exist only in session memory for the duration of the Streamlit interaction.
115
+
116
+ **Q: Why is my valid key showing limited models?**
117
+ A: Some models require special access or are in restricted beta.
118
+
119
+ **Q: Can I deploy this?**
120
+ A: Yes—e.g., Streamlit Community Cloud can run Gradio apps too. Select your GitHub repo, branch `master`, and main file path `app.py`. Leave the App URL blank or choose a simple subdomain. Alternatively, deploy on Spaces (Hugging Face) or Render.
121
+
122
+ **Q: How can I add another provider?**
123
+ A: Create a new helper similar to `test_openai_key`, call its endpoint, parse model list, and extend the UI block.
124
+
125
+ ---
126
+ Feel free to customize sections like License or add CI badges once the project is in a public repo.
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import gradio as gr
3
+ import os
4
+
5
+ # ----------- Helper Functions -----------
6
+ def test_openai_key(key: str):
7
+ try:
8
+ headers = {"Authorization": f"Bearer {key}"}
9
+ resp = requests.get("https://api.openai.com/v1/models", headers=headers)
10
+ if resp.status_code == 200:
11
+ return True, [m.get("id") for m in resp.json().get("data", [])]
12
+ return False, resp.text
13
+ except Exception as e:
14
+ return False, str(e)
15
+
16
+ def test_gemini_key(key: str):
17
+ try:
18
+ url = f"https://generativelanguage.googleapis.com/v1beta/models?key={key}"
19
+ resp = requests.get(url)
20
+ if resp.status_code == 200:
21
+ models = [m.get("name") for m in resp.json().get("models", [])]
22
+ return True, models
23
+ return False, resp.text
24
+ except Exception as e:
25
+ return False, str(e)
26
+
27
+ # ----------- Gradio Interface -----------
28
+ def validate_keys(openai_key: str, gemini_key: str):
29
+ parts = ["## Results"]
30
+ openai_models = None
31
+ gemini_models = None
32
+
33
+ if openai_key:
34
+ valid, data = test_openai_key(openai_key)
35
+ if valid:
36
+ parts.append("### OpenAI Key: ✅ Valid")
37
+ openai_models = data
38
+ else:
39
+ parts.append("### OpenAI Key: ❌ Invalid")
40
+ parts.append(f"```\n{str(data)}\n```")
41
+
42
+ if gemini_key:
43
+ valid, data = test_gemini_key(gemini_key)
44
+ if valid:
45
+ parts.append("### Gemini Key: ✅ Valid")
46
+ gemini_models = data
47
+ else:
48
+ parts.append("### Gemini Key: ❌ Invalid")
49
+ parts.append(f"```\n{str(data)}\n```")
50
+
51
+ if not openai_key and not gemini_key:
52
+ parts.append("Enter at least one key to test.")
53
+
54
+ summary_md = "\n\n".join(parts)
55
+ return summary_md, (openai_models or []), (gemini_models or [])
56
+
57
+ with gr.Blocks(title="API Key Validator for OpenAI & Gemini") as demo:
58
+ gr.Markdown("# API Key Validator for OpenAI & Gemini")
59
+ gr.Markdown(
60
+ "This tool checks the validity of API keys and lists available models for OpenAI & Gemini."
61
+ )
62
+
63
+ with gr.Row():
64
+ openai_key_box = gr.Textbox(label="OpenAI API Key", type="password", placeholder="sk-...")
65
+ gemini_key_box = gr.Textbox(label="Gemini API Key", type="password", placeholder="AI Studio key...")
66
+
67
+ test_btn = gr.Button("Test Keys")
68
+
69
+ summary = gr.Markdown()
70
+ with gr.Row():
71
+ openai_models_json = gr.JSON(label="OpenAI Models")
72
+ gemini_models_json = gr.JSON(label="Gemini Models")
73
+
74
+ test_btn.click(
75
+ fn=validate_keys,
76
+ inputs=[openai_key_box, gemini_key_box],
77
+ outputs=[summary, openai_models_json, gemini_models_json],
78
+ )
79
+
80
+ if __name__ == "__main__":
81
+ share = os.getenv("GRADIO_SHARE", "false").lower() in {"1", "true", "yes"}
82
+ port = int(os.getenv("PORT", "7860"))
83
+ demo.launch(server_name="0.0.0.0", server_port=port, share=share)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ requests>=2.31,<3
2
+ gradio>=4.31,<5