LangChain LLM With Tools: Tool Calling Tutorial
A LangChain LLM with tools needs three things: a chat model pointed at an OpenAI-compatible endpoint, a list of tool functions bound to it, and a loop that runs the tools the model asks for. This tutorial builds that against the uncensored text API on this site.

Key points
- ChatOpenAI works with any OpenAI-compatible endpoint when you set base_url, api_key and model.
- bind_tools sends your function schemas; you run the tools and return the results as tool messages.
- JSON mode gives parseable output when you do not need tools.
- Mind the limits: 8 concurrent requests and 300 requests per minute on a full key.
Setup
Install the packages and keep your key in an environment variable. You can get a key, and claim the $0.50 trial credit, on the API key page.
pip install langchain-openai langchain-core
export API_KEY="your-key-here"
The service speaks the OpenAI chat completions format, so LangChain's ChatOpenAI class works unchanged. Three values matter: the base URL, the key and the model ID, which is uncensored.
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.acestep.cc/v1",
api_key=os.environ["API_KEY"],
temperature=0,
max_retries=2,
)
print(llm.invoke("Say hello in five words.").content)
If that prints a short greeting, the connection works. A low temperature is a good default for tool use because you want stable argument values.
Define a tool and bind it
The @tool decorator turns a Python function into a tool. LangChain reads the function name, the type hints and the docstring to build the JSON schema that gets sent to the model, so write the docstring as an instruction to the model, not to a human reader.
from langchain_core.tools import tool
@tool
def word_count(text: str) -> int:
"""Count the words in a piece of text, for example song lyrics."""
return len(text.split())
tools = [word_count]
llm_with_tools = llm.bind_tools(tools)
bind_tools adds the tools field to each request. You can also pass tool_choice to force a specific tool, or leave it out and let the model decide.
Run the call loop
The model does not execute anything. It returns an assistant message with tool_calls, each with a name, arguments and an ID. Your code runs the function and sends back a tool message with the same ID. Then you call the model again so it can write the final answer.
from langchain_core.messages import HumanMessage, ToolMessage
registry = {t.name: t for t in tools}
messages = [HumanMessage("How many words are in: 'the rain keeps writing the chorus'?")]
ai = llm_with_tools.invoke(messages)
messages.append(ai)
for call in ai.tool_calls:
result = registry[call["name"]].invoke(call["args"])
messages.append(ToolMessage(content=str(result), tool_call_id=call["id"]))
final = llm_with_tools.invoke(messages)
print(final.content)
The result should say six words. In an API request this is the same flow as the raw format: the tool result goes back with role: "tool", and LangChain's ToolMessage maps to that.
A loop that handles several rounds
Real tasks often need more than one round: the model calls a tool, reads the result and calls another. Wrap the steps in a loop with a hard cap so a confused model cannot spin forever.
def run(question, max_rounds=5):
messages = [HumanMessage(question)]
for _ in range(max_rounds):
ai = llm_with_tools.invoke(messages)
messages.append(ai)
if not ai.tool_calls:
return ai.content
for call in ai.tool_calls:
try:
out = registry[call["name"]].invoke(call["args"])
except Exception as exc:
out = f"Tool error: {exc}"
messages.append(ToolMessage(content=str(out), tool_call_id=call["id"]))
return "Stopped after too many tool rounds."
print(run("Count the words in 'hold the line' and in 'break the silence', then add them."))
Returning the error text as the tool result, instead of raising, lets the model see what went wrong and try again with better arguments. When the model sends several tool calls in one message, run them all and append one tool message per call.
LangChain also ships ready-made agent helpers, and they work with this endpoint for the same reason: they only need a chat model that supports tool calling. Writing the loop by hand once is still worth it, because you then know exactly what is sent and billed.
Streaming tool calls
The API streams over server-sent events, and tool calls arrive in pieces. LangChain message chunks can be added together, which rebuilds the complete call:
full = None
for chunk in llm_with_tools.stream("How many words are in 'one two three'?"):
full = chunk if full is None else full + chunk
print(full.tool_calls)
Stream text for the user while you wait, and only act on a tool call once the stream is complete. Usage is reported at the end of a stream, so billing figures are available after the last chunk.
Using tools inside a chain
If you prefer LangChain's pipe syntax, the bound model slots into a chain like any other runnable. A prompt template feeds the model, and a parser turns the final message into text:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You help writers check their drafts. Use tools when counting is needed."),
("human", "{question}"),
])
chain = prompt | llm | StrOutputParser()
print(chain.invoke({"question": "Write a two-line chorus about rain."}))
This chain does not run tools. It is the right shape for plain generation steps. When a step needs tools, call the bound model and use the loop above, or put that loop inside a function and wrap it with a runnable lambda. Keeping the tool loop explicit makes it easier to log each call, which helps when an argument looks wrong.
Structured JSON without tools
When you want data and do not need function execution, use JSON mode. It sets response_format to {"type": "json_object"}. The prompt must also tell the model what shape to return.
import json
json_llm = llm.bind(response_format={"type": "json_object"})
msg = json_llm.invoke(
"Return a JSON object with keys 'title' (string) and 'tags' (list of 3 strings) "
"for a song about a night train."
)
data = json.loads(msg.content)
print(data["title"], data["tags"])
JSON mode makes valid JSON likely, but it does not enforce your schema. Validate the keys and types yourself, for example with Pydantic, and retry once if validation fails.
Pitfalls and limits
- Arguments arrive as the model wrote them. Validate types in your tool; do not trust that a number is a number.
- Tool descriptions steer behaviour. Vague docstrings cause wrong tool choices. Say when to use the tool and when not to.
- HTTP 429. Full keys allow 8 concurrent requests and 300 requests per minute; trial keys allow 2 and 60. The codes are
rate_limitedandconcurrency. A 429 withRetry-After: 5means temporary overload, andmax_retrieson the client helps with that. A stream holds its slot until it ends. - Context. The window is 100,000 tokens, prompt plus completion. Every tool round resends the history, so long agent runs grow quickly.
The quickstart has the full parameter list. This model is text only, so tools that depend on images, audio or embeddings need another service for that part of the pipeline.
What a tool loop costs
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. A question answered with one tool round makes two calls. Suppose the two calls together send 4,000 input tokens and produce 600 output tokens. Input is 4,000 / 1,000,000 x $0.15 = $0.0006, and output is 600 / 1,000,000 x $0.50 = $0.0003, so the question costs $0.0009. Failed or refused requests are not charged. See the pricing page for top-up amounts and payment methods.
More guides
Questions and answers
Does this API support tool calling?
Yes. It accepts tools and tool_choice, returns tool_calls (also when streaming), and takes results as messages with role tool.
Which LangChain class should I use?
ChatOpenAI from langchain-openai, with base_url set to the API endpoint, your key and the model ID uncensored.
Can I get structured output with a schema?
JSON mode returns a valid JSON object, but it does not enforce a schema. Describe the shape in the prompt and validate the result in your code.
How do I avoid rate limit errors with parallel chains?
Keep concurrency at or below 8 on a full key, and use client retries for 429 responses. Trial keys allow 2 concurrent requests.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.