Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you provide an example of using DeepSeek-R1 with FastAPI for resume analysis


Can you provide an example of using DeepSeek-R1 with FastAPI for resume analysis


Here's a detailed example of using DeepSeek-R1 with FastAPI for resume analysis. This example will guide you through setting up a FastAPI application that integrates with the DeepSeek-R1 model for analyzing resumes.

Step 1: Setting Up the Environment

First, ensure you have Python installed on your system. You will also need to install FastAPI and other necessary packages. You can install them using pip:

bash
pip install fastapi uvicorn together

Additionally, you need to set up the DeepSeek-R1 model. Since DeepSeek-R1 can be run locally, you might need to download and configure it according to your setup. For this example, we'll assume you're using the Together.ai API for simplicity.

Step 2: Creating the FastAPI Application

Create a new Python file named `main.py` and start by setting up your FastAPI application:

python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import together
import json

# Initialize the FastAPI app
app = FastAPI()

# Set up the Together.ai API client
class TogetherAIService:
    def __init__(self):
        together.api_key = "YOUR_TOGETHER_API_KEY"
        self.model = "deepseek-ai/DeepSeek-R1"

    def _construct_prompt(self, resume_content: str, career_interests: Optional[str] = None) -> str:
        base_prompt = f"""Please analyze this resume and provide detailed feedback in the following format:

Resume Content:

{resume_content}

Please provide your analysis in JSON format with the following structure:

{
"summary": "Brief overview of the resume",
"strengths": ["List of key strengths"],
"weaknesses": ["Areas for improvement"],
"recommendations": ["Specific recommendations"],
"keywords_missing": ["Important keywords that should be added"],
"formatting_suggestions": ["Suggestions for better formatting"],
"impact_score": "Score out of 10",
"detailed_feedback": {
"experience": "Feedback on experience section",
"education": "Feedback on education section",
"skills": "Feedback on skills section"
}
}

"""
        
        if career_interests:
            base_prompt += f"\n\nCareer Interests/Goals:\n{career_interests}\nPlease tailor the feedback considering these career interests."
        
        return base_prompt

    async def analyze_resume(self, resume_content: str, career_interests: Optional[str] = None) -> dict:
        try:
            prompt = self._construct_prompt(resume_content, career_interests)
            system_prompt = "You are an expert resume reviewer with years of experience in HR and recruitment. Provide detailed, constructive feedback on resumes."
            full_prompt = f"{system_prompt}\n\n{prompt}"
            
            response = together.Completion.create(
                prompt=full_prompt,
                model=self.model,
                max_tokens=2048,
                temperature=0.7,
                top_p=0.9,
                top_k=50,
                repetition_penalty=1.0,
                stop=['']
            )
            
            text = response.output.choices[0].text if hasattr(response, 'output') else response.choices[0].text
            
            # Parse the response
            start_idx = text.find('{')
            end_idx = text.rfind('}') + 1
            
            if start_idx == -1 or end_idx == 0:
                raise json.JSONDecodeError("No JSON found in response", text, 0)
            
            json_str = text[start_idx:end_idx]
            analysis = json.loads(json_str)
            
            required_fields = [
                "summary", "strengths", "weaknesses", "recommendations",
                "keywords_missing", "formatting_suggestions", "impact_score",
                "detailed_feedback"
            ]
            
            for field in required_fields:
                if field not in analysis:
                    analysis[field] = []
            
            return analysis
        
        except Exception as e:
            raise Exception(f"Error calling Together AI API: {str(e)}")

# Initialize the service
service = TogetherAIService()

# Define the request model
class ResumeRequest(BaseModel):
    resume_content: str
    career_interests: Optional[str]

# Define the endpoint for resume analysis
@app.post("/analyze_resume")
async def analyze_resume(request: ResumeRequest):
    analysis = await service.analyze_resume(request.resume_content, request.career_interests)
    return analysis

Step 3: Running the Application

To run the FastAPI application, use the following command:

bash
uvicorn main:app --reload

This will start your server, and you can now interact with it by sending POST requests to the `/analyze_resume` endpoint.

Example Usage

To test the endpoint, you can use a tool like `curl` or Postman. Here's an example using `curl`:

bash
curl -X POST \
  http://127.0.0.1:8000/analyze_resume \
  -H 'Content-Type: application/json' \
  -d '{"resume_content": "Your resume content here", "career_interests": "Optional career interests"}'

Replace `"Your resume content here"` with the actual content of the resume you want to analyze, and optionally include career interests if desired.

Conclusion

This example demonstrates how to integrate DeepSeek-R1 with FastAPI for resume analysis. By leveraging the capabilities of DeepSeek-R1, you can create a robust and cost-effective resume analysis tool that provides detailed feedback and insights. Remember to replace `"YOUR_TOGETHER_API_KEY"` with your actual API key if you're using the Together.ai API. If you're running DeepSeek-R1 locally, you'll need to adjust the code accordingly to interact with your local setup.

Citations:
[1] https://blog.stackademic.com/integrating-deepseek-r1-with-fastapi-building-an-ai-powered-resume-analyzer-code-demo-4e1cc29cdc6e
[2] https://www.youtube.com/watch?v=sGUjmyfof4Q
[3] https://www.datacamp.com/blog/deepseek-r1-vs-v3
[4] https://dzone.com/articles/smarter-hiring-building-an-ai-powered-full-stack-r
[5] https://www.datacamp.com/tutorial/fine-tuning-deepseek-r1-reasoning-model
[6] https://github.com/taishi-i/awesome-ChatGPT-repositories
[7] https://www.linkedin.com/posts/glencathey_check-out-how-deepseeks-r1-transparently-activity-7290398540256727040-HQaW
[8] https://www.reddit.com/r/singularity/comments/1i9rcog/seems_like_deepseek_is_a_better_choice_than/
[9] https://www.linkedin.com/pulse/building-langchain-powered-fastapi-service-optimize-rany-d6d0c