|
397 | 397 | "For more on binding tools and tool call outputs, head to the [tool calling](/docs/how_to/function_calling) docs."
|
398 | 398 | ]
|
399 | 399 | },
|
| 400 | + { |
| 401 | + "cell_type": "markdown", |
| 402 | + "id": "f06789fb-61e1-4b35-a2b5-2dea18c1a949", |
| 403 | + "metadata": {}, |
| 404 | + "source": [ |
| 405 | + "### Structured output and tool calls\n", |
| 406 | + "\n", |
| 407 | + "OpenAI's [structured output](https://platform.openai.com/docs/guides/structured-outputs) feature can be used simultaneously with tool-calling. The model will either generate tool calls or a response adhering to a desired schema. See example below:" |
| 408 | + ] |
| 409 | + }, |
| 410 | + { |
| 411 | + "cell_type": "code", |
| 412 | + "execution_count": null, |
| 413 | + "id": "15d2b6e0-f457-4abd-a4d5-08b210d09c04", |
| 414 | + "metadata": {}, |
| 415 | + "outputs": [], |
| 416 | + "source": [ |
| 417 | + "from langchain_openai import ChatOpenAI\n", |
| 418 | + "from pydantic import BaseModel\n", |
| 419 | + "\n", |
| 420 | + "\n", |
| 421 | + "def get_weather(location: str) -> None:\n", |
| 422 | + " \"\"\"Get weather at a location.\"\"\"\n", |
| 423 | + " return \"It's sunny.\"\n", |
| 424 | + "\n", |
| 425 | + "\n", |
| 426 | + "class OutputSchema(BaseModel):\n", |
| 427 | + " \"\"\"Schema for response.\"\"\"\n", |
| 428 | + "\n", |
| 429 | + " answer: str\n", |
| 430 | + " justification: str\n", |
| 431 | + "\n", |
| 432 | + "\n", |
| 433 | + "llm = ChatOpenAI(model=\"gpt-4.1\")\n", |
| 434 | + "\n", |
| 435 | + "structured_llm = llm.bind_tools(\n", |
| 436 | + " [get_weather],\n", |
| 437 | + " response_format=OutputSchema,\n", |
| 438 | + " strict=True,\n", |
| 439 | + ")\n", |
| 440 | + "\n", |
| 441 | + "# Response contains tool calls:\n", |
| 442 | + "tool_call_response = structured_llm.invoke(\"What is the weather in SF?\")\n", |
| 443 | + "\n", |
| 444 | + "# structured_response.additional_kwargs[\"parsed\"] contains parsed output\n", |
| 445 | + "structured_response = structured_llm.invoke(\n", |
| 446 | + " \"What weighs more, a pound of feathers or a pound of gold?\"\n", |
| 447 | + ")" |
| 448 | + ] |
| 449 | + }, |
400 | 450 | {
|
401 | 451 | "cell_type": "markdown",
|
402 | 452 | "id": "84833dd0-17e9-4269-82ed-550639d65751",
|
|
0 commit comments