LangChain with FreeModel: ChatOpenAI and Tool Calling
Code first. Connect LangChain's ChatOpenAI to FreeModel, stream a reply, run a complete tool-calling loop, and handle the errors you will actually see.
LangChain's ChatOpenAI class talks to any API that follows the OpenAI chat format. FreeModel does, so connecting the two is one argument: base_url. This post is mostly code; every snippet runs as written with a FreeModel key and the free model gpt-6-luna.
Install and connect
pip install -U langchain-openai
export FREEMODEL_API_KEY=fm_your_key_here
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="gpt-6-luna",
base_url="https://freemodel.in/v1",
api_key=os.environ["FREEMODEL_API_KEY"],
)
reply = llm.invoke("Explain a Python list comprehension in one sentence.")
print(reply.content)
Three things to get right:
base_urlends at/v1. The client adds/chat/completions.modelis an exact id fromGET /v1/models. FreeModel does not map names likegpt-4oto another model; they return 404.- The key is sent as a Bearer token, which is what FreeModel expects. Keys are created at Dashboard → API Keys.
Streaming
for chunk in llm.stream("Write a haiku about unit tests."):
print(chunk.content, end="", flush=True)
print()
FreeModel streams over server-sent events and keeps long streams alive with a ping every 8 seconds. The streaming docs show the raw format if you need to debug below LangChain.
A small chain
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You write short, plain commit messages."),
("user", "Diff summary: {summary}"),
])
chain = prompt | llm | StrOutputParser()
print(chain.invoke({"summary": "rename get_user to fetch_user in api.py"}))
Nothing here is FreeModel-specific. That is the point: once llm is built, the rest of LangChain does not care where it points.
Tool calling: the full round trip
Tool calling needs a model with the Tools capability. All of the free models have it; for the rest, check the models page.
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage
@tool
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"Sunny and 31 degrees in {city}." # replace with a real lookup
llm_with_tools = llm.bind_tools([get_weather])
messages = [HumanMessage("What is the weather in Dhaka?")]
ai_msg = llm_with_tools.invoke(messages)
messages.append(ai_msg)
for call in ai_msg.tool_calls:
tool_msg = get_weather.invoke(call) # returns a ToolMessage with the right tool_call_id
messages.append(tool_msg)
final = llm_with_tools.invoke(messages)
print(final.content)
What happens on the wire:
- The first request carries the tool's JSON schema. The model answers with
tool_callsinstead of text. - LangChain parses the arguments into
ai_msg.tool_calls, a list of dicts withname,argsandid. - Invoking the tool with the whole call returns a
ToolMessagelinked to that id. - The second request sends the history plus the tool result, and the model writes the final answer.
Each round trip is two billed requests, and the second one resends the whole history. Input and output tokens both count. For the protocol itself, see the tool calling docs.
If the model never calls the tool
- Make the docstring specific. It becomes the tool description the model reads.
- Check the model has the Tools capability.
- Force a call when you need one:
llm.bind_tools([get_weather], tool_choice="get_weather").
Batching and async without hitting limits
LangChain makes it easy to fire many requests at once, and that is where rate limits show up. FreeModel limits are per key and per plan: 30 requests per minute on the free plan (whole account), 120 on Starter, up to 1,500 on Ultra. Cap the concurrency yourself:
questions = ["What is a mutex?", "What is a semaphore?", "What is a deadlock?"]
answers = llm.batch(questions, config={"max_concurrency": 3})
for a in answers:
print(a.content[:80])
The async versions work the same way inside an event loop: await llm.ainvoke(...), llm.astream(...) and await llm.abatch(...).
Two habits keep token use predictable:
- Trim history. Every call resends the messages you pass. Long chat histories are the most common reason a bill grows.
- Set
max_tokensdeliberately. Too low and a reasoning model may spend the whole budget thinking and return an empty answer; too high and a chatty model writes more than you need.
The free plan has no daily cap, but a free account is limited to 400K tokens per minute, so a large batch job on a free key may get 429 free_tpm_limit partway through; wait for Retry-After.
Claude through the Anthropic format
FreeModel also speaks the Anthropic Messages format at base https://freemodel.in. If you prefer LangChain's Anthropic class:
# pip install -U langchain-anthropic
import os
from langchain_anthropic import ChatAnthropic
claude = ChatAnthropic(
model="claude-sonnet-5",
base_url="https://freemodel.in",
api_key=os.environ["FREEMODEL_API_KEY"],
)
print(claude.invoke("Say hello in five words.").content)
Claude models other than Claude Haiku 5.5 need a paid plan; a free key gets 403 upgrade_required. You can also keep ChatOpenAI and simply set model="claude-sonnet-5". Claude Sonnet 5 uses plan tokens at 3×; the full table is on the pricing page.
Errors and retries
ChatOpenAI uses the official openai package underneath, so errors arrive as its exception classes:
import openai
try:
llm.invoke("Hello")
except openai.AuthenticationError:
print("401: check the key")
except openai.NotFoundError:
print("404: model id not listed")
except openai.RateLimitError:
print("429: per-key rate limit, slow down")
except openai.APIStatusError as e:
print(e.status_code, e.message) # 402 tokens used up, 403 upgrade_required, 503 unavailable
ChatOpenAI also takes max_retries and timeout. Retrying a 402 or 403 will not help; retrying a 429 or 503 after a pause usually does. A request that fails is not charged.
FAQ
Do I need a special LangChain integration for FreeModel?
No. FreeModel speaks the OpenAI format, so the standard ChatOpenAI class from langchain-openai works once base_url points at https://freemodel.in/v1.
Which models support bind_tools?
Models with the Tools capability on the FreeModel models page. All of the free models, including gpt-6-luna, have it.
Can I use Claude through LangChain?
Yes. Claude Haiku 5.5 works on a free key; the other Claude models need a paid plan. Use ChatOpenAI with a Claude model id, or ChatAnthropic with base_url set to https://freemodel.in for the Anthropic format.
What happens when my tokens run out mid-run?
The API answers HTTP 402 with a clear message and nothing is charged on top. In Python this surfaces as an openai APIStatusError that you can catch.
Grab a free API key — 1M tokens on 8 free models after a one-time Telegram verification, no card. Every model from $1.20.