Implementation Plan – OpenAI Middleware Server

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/chat route.
  • 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 HJHKeys flag.

Verification

  1. Start PC Server using Gradle.
  2. Run Android App (Emulator).
  3. Toggle USE_RELAY_SERVER to true.
  4. 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.

2. Android Integration

Updated the Android app to optionally route requests through this server.

  • Configuration: HJHKeys.kt
    • Added USE_RELAY_SERVER (set to true).
    • Added RELAY_SERVER_URL (http://10.0.2.2:8080 for Emulator).
  • Client Logic: OpenAIService.kt
    • Dynamically selects the URL based on the HJHKeys config.

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 HJHKeysAction Required: Move the key to an Environment Variable or a secure .env file on the server before deploying to production.

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다