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.

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_callresults 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?
- Install the required packages:
bash pip install -U "langchain[openai]" "langchain-openai"
- Obtain an OpenAI API key from the OpenAI Platform and expose it as an environment variable:
bash export OPENAI_API_KEY=sk-...
The ChatOpenAI class reads OPENAI_API_KEY automatically [S4].
- (Optional) If you use Azure OpenAI, set
OPENAI_API_BASEor passbase_urlwhen constructing the model as described in the same docs. - Verify the installation by creating a simple
ChatOpenAIinstance:
python from langchain.chat_models import ChatOpenAI llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

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?
- Add a
vercel.jsonthat routes POST requests to a Python serverless function. - In
api/agent.py, expose a tiny FastAPI (or Flask) endpoint that loads the LangChain agent created above and callsagent.invokewith the incoming user message. - Set the
OPENAI_API_KEYsecret in Vercel’s dashboard. - 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?
- Check the API key – ensure
OPENAI_API_KEYis set and not expired. TheChatOpenAIconstructor raises an authentication error if the key is missing. - 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.
- Confirm tool schema – the function signature must be serializable to JSON. If you receive a
function_callwith missing arguments, enablestrict=Trueto force schema compliance. - 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 theinvokecall includes the updated message history. - Enable debugging – set
langchain.debug = True(as shown in the Medium example [[S5]]) to see the full chain of tool calls and responses. - Network issues – confirm that the external API endpoint is reachable from your deployment environment; a timeout will cause the LangChain step to fail.
- 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]].