使用OllamaFunctions调用with_structured_output()遇报错求助
解决Ollama结构化输出的两个错误问题
错误原因分析
- 第一个ValidationError:
OllamaFunctions底层依赖ChatOllama,但format参数会被OllamaFunctions内部自动设置为json以支持工具调用,手动传递format="json"会导致重复赋值冲突。 - 第二个NotImplementedError:
OllamaFunctions并未实现with_structured_output方法,该方法是针对支持原生结构化输出的模型(如OpenAI)设计的,不适用于OllamaFunctions。
解决方案
下面提供两种可行的实现方式,推荐使用方案一(基于ChatOllama的原生结构化输出支持):
方案一:使用ChatOllama + with_structured_output(推荐)
LangChain新版本的ChatOllama已经支持with_structured_output方法,直接替换OllamaFunctions即可:
from langchain_community.chat_models import ChatOllama from langchain_core.prompts import PromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field # 定义结构化输出Schema class Person(BaseModel): name: str = Field(description="The person's name", required=True) height: float = Field(description="The person's height", required=True) hair_color: str = Field(description="The person's hair color") # 提示词模板 prompt = PromptTemplate.from_template( """Alex is 5 feet tall. Claudia is 1 feet taller than Alex and jumps higher than him. Claudia is a brunette and Alex is blonde. Human: {question} AI: """ ) # 初始化ChatOllama并设置结构化输出 llm = ChatOllama(model="phi3", temperature=0, format="json") structured_llm = llm.with_structured_output(Person) chain = prompt | structured_llm # 测试调用 result = chain.invoke({"question": "Extract information about Claudia"}) print(result)
方案二:使用OllamaFunctions + bind_tools(兼容旧版本)
如果必须使用OllamaFunctions,需要通过绑定工具(Pydantic模型)的方式实现结构化输出,而不是with_structured_output:
from langchain_experimental.llms.ollama_functions import OllamaFunctions from langchain_core.prompts import PromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field # 定义结构化输出Schema class Person(BaseModel): name: str = Field(description="The person's name", required=True) height: float = Field(description="The person's height", required=True) hair_color: str = Field(description="The person's hair color") # 提示词模板 prompt = PromptTemplate.from_template( """Alex is 5 feet tall. Claudia is 1 feet taller than Alex and jumps higher than him. Claudia is a brunette and Alex is blonde. Human: {question} AI: """ ) # 初始化OllamaFunctions并绑定工具 llm = OllamaFunctions(model="phi3", temperature=0) # 将Person模型绑定为工具,指定强制调用 structured_llm = llm.bind_tools([Person], tool_choice="Person") chain = prompt | structured_llm # 测试调用,结果会包含工具调用信息,需要提取内容 result = chain.invoke({"question": "Extract information about Claudia"}) # 提取结构化输出 structured_result = result.additional_kwargs["function_call"]["arguments"] print(structured_result)
关键注意事项
- 确保你的LangChain版本是最新的(执行
pip install --upgrade langchain langchain-community langchain-experimental),旧版本可能不支持ChatOllama的with_structured_output。 - 使用
phi3模型时,确保Ollama已经拉取了该模型(执行ollama pull phi3),且模型本身支持工具调用/结构化输出。
内容的提问来源于stack exchange,提问作者Jack Damiani
相关产品推荐
相关产品推荐

