Files

150 lines
4.3 KiB
Go

package analyzer
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
type DeepSeekAnalyzer struct {
apiKey string
baseURL string
systemPrompt string
userPromptTemplate string
client *http.Client
}
func NewDeepSeekAnalyzer(apiKey, baseURL, systemPrompt, userPromptTemplate string) *DeepSeekAnalyzer {
if baseURL == "" {
baseURL = "https://api.deepseek.com"
}
return &DeepSeekAnalyzer{
apiKey: apiKey,
baseURL: strings.TrimRight(baseURL, "/"),
systemPrompt: systemPrompt,
userPromptTemplate: userPromptTemplate,
client: &http.Client{Timeout: 30 * time.Second},
}
}
func (d *DeepSeekAnalyzer) buildUserPrompt(jobTitle, rawContent string) string {
if d.userPromptTemplate == "" {
return fmt.Sprintf("Analyze the following job description for candidate Pengzhan Hao.\n\nJob Title: %s\n\nJob Description:\n%s\n\nProvide the structured evaluation adhering to the JSON schema.", jobTitle, rawContent)
}
res := strings.ReplaceAll(d.userPromptTemplate, "{{.JobTitle}}", jobTitle)
res = strings.ReplaceAll(res, "{{.JobContent}}", rawContent)
return res
}
func (d *DeepSeekAnalyzer) AnalyzeJD(ctx context.Context, jobTitle, rawContent string) (*AnalysisOutput, error) {
sysPrompt := d.systemPrompt
if sysPrompt == "" {
sysPrompt = "You are an expert technical resume screener. You MUST respond with a valid JSON object matching {\"ai_score\": 80.0, \"is_qualified\": true, \"summary\": \"...\", \"matched_highlights\": [...], \"missing_highlights\": [...], \"tailoring_suggestions\": [...]}."
}
userPrompt := d.buildUserPrompt(jobTitle, rawContent)
reqBody := map[string]interface{}{
"model": "deepseek-chat",
"messages": []map[string]string{
{"role": "system", "content": sysPrompt},
{"role": "user", "content": userPrompt},
},
"response_format": map[string]string{
"type": "json_object",
},
}
jsonBytes, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal DeepSeek payload: %w", err)
}
url := fmt.Sprintf("%s/chat/completions", d.baseURL)
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonBytes))
if err != nil {
return nil, fmt.Errorf("failed to create DeepSeek request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", d.apiKey))
resp, err := d.client.Do(req)
if err != nil {
return nil, fmt.Errorf("DeepSeek API call failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read DeepSeek response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("DeepSeek API error (status %d): %s", resp.StatusCode, string(respBytes))
}
var dsResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBytes, &dsResp); err != nil {
return nil, fmt.Errorf("failed to decode DeepSeek envelope: %w", err)
}
if len(dsResp.Choices) == 0 {
return nil, fmt.Errorf("empty choices in DeepSeek response")
}
rawJSON := cleanJSONResponse(dsResp.Choices[0].Message.Content)
var output AnalysisOutput
if err := json.Unmarshal([]byte(rawJSON), &output); err != nil {
return nil, fmt.Errorf("failed to parse DeepSeek JSON output: %w (content: %s)", err, rawJSON)
}
// Sanitize output bounds
if output.AIScore < 0 {
output.AIScore = 0
} else if output.AIScore > 100 {
output.AIScore = 100
}
if output.AIScore >= 60.0 {
output.IsQualified = true
}
if output.MatchedHighlights == nil {
output.MatchedHighlights = []string{}
}
if output.MissingHighlights == nil {
output.MissingHighlights = []string{}
}
if output.TailoringSuggestions == nil {
output.TailoringSuggestions = []string{}
}
return &output, nil
}
func cleanJSONResponse(raw string) string {
cleaned := strings.TrimSpace(raw)
if strings.HasPrefix(cleaned, "```json") {
cleaned = strings.TrimPrefix(cleaned, "```json")
cleaned = strings.TrimSuffix(cleaned, "```")
} else if strings.HasPrefix(cleaned, "```") {
cleaned = strings.TrimPrefix(cleaned, "```")
cleaned = strings.TrimSuffix(cleaned, "```")
}
return strings.TrimSpace(cleaned)
}