{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://docs.aws.amazon.com/it_it/bedrock/latest/userguide/model-parameters-anthropic-claude-text-completion.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import boto3\n",
    "import yaml"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load credentials from YAML file\n",
    "with open(\"credentials.yml\", \"r\") as keyholder:\n",
    "    try:\n",
    "        credentials=yaml.safe_load(keyholder)\n",
    "    except yaml.YAMLError as exc:\n",
    "        print(exc)\n",
    "\n",
    "AWS_SERVER_PUBLIC_KEY=credentials['bedrock']['AWS_SERVER_PUBLIC_KEY']\n",
    "AWS_SERVER_SECRET_KEY=credentials['bedrock']['AWS_SERVER_SECRET_KEY']\n",
    "REGION_NAME=credentials['bedrock']['REGION_NAME']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_input_files():\n",
    "    # Load candidate resumes\n",
    "    with open(\"candidate_resumes.json\", \"r\") as candidates_file:\n",
    "        candidates = json.load(candidates_file)\n",
    "\n",
    "    # Load job description\n",
    "    with open(\"job_description.json\", \"r\") as job_desc_file:\n",
    "        job_description = json.load(job_desc_file)\n",
    "\n",
    "    return candidates, job_description"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize the Bedrock client\n",
    "client = boto3.client(\n",
    "    \"bedrock-runtime\",\n",
    "    region_name=REGION_NAME,\n",
    "    aws_access_key_id=AWS_SERVER_PUBLIC_KEY,\n",
    "    aws_secret_access_key=AWS_SERVER_SECRET_KEY,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rank_candidates_with_claude(candidates, job_description):\n",
    "    \n",
    "    job_desc_text = job_description[\"job_description\"]\n",
    "\n",
    "    prompt_template = (\n",
    "        \"Human: You are an AI model skilled in evaluating resumes for job positions. \"\n",
    "        \"The job description is as follows:\\n{job_description}\\n\\n\"\n",
    "        \"Here are the candidate resumes:\\n\"\n",
    "        \"{candidate_resumes}\\n\\n\"\n",
    "        \"Please rank the candidates based on how well they match the job description, \"\n",
    "        \"providing a brief explanation for each ranking. Please explicitly give a number from 0 to 100 on how the candidate fits the position.\\n\\n\"\n",
    "        \"Assistant:\"\n",
    "    )\n",
    "\n",
    "    # Prepare the candidates' details as text\n",
    "    candidate_texts = []\n",
    "    for candidate in candidates:\n",
    "        candidate_texts.append(\n",
    "            f\"Name: {candidate['name']}\\n\"\n",
    "            f\"Skills: {candidate['skills']}\\n\"\n",
    "            f\"Experience: {candidate['experience']}\\n\"\n",
    "            f\"Education: {candidate['education']}\\n\"\n",
    "        )\n",
    "    candidates_combined = \"\\n\\n\".join(candidate_texts)\n",
    "\n",
    "    # Construct the prompt\n",
    "    prompt = prompt_template.format(\n",
    "        job_description=job_desc_text,\n",
    "        candidate_resumes=candidates_combined\n",
    "    )\n",
    "\n",
    "    try:\n",
    "        # Invoke Anthropic Claude v2 model\n",
    "        body = json.dumps({\n",
    "                \"prompt\": prompt,\n",
    "                \"max_tokens_to_sample\": 1000  # Adjust as needed\n",
    "            })\n",
    "        modelId = \"anthropic.claude-v2\"\n",
    "        accept = \"application/json\"\n",
    "        contentType = \"application/json\"\n",
    "\n",
    "        response = client.invoke_model(\n",
    "            body=body, modelId=modelId, accept=accept, contentType=contentType\n",
    "        )\n",
    "\n",
    "\n",
    "        # Access token counts from response headers\n",
    "        input_tokens = response[\"ResponseMetadata\"][\"HTTPHeaders\"].get(\"x-amzn-bedrock-input-token-count\", \"Unknown\")\n",
    "        output_tokens = response[\"ResponseMetadata\"][\"HTTPHeaders\"].get(\"x-amzn-bedrock-output-token-count\", \"Unknown\")\n",
    "\n",
    "        print(f\"Input Tokens: {input_tokens}\")\n",
    "        print(f\"Output Tokens: {output_tokens}\")\n",
    "\n",
    "        # Debug: Print the raw response\n",
    "        print(\"Raw response received from the model:\")\n",
    "        print(response)\n",
    "\n",
    "        # Parse the model's response\n",
    "        response_body = response[\"body\"].read().decode('utf-8')\n",
    "        print(\"Decoded response body:\")\n",
    "        print(response_body)  # Debug the decoded response body\n",
    "        model_output = json.loads(response_body)\n",
    "\n",
    "        if \"completion\" in model_output:\n",
    "            return model_output[\"completion\"]\n",
    "        else:\n",
    "            print(\"Error: Missing 'completion' in response.\")\n",
    "            return None\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Error while calling the model: {e}\")\n",
    "        return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input Tokens: 550\n",
      "Output Tokens: 285\n",
      "Raw response received from the model:\n",
      "{'ResponseMetadata': {'RequestId': '8c951b62-eecf-431f-b4a9-2c4d9c6684ef', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Thu, 19 Dec 2024 11:01:31 GMT', 'content-type': 'application/json', 'content-length': '1415', 'connection': 'keep-alive', 'x-amzn-requestid': '8c951b62-eecf-431f-b4a9-2c4d9c6684ef', 'x-amzn-bedrock-invocation-latency': '10341', 'x-amzn-bedrock-output-token-count': '285', 'x-amzn-bedrock-input-token-count': '550'}, 'RetryAttempts': 0}, 'contentType': 'application/json', 'body': <botocore.response.StreamingBody object at 0x1098bb7c0>}\n",
      "Decoded response body:\n",
      "{\"type\":\"completion\",\"completion\":\" Here are the candidate rankings and explanations:\\n\\n1. Edward Turner (90/100) - Has very relevant skills in Python, Django, AWS services like S3, and infrastructure provisioning with Terraform. 4+ years of backend development experience and has worked on designing REST APIs. Fits the job requirements very closely.\\n\\n2. Alice Smith (80/100) - Strong skills in Python, Django and AWS Lambda, S3. 3 years of relevant development experience including building web applications with Django. Lacks explicit mention of REST APIs or communication skills. Overall a good fit.\\n\\n3. Diana Morales (70/100) - Has Python experience and some AWS/cloud knowledge. Background seems more tailored for data science and analytics roles though. The FastAPI and Azure experience is less relevant for this position focused on Django and AWS. Still moderately aligned.\\n\\n4. Charlie Lee (60/100) - Has some relevant Python and DynamoDB experience, but is missing skills in Django and broader AWS services. Experience is focused on front-end web development rather than back-end systems. Partial fit but lacks key requirements.  \\n\\n5. Bob Johnson (40/100) - Does not have any Python or AWS experience specified. The Java and Spring background is less relevant for this Python/Django focused role. Weak alignment with the job description overall.\",\"stop_reason\":\"stop_sequence\",\"stop\":\"\\n\\nHuman:\"}\n",
      "Ranking and feedback from Claude v2:\n",
      " Here are the candidate rankings and explanations:\n",
      "\n",
      "1. Edward Turner (90/100) - Has very relevant skills in Python, Django, AWS services like S3, and infrastructure provisioning with Terraform. 4+ years of backend development experience and has worked on designing REST APIs. Fits the job requirements very closely.\n",
      "\n",
      "2. Alice Smith (80/100) - Strong skills in Python, Django and AWS Lambda, S3. 3 years of relevant development experience including building web applications with Django. Lacks explicit mention of REST APIs or communication skills. Overall a good fit.\n",
      "\n",
      "3. Diana Morales (70/100) - Has Python experience and some AWS/cloud knowledge. Background seems more tailored for data science and analytics roles though. The FastAPI and Azure experience is less relevant for this position focused on Django and AWS. Still moderately aligned.\n",
      "\n",
      "4. Charlie Lee (60/100) - Has some relevant Python and DynamoDB experience, but is missing skills in Django and broader AWS services. Experience is focused on front-end web development rather than back-end systems. Partial fit but lacks key requirements.  \n",
      "\n",
      "5. Bob Johnson (40/100) - Does not have any Python or AWS experience specified. The Java and Spring background is less relevant for this Python/Django focused role. Weak alignment with the job description overall.\n"
     ]
    }
   ],
   "source": [
    "candidates, job_description = read_input_files()\n",
    "result = rank_candidates_with_claude(candidates, job_description)\n",
    "\n",
    "if result:\n",
    "    print(\"Ranking and feedback from Claude v2:\")\n",
    "    print(result)\n",
    "else:\n",
    "    print(\"Failed to get results from the model.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "dinoVenv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
