SOCAv2 / main.py
Rakshitjan's picture
Update main.py
c57cc4a verified
raw
history blame
11 kB
# # main.py
# from fastapi import FastAPI, HTTPException
# from pydantic import BaseModel
# from typing import Dict
# import os
# from groq import Groq
# app = FastAPI()
# # Pydantic model for request
# class ScoreInput(BaseModel):
# score_percentages: Dict[str, float]
# time_percentages: Dict[str, float]
# # Helper functions
# def get_final_score(score_percentages: Dict[str, float], time_percentages: Dict[str, float]) -> Dict[str, float]:
# final_score = {}
# for skill in score_percentages:
# score_avg = (score_percentages[skill] + time_percentages[skill]) / 2
# final_score[skill] = score_avg
# return final_score
# def get_strengths_and_weaknesses(final_score: Dict[str, float]):
# sorted_skills = sorted(
# [(skill, score) for skill, score in final_score.items()],
# key=lambda item: item[1],
# reverse=True
# )
# num_skills = len(sorted_skills)
# if num_skills == 0:
# return [], [], []
# split1 = num_skills // 3
# split2 = 2 * (num_skills // 3)
# strengths = sorted_skills[:split1]
# opportunities = sorted_skills[split1:split2]
# challenges = sorted_skills[split2:]
# return strengths, opportunities, challenges
# # FastAPI route
# @app.post("/analyze")
# async def analyze_scores(input_data: ScoreInput):
# final_score = get_final_score(input_data.score_percentages, input_data.time_percentages)
# strengths, opportunities, challenges = get_strengths_and_weaknesses(final_score)
# # Groq API call
# api_key = os.getenv("GROQ_API_KEY")
# if not api_key:
# raise HTTPException(status_code=500, detail="Groq API key not found")
# client = Groq(api_key=api_key)
# sys_prompt = f"""You are an advanced language model trained to analyze student responses from a questionnaire on Academic, Cognitive, and Study Profile aspects related to JEE Mains preparation. Your task is to generate a personalized SCO (Strengths, Challenges, Opportunities) analysis and an Action Plan section based on the user's inputs.
# You have been provided with the strengths {strengths}, Opportunities {opportunities} and Challenges {challenges} skills of the user
# Output Structure:
# SCO Analysis:
# Strengths:
# - List the student's strengths based on their {strengths} skills
# - Let the student now how they can use these strengths in their JEE preparation and exam to improve their score.
# - Also tell them how do they improve their score more.
# Opportunities:
# - List the student's strengths based on their {opportunities} skills
# - Suggest opportunities for improvement by leveraging the student's strengths and addressing their challenges.
# - Recommend ways to enhance their score in the {opportunities} skills.
# - Also tell them if they improve in these skills what opportunities they have in improving their scores
# Challenges:
# - List the student's strengths based on their {challenges} skills
# - Guide the student that these skills are basically the core area where they are lacking
# - Tell them that if they continue not focusing upon them they might get far away from their JEE goal.
# Action Plan:
# - Provide a detailed plan to the student to improve in the {challenges} skills.
# - Recommend targeted strategies, resources, and techniques to improve their {challenges} skills.
# - Let them know if they improve these areas how it can help boost their scores and make their preparation more effective.
# - Incorporate time management, revision, and test-taking strategies specific to JEE Mains and the identified subjects/topics/subtopics.
# Things that LLM need to make sure:
# 1) Your analysis and action plan should be comprehensive, consistent, and tailored to the individual student's responses while leveraging your knowledge of the JEE Mains exam context, the mapping of subjects/topics to general cognitive traits and skills, and the ability to identify overarching trends across related subjects/topics.
# 2) Make sure you give the output that extracts the student.
# 3) Make sure you give out output in bullet points.
# 4) While entering a new line in the output use "\n" new line character.
# 5) Make the output very much JEE (Joint Entrance Examination) based and give everything with context to Physics , Chemistry and Maths JEE syllabus.
# 6) Use Italics, Bold and underline appropriately to improve the output more.
# 7) Bold text where you are taking chapter names from Physics , Chemsitry and Maths only which are in syllabus of Joint Entrance Examination.
# 8) Dont use "+" or any other special symbol whenever you want to break a line use "\n" to do it in the output.
# """
# try:
# chat_completion = client.chat.completions.create(
# messages=[
# {"role": "system", "content": sys_prompt},
# {"role": "user", "content": f"Generate the SOCA analysis based on the system prompt and {strengths}, {opportunities} and {challenges}. MAKE SURE WE STRICTLY FOLLOW THE STRUCTURE."},
# ],
# model="llama3-70b-8192",
# )
# analysis = chat_completion.choices[0].message.content
# except Exception as e:
# raise HTTPException(status_code=500, detail=f"Error calling Groq API: {str(e)}")
# return {"analysis": analysis}
# if __name__ == "__main__":
# import uvicorn
# uvicorn.run(app, host="0.0.0.0", port=8000)
# Merger of SOCA v1 and SOCA v2
from embedchain import App
from fastapi import FastAPI, HTTPException
from mangum import Mangum
from pydantic import BaseModel
from typing import Dict
import os
from groq import Groq
app = FastAPI()
handler = Mangum(app)
# Pydantic model for request
class ScoreInput(BaseModel):
score_percentages: Dict[str, float]
time_percentages: Dict[str, float]
# Helper functions
def get_final_score(score_percentages: Dict[str, float], time_percentages: Dict[str, float]) -> Dict[str, float]:
final_score = {}
for skill in score_percentages:
score_avg = (score_percentages[skill] + time_percentages[skill]) / 2
final_score[skill] = score_avg
return final_score
def get_strengths_and_weaknesses(final_score: Dict[str, float]):
sorted_skills = sorted(
[(skill, score) for skill, score in final_score.items()],
key=lambda item: item[1],
reverse=True
)
num_skills = len(sorted_skills)
if num_skills == 0:
return [], [], []
split1 = num_skills // 3
split2 = 2 * (num_skills // 3)
strengths = sorted_skills[:split1]
opportunities = sorted_skills[split1:split2]
challenges = sorted_skills[split2:]
return strengths, opportunities, challenges
# FastAPI route
@app.post("/analyze")
async def analyze_scores(input_data: ScoreInput):
final_score = get_final_score(input_data.score_percentages, input_data.time_percentages)
strengths, opportunities, challenges = get_strengths_and_weaknesses(final_score)
# Groq API call
api_key2 = os.getenv("GROQ_API_KEY")
if not api_key:
raise HTTPException(status_code=500, detail="Groq API key not found")
client2 = Groq(api_key=api_key2)
sys_prompt = f"""You are an advanced language model trained to analyze student responses from a questionnaire on Academic, Cognitive, and Study Profile aspects related to JEE Mains preparation. Your task is to generate a personalized SCO (Strengths, Challenges, Opportunities) analysis and an Action Plan section based on the user's inputs.
You have been provided with the strengths {strengths}, Opportunities {opportunities} and Challenges {challenges} skills of the user
Output Structure:
SCO Analysis:
Strengths:
- List the student's strengths based on their {strengths} skills
- Let the student now how they can use these strengths in their JEE preparation and exam to improve their score.
- Also tell them how do they improve their score more.
Opportunities:
- List the student's strengths based on their {opportunities} skills
- Suggest opportunities for improvement by leveraging the student's strengths and addressing their challenges.
- Recommend ways to enhance their score in the {opportunities} skills.
- Also tell them if they improve in these skills what opportunities they have in improving their scores
Challenges:
- List the student's strengths based on their {challenges} skills
- Guide the student that these skills are basically the core area where they are lacking
- Tell them that if they continue not focusing upon them they might get far away from their JEE goal.
Action Plan:
- Provide a detailed plan to the student to improve in the {challenges} skills.
- Recommend targeted strategies, resources, and techniques to improve their {challenges} skills.
- Let them know if they improve these areas how it can help boost their scores and make their preparation more effective.
- Incorporate time management, revision, and test-taking strategies specific to JEE Mains and the identified subjects/topics/subtopics.
Things that LLM need to make sure:
1) Your analysis and action plan should be comprehensive, consistent, and tailored to the individual student's responses while leveraging your knowledge of the JEE Mains exam context, the mapping of subjects/topics to general cognitive traits and skills, and the ability to identify overarching trends across related subjects/topics.
2) Make sure you give the output that extracts the student.
3) Make sure you give out output in bullet points.
4) While entering a new line in the output use "\n" new line character.
5) Make the output very much JEE (Joint Entrance Examination) based and give everything with context to Physics , Chemistry and Maths JEE syllabus.
6) Use Italics, Bold and underline appropriately to improve the output more.
7) Bold text where you are taking chapter names from Physics , Chemsitry and Maths only which are in syllabus of Joint Entrance Examination.
8) Dont use "+" or any other special symbol whenever you want to break a line use "\n" to do it in the output.
"""
try:
chat_completion = client2.chat.completions.create(
messages=[
{"role": "system", "content": sys_prompt},
{"role": "user", "content": f"Generate the SOCA analysis based on the system prompt and {strengths}, {opportunities} and {challenges}. MAKE SURE WE STRICTLY FOLLOW THE STRUCTURE."},
],
model="llama3-70b-8192",
)
analysis = chat_completion.choices[0].message.content
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error calling Groq API: {str(e)}")
return {"analysis": analysis}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)