Spaces:
Sleeping
Sleeping
Quincy Hsieh commited on
Commit ·
4cf3b63
1
Parent(s): c8361c5
Call LLM model from Azure OpenAI endpoint
Browse filesFiles changed (5)
- README.md+12-8
- app.py+50-34
- config.jsonAdded+9
- prompts/rag_prompt.txt+2-2
- requirements.txt+1
58 unmodified lines5960616263646578 unmodified lines144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173161 unmodified lines33533633733833934034142 unmodified lines38438538638738838939058 unmodified lines│ ┌──────────────────┐ ┌─────────────────┐ ││ │ HF Inference │ │ Sentence │ ││ │ API (LLM) │ │ Transformers │ ││ │ Mistral-7B │ │ (Embeddings) │ ││ └──────────────────┘ └─────────────────┘ │└─────────────────────────────────────────────────────────────┘```78 unmodified linesCombine retrieved context with the user's question and generate an answer.1. **Build prompt** — Load the template from [`prompts/rag_prompt.txt`](prompts/rag_prompt.txt), inject retrieved context and the user's question2. **Call LLM API** — Send the prompt to the Hugging Face Inference API (Mistral-7B-Instruct-v0.3)3. **Return response** — The LLM generates an answer grounded in the provided contextThe prompt template (`prompts/rag_prompt.txt`):```<s>[INST] You are a helpful assistant. Answer the user's question based ONLY on the provided context.If the context does not contain enough information to answer, say "I don't have enough information to answer this question."Always be concise and factual.Context:{context}Question: {question} [/INST]```The template is loaded once at startup and filled at query time:```pythonRAG_PROMPT_TEMPLATE = Path("prompts/rag_prompt.txt").read_text(encoding="utf-8")# At query time:prompt = RAG_PROMPT_TEMPLATE.format(context=context_text, question=user_query)response = client.text_generation(prompt, max_new_tokens=512)```> **Tip:** Edit `prompts/rag_prompt.txt` to tune the model's behaviour (tone, language, output format) without touching application code.161 unmodified lines|---|---|---|| `HF_TOKEN` | (Space Secret) | Hugging Face API token for Inference API || `EMBEDDING_MODEL_NAME` | `sentence-transformers/all-MiniLM-L6-v2` | Model for text embeddings || `LLM_MODEL_NAME` | `mistralai/Mistral-7B-Instruct-v0.3` | LLM for answer generation || `CHROMA_PERSIST_DIR` | `./chroma_db` | ChromaDB storage path || `CHUNK_SIZE` | `512` | Text chunk size in characters || `CHUNK_OVERLAP` | `50` | Overlap between chunks |42 unmodified lines### LLM 404 — Model Not FoundIf the `/query` endpoint logs a `404 Not Found` for the Inference API URL, the configured model has been removed from the free serverless tier. Update `LLM_MODEL_NAME` in `app.py` to an available model and adjust `prompts/rag_prompt.txt` to match its instruction format. The current default (`mistralai/Mistral-7B-Instruct-v0.3`) uses the `<s>[INST] … [/INST]` format.### SSL Certificate Verification Error58 unmodified lines5960616263646578 unmodified lines144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177161 unmodified lines33934034134234334434542 unmodified lines38838939039139239339458 unmodified lines│ ┌──────────────────┐ ┌─────────────────┐ ││ │ HF Inference │ │ Sentence │ ││ │ API (LLM) │ │ Transformers │ ││ │ Qwen2.5-72B │ │ (Embeddings) │ ││ └──────────────────┘ └─────────────────┘ │└─────────────────────────────────────────────────────────────┘```78 unmodified linesCombine retrieved context with the user's question and generate an answer.1. **Build prompt** — Load the template from [`prompts/rag_prompt.txt`](prompts/rag_prompt.txt), inject retrieved context and the user's question2. **Call LLM API** — Send the prompt to the Hugging Face Inference API (`chat_completion`, Qwen2.5-72B-Instruct)3. **Return response** — The LLM generates an answer grounded in the provided contextThe prompt template (`prompts/rag_prompt.txt`):```You are a helpful assistant. Answer the user's question based ONLY on the provided context.If the context does not contain enough information to answer, say "I don't have enough information to answer this question."Always be concise and factual.Context:{context}Question: {question}```The template is loaded once at startup and sent as the user message to the chat endpoint:```pythonRAG_PROMPT_TEMPLATE = Path("prompts/rag_prompt.txt").read_text(encoding="utf-8")# At query time:prompt = RAG_PROMPT_TEMPLATE.format(context=context_text, question=user_query)response = llm_client.chat_completion(messages=[{"role": "user", "content": prompt}],max_tokens=512,)answer = response.choices[0].message.content```> **Tip:** Edit `prompts/rag_prompt.txt` to tune the model's behaviour (tone, language, output format) without touching application code.161 unmodified lines|---|---|---|| `HF_TOKEN` | (Space Secret) | Hugging Face API token for Inference API || `EMBEDDING_MODEL_NAME` | `sentence-transformers/all-MiniLM-L6-v2` | Model for text embeddings || `LLM_MODEL_NAME` | `Qwen/Qwen2.5-72B-Instruct` | LLM for answer generation || `CHROMA_PERSIST_DIR` | `./chroma_db` | ChromaDB storage path || `CHUNK_SIZE` | `512` | Text chunk size in characters || `CHUNK_OVERLAP` | `50` | Overlap between chunks |42 unmodified lines### LLM 404 — Model Not FoundIf the `/query` endpoint logs a `404 Not Found` for the Inference API URL, the configured model has been removed from the free serverless tier. Update `LLM_MODEL_NAME` in `app.py` to an available model. The app now uses `chat_completion` (`/v1/chat/completions`) rather than the legacy `text_generation` endpoint, so any model listed under **Inference Providers** on huggingface.co will work. The prompt in `prompts/rag_prompt.txt` is model-agnostic (no special tokens).### SSL Certificate Verification Error
15 unmodified lines161718192021222324251 unmodified line272829303132333435363738394041424344454647484950515253545556575859606162636427 unmodified lines9293949596979899100101102103104110 unmodified lines21521621721821922022122222322422522622722822923023123223323423523623723823915 unmodified lines"""import osimport loggingfrom pathlib import Pathfrom typing import Optionalimport gradio as grfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import JSONResponse1 unmodified lineimport chromadbfrom chromadb.config import Settingsfrom sentence_transformers import SentenceTransformerfrom huggingface_hub import InferenceClientfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom pypdf import PdfReaderlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# ---------------------------------------------------------------------------# Configuration# ---------------------------------------------------------------------------EMBEDDING_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"LLM_MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.3"CHROMA_PERSIST_DIR = "./chroma_db"COLLECTION_NAME = "rag_documents"CHUNK_SIZE = 512CHUNK_OVERLAP = 50TOP_K_RESULTS = 3# HF_TOKEN is set as a Space secret for authenticated Inference API callsHF_TOKEN = os.environ.get("HF_TOKEN")# Corporate proxy / SSL inspection support:# If HTTPS requests to huggingface.co fail with certificate errors, point this# variable to your organisation's CA bundle before starting the app.# export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt # Linux system bundle# export REQUESTS_CA_BUNDLE=/path/to/corporate-ca.crt # custom bundle# The requests library (used by huggingface_hub and sentence-transformers) reads# this variable automatically — no code change required._ca_bundle = os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("SSL_CERT_FILE")if _ca_bundle:logger.info(f"Using custom CA bundle for HTTPS: {_ca_bundle}")# Prompt template loaded from file so it can be edited without touching application code_PROMPT_TEMPLATE_PATH = Path(__file__).parent / "prompts" / "rag_prompt.txt"27 unmodified lineslogger.info(f"ChromaDB collection '{COLLECTION_NAME}' ready. Documents: {collection.count()}")# ---------------------------------------------------------------------------# Step 3: Initialize the LLM Client (Hugging Face Inference API)# ---------------------------------------------------------------------------# We use the Hugging Face Inference API to call a hosted LLM model.# This avoids loading large models into the Space's limited memory.llm_client = InferenceClient(model=LLM_MODEL_NAME, token=HF_TOKEN)logger.info(f"LLM client initialized for model: {LLM_MODEL_NAME}")# ---------------------------------------------------------------------------110 unmodified linesdef call_llm(prompt: str) -> str:"""Make a call to the LLM via Hugging Face Inference API.This demonstrates Step 2a: How to call a given LLM model API.We use the text_generation endpoint with a structured promptthat includes the retrieved context and the user's question."""try:response = llm_client.text_generation(prompt,max_new_tokens=512,temperature=0.7,top_p=0.95,repetition_penalty=1.1,do_sample=True,)return response.strip()except Exception as e:logger.error(f"LLM API call failed: {e}")raise HTTPException(status_code=503, detail=f"LLM service unavailable: {str(e)}")def build_rag_prompt(query: str, contexts: list[dict]) -> str:15 unmodified lines161718192021222324252627282930311 unmodified line333435363738394041424344454647484950515253545556575859606162636465666768697071727327 unmodified lines101102103104105106107108109110111112110 unmodified lines22322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425515 unmodified lines"""import osimport jsonimport loggingfrom pathlib import Pathfrom typing import Optional# Must be set before chromadb is imported so the module never registers its# posthog telemetry hook (workaround for posthog v3 API incompatibility).os.environ.setdefault("ANONYMIZED_TELEMETRY", "False")import requests as http_requestsimport gradio as grfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import JSONResponse1 unmodified lineimport chromadbfrom chromadb.config import Settingsfrom sentence_transformers import SentenceTransformerfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom pypdf import PdfReaderlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Suppress non-fatal chromadb telemetry errors (posthog v3 API incompatibility)logging.getLogger("chromadb.telemetry.product.posthog").setLevel(logging.CRITICAL)# ---------------------------------------------------------------------------# Configuration# ---------------------------------------------------------------------------EMBEDDING_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"CHROMA_PERSIST_DIR = "./chroma_db"COLLECTION_NAME = "rag_documents"CHUNK_SIZE = 512CHUNK_OVERLAP = 50TOP_K_RESULTS = 3# LLM settings loaded from config.json_CONFIG_PATH = Path(__file__).parent / "config.json"with open(_CONFIG_PATH, encoding="utf-8") as _f:_config = json.load(_f)LLM_ENDPOINT_URL = _config["llm"]["endpoint_url"]LLM_MODEL_NAME = _config["llm"]["model"]LLM_MAX_TOKENS = _config["llm"].get("max_tokens", 512)LLM_TEMPERATURE = _config["llm"].get("temperature", 0.7)LLM_TOP_P = _config["llm"].get("top_p", 0.95)# Azure Foundry API key from environment variableAZURE_API_KEY = os.environ.get("AZURE_API_KEY")if not AZURE_API_KEY:logger.warning("AZURE_API_KEY is not set — LLM calls will fail.")# Prompt template loaded from file so it can be edited without touching application code_PROMPT_TEMPLATE_PATH = Path(__file__).parent / "prompts" / "rag_prompt.txt"27 unmodified lineslogger.info(f"ChromaDB collection '{COLLECTION_NAME}' ready. Documents: {collection.count()}")# ---------------------------------------------------------------------------# Step 3: LLM Configuration (Azure Foundry GPT-5)# ---------------------------------------------------------------------------# We call the Azure OpenAI-compatible endpoint directly via requests.# Endpoint URL and model are configured in config.json.logger.info(f"LLM configured: {LLM_MODEL_NAME} via {LLM_ENDPOINT_URL}")# ---------------------------------------------------------------------------110 unmodified linesdef call_llm(prompt: str) -> str:"""Make a call to the LLM via Azure Foundry (GPT-5).Calls the Azure OpenAI-compatible chat/completions endpoint.Endpoint URL is loaded from config.json; API key from AZURE_API_KEY env var."""headers = {"api-key": AZURE_API_KEY,"Content-Type": "application/json",}payload = {"model": LLM_MODEL_NAME,"messages": [{"role": "user", "content": prompt}],"max_tokens": LLM_MAX_TOKENS,"temperature": LLM_TEMPERATURE,"top_p": LLM_TOP_P,}try:resp = http_requests.post(LLM_ENDPOINT_URL, headers=headers, json=payload, timeout=60)resp.raise_for_status()data = resp.json()return data["choices"][0]["message"]["content"].strip()except http_requests.exceptions.HTTPError as e:logger.error(f"LLM API call failed: {e} — {resp.text}")raise HTTPException(status_code=503, detail=f"LLM service unavailable: {str(e)}")except (KeyError, IndexError) as e:logger.error(f"Unexpected LLM response format: {e}")raise HTTPException(status_code=502, detail="Unexpected response from LLM service")def build_rag_prompt(query: str, contexts: list[dict]) -> str:
123456789{ "llm": { "endpoint_url": "https://<your-resource>.openai.azure.com/openai/deployments/<your-deployment>/chat/completions?api-version=2024-12-01-preview", "model": "gpt-5", "max_tokens": 512, "temperature": 0.7, "top_p": 0.95 }}123456789<s>[INST] You are a helpful assistant. Answer the user's question based ONLY on the provided context.If the context does not contain enough information to answer, say "I don't have enough information to answer this question."Always be concise and factual.Context:{context}Question: {question} [/INST]123456789You are a helpful assistant. Answer the user's question based ONLY on the provided context.If the context does not contain enough information to answer, say "I don't have enough information to answer this question."Always be concise and factual.Context:{context}Question: {question}
11 unmodified lines12131411 unmodified linespypdf==4.3.0python-multipart==0.0.9pydantic==2.9.011 unmodified lines1213141511 unmodified linespypdf==4.3.0python-multipart==0.0.9pydantic==2.9.0requests>=2.31.0
README.md+12-8
app.py+50-34
config.jsonAdded+9
prompts/rag_prompt.txt+2-2
requirements.txt+1