pythonimport openai # 假设使用OpenAI APIdef test_semantic_robustness(question_pairs, model="gpt-3.5-turbo"): """ 测试LLM对语义变化的鲁棒性 question_pairs: 列表,每个元素为(原始问题, 同义问题, 否定问题) """ results = [] for original, synonym, negated in question_pairs: # 获取模型回答 resp_orig = openai.ChatCompletion.create( model=model, messages=[{"role": "user", "content": original}] )["choices"][0]["message"]["content"] resp_syn = openai.ChatCompletion.create( model=model, messages=[{"role": "user", "content": synonym}] )["choices"][0]["message"]["content"] resp_neg = openai.ChatCompletion.create( model=model, messages=[{"role": "user", "content": negated}] )["choices"][0]["message"]["content"] # 简单评估:检查答案是否一致(这里用关键词匹配,实际需更精细) consistent = (resp_orig.strip() == resp_syn.strip()) neg_correct = ("不应该" in resp_neg or "不推荐" in resp_neg) results.append({ "original": original, "original_answer": resp_orig, "synonym_answer": resp_syn, "negated_answer": resp_neg, "semantic_consistent": consistent, "negation_handled": neg_correct }) return results# 示例数据questions = [ ("高血压患者应该避免什么食物?", "患有高血压的人应远离哪类食物?", "高血压患者不应该避免什么食物?"), ("阿司匹林可以用于缓解头痛吗?", "头痛时服用阿司匹林是否有效?", "阿司匹林不可以用于缓解头痛吗?")]# 运行测试(需要设置API密钥)results = test_semantic_robustness(questions)for r in results: print(f"原始问题: {r['original']}") print(f"同义答案一致: {r['semantic_consistent']}") print(f"否定处理正确: {r['negation_handled']}") print("---")这个测试暴露了模型的一个常见问题:当问题被否定时,模型可能直接照搬原答案,比如把“高血压患者不应该避免什么食物?”误解为“高血压患者应该避免什么食物?”——这就翻车了。### 代码示例2:推理深度测试接下来,我们测试模型是否能给出推理过程,而不是简单答案。pythondef test_reasoning_depth(questions_with_expectations, model="gpt-3.5-turbo"): """ 测试模型是否提供推理步骤 questions_with_expectations: 列表,每个元素为(问题, 期望答案关键词) """ reasoning_prompt = "请先给出诊断依据,再给出答案。" results = [] for question, expected_keyword in questions_with_expectations: full_prompt = question + "\n" + reasoning_prompt resp = openai.ChatCompletion.create( model=model, messages=[{"role": "user", "content": full_prompt}] )["choices"][0]["message"]["content"] # 检查是否有推理步骤 has_reasoning = ("因为" in resp or "由于" in resp or "依据" in resp) contains_answer = expected_keyword in resp results.append({ "question": question, "response": resp, "has_reasoning": has_reasoning, "correct_keyword": contains_answer }) return results# 示例:需要推理的医学问题questions = [ ("患者持续咳嗽两周,夜间加重,无发热,痰液清稀,可能是什么病?", "过敏性咳嗽"), ("糖尿病患者出现视力模糊,可能是什么并发症?", "糖尿病视网膜病变")]results = test_reasoning_depth(questions)for r in results: print(f"问题: {r['question']}") print(f"包含推理: {r['has_reasoning']}") print(f"关键词正确: {r['correct_keyword']}") print("---")这个测试逼着模型“思考”。如果模型直接说“过敏性咳嗽”而不给原因,就说明它可能只是碰运气。## 多样性与可靠性:如何平衡?多样性意味着覆盖不同疾病、不同难度、不同语言风格。可靠性则要求测试结果可重复。我们可以用统计学方法,比如在不同温度参数下多次运行,计算答案的方差。方差大说明模型不稳定。另外,我们还可以引入“对抗样本”——故意制造模棱两可的问题,比如“患者有胸痛,可能是心梗还是焦虑症?”——测试模型是否能区分模糊场景。## 总结:让AI医生更靠谱医学知识评测不是简单的“考考你”,而是一场“心理战”。我们需要:-语义鲁棒性:确保模型不会被同义句或否定句骗倒。-推理深度:模型必须展示思考过程,而不是猜答案。-多样性覆盖:从感冒到癌症,从儿童到老人,全面测试。-可靠性验证:多次测试,确保结果稳定。最后,记住:一个能通过所有测试的LLM,未必能当医生;但一个通不过的,绝对不行。我们的目标不是制造“考试机器”,而是培养“会思考的助手”。下次AI医生给你开药时,至少可以问一句:“你确定吗?给出你的推理过程。”——如果它支支吾吾,那还是找人类医生吧。