Model wrapper that returns outputs formatted to match the given schema.
with_structured_output(
self,
schema: Optional[Union[Dict, Type[BaseModel]]] = None,
*,
method: Literal['function_calling', 'json_mode'] = 'function_calling',
include_raw: bool = False,
**kwargs: Any = {}
) -> Runnable[LanguageModelInput, Union[Dict, BaseModel]]Function-calling, Pydantic schema (method="function_calling", include_raw=False)::
.. code-block:: python
from langchain_community.chat_models import ChatZhipuAI from pydantic import BaseModel
class AnswerWithJustification(BaseModel): '''An answer to the user question along with justification for the answer.''' answer: str justification: str
llm = ChatZhipuAI(temperature=0) structured_llm = llm.with_structured_output(AnswerWithJustification)
structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
Function-calling, Pydantic schema (method="function_calling", include_raw=True)::
.. code-block:: python
from langchain_community.chat_models import ChatZhipuAI from pydantic import BaseModel
class AnswerWithJustification(BaseModel): '''An answer to the user question along with justification for the answer.''' answer: str justification: str
llm = ChatZhipuAI(temperature=0) structured_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True)
structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
Function-calling, dict schema (method="function_calling", include_raw=False)::
.. code-block:: python
from langchain_community.chat_models import ChatZhipuAI from pydantic import BaseModel from langchain_core.utils.function_calling import convert_to_openai_tool
class AnswerWithJustification(BaseModel): '''An answer to the user question along with justification for the answer.''' answer: str justification: str
dict_schema = convert_to_openai_tool(AnswerWithJustification) llm = ChatZhipuAI(temperature=0) structured_llm = llm.with_structured_output(dict_schema)
structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
| Name | Type | Description |
|---|---|---|
schema | Optional[Union[Dict, Type[BaseModel]]] | Default: NoneThe output schema as a dict or a Pydantic class. If a Pydantic class
then the model output will be an object of that class. If a dict then
the model output will be a dict. With a Pydantic class the returned
attributes will be validated, whereas with a dict they will not be. If
|
method | Literal['function_calling', 'json_mode'] | Default: 'function_calling'The method for steering model generation, either "function_calling" or "json_mode". ZhipuAI only supports "function_calling" which converts the schema to a OpenAI function and the model will make use of the function-calling API. |
include_raw | bool | Default: FalseIf If an error occurs during model output parsing it will be raised. If If an error occurs during output parsing it will be caught and returned as well. The final output is always a |