Skip to content

Commit 1a2c3d3

Browse files
replace Keycloak authentication with token-based inference API authentication
1 parent ef727ad commit 1a2c3d3

7 files changed

Lines changed: 51 additions & 101 deletions

File tree

CodeTranslation/README.md

Lines changed: 25 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
## Code Translation
22

33
A full-stack code translation application that converts code between programming languages using AI.
4-
The system integrates a FastAPI backend powered by CodeLlama-34b-instruct, alongside a modern React + Vite + Tailwind CSS frontend for an intuitive translation experience.
4+
The system integrates a FastAPI backend, alongside a modern React + Vite + Tailwind CSS frontend for an intuitive translation experience.
55

66
## Table of Contents
77

@@ -17,7 +17,7 @@ The system integrates a FastAPI backend powered by CodeLlama-34b-instruct, along
1717

1818
## Project Overview
1919

20-
The **Code Translation** application demonstrates how large language models can be used to translate code between different programming languages. It accepts source code in one language, processes it through CodeLlama-34b-instruct, and returns translated code in the target language. This project integrates seamlessly with cloud-hosted APIs or local model endpoints, offering flexibility for research, enterprise, or educational use.
20+
The **Code Translation** application demonstrates how large language models can be used to translate code between different programming languages. It accepts source code in one language, processes it and returns translated code in the target language. This project integrates seamlessly with cloud-hosted APIs or local model endpoints, offering flexibility for research, enterprise, or educational use.
2121

2222
---
2323

@@ -27,9 +27,8 @@ The **Code Translation** application demonstrates how large language models can
2727

