# OpenAI Function calling

import CodeBlock from "@theme/CodeBlock";
import OpenAIFunctionsExample from "@examples/models/chat/openai_functions.ts";
import OpenAIFunctionsZodExample from "@examples/models/chat/openai_functions_zod.ts";

Function calling is a useful way to get structured output from an LLM for a wide range of purposes.
By providing schemas for "functions", the LLM will choose one and attempt to output a response matching that schema.

Though the name implies that the LLM is actually running code and calling a function, it is more accurate to say that the LLM is
populating parameters that match the schema for the arguments a hypothetical function would take. We can use these
structured responses for whatever we'd like!

Function calling serves as a building block for several other popular features in LangChain, including the [`OpenAI Functions agent`](/docs/modules/agents/agent_types/openai_functions_agent)
and [`structured output chain`](/docs/modules/chains/popular/structured_output). In addition to these more specific use cases, you can also attach function parameters
directly to the model and call it, as shown below.

## Usage

OpenAI requires parameter schemas in the format below, where `parameters` must be [JSON Schema](https://json-schema.org/).
Specifying the `function_call` parameter will force the model to return a response using the specified function.
This is useful if you have multiple schemas you'd like the model to pick from.

<CodeBlock language="typescript">{OpenAIFunctionsExample}</CodeBlock>

## Usage with Zod

An alternative way to declare function schema is to use the [Zod](https://zod.dev) schema library with the
[zod-to-json-schema](https://www.npmjs.com/package/zod-to-json-schema) utility package to translate it:

```bash npm2yarn
npm install zod
npm install zod-to-json-schema
```

<CodeBlock language="typescript">{OpenAIFunctionsZodExample}</CodeBlock>
