import jsonimport torchfrom peft import PeftModelfrom transformers import AutoModelForCausalLM, AutoTokenizer base_model_id = "Qwen/Qwen3-8B"adapter_id = "wli14/HistAgent-Qwen3-8B-LoRA-10K" tokenizer = AutoTokenizer.from_pretrained(adapter_id)base_model = AutoModelForCausalLM.from_pretrained( base_model_id, torch_dtype=torch.bfloat16, device_map="auto",)model = PeftModel.from_pretrained(base_model, adapter_id).eval() evidence_card = { "spot": {"species": "human", "organ": "kidney"}, "ranked_genes": ["GENE1", "GENE2"], "cell_type_composition": [], "pathway_evidence": {}, "spatial_context": {}, "quality_flags": {},}question = "What tissue state is supported by this spot?" messages = [ { "role": "system", "content": ( "You are HistAgent, a molecular reasoning assistant for histology images. " "Use only the supplied evidence card to answer questions about the selected " "tissue spot. Do not fabricate genes, pathways, cell types or spatial " "conclusions that are absent from the evidence. State uncertainty when the " "evidence is limited or ambiguous. Answer in the same language as the user. " "Do not expose chain-of-thought, hidden reasoning or <think> tags." ), }, { "role": "system", "content": "Selected-spot evidence card:\n" + json.dumps(evidence_card, ensure_ascii=False), }, {"role": "user", "content": question},] input_ids = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, enable_thinking=False, return_tensors="pt",).to(model.device) with torch.inference_mode(): output_ids = model.generate( input_ids=input_ids, attention_mask=torch.ones_like(input_ids), max_new_tokens=256, do_sample=False, pad_token_id=tokenizer.eos_token_id, ) answer = tokenizer.decode( output_ids[0, input_ids.shape[-1]:], skip_special_tokens=True,)print(answer)