Goal
Create a secure “Relay/Proxy Server” (중계 서버) in Kotlin to handle OpenAI API requests, removing the need to expose API keys in the Android app.
User Review Required
IMPORTANT
The server will need the OpenAI API Key. For this local setup, I will hardcode it or read from an environment variable in the server code, but it should be properly managed in production (.env file).
Proposed Changes
Neural Center (Server)
[NEW] server/build.gradle.kts
- Gradle build script for Ktor server.
[NEW] server/src/main/kotlin/com/zeliai/server/Application.kt
- Main entry point.
- POST
/api/chatroute. - Logic to forward request to OpenAI and return response.
Android App
[MODIFY] HJHKeys.kt
- Add
const val USE_RELAY_SERVER = true(toggle). - Add
const val RELAY_SERVER_URL = "http://10.0.2.2:8080"(Android Emulator loopback to host).
[MODIFY] OpenAIService.kt (or Repostiory)
- Logic to choose between Direct OpenAI API or Relay Server based on
HJHKeysflag.
Verification
- Start PC Server using Gradle.
- Run Android App (Emulator).
- Toggle
USE_RELAY_SERVERto true. - Verify chat functionality works via the server logs.
OpenAI Middleware Server Walkthrough
I have implemented a Kotlin Ktor server to act as a secure relay for OpenAI API requests. This prevents exposing API keys directly in the Android application.
1. Server Implementation
Created a new server project in c:\claude\yejinai_android1\server.
- Build Config: build.gradle.kts
- Application Logic: Application.kt
- Runs on port
8080. - Endpoint:
POST /chat/completions. - Relays requests to OpenAI using a secure (server-side) API Key.
- Runs on port
2. Android Integration
Updated the Android app to optionally route requests through this server.
- Configuration: HJHKeys.kt
- Added
USE_RELAY_SERVER(set totrue). - Added
RELAY_SERVER_URL(http://10.0.2.2:8080for Emulator).
- Added
- Client Logic: OpenAIService.kt
- Dynamically selects the URL based on the
HJHKeysconfig.
- Dynamically selects the URL based on the
3. How to Run
Step 1: Start the Server
Open a terminal in the project root and run:
cd server..\gradlew.bat run
Note: Make sure JAVA_HOME is set if you encounter errors.
Step 2: Run the Android App
Launch the app in the Android Emulator.
- The app is configured to connect to
10.0.2.2:8080(Emulator’s loopback to host PC). - Use the Chat or Translate features.
- Check the terminal where the server is running to see logs of incoming requests and OpenAI responses.
Checklist for Production
WARNING
The OpenAI API Key is currently hardcoded in Application.kt for demonstration using the key from HJHKeys. Action Required: Move the key to an Environment Variable or a secure .env file on the server before deploying to production.