Skip to content

Commit

Permalink
fIxed Backend
Browse files Browse the repository at this point in the history
  • Loading branch information
dedsecrattle committed Nov 9, 2024
1 parent 4e7729d commit 38f73e1
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 42 deletions.
102 changes: 102 additions & 0 deletions backend/ai-hint-service/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,103 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# Virtual Environment
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# FastAPI specific
.env
.env.local
.env.*.local

# IDE - VSCode
.vscode/
*.code-workspace
.history/

# IDE - PyCharm
.idea/
*.iml
*.iws
.idea_modules/

# IDE - Jupyter Notebook
.ipynb_checkpoints
*.ipynb

# Logs
logs/
*.log
log.txt

# Database
*.db
*.sqlite
*.sqlite3

# Coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# macOS
.DS_Store
.AppleDouble
.LSOverride
._*

# Windows
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/

# Linux
*~
.fuse_hidden*
.directory
.Trash-*
.nfs*

# Project specific
data/
temp/
config.local.py
local_settings.py

.env
2 changes: 2 additions & 0 deletions backend/ai-hint-service/app/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
OPENAI_API_KEY="API_KEY"
QUESTION_SERVICE_URL = "http://question:3002"
11 changes: 0 additions & 11 deletions backend/ai-hint-service/app/dependencies.py

This file was deleted.

13 changes: 7 additions & 6 deletions backend/ai-hint-service/app/main.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
# backend/ai-hint-service/app/main.py

from fastapi import FastAPI
from openai import OpenAI
from .routes import hint, code_analysis, model_answer
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
import os

load_dotenv()

app = FastAPI(
title="AI Hint Service",
description="Provides AI-generated hints, code complexity analysis, and model answers.",
version="1.0.0",
)

# CORS settings - adjust origins as needed

origins = [
"http://localhost",
"http://localhost:80",
# Add other frontend URLs here
"*",
]

app.add_middleware(
Expand Down
12 changes: 5 additions & 7 deletions backend/ai-hint-service/app/routes/hint.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from ..services.openai_service import generate_hint
from ..schemas.hint import HintResponse
from typing import Optional
import requests
import os

router = APIRouter()

Expand All @@ -10,13 +12,11 @@ async def get_hint(question_id: int):
"""
Generate a hint for the given question ID.
"""
# Placeholder: Fetch question description from the question service
# You need to integrate with your question service's API to get the description
question_description = fetch_question_description(question_id)
if not question_description:
raise HTTPException(status_code=404, detail="Question not found.")

try:
try:
hint = generate_hint(question_description)
return HintResponse(hint=hint)
except Exception as e:
Expand All @@ -25,14 +25,12 @@ async def get_hint(question_id: int):
def fetch_question_description(question_id: int) -> Optional[str]:
# Implement the logic to fetch question description from the question service
# For example, make an HTTP request to the question service's API
import requests
QUESTION_SERVICE_URL = "http://localhost/api/questions"
QUESTION_SERVICE_URL = "http://question:3002"

QUESTION_SERVICE_URL = os.getenv("QUESTION_SERVICE_URL")
try:
link = f"{QUESTION_SERVICE_URL}/{question_id}"
print(link)
response = requests.get(link)
print(response)
if response.status_code == 200:
data = response.json()
return data.get("description")
Expand Down
19 changes: 6 additions & 13 deletions backend/ai-hint-service/app/services/openai_service.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,33 @@
from openai import OpenAI
# from ..dependencies import OPENAI_API_KEY
from dotenv import load_dotenv
import os
import openai


load_dotenv()

client = OpenAI(
api_key = os.getenv("OPENAI_API_KEY")
)

model = 'gpt-3.5-turbo-0125'

def generate_hint(question_description: str) -> str:
prompt = f"Provide a concise hint for the following programming problem:\n\n{question_description}\n\nHint:"
completion = client.chat.completions.create(
completion = openai.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
)

hint = completion.choices[0].message.content
print(hint)
return hint

def analyze_code_complexity(code: str, language: str) -> dict:
prompt = f"Analyze the following {language} code for its time and space complexity. Provide a detailed explanation.\n\nCode:\n{code}\n\nAnalysis:"
completion = client.completions.create(
completion = openai.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
)
analysis = completion.choices[0].message['content']
# Simple heuristic to determine complexity
if "O(" in analysis:
start = analysis.find("O(")
end = analysis.find(")", start) + 1
Expand All @@ -45,7 +38,7 @@ def analyze_code_complexity(code: str, language: str) -> dict:

def generate_model_answer(question_description: str, language: str) -> str:
prompt = f"Provide a complete and optimized {language} solution for the following programming problem:\n\n{question_description}\n\nSolution:"
completion = client.completions.create(
completion = openai.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
Expand Down
7 changes: 2 additions & 5 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,9 @@ services:
ai-hint-service:
build: ./backend/ai-hint-service
ports:
- "8000:8000"
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY} # Ensure you set this in your environment or .env file
- "3006:8000"
depends_on:
- question # Assuming 'question' service is needed to fetch question descriptions

- question # Assuming 'question' service is needed to fetch question descriptions

frontend:
build: ./frontend
Expand Down

0 comments on commit 38f73e1

Please sign in to comment.