
LangChain 的 ChatGroq 不支持 format="json" 参数(如 ChatOllama 所提供),需通过提示词工程 + 正则解析实现结构化 JSON 输出。本文详解操作步骤、完整代码示例及关键注意事项。
langchain 的 `chatgroq` 不支持 `format="json"` 参数(如 `chatollama` 所提供),需通过提示词工程 + 正则解析实现结构化 json 输出。本文详解操作步骤、完整代码示例及关键注意事项。
ChatGroq 当前版本(langchain-groq==0.2.1)不提供原生 format 参数,无法像 ChatOllama(model=..., format="json") 那样直接声明输出格式。但这并不意味着无法获得可靠 JSON 输出——核心策略是:在系统/用户提示中明确指令模型以严格 JSON 格式响应,并用代码安全提取。
✅ 推荐实践:提示词约束 + 正则提取
首先,在调用 ChatGroq 时,将 JSON 格式要求写入提示词(推荐放在系统消息中,增强一致性):
from langchain_groq import ChatGroq
from langchain_core.messages import SystemMessage, HumanMessage
import re
llm = ChatGroq(
model="llama3-70b-8192", # 或其他支持的 Groq 模型
temperature=0,
api_key="your_api_key" # 如已配置环境变量可省略
)
# 构建结构化提示
system_prompt = (
"You are a helpful assistant that ONLY outputs valid JSON. "
"Never add explanations, markdown, or extra text outside the JSON. "
"Always wrap the JSON output in triple backticks with 'json' language tag, like:\n"
"```json\n{...}\n```"
)
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content="Extract user info from: 'Name: Alice, Age: 30, City: Berlin'. Return as JSON with keys 'name', 'age', 'city'.")
]
response = llm.invoke(messages)
raw_output = response.content
? 安全提取 JSON 内容
使用正则表达式精准捕获 json 代码块中的内容,避免模型“幻觉”导致的解析失败:
def extract_json_from_response(text: str) -> dict | None:
pattern = r'```json\s*([\s\S]*?)\s*```'
match = re.search(pattern, text, re.DOTALL)
if not match:
raise ValueError("No JSON code block found in LLM response")
try:
import json
return json.loads(match.group(1).strip())
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON syntax in extracted content: {e}")
# 使用示例
try:
data = extract_json_from_response(raw_output)
print(data) # {'name': 'Alice', 'age': 30, 'city': 'Berlin'}
except (ValueError, json.JSONDecodeError) as e:
print(f"JSON parsing failed: {e}")
⚠️ 关键注意事项
-
模型能力依赖:确保所选 Groq 模型(如
llama3-70b-8192或mixtral-8x7b-32768)具备良好 JSON 生成能力;小模型可能忽略格式指令。 -
温度设为 0:务必设置
temperature=0以最小化随机性,提升 JSON 结构稳定性。 -
避免纯正则 fallback:不要仅靠
re.findall(r'{.*?}', text)提取——易匹配到不完整或嵌套错误的 JSON 片段。 -
生产环境建议加重试与校验:对关键任务,可封装带重试机制的调用函数,并结合
jsonschema验证字段完整性。 -
未来兼容性提示:LangChain 0.3+ 已逐步统一工具调用(Tool Calling)范式,后续可通过
StructuredTool或PydanticOutputParser实现更健壮的结构化输出(需模型支持函数调用)。
综上,虽无 format="json" 便捷参数,但通过强提示约束 + 精准正则提取 + 错误防护三步法,即可在 ChatGroq 中稳定获得符合预期的 JSON 输出,兼顾灵活性与可靠性。