2828
- Code translation between 6 languages (Java, C, C++, Python, Rust, Go)
2929
- PDF code extraction with pattern recognition
30-
- CodeLlama-34b-instruct for accurate translations
3130
- Enterprise inference endpoints
32-
- Keycloak authentication for secure API access
31+
- Token-based authentication for inference API
3332
- Comprehensive error handling and logging
3433
- File validation and size limits
3534
- CORS enabled for web integration
@@ -70,8 +69,7 @@ Below is the architecture as it consists of a server that waits for code input o
7069
end
7170
7271
subgraph "External Services"
73-
E[Keycloak Auth]
74-
F[CodeLlama-34b Model]
72+
E[CodeLlama-34b Model]
7573
end
7674
7775
A1 --> B
@@ -80,31 +78,29 @@ Below is the architecture as it consists of a server that waits for code input o
8078
B --> C
8179
C -->|Extracted Code| B
8280
B --> D
83-
D -->|Get Token| E
84-
E -->|Access Token| D
85-
D -->|Translate Code + Token| F
86-
F -->|Translated Code| D
81+
D -->|Translate Code + Token| E
82+
E -->|Translated Code| D
8783
D --> B
8884
B --> A
8985
9086
style A fill:#e1f5ff
9187
style B fill:#fff4e1
92-
style F fill:#e1ffe1
88+
style E fill:#e1ffe1
9389
```
9490

95-
This application is built with enterprise inference capabilities using Keycloak for authentication and CodeLlama-34b-instruct for code translation.
91+
This application is built with enterprise inference capabilities using token-based authentication and CodeLlama-34b-instruct for code translation.
9692

9793
**Service Components:**
9894

9995
1. **React Web UI (Port 3000)** - Provides side-by-side code comparison interface with language selection, PDF upload, and real-time translation results
10096

101-
2. **FastAPI Backend (Port 5001)** - Handles code validation, PDF extraction, Keycloak authentication, and orchestrates code translation through CodeLlama model
97+
2. **FastAPI Backend (Port 5001)** - Handles code validation, PDF extraction, inference API authentication, and orchestrates code translation through CodeLlama model
10298

10399
**Typical Flow:**
104100

105101
1. User enters code or uploads a PDF through the web UI.
106102
2. The backend validates the input and extracts code if needed.
107-
3. The backend authenticates with Keycloak and calls CodeLlama model.
103+
3. The backend authenticates with inference API and calls CodeLlama model.
108104
4. The model translates the code to the target language.
109105
5. The translated code is returned and displayed to the user.
110106
6. User can copy the translated code with one click.
@@ -118,7 +114,13 @@ This application is built with enterprise inference capabilities using Keycloak
118114
Before you begin, ensure you have the following installed:
119115

120116
- **Docker and Docker Compose**
121-
- **Enterprise inference endpoint access** (Keycloak authentication)
117+
- **Enterprise inference endpoint access** (token-based authentication)
118+
119+
### Required API Configuration
120+
121+
**For Inference Service (Code Translation):**
122+
- INFERENCE_API_ENDPOINT: URL of the deployed model inference service
123+
- INFERENCE_API_TOKEN: API key / bearer token used to authenticate requests
122124

123125
### Verify Docker Installation
124126

@@ -139,7 +141,7 @@ docker ps
139141
### Clone the Repository
140142

141143
```bash
142-
git clone https://github.com/opea-project/GenAIExamples.git
144+
git clone https://github.com/cld2labs/GenAIExamples.git
143145
cd GenAIExamples/CodeTranslation
144146
```
145147

@@ -153,13 +155,9 @@ cat > .env << EOF
153155
# Backend API Configuration
154156
BACKEND_PORT=5001
155157
156-
# Required - Enterprise/Keycloak Configuration
157-
BASE_URL=https://api.example.com
158-
KEYCLOAK_CLIENT_ID=api
159-
KEYCLOAK_CLIENT_SECRET=your_client_secret
160-
161-
# Required - Model Configuration
162-
INFERENCE_MODEL_ENDPOINT=CodeLlama-34b-Instruct-hf
158+
# Inference API Configuration
159+
INFERENCE_API_ENDPOINT=https://your-api-endpoint.com/deployment
160+
INFERENCE_API_TOKEN=your-pre-generated-token-here
163161
INFERENCE_MODEL_NAME=codellama/CodeLlama-34b-Instruct-hf
164162
165163
# LLM Settings
@@ -181,13 +179,9 @@ Or manually create `.env` with:
181179
# Backend API Configuration
182180
BACKEND_PORT=5001
183181

184-
# Required - Enterprise/Keycloak Configuration
185-
BASE_URL=https://api.example.com
186-
KEYCLOAK_CLIENT_ID=api
187-
KEYCLOAK_CLIENT_SECRET=your_client_secret
188-
189-
# Required - Model Configuration
190-
INFERENCE_MODEL_ENDPOINT=CodeLlama-34b-Instruct-hf
182+
# Inference API Configuration
183+
INFERENCE_API_ENDPOINT=https://your-api-endpoint.com/deployment
184+
INFERENCE_API_TOKEN=your-pre-generated-token-here
191185
INFERENCE_MODEL_NAME=codellama/CodeLlama-34b-Instruct-hf
192186

193187
# LLM Settings
@@ -209,7 +203,7 @@ CORS_ALLOW_ORIGINS=["http://localhost:5173", "http://localhost:3000"]
209203
Start both API and UI services together with Docker Compose:
210204

211205
```bash
212-
# From the CodeTranslation directory
206+
# From the code-translation directory
213207
docker compose up --build
214208

215209
# Or run in detached mode (background)

CodeTranslation/TROUBLESHOOTING.md

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,16 @@ This document contains all common issues encountered during development and thei
99

1010
### API Common Issues
1111

12-
#### "API client not initialized. Check Keycloak configuration."
12+
#### "API client not initialized. Check inference API configuration."
1313

1414
**Solution**:
1515

1616
1. Create a `.env` file in the root directory
17-
2. Add your Keycloak credentials:
17+
2. Add your inference API credentials:
1818
```
19-
BASE_URL=https://api.example.com
20-
KEYCLOAK_CLIENT_ID=api
21-
KEYCLOAK_CLIENT_SECRET=your_client_secret
19+
INFERENCE_API_ENDPOINT=https://your-api-endpoint.com/deployment
20+
INFERENCE_API_TOKEN=your-pre-generated-token-here
21+
INFERENCE_MODEL_NAME=codellama/CodeLlama-34b-Instruct-hf
2222
```
2323
3. Restart the server
2424

