Compact ZeroGPU v14p navigator prompt
Browse filesFiles changed (4)
16 unmodified lines1718192021222324252616 unmodified linesLLAMA_BASE_URL=http://127.0.0.1:8001/v1ZEROGPU_MODEL_REPO=build-small-hackathon/figment-finetuned-model-archiveZEROGPU_MODEL_SUBFOLDER=figment_sft_v14p/figment-sft-v14p-lora-merged-bf16ZEROGPU_DURATION_SECONDS=120ZEROGPU_SIZE=largeZEROGPU_MAX_CONTEXT_TOKENS=16384ZEROGPU_MAX_GENERATION_TOKENS=1536FIGMENT_TRACE_DIR=tracesFIGMENT_SMOKE_ALLOW_NETWORK=falseFIGMENT_SMOKE_TIMEOUT_SECONDS=816 unmodified lines1718192021222324252616 unmodified linesLLAMA_BASE_URL=http://127.0.0.1:8001/v1ZEROGPU_MODEL_REPO=build-small-hackathon/figment-finetuned-model-archiveZEROGPU_MODEL_SUBFOLDER=figment_sft_v14p/figment-sft-v14p-lora-merged-bf16ZEROGPU_DURATION_SECONDS=60ZEROGPU_SIZE=largeZEROGPU_MAX_CONTEXT_TOKENS=4096ZEROGPU_MAX_GENERATION_TOKENS=768FIGMENT_TRACE_DIR=tracesFIGMENT_SMOKE_ALLOW_NETWORK=falseFIGMENT_SMOKE_TIMEOUT_SECONDS=8
14 unmodified lines151617181920108 unmodified lines129130131132133134135113 unmodified lines24925025125225325414 unmodified linesfrom typing import Anyfrom .config import FigmentConfig, load_configfrom .zerogpu_runtime import generate_zero_gpu_json108 unmodified lines)if self.config.model_backend == "hf_zerogpu":return generate_zero_gpu_json(prompt=prompt,model_repo=self.config.zerogpu_model_repo,model_subfolder=self.config.zerogpu_model_subfolder,model_id=self.config.local_model_id,113 unmodified linesreturn {}def _timeout_seconds_from_env() -> float:raw_value = os.getenv(MODEL_TIMEOUT_ENV, "").strip()if not raw_value:14 unmodified lines15161718192021108 unmodified lines130131132133134135136113 unmodified lines25025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529614 unmodified linesfrom typing import Anyfrom .config import FigmentConfig, load_configfrom .prompt_builder import OUTPUT_SCHEMA, REQUIRED_JSON_SKELETONfrom .zerogpu_runtime import generate_zero_gpu_json108 unmodified lines)if self.config.model_backend == "hf_zerogpu":return generate_zero_gpu_json(prompt=_zero_gpu_compact_prompt(prompt, context),model_repo=self.config.zerogpu_model_repo,model_subfolder=self.config.zerogpu_model_subfolder,model_id=self.config.local_model_id,113 unmodified linesreturn {}ZERO_GPU_SYSTEM_PROMPT = """You are Figment, an offline protocol navigator for a trained responder.Use ONLY the compact protocol-card facts in CONTEXT. Return ONLY JSON matching REQUIRED_JSON_SKELETON.Do not diagnose, prescribe, dose medication, autonomously triage, discharge, or downgrade deterministic red flags.Every candidate_protocol_pathways item must cite a retrieved clinical card_id. source_cards must cite every card used.If information is missing or uncertain, list it instead of inventing it."""def _zero_gpu_compact_prompt(prompt: str, context: dict[str, Any]) -> str:if not context:return promptcompact_context = {"structured_intake": context.get("intake", {}),"deterministic_red_flags": context.get("rule_results", []),"protocol_urgency_floor": context.get("urgency_floor", "routine"),"retrieved_protocol_cards": [_compact_protocol_card(item.get("card", item)) for item in context.get("retrieved_cards", [])[:6]],"navigator_output_schema": OUTPUT_SCHEMA,}return (f"{ZERO_GPU_SYSTEM_PROMPT}\n\n"f"REQUIRED_JSON_SKELETON:\n{json.dumps(REQUIRED_JSON_SKELETON, sort_keys=True, separators=(',', ':'))}\n\n"f"CONTEXT:\n{json.dumps(compact_context, sort_keys=True, separators=(',', ':'))}")def _compact_protocol_card(card: dict[str, Any]) -> dict[str, Any]:kept_fields = ("card_id","title","applies_to","required_observations","red_flags","escalation_criteria","local_actions","forbidden_actions","safety_boundary",)return {field: card.get(field) for field in kept_fields if card.get(field)}def _timeout_seconds_from_env() -> float:raw_value = os.getenv(MODEL_TIMEOUT_ENV, "").strip()if not raw_value:
28 unmodified lines2930313233343525 unmodified lines616263646566676840 unmodified lines10911011111211311428 unmodified lines@spaces.GPU(duration=int(os.getenv("ZEROGPU_DURATION_SECONDS", "120")),size=os.getenv("ZEROGPU_SIZE", "large"),)def generate_zero_gpu_json(25 unmodified linesfrom transformers import AutoTokenizerself.model_id = model_idself.max_context_tokens = int(os.getenv("ZEROGPU_MAX_CONTEXT_TOKENS", "16384"))self.max_generation_tokens = int(os.getenv("ZEROGPU_MAX_GENERATION_TOKENS", "1536"))self.lock = threading.Lock()self.torch = torchself.tokenizer = AutoTokenizer.from_pretrained(40 unmodified linesattention_mask = self.torch.ones_like(input_ids)else:attention_mask = attention_mask.to(device)input_len = int(input_ids.shape[-1])available_tokens = max(1, self.max_context_tokens - input_len - 8)max_new_tokens = max(1, min(self.max_generation_tokens, available_tokens))28 unmodified lines2930313233343525 unmodified lines616263646566676840 unmodified lines10911011111211311411511611711828 unmodified lines@spaces.GPU(duration=int(os.getenv("ZEROGPU_DURATION_SECONDS", "60")),size=os.getenv("ZEROGPU_SIZE", "large"),)def generate_zero_gpu_json(25 unmodified linesfrom transformers import AutoTokenizerself.model_id = model_idself.max_context_tokens = int(os.getenv("ZEROGPU_MAX_CONTEXT_TOKENS", "4096"))self.max_generation_tokens = int(os.getenv("ZEROGPU_MAX_GENERATION_TOKENS", "768"))self.lock = threading.Lock()self.torch = torchself.tokenizer = AutoTokenizer.from_pretrained(40 unmodified linesattention_mask = self.torch.ones_like(input_ids)else:attention_mask = attention_mask.to(device)max_input_tokens = max(1, self.max_context_tokens - self.max_generation_tokens - 8)if int(input_ids.shape[-1]) > max_input_tokens:input_ids = input_ids[:, -max_input_tokens:]attention_mask = attention_mask[:, -max_input_tokens:]input_len = int(input_ids.shape[-1])available_tokens = max(1, self.max_context_tokens - input_len - 8)max_new_tokens = max(1, min(self.max_generation_tokens, available_tokens))
5 unmodified lines6789101112164 unmodified lines1771781791801811825 unmodified linesfrom figment.config import FigmentConfigimport pytestfrom figment.model_client import ModelClient, ModelClientErrorEXPECTED_NVIDIA_OMNI_API_MODEL_ID = "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning"164 unmodified lines}def test_custom_hf_endpoint_prefers_hf_token_over_nvidia_key(monkeypatch: Any) -> None:captured: dict[str, Any] = {}5 unmodified lines6789101112164 unmodified lines1771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122135 unmodified linesfrom figment.config import FigmentConfigimport pytestfrom figment.model_client import ModelClient, ModelClientError, _zero_gpu_compact_promptEXPECTED_NVIDIA_OMNI_API_MODEL_ID = "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning"164 unmodified lines}def test_hf_zerogpu_compact_prompt_preserves_route_facts_without_verbose_card_text() -> None:prompt = "VERBOSE " * 5000compact = _zero_gpu_compact_prompt(prompt,{"intake": {"confirmed": True, "chief_concern": "vomiting"},"rule_results": [],"urgency_floor": "routine","retrieved_cards": [{"card": {"card_id": "PED-DEHYD-RED-FLAGS-v1","title": "Pediatric dehydration red flags","required_observations": ["mental status", "urine output"],"red_flags": ["lethargy"],"escalation_criteria": ["Any listed red flag requires urgent escalation."],"source_note": "omit this verbose provenance field",}}],},)assert len(compact) < 5000assert "PED-DEHYD-RED-FLAGS-v1" in compactassert "chief_concern" in compactassert "REQUIRED_JSON_SKELETON" in compactassert "source_note" not in compactassert "VERBOSE" not in compactdef test_custom_hf_endpoint_prefers_hf_token_over_nvidia_key(monkeypatch: Any) -> None:captured: dict[str, Any] = {}
.env.example+3-3
figment/model_client.py+43-1
figment/zerogpu_runtime.py+7-3
tests/test_model_client.py+32-1