Latest AI news

Home  /  How-To  /  OpenAI Function Calling with LangChain: Real‑Time Retrieval

OpenAI Function Calling with LangChain: Real‑Time Retrieval

You can integrate OpenAI's function calling into a LangChain agent by defining Python functions as tools, binding them with ChatOpenAI (or create_agent), and allowing the model to invoke those tools at runtime to retrieve live data like weather or stock prices.

By AI Decodes Editorial  ·  Published  ·  Last verified 27 November 2026

Diagram of code linking OpenAI function calling to LangChain tools
A LangChain agent calling an OpenAI function to retrieve live information.

What is function calling and why pair it with LangChain?

OpenAI’s function calling lets a model return a JSON‑structured request for a tool instead of free‑form text. LangChain can turn Python functions into those tool specifications, so the agent can automatically call external APIs during a conversation. This reduces prompt length, improves reliability, and enables real‑time data retrieval without writing custom request logic.

  • Function calling is defined in the OpenAI API docs [S1].
  • LangChain integration converts functions to the OpenAI tool schema and parses function_call results back into the agent [S4].
  • Using both lets you build agents that answer up‑to‑date queries (weather, stock prices, DB rows) while keeping the codebase simple.

How do I set up the environment and API credentials?

  1. Install the required packages:
  2. bash pip install -U "langchain[openai]" "langchain-openai"

  1. Obtain an OpenAI API key from the OpenAI Platform and expose it as an environment variable:
  2. bash export OPENAI_API_KEY=sk-...

The ChatOpenAI class reads OPENAI_API_KEY automatically [S4].

  1. (Optional) If you use Azure OpenAI, set OPENAI_API_BASE or pass base_url when constructing the model as described in the same docs.
  2. Verify the installation by creating a simple ChatOpenAI instance:
  3. python from langchain.chat_models import ChatOpenAI llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

Flowchart of a LangChain agent invoking an OpenAI function to fetch external data
Step‑by‑step flow of real‑time data retrieval.

Step‑by‑step: wiring a LangChain agent to call a live API

#### 1. Define the tool function python import requests

def get_stock_price(symbol: str) -> float: """Return the latest price for *symbol* using a public API.""" resp = requests.get(f"https://api.example.com/price/{symbol}") resp.raise_for_status() return resp.json()["price"]

#### 2. Bind the function as a tool python from langchain.chat_models import ChatOpenAI from langchain.schema import Tool

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) stock_tool = Tool(name="GetStockPrice", func=get_stock_price, description="Fetch current stock price for a ticker symbol.")

# Bind tools – the SDK converts the Python signature to an OpenAI tool schema bound_llm = llm.bind_tools([stock_tool])

#### 3. Create an agent (or call the model directly) python from langchain.agents import create_agent

agent = create_agent(model=bound_llm, tools=[stock_tool], system_prompt="You are a finance assistant that can retrieve live stock prices.")

result = agent.invoke({"messages": [{"role": "user", "content": "What is the price of AAPL today?"}]}) print(result["messages"][-1].content)

The model will output a tool_call for GetStockPrice, LangChain executes get_stock_price, feeds the result back, and finally returns a natural‑language answer.

#### 4. Enabling strict mode (optional) If you want the model to respect the exact JSON schema, pass strict=True when binding tools [S4]. python bound_llm = llm.bind_tools([stock_tool], strict=True)

How can I deploy the agent, for example on Vercel?

  1. Add a vercel.json that routes POST requests to a Python serverless function.
  2. In api/agent.py, expose a tiny FastAPI (or Flask) endpoint that loads the LangChain agent created above and calls agent.invoke with the incoming user message.
  3. Set the OPENAI_API_KEY secret in Vercel’s dashboard.
  4. Deploy with vercel --prod. The endpoint now handles real‑time queries without any additional plumbing because the function‑calling logic lives inside the LangChain agent.

*Deploying serverless functions is covered in OpenAI’s production best‑practice guide, which recommends keeping the API key out of source code and using environment variables.*

What to do if it does not work?

  1. Check the API key – ensure OPENAI_API_KEY is set and not expired. The ChatOpenAI constructor raises an authentication error if the key is missing.
  2. Validate the model name – GPT‑4o or GPT‑4o‑mini are the only models that currently support function calling. Using an older model returns a normal text response.
  3. Confirm tool schema – the function signature must be serializable to JSON. If you receive a function_call with missing arguments, enable strict=True to force schema compliance.
  4. Inspect the response – after a tool call, LangChain stores the result in a FunctionMessage. If the agent never returns a final answer, verify that the tool actually returned data and that the invoke call includes the updated message history.
  5. Enable debugging – set langchain.debug = True (as shown in the Medium example [[S5]]) to see the full chain of tool calls and responses.
  6. Network issues – confirm that the external API endpoint is reachable from your deployment environment; a timeout will cause the LangChain step to fail.
  7. Review OpenAI rate limits – excessive calls may be throttled; respect the usage limits documented in the OpenAI API guide.

Menus and names can change as products update. If a step looks different, check the product's own help page.

Frequently asked questions

Do I need to use LangChain’s create_agent or can I call the model directly?
Both approaches work. create_agent bundles the model, tools, and system prompt into a single object, while binding tools to a ChatOpenAI instance lets you call invoke manually.

Can I use async tool calls for faster performance?
Yes. When using the Responses API, pass extras={"async": True} to the @tool decorator. LangChain will continue processing without waiting for the tool result [[S4]].

Is function calling supported on Azure OpenAI?
Azure OpenAI v1 endpoints support function calling. Set base_url to your Azure endpoint and use ChatOpenAI with the same tool‑binding workflow [[S4]].

What models currently support function calling?
GPT‑4o and GPT‑4o‑mini (and compatible versions like gpt‑3.5‑turbo‑0613) support function calling as described in the OpenAI function calling guide [[S1]], [[S6]].