A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Job Posting Agent using DeepSeek V4 Flash on NVIDIA NIM
Tiioluwani301f68362b28
diff --git a/ai_agents/job_posting_agent/.env.example b/ai_agents/job_posting_agent/.env.examplenew file mode 100644index 0000000..78b5611--- /dev/null+++ b/ai_agents/job_posting_agent/.env.example@@ -0,0 +1 @@+NVIDIA_API_KEY=your_nvidia_api_key_herediff --git a/ai_agents/job_posting_agent/README.md b/ai_agents/job_posting_agent/README.mdnew file mode 100644index 0000000..dd8c94e--- /dev/null+++ b/ai_agents/job_posting_agent/README.md@@ -0,0 +1,116 @@+# Job Posting Agent++> Generate tailored job postings from a company name and role using DeepSeek V4 Flash on NVIDIA NIM.++## Overview++Job Posting Agent is a Streamlit app that turns a company name and job title into a complete, professional job posting. Three LangChain agents run in sequence: a Research Analyst gathers company context, a Job Requirements Specialist defines role skills and qualifications, and a Job Posting Writer produces the final posting. Results appear in expandable research and requirements sections, with the full posting ready to copy.++**Example input:** Company `Anthropic` · Role `Senior Technical Writer`++## Demo++++## Features++- Simple Streamlit form for company name and job role+- Sequential multi-agent pipeline (research → requirements → job posting)+- Company culture and values research via web search+- Role-specific technical and soft skill requirements+- Polished job posting with summary, responsibilities, requirements, and apply instructions+- Expandable **Company Research** and **Role Requirements** sections+- **Copy to Clipboard** button for the final posting++## Tech Stack++| Layer | Technology |+|-------|------------|+| Agent orchestration | LangChain |+| LLM | [DeepSeek V4 Flash](https://build.nvidia.com/deepseek-ai/deepseek-v4-flash) (`deepseek-ai/deepseek-v4-flash`) via NVIDIA NIM |+| Web search | DuckDuckGo (`ddgs`) via `langchain-community` |+| UI | Streamlit |+| API base URL | `https://integrate.api.nvidia.com/v1` |++## Prerequisites++- Python 3.11 or later+- [NVIDIA API key](https://build.nvidia.com/) (starts with `nvapi-`)+- Internet access for NVIDIA NIM and DuckDuckGo search++## Installation++Clone the repository and open the project directory:++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/job-posting-agent+```++**Windows**++```bash+py -m venv .venv+.\.venv\Scripts\Activate.ps1+pip install -r requirements.txt+```++**macOS / Linux**++```bash+python3 -m venv .venv+source .venv/bin/activate+pip install -r requirements.txt+```++Copy the example environment file and add your API key:++```bash+cp .env.example .env+```++## Usage++1. Set `NVIDIA_API_KEY` in `.env` (see [Environment Variables](#environment-variables)).+2. Start the app:++```bash+streamlit run app.py+```++3. Enter a company and role (e.g. **Anthropic**, **Senior Technical Writer**).+4. Click **Generate Job Posting** and wait for the pipeline to finish.++> **Note:** The first request on the NVIDIA NIM free tier may take **30–60 seconds** while the model warms up. Later requests are usually faster.++## Environment Variables++| Variable | Required | Description |+|----------|----------|-------------|+| `NVIDIA_API_KEY` | Yes | API key from [NVIDIA Build](https://build.nvidia.com/). Used to call DeepSeek V4 Flash on NVIDIA NIM. |++Example `.env`:++```env+NVIDIA_API_KEY=nvapi-your-key-here+```++## Project Structure++```text+job-posting-agent/+├── app.py # Streamlit UI+├── nvidia_client.py # NVIDIA NIM client (chat completions + polling)+├── config.py # Configuration helpers+├── prompts.py # Agent system prompts+├── agents/+│ ├── __init__.py+│ └── pipeline.py # Multi-step agent orchestration+├── scripts/+│ └── test_nvidia.py # Optional API connectivity test+├── assets/+│ └── demo.png # Screenshot for README+├── requirements.txt+├── .env.example+└── README.md+```diff --git a/ai_agents/job_posting_agent/agents/__init__.py b/ai_agents/job_posting_agent/agents/__init__.pynew file mode 100644index 0000000..fd05abf--- /dev/null+++ b/ai_agents/job_posting_agent/agents/__init__.py@@ -0,0 +1,3 @@+from agents.pipeline import run_pipeline++__all__ = ["run_pipeline"]diff --git a/ai_agents/job_posting_agent/agents/pipeline.py b/ai_agents/job_posting_agent/agents/pipeline.pynew file mode 100644index 0000000..5d6d3f2--- /dev/null+++ b/ai_agents/job_posting_agent/agents/pipeline.py@@ -0,0 +1,103 @@+import re+import time+from collections.abc import Callable++import httpx++from nvidia_client import NvidiaAPIError, chat_completion++SECTION_NAMES = ("COMPANY RESEARCH", "ROLE REQUIREMENTS", "JOB POSTING")+MAX_OUTPUT_TOKENS = 1500+++class PipelineResult:+ def __init__(+ self,+ company_research: str,+ role_requirements: str,+ job_posting: str,+ ):+ self.company_research = company_research+ self.role_requirements = role_requirements+ self.job_posting = job_posting+++def _build_prompt(company: str, role: str) -> str:+ return f"""+You are a job posting expert. Complete these three tasks for {company} hiring a {role}:++1. COMPANY RESEARCH: Based on your knowledge of {company}, describe their culture, values, and work environment in 2-3 sentences.++2. ROLE REQUIREMENTS: List the top 5 technical skills and 3 soft skills required for a {role} at {company}.++3. JOB POSTING: Write a complete professional job posting for a {role} at {company} including: job summary, responsibilities (5 bullet points), requirements (5 bullet points), and how to apply.++Format each section clearly with the headers: COMPANY RESEARCH, ROLE REQUIREMENTS, JOB POSTING.+""".strip()+++def _normalize_header(line: str) -> str | None:+ cleaned = line.strip().upper()+ cleaned = re.sub(r"^#+\s*", "", cleaned)+ cleaned = re.sub(r"^\*+|\*+$", "", cleaned).strip()+ cleaned = cleaned.rstrip(":").strip()+ if cleaned in SECTION_NAMES:+ return cleaned+ return None+++def parse_sections(response: str) -> dict[str, str]:+ sections: dict[str, list[str]] = {name: [] for name in SECTION_NAMES}+ current: str | None = None++ for line in response.splitlines():+ header = _normalize_header(line)+ if header:+ current = header+ continue+ if current:+ sections[current].append(line)++ return {name: "\n".join(lines).strip() for name, lines in sections.items()}+++def run_pipeline(+ company: str,+ role: str,+ on_stage: Callable[[str], None] | None = None,+) -> PipelineResult:+ pipeline_start = time.perf_counter()++ def notify(stage: str) -> None:+ if on_stage:+ on_stage(stage)++ notify("Generating with DeepSeek V4 Flash (single request)...")+ print(f"[Pipeline] Calling NVIDIA NIM for {company} / {role}", flush=True)++ try:+ response = chat_completion(+ [{"role": "user", "content": _build_prompt(company, role)}],+ max_tokens=MAX_OUTPUT_TOKENS,+ )+ except (NvidiaAPIError, TimeoutError, ValueError, httpx.HTTPError) as exc:+ raise ValueError(+ f"Could not complete NVIDIA API request: {exc}\n\n"+ "Wait 1–2 minutes and try again. Confirm NVIDIA_API_KEY in .env "+ "from https://build.nvidia.com/ (keys start with nvapi-)."+ ) from exc++ parsed = parse_sections(response)+ company_research = parsed["COMPANY RESEARCH"] or response+ role_requirements = parsed["ROLE REQUIREMENTS"] or ""+ job_posting = parsed["JOB POSTING"] or response++ elapsed = time.perf_counter() - pipeline_start+ print(f"[Pipeline] Finished in {elapsed:.1f}s", flush=True)++ notify("Complete")+ return PipelineResult(+ company_research=company_research,+ role_requirements=role_requirements,+ job_posting=job_posting,+ )diff --git a/ai_agents/job_posting_agent/app.py b/ai_agents/job_posting_agent/app.pynew file mode 100644index 0000000..7d762fe--- /dev/null+++ b/ai_agents/job_posting_agent/app.py@@ -0,0 +1,125 @@+import json+import traceback++import streamlit as st+import streamlit.components.v1 as components++from agents.pipeline import run_pipeline++st.set_page_config(+ page_title="Job Posting Agent",+ page_icon="📋",+ layout="wide",+)++st.title("📋 Job Posting Agent")+st.markdown(+ "Enter a company and role. Three LangChain agents research the company, "+ "define requirements, and write a tailored job posting."+)++col1, col2 = st.columns(2)+with col1:+ company = st.text_input("Company Name", placeholder="e.g. Stripe")+with col2:+ role = st.text_input("Job Role", placeholder="e.g. Senior Software Engineer")++generate = st.button("Generate Job Posting", type="primary", use_container_width=True)++if generate:+ if not company.strip() or not role.strip():+ st.error("Please enter both a company name and a job role.")+ else:+ try:+ with st.status("Running agents...", expanded=True) as status:++ def on_stage(message: str) -> None:+ status.update(label=message)++ result = run_pipeline(+ company.strip(),+ role.strip(),+ on_stage=on_stage,+ )+ status.update(label="All agents finished.", state="complete")++ st.divider()+ st.subheader("Final Job Posting")++ st.text_area(+ "Job Posting",+ value=result.job_posting,+ height=420,+ label_visibility="collapsed",+ )++ posting_json = json.dumps(result.job_posting)+ components.html(+ f"""+ <button id="copy-btn" style="+ margin-top: 0.5rem;+ padding: 0.5rem 1.25rem;+ background: #ff4b4b;+ color: white;+ border: none;+ border-radius: 0.5rem;+ font-size: 0.95rem;+ cursor: pointer;+ ">Copy to Clipboard</button>+ <span id="copy-status" style="margin-left: 0.75rem; color: #0a7;"></span>+ <script>+ const text = {posting_json};+ document.getElementById('copy-btn').onclick = async () => {{+ try {{+ await navigator.clipboard.writeText(text);+ document.getElementById('copy-status').textContent = 'Copied!';+ setTimeout(() => {{+ document.getElementById('copy-status').textContent = '';+ }}, 2000);+ }} catch (e) {{+ document.getElementById('copy-status').textContent = 'Copy failed';+ }}+ }};+ </script>+ """,+ height=60,+ )++ with st.expander("Company Research", expanded=False):+ st.markdown(result.company_research)++ with st.expander("Role Requirements", expanded=False):+ st.markdown(result.role_requirements)++ except ValueError as exc:+ st.error(str(exc))+ except Exception as exc:+ st.error(f"Pipeline failed: {exc}")+ with st.expander("Error details"):+ st.code(traceback.format_exc())+ st.caption(+ "Check your terminal for `[Pipeline]` / `[Research Analyst]` logs. "+ "Confirm `NVIDIA_API_KEY` in `.env` is valid and you have internet access."+ )++else:+ st.info("Fill in the form above and click **Generate Job Posting** to start.")++with st.sidebar:+ st.header("How it works")+ st.markdown(+ """+ 1. **Research Analyst** — searches DuckDuckGo for company culture, values, and news+ 2. **Job Requirements Specialist** — defines skills and qualifications for the role+ 3. **Job Posting Writer** — produces a polished, tailored job posting++ Powered by **DeepSeek V4 Flash** via NVIDIA NIM.+ """+ )+ st.markdown("---")+ st.caption("Set `NVIDIA_API_KEY` in your `.env` file to run.")+ st.caption("Watch the terminal running Streamlit for step-by-step logs.")+ st.caption(+ "First NVIDIA request may take 30–60s while the model warms up "+ "(you will see polling messages in the terminal)."+ )diff --git a/ai_agents/job_posting_agent/assets/demo.png b/ai_agents/job_posting_agent/assets/demo.pngnew file mode 100644index 0000000..5629f7aBinary files /dev/null and b/ai_agents/job_posting_agent/assets/demo.png differdiff --git a/ai_agents/job_posting_agent/config.py b/ai_agents/job_posting_agent/config.pynew file mode 100644index 0000000..6b860c6--- /dev/null+++ b/ai_agents/job_posting_agent/config.py@@ -0,0 +1,5 @@+"""Configuration constants (API calls go through nvidia_client.py)."""++from nvidia_client import MODEL_ID, REQUEST_TIMEOUT, get_api_key++__all__ = ["MODEL_ID", "REQUEST_TIMEOUT", "get_api_key"]diff --git a/ai_agents/job_posting_agent/nvidia_client.py b/ai_agents/job_posting_agent/nvidia_client.pynew file mode 100644index 0000000..1a50a7a--- /dev/null+++ b/ai_agents/job_posting_agent/nvidia_client.py@@ -0,0 +1,241 @@+"""+NVIDIA NIM client with 202 async polling support.++LangChain's OpenAI wrapper does not handle NVIDIA's 202 + NVCF-REQID polling,+which causes requests to hang indefinitely on cold starts.+"""++from __future__ import annotations++import os+import time+from typing import Any++import httpx+from dotenv import load_dotenv+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage++load_dotenv()++NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"+MODEL_ID = "deepseek-ai/deepseek-v4-flash"+HTTPX_TIMEOUT = httpx.Timeout(240.0, connect=30.0)+POLL_INTERVAL_SECONDS = 2+MAX_POLL_SECONDS = 280+MAX_RETRIES = 4+RETRY_BACKOFF_SECONDS = 3.0++# Transient errors when NVIDIA closes connections during warm-up (common on Windows).+TRANSIENT_ERRORS = (+ httpx.ReadError,+ httpx.ConnectError,+ httpx.RemoteProtocolError,+ httpx.WriteError,+ httpx.PoolTimeout,+ ConnectionError,+ TimeoutError,+)+++class NvidiaAPIError(Exception):+ """Raised when the NVIDIA API returns an error response."""+++def get_api_key() -> str:+ api_key = os.getenv("NVIDIA_API_KEY", "").strip()+ if not api_key or api_key == "your_nvidia_api_key_here":+ raise ValueError(+ "NVIDIA_API_KEY is not set. Add a valid key to your .env file "+ "(see .env.example). Get one at https://build.nvidia.com/"+ )+ return api_key+++def create_http_client() -> httpx.Client:+ """Fresh client per request — avoids reusing a connection NVIDIA already closed."""+ return httpx.Client(+ timeout=HTTPX_TIMEOUT,+ limits=httpx.Limits(max_keepalive_connections=0, max_connections=10),+ )+++def messages_to_openai(messages: list[BaseMessage]) -> list[dict[str, str]]:+ openai_messages: list[dict[str, str]] = []+ for message in messages:+ if isinstance(message, SystemMessage):+ openai_messages.append({"role": "system", "content": str(message.content)})+ elif isinstance(message, HumanMessage):+ openai_messages.append({"role": "user", "content": str(message.content)})+ elif isinstance(message, AIMessage):+ openai_messages.append({"role": "assistant", "content": str(message.content)})+ else:+ openai_messages.append({"role": "user", "content": str(message.content)})+ return openai_messages+++def _headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ "Accept": "application/json",+ }+++def _extract_content(data: dict[str, Any]) -> str:+ choices = data.get("choices")+ if choices:+ message = choices[0].get("message") or {}+ content = message.get("content")+ if content:+ return str(content)+ raise NvidiaAPIError(f"Unexpected NVIDIA response shape: {data!r}")+++def _raise_for_status(response: httpx.Response) -> None:+ if response.status_code == 401:+ raise NvidiaAPIError(+ "NVIDIA API unauthorized (401). Check that NVIDIA_API_KEY is valid."+ )+ if response.status_code == 403:+ raise NvidiaAPIError(+ "NVIDIA API forbidden (403). Your key may lack access to this model."+ )+ if response.status_code == 404:+ raise NvidiaAPIError(+ f"NVIDIA API not found (404). Model '{MODEL_ID}' may be unavailable."+ )+ try:+ response.raise_for_status()+ except httpx.HTTPStatusError as exc:+ detail = response.text[:500]+ raise NvidiaAPIError(+ f"NVIDIA API error {response.status_code}: {detail}"+ ) from exc+++def _request_with_retries(request_fn, label: str) -> httpx.Response:+ last_error: Exception | None = None+ for attempt in range(1, MAX_RETRIES + 1):+ client = create_http_client()+ try:+ response = request_fn(client)+ response.read()+ return response+ except TRANSIENT_ERRORS as exc:+ last_error = exc+ if attempt < MAX_RETRIES:+ wait = RETRY_BACKOFF_SECONDS * attempt+ print(+ f"[NVIDIA] {label} failed ({exc!r}) — "+ f"retry {attempt}/{MAX_RETRIES - 1} in {wait:.0f}s",+ flush=True,+ )+ time.sleep(wait)+ else:+ raise NvidiaAPIError(+ f"NVIDIA API connection failed after {MAX_RETRIES} attempts. "+ f"Last error: {exc}. This often happens when the free-tier "+ f"model is warming up — wait a minute and try again."+ ) from exc+ finally:+ client.close()+ raise NvidiaAPIError(f"NVIDIA API failed: {last_error}")+++def _poll_for_completion(api_key: str, request_id: str) -> dict[str, Any]:+ deadline = time.monotonic() + MAX_POLL_SECONDS+ poll_url = f"{NVIDIA_BASE_URL}/status/{request_id}"++ print(+ f"[NVIDIA] Model warming up (request {request_id[:8]}...) — polling",+ flush=True,+ )++ while time.monotonic() < deadline:+ def poll_once(client: httpx.Client) -> httpx.Response:+ return client.get(poll_url, headers=_headers(api_key))++ response = _request_with_retries(poll_once, "status poll")++ if response.status_code == 200:+ return response.json()++ if response.status_code == 202:+ status = response.headers.get("NVCF-STATUS", "pending")+ print(f"[NVIDIA] Still pending ({status})...", flush=True)+ time.sleep(POLL_INTERVAL_SECONDS)+ continue++ _raise_for_status(response)++ raise TimeoutError(+ f"NVIDIA API did not become ready within {MAX_POLL_SECONDS}s "+ f"(request {request_id})"+ )+++def _post_chat_completion(+ api_key: str, body: dict[str, Any]+) -> httpx.Response:+ def do_post(client: httpx.Client) -> httpx.Response:+ return client.post(+ f"{NVIDIA_BASE_URL}/chat/completions",+ headers=_headers(api_key),+ json=body,+ )++ return _request_with_retries(do_post, "chat completion")+++def chat_completion(+ messages: list[dict[str, str]] | list[BaseMessage],+ *,+ max_tokens: int = 500,+ temperature: float = 0.7,+) -> str:+ api_key = get_api_key()+ if messages and isinstance(messages[0], BaseMessage):+ payload_messages = messages_to_openai(messages) # type: ignore[arg-type]+ else:+ payload_messages = messages # type: ignore[assignment]++ body = {+ "model": MODEL_ID,+ "messages": payload_messages,+ "max_tokens": max_tokens,+ "temperature": temperature,+ "stream": False,+ }++ print(f"[NVIDIA] Calling {MODEL_ID}...", flush=True)++ response = _post_chat_completion(api_key, body)++ if response.status_code == 200:+ content = _extract_content(response.json())+ print("[NVIDIA] Response received.", flush=True)+ return content++ if response.status_code == 202:+ request_id = response.headers.get("NVCF-REQID") or response.headers.get(+ "nvcf-reqid"+ )+ if not request_id:+ raise NvidiaAPIError(+ "NVIDIA returned 202 but no NVCF-REQID header for polling."+ )+ result = _poll_for_completion(api_key, request_id)+ content = _extract_content(result)+ print("[NVIDIA] Response received after polling.", flush=True)+ return content++ _raise_for_status(response)+ raise NvidiaAPIError("Unreachable")+++def verify_connection() -> None:+ """Quick API check; raises on failure."""+ chat_completion(+ [{"role": "user", "content": "Reply with exactly: OK"}],+ max_tokens=16,+ )diff --git a/ai_agents/job_posting_agent/prompts.py b/ai_agents/job_posting_agent/prompts.pynew file mode 100644index 0000000..3f86916--- /dev/null+++ b/ai_agents/job_posting_agent/prompts.py@@ -0,0 +1,41 @@+RESEARCH_ANALYST_SYSTEM = """You are a Research Analyst specializing in employer branding and company intelligence.++Your job is to search the web and compile thorough, factual research about a company for use in a tailored job posting.++Focus your research on:+- Company culture and values+- Mission and vision+- Recent news, announcements, and milestones+- Work environment and employee experience signals+- Industry positioning and reputation++Synthesize the provided web search results into a clear, well-organized report with bullet points and short sections.+Cite specific facts where possible. If information is limited, note gaps honestly.+Do not invent facts—only report what your searches support."""++JOB_REQUIREMENTS_SPECIALIST_SYSTEM = """You are a Job Requirements Specialist and talent acquisition expert.++Given company research and a target job role, identify the key requirements for that role at this specific company.++Produce a structured analysis covering:+- Technical skills and tools+- Soft skills and interpersonal competencies+- Experience level and years of experience+- Education and certifications+- Nice-to-have qualifications+- How requirements align with the company's culture and values++Be specific to the company context—reference cultural fit where relevant.+Use clear headings and bullet points. Prioritize the most important requirements first."""++JOB_POSTING_WRITER_SYSTEM = """You are an expert Job Posting Writer who creates compelling, professional job postings.++Using company research and role requirements, write a comprehensive, tailored job posting that:+- Opens with an engaging summary tied to the company's mission and culture+- Includes sections: About the Company, Role Overview, Key Responsibilities, Required Qualifications, Preferred Qualifications, What We Offer, How to Apply+- Uses inclusive, professional language+- Reflects the company's tone and values authentically+- Is ready to publish on a careers page or job board++Format with clear markdown headings (##). Be thorough but scannable.+Do not include placeholder brackets like [Company Name]—use the actual company name throughout."""diff --git a/ai_agents/job_posting_agent/requirements.txt b/ai_agents/job_posting_agent/requirements.txtnew file mode 100644index 0000000..4590466--- /dev/null+++ b/ai_agents/job_posting_agent/requirements.txt@@ -0,0 +1,9 @@+streamlit>=1.32.0+python-dotenv>=1.0.0+langchain>=0.3.0+langchain-openai>=0.2.0+langchain-community>=0.3.0+langchain-core>=0.3.0+duckduckgo-search>=6.0.0+openai>=1.0.0+httpx>=0.27.0diff --git a/ai_agents/job_posting_agent/scripts/test_nvidia.py b/ai_agents/job_posting_agent/scripts/test_nvidia.pynew file mode 100644index 0000000..338ab2b--- /dev/null+++ b/ai_agents/job_posting_agent/scripts/test_nvidia.py@@ -0,0 +1,26 @@+"""Run: python scripts/test_nvidia.py"""++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from nvidia_client import MODEL_ID, chat_completion, get_api_key, verify_connection+++def main() -> None:+ key = get_api_key()+ print(f"API key loaded: {key[:8]}...{key[-4:]}")+ print(f"Model: {MODEL_ID}")+ print("Testing connection...")+ verify_connection()+ print("verify_connection() OK")+ reply = chat_completion(+ [{"role": "user", "content": "Say hello in 5 words or fewer."}],+ max_tokens=32,+ )+ print(f"Reply: {reply}")+++if __name__ == "__main__":+ main()