Coder19/interview_system
0
1from typing import Dict, List, TypedDict, Union2import os3from dotenv import load_dotenv4from openai import OpenAI5import base646 7# Load environment variables from .env file8load_dotenv()9 10# Type definitions11class QuestionInfo(TypedDict):12 title: str13 difficulty: str14 tags: List[str]15 url: str16 17# Configuration18class Config:19 SAMBANOVA_API_KEY = os.getenv("SAMBANOVA_API_KEY") or os.getenv("OPENAI_API_KEY")20 SAMBANOVA_BASE_URL = "https://api.sambanova.ai/v1"21 22 @classmethod23 def validate(cls):24 if not cls.SAMBANOVA_API_KEY:25 raise ValueError(26 "SambaNova API key not found. Please set SAMBASTUDIO_API_KEY or OPENAI_API_KEY in your .env"27 )28 29Config.validate()30 31# Initialize SambaNova client32try:33 client = OpenAI(api_key=Config.SAMBANOVA_API_KEY, base_url=Config.SAMBANOVA_BASE_URL)34except Exception as e:35 raise RuntimeError(f"Failed to initialize SambaNova client: {str(e)}")36 37# Initialize LeetCode client38try:39 from gql import Client, gql40 from gql.transport.requests import RequestsHTTPTransport41 42 transport = RequestsHTTPTransport(43 url="https://leetcode.com/graphql",44 verify=True,45 retries=3,46 timeout=1047 )48 leetcode_client = Client(transport=transport, fetch_schema_from_transport=False)49except ImportError:50 leetcode_client = None51 print("Warning: gql package not installed. LeetCode functionality will be limited.")52except Exception as e:53 leetcode_client = None54 print(f"Warning: Failed to initialize LeetCode client: {str(e)}")55 56# ---------------- MCQ Generation ----------------57def generate_mcqs(domain: str, image_path: str = None, count: int = 5) -> str:58 """59 Generate multiple-choice questions for the given domain using SambaNova.60 Optional image can be included in the prompt.61 """62 if not 1 <= count <= 10:63 count = 564 65 prompt = f"""Generate {count} multiple-choice questions about {domain}.66For each question:671. Make it clear and specific682. Include 4 answer choices (A, B, C, D)693. Mark the correct answer with [CORRECT] at the end704. Format as:71 Q1. [Question]72 A) [Option 1]73 B) [Option 2] [CORRECT]74 C) [Option 3]75 D) [Option 4]76Example:77Q1. What is the capital of France?78A) London79B) Berlin80C) Paris [CORRECT]81D) Madrid82"""83 84 messages = [85 {"role": "system", "content": "You are a helpful AI that generates high-quality MCQs."},86 {"role": "user", "content": prompt}87 ]88 89 # If an image is provided, encode and add to message90 if image_path:91 with open(image_path, "rb") as f:92 b64 = base64.b64encode(f.read()).decode("utf-8")93 image_data_uri = f"data:image/png;base64,{b64}"94 messages[1]["content"] = [95 {"type": "text", "text": prompt},96 {"type": "image_url", "image_url": {"url": image_data_uri}}97 ]98 99 try:100 response = client.chat.completions.create(101 model="Llama-4-Maverick-17B-128E-Instruct",102 messages=messages,103 temperature=0.7,104 max_tokens=2000105 )106 if response and response.choices:107 return response.choices[0].message.content.strip()108 else:109 return f"No choices returned. Full response: {response}"110 except Exception as e:111 return f"Error generating MCQs: {str(e)}"112 113# ---------------- LeetCode Coding Questions ----------------114def generate_coding_questions(limit: int = 5) -> Union[List[QuestionInfo], str]:115 if leetcode_client is None:116 return "LeetCode client not available. Install 'gql' package."117 118 limit = max(1, min(10, limit)) # Ensure limit between 1-10119 120 query = gql("""121 {122 problemsetQuestionListV2(limit: %d) {123 questions {124 title125 titleSlug126 difficulty127 topicTags { name }128 }129 }130 }131 """ % limit)132 133 try:134 data = leetcode_client.execute(query)135 questions = data.get("problemsetQuestionListV2", {}).get("questions", [])136 if not questions:137 return "No questions found on LeetCode."138 139 question_list = []140 for q in questions:141 question_list.append({142 "title": q["title"],143 "difficulty": q["difficulty"],144 "tags": [tag["name"] for tag in q["topicTags"]],145 "url": f"https://leetcode.com/problems/{q['titleSlug']}/"146 })147 return question_list148 except Exception as e:149 return f"Error fetching LeetCode questions: {str(e)}"150 151# ---------------- Helper to print questions ----------------152def print_questions(question_list: List[QuestionInfo]):153 for idx, question in enumerate(question_list, start=1):154 print(f"🔹 Question {idx}: {question['title']} ({question['difficulty']})")155 print(f" Tags: {', '.join(question['tags'])}")156 print(f" LeetCode Link: {question['url']}\n")157 158# ---------------- Main ----------------159if __name__ == "__main__":160 # Example: Generate MCQs161 domain = "Python Programming"162 mcqs = generate_mcqs(domain)163 print(f"MCQs for domain '{domain}':\n")164 print(mcqs)165 166 # Example: Fetch coding questions167 coding_questions = generate_coding_questions(limit=5)168 if isinstance(coding_questions, list):169 print("\nHere are 5 random LeetCode questions:\n")170 print_questions(coding_questions)171 else:172 print(f"\nError: {coding_questions}")173 