A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
audit: fix job_posting_agent - add env comments, docstring, logging, fix em dashes
Tiioluwaniaeeb9bcc59eb
diff --git a/ai_agents/job_posting_agent/.env.example b/ai_agents/job_posting_agent/.env.exampleindex 78b5611..81f201d 100644--- a/ai_agents/job_posting_agent/.env.example+++ b/ai_agents/job_posting_agent/.env.example@@ -1 +1,2 @@+# Get your NVIDIA NIM API key at https://build.nvidia.com/NVIDIA_API_KEY=your_nvidia_api_key_herediff --git a/ai_agents/job_posting_agent/agents/pipeline.py b/ai_agents/job_posting_agent/agents/pipeline.pyindex 5d6d3f2..b8e71fe 100644--- a/ai_agents/job_posting_agent/agents/pipeline.py+++ b/ai_agents/job_posting_agent/agents/pipeline.py@@ -1,3 +1,4 @@+import loggingimport reimport timefrom collections.abc import Callable@@ -6,6 +7,8 @@ import httpxfrom nvidia_client import NvidiaAPIError, chat_completion+logger = logging.getLogger(__name__)+SECTION_NAMES = ("COMPANY RESEARCH", "ROLE REQUIREMENTS", "JOB POSTING")MAX_OUTPUT_TOKENS = 1500@@ -73,7 +76,7 @@ def run_pipeline(on_stage(stage)notify("Generating with DeepSeek V4 Flash (single request)...")- print(f"[Pipeline] Calling NVIDIA NIM for {company} / {role}", flush=True)+ logger.info("[Pipeline] Calling NVIDIA NIM for %s / %s", company, role)try:response = chat_completion(@@ -93,7 +96,7 @@ def run_pipeline(job_posting = parsed["JOB POSTING"] or responseelapsed = time.perf_counter() - pipeline_start- print(f"[Pipeline] Finished in {elapsed:.1f}s", flush=True)+ logger.info("[Pipeline] Finished in %.1fs", elapsed)notify("Complete")return PipelineResult(diff --git a/ai_agents/job_posting_agent/app.py b/ai_agents/job_posting_agent/app.pyindex 7d762fe..58e8a17 100644--- a/ai_agents/job_posting_agent/app.py+++ b/ai_agents/job_posting_agent/app.py@@ -1,6 +1,11 @@+"""Streamlit app for the Job Posting Agent. Enter a company and role to generate a tailored, professional job posting using a multi-agent LangChain pipeline backed by DeepSeek V4 Flash on NVIDIA NIM."""+import json+import loggingimport traceback+logging.basicConfig(level=logging.INFO, format="%(message)s")+import streamlit as stimport streamlit.components.v1 as components@@ -109,9 +114,9 @@ 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+ 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 postingPowered by **DeepSeek V4 Flash** via NVIDIA NIM."""diff --git a/ai_agents/job_posting_agent/nvidia_client.py b/ai_agents/job_posting_agent/nvidia_client.pyindex 1a50a7a..e785659 100644--- a/ai_agents/job_posting_agent/nvidia_client.py+++ b/ai_agents/job_posting_agent/nvidia_client.py@@ -7,6 +7,7 @@ which causes requests to hang indefinitely on cold starts.from __future__ import annotations+import loggingimport osimport timefrom typing import Any@@ -17,6 +18,8 @@ from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, Systemload_dotenv()+logger = logging.getLogger(__name__)+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)@@ -52,7 +55,7 @@ def get_api_key() -> str:def create_http_client() -> httpx.Client:- """Fresh client per request — avoids reusing a connection NVIDIA already closed."""+ """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),@@ -125,17 +128,16 @@ def _request_with_retries(request_fn, label: str) -> httpx.Response:last_error = excif 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,+ logger.warning(+ "[NVIDIA] %s failed (%r), retry %d/%d in %.0fs",+ label, exc, attempt, MAX_RETRIES - 1, wait,)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."+ f"model is warming up; wait a minute and try again.") from excfinally:client.close()@@ -146,10 +148,7 @@ def _poll_for_completion(api_key: str, request_id: str) -> dict[str, Any]:deadline = time.monotonic() + MAX_POLL_SECONDSpoll_url = f"{NVIDIA_BASE_URL}/status/{request_id}"- print(- f"[NVIDIA] Model warming up (request {request_id[:8]}...) — polling",- flush=True,- )+ logger.info("[NVIDIA] Model warming up (request %s...), polling", request_id[:8])while time.monotonic() < deadline:def poll_once(client: httpx.Client) -> httpx.Response:@@ -162,7 +161,7 @@ def _poll_for_completion(api_key: str, request_id: str) -> dict[str, Any]:if response.status_code == 202:status = response.headers.get("NVCF-STATUS", "pending")- print(f"[NVIDIA] Still pending ({status})...", flush=True)+ logger.info("[NVIDIA] Still pending (%s)...", status)time.sleep(POLL_INTERVAL_SECONDS)continue@@ -207,13 +206,13 @@ def chat_completion("stream": False,}- print(f"[NVIDIA] Calling {MODEL_ID}...", flush=True)+ logger.info("[NVIDIA] Calling %s...", MODEL_ID)response = _post_chat_completion(api_key, body)if response.status_code == 200:content = _extract_content(response.json())- print("[NVIDIA] Response received.", flush=True)+ logger.info("[NVIDIA] Response received.")return contentif response.status_code == 202:@@ -226,7 +225,7 @@ def chat_completion()result = _poll_for_completion(api_key, request_id)content = _extract_content(result)- print("[NVIDIA] Response received after polling.", flush=True)+ logger.info("[NVIDIA] Response received after polling.")return content_raise_for_status(response)diff --git a/ai_agents/job_posting_agent/prompts.py b/ai_agents/job_posting_agent/prompts.pyindex 3f86916..5214abc 100644--- a/ai_agents/job_posting_agent/prompts.py+++ b/ai_agents/job_posting_agent/prompts.py@@ -11,7 +11,7 @@ Focus your research on: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."""+Do not invent facts; only report what your searches support."""JOB_REQUIREMENTS_SPECIALIST_SYSTEM = """You are a Job Requirements Specialist and talent acquisition expert.@@ -25,7 +25,7 @@ Produce a structured analysis covering:- 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.+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.@@ -38,4 +38,4 @@ Using company research and role requirements, write a comprehensive, tailored jo- Is ready to publish on a careers page or job boardFormat with clear markdown headings (##). Be thorough but scannable.-Do not include placeholder brackets like [Company Name]—use the actual company name throughout."""+Do not include placeholder brackets like [Company Name]; use the actual company name throughout."""