@@ -68,10 +68,11 @@ This document contains all common issues encountered during development and thei
6868

6969
**Solution**:
7070

71-
1. Verify Keycloak authentication is working (check `/health` endpoint)
71+
1. Verify inference API authentication is working (check `/health` endpoint)
7272
2. Check if the model endpoint is accessible
73-
3. Try with simpler code first
74-
4. Check server logs for API errors
73+
3. Verify INFERENCE_API_TOKEN is valid and not expired
74+
4. Try with simpler code first
75+
5. Check server logs for API errors
7576

7677
#### "No module named 'pypdf'"
7778

CodeTranslation/api/config.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,11 @@
88
# Load environment variables from .env file
99
load_dotenv()
1010

11-
# Custom API Configuration for Keycloak
12-
BASE_URL = os.getenv("BASE_URL", "https://api.example.com")
13-
KEYCLOAK_REALM = os.getenv("KEYCLOAK_REALM", "master")
14-
KEYCLOAK_CLIENT_ID = os.getenv("KEYCLOAK_CLIENT_ID", "api")
15-
KEYCLOAK_CLIENT_SECRET = os.getenv("KEYCLOAK_CLIENT_SECRET")
16-
17-
# Model Configuration for CodeLlama-34b-instruct
18-
INFERENCE_MODEL_ENDPOINT = os.getenv("INFERENCE_MODEL_ENDPOINT", "CodeLlama-34b-Instruct")
11+
# Inference API Configuration
12+
INFERENCE_API_ENDPOINT = os.getenv("INFERENCE_API_ENDPOINT")
13+
INFERENCE_API_TOKEN = os.getenv("INFERENCE_API_TOKEN")
1914
INFERENCE_MODEL_NAME = os.getenv("INFERENCE_MODEL_NAME", "codellama/CodeLlama-34b-Instruct-hf")
2015

21-
# Validate required configuration
22-
if not KEYCLOAK_CLIENT_SECRET:
23-
raise ValueError("KEYCLOAK_CLIENT_SECRET must be set in environment variables")
24-
2516
# Application Settings
2617
APP_TITLE = "Code Translation API"
2718
APP_DESCRIPTION = "AI-powered code translation service using CodeLlama-34b-instruct"

CodeTranslation/api/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class HealthResponse(BaseModel):
6060
"""Response model for health check"""
6161
status: str = Field(..., description="Health status")
6262
model_configured: bool = Field(..., description="Whether model is configured")
63-
keycloak_authenticated: bool = Field(..., description="Whether Keycloak auth is successful")
63+
inference_authenticated: bool = Field(..., description="Whether inference API auth is successful")
6464

6565

6666
class SupportedLanguagesResponse(BaseModel):

CodeTranslation/api/server.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ async def lifespan(app: FastAPI):
3333
try:
3434
api_client = get_api_client()
3535
app.state.api_client = api_client
36-
logger.info("API client initialized with Keycloak authentication")
36+
logger.info("API client initialized with inference endpoint")
3737
except Exception as e:
3838
logger.error(f"Failed to initialize API client: {str(e)}")
3939
app.state.api_client = None
@@ -81,7 +81,7 @@ def health_check():
8181
return HealthResponse(
8282
status="healthy",
8383
model_configured=bool(config.INFERENCE_MODEL_NAME),
84-
keycloak_authenticated=app.state.api_client is not None and app.state.api_client.is_authenticated()
84+
inference_authenticated=app.state.api_client is not None and app.state.api_client.is_authenticated()
8585
)
8686

8787

@@ -105,7 +105,7 @@ def translate_code_endpoint(request: TranslateRequest):
105105
if not app.state.api_client:
106106
raise HTTPException(
107107
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
108-
detail="API client not initialized. Check Keycloak configuration."
108+
detail="API client not initialized. Check inference API configuration."
109109
)
110110

111111
# Validate languages
@@ -144,7 +144,7 @@ def translate_code_endpoint(request: TranslateRequest):
144144
detail="Translation failed. No output received from model."
145145
)
146146

147-
logger.info(f"Successfully translated code")
147+
logger.info(f"Successfully translated code")
148148

149149
return TranslateResponse(
150150
translated_code=translated_code,
@@ -196,7 +196,7 @@ async def upload_pdf(file: UploadFile = File(...)):
196196
detail="No code content could be extracted from the PDF"
197197
)
198198

199-
logger.info(f"Successfully extracted code from PDF: {file.filename}")
199+
logger.info(f"Successfully extracted code from PDF: {file.filename}")
200200

201201
return UploadPdfResponse(
202202
message=f"Successfully extracted code from '{file.filename}'",

CodeTranslation/api/services/api_client.py

Lines changed: 6 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
"""
2-
API Client for Keycloak authentication and API calls
2+
API Client for inference API calls
33
"""
44

55
import logging
6-
import requests
76
import httpx
87
from typing import Optional
98
import config
@@ -13,54 +12,23 @@
1312

1413
class APIClient:
1514
"""
16-
Client for handling Keycloak authentication and API calls
15+
Client for handling inference API calls
1716
"""
1817

1918
def __init__(self):
20-
self.base_url = config.BASE_URL
21-
self.token = None
22-
self.http_client = None
23-
self._authenticate()
24-
25-
def _authenticate(self) -> None:
26-
"""
27-
Authenticate and obtain access token from Keycloak
28-
"""
29-
token_url = f"{self.base_url}/token"
30-
payload = {
31-
"grant_type": "client_credentials",
32-
"client_id": config.KEYCLOAK_CLIENT_ID,
33-
"client_secret": config.KEYCLOAK_CLIENT_SECRET,
34-
}
35-
36-
try:
37-
response = requests.post(token_url, data=payload, verify=False)
38-
39-
if response.status_code == 200:
40-
self.token = response.json().get("access_token")
41-
logger.info(f"✓ Access token obtained: {self.token[:20]}..." if self.token else "Failed to get token")
42-
43-
# Create httpx client with SSL verification disabled
44-
self.http_client = httpx.Client(verify=False)
45-
46-
else:
47-
logger.error(f"Error obtaining token: {response.status_code} - {response.text}")
48-
raise Exception(f"Authentication failed: {response.status_code}")
49-
50-
except Exception as e:
51-
logger.error(f"Error during authentication: {str(e)}")
52-
raise
19+
self.endpoint = config.INFERENCE_API_ENDPOINT
20+
self.token = config.INFERENCE_API_TOKEN
21+
self.http_client = httpx.Client(verify=False) if self.token else None
5322

5423
def get_inference_client(self):
5524
"""
5625
Get OpenAI-style client for code generation inference
57-
Uses CodeLlama-34b-instruct endpoint
5826
"""
5927
from openai import OpenAI
6028

6129
return OpenAI(
6230
api_key=self.token,
63-
base_url=f"{self.base_url}/{config.INFERENCE_MODEL_ENDPOINT}/v1",
31+
base_url=f"{self.endpoint}/v1",
6432
http_client=self.http_client
6533
)
6634

CodeTranslation/docker-compose.yaml

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
version: '3.8'
2-
31
services:
42
backend:
53
build:
@@ -11,10 +9,8 @@ services:
119
env_file:
1210
- .env
1311
environment:
14-
- BASE_URL=${BASE_URL}
15-
- KEYCLOAK_CLIENT_ID=${KEYCLOAK_CLIENT_ID}
16-
- KEYCLOAK_CLIENT_SECRET=${KEYCLOAK_CLIENT_SECRET}
17-
- INFERENCE_MODEL_ENDPOINT=${INFERENCE_MODEL_ENDPOINT}
12+
- INFERENCE_API_ENDPOINT=${INFERENCE_API_ENDPOINT}
13+
- INFERENCE_API_TOKEN=${INFERENCE_API_TOKEN}
1814
- INFERENCE_MODEL_NAME=${INFERENCE_MODEL_NAME}
1915
- LLM_TEMPERATURE=${LLM_TEMPERATURE:-0.2}
2016
- LLM_MAX_TOKENS=${LLM_MAX_TOKENS:-4096}

0 commit comments

Comments
 (0)