Agentic AI Using LangChain With an Uncensored API
Agentic AI using LangChain comes down to a loop: the model decides on a tool, your code runs it, and the result goes back to the model. This guide builds that loop against an OpenAI-compatible API, with tool calling and JSON mode.

Key points
- LangChain's ChatOpenAI class works with any OpenAI-compatible endpoint through base_url.
- An agent is a bounded loop: model call, tool execution, repeat until no tool calls remain.
- JSON mode gives machine-readable output for planner and router steps.
- A six-step agent run costs well under half a cent at our token prices.
On this page
How the pieces fit together
An agent is a language model that can call functions. You describe a set of tools, the model replies either with text or with a request to call one of them, your program executes the call, and you send the output back. The cycle repeats until the model answers in plain text. That is what agentic AI using LangChain amounts to in practice, and the framework mostly helps with the plumbing: describing tools, packaging messages and retrying failed calls.
Our API supports everything the loop needs. It accepts tools and tool_choice, streams tool_calls, and takes tool results as messages with role: "tool". It also supports JSON mode through response_format: {"type":"json_object"}. The model ID is uncensored and the base URL is https://api.unrestrictedai.cc/v1.
The model is an open-weight one, run by an independent provider and tuned to answer without content refusals for lawful adult use. That is useful for agents that handle fiction, moderation research or other material that mainstream models decline. It is text only, so tools return text or JSON, not images.
Install and connect
You need Python and the LangChain packages for OpenAI-style chat models. Package layouts change between releases, so check the LangChain documentation if an import fails. At the time of writing these are the two you need:
pip install langchain-openai langchain-core
export UNRESTRICTED_KEY="paste-your-key-here"
Create a key on the API key page. New users can claim $0.50 of trial credit with one click, valid for 7 days and no card required. Then build the model object. The only differences from a standard OpenAI setup are base_url and model:
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
base_url="https://api.unrestrictedai.cc/v1",
api_key=os.environ["UNRESTRICTED_KEY"],
model="uncensored",
temperature=0.3,
max_retries=3,
)
print(llm.invoke("Reply with the single word: ready").content)
If that prints a reply, authentication, routing and the model name are all correct. A 401 means the key is wrong; a 404 usually means the base URL is missing its /v1 suffix.
Define tools the model can call
A tool is a normal Python function with a type-annotated signature and a docstring. LangChain turns both into the schema the model sees, so the docstring is effectively the prompt for that tool. Write it for the model: what the tool does, what each argument means, what it returns.
from langchain_core.tools import tool
NOTES = {
"chapter-1": "The courier arrives at the harbour at dusk carrying a sealed tin.",
"chapter-2": "Inspector Voss notices the tin was opened and resealed.",
}
@tool
def get_note(key: str) -> str:
"""Fetch a story note by key, for example chapter-1. Returns the note text or 'not found'."""
return NOTES.get(key, "not found")
@tool
def word_count(text: str) -> int:
"""Count the words in a piece of text."""
return len(text.split())
Keep tools small and single-purpose. A model picks between five clear tools far more reliably than it uses one tool with a dozen modes. Return short strings: the output goes straight back into the context, and you pay for it as input tokens on every following step.
Run the agent loop
You can use a prebuilt agent helper, but writing the loop yourself takes fifteen lines and makes the behaviour obvious, which helps when something goes wrong. Bind the tools to the model, call it, execute any requested tools, append their results, and go again.
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
tools = [get_note, word_count]
by_name = {t.name: t for t in tools}
agent = llm.bind_tools(tools)
messages = [
SystemMessage(content="You are a research assistant. Use tools when you need facts. Be brief."),
HumanMessage(content="Read chapter-1 and chapter-2, then tell me how many words the two notes have in total."),
]
for step in range(6): # hard cap on iterations
ai = agent.invoke(messages)
messages.append(ai)
if not ai.tool_calls: # model answered in plain text
break
for call in ai.tool_calls:
result = by_name[call["name"]].invoke(call["args"])
messages.append(ToolMessage(content=str(result), tool_call_id=call["id"]))
print(ai.content)
Three details keep this honest. The loop has a hard cap, because a confused model can call tools forever. Every tool call receives a ToolMessage with the matching tool_call_id; skip one and the next request fails. And errors from your tools should come back as text, not exceptions, so the model can correct itself: wrap the call in a try block and return the error message as the result.
You can also pass tool_choice to force a specific tool on the first step, which is a handy way to build a router that always starts with the same lookup.
Use JSON mode for planners and routers
Agents often need structured output in the middle of the flow: a plan, a classification, a list of steps. JSON mode makes the model return a valid JSON object. In LangChain you can bind the parameter straight onto the model:
import json
json_llm = llm.bind(response_format={"type": "json_object"})
plan = json_llm.invoke([
SystemMessage(content="Return a JSON object with keys 'steps' (list of strings) and 'needs_tools' (boolean)."),
HumanMessage(content="Plan how to summarise three chapters of a novel."),
])
data = json.loads(plan.content)
print(data["steps"])
Mention JSON in the prompt and spell out the keys you expect, as the example does. JSON mode guarantees syntax, not your schema, so validate the fields before you rely on them. Pydantic works well for that. Do not combine a JSON-mode call with tools in the same step; use JSON mode for planning calls and plain tool binding for action calls.
Run many agents at once without hitting limits
Limits matter more for agents than for chatbots, because one task makes several model calls. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Exceed either and the API returns HTTP 429, with error code rate_limited or concurrency. Temporary overload also gives a 429 with Retry-After: 5.
When you process a batch of tasks, cap concurrency below the limit. LangChain's batch method takes a config for exactly this:
prompts = [f"Give one title idea for story number {i}." for i in range(40)]
answers = llm.batch(prompts, config={"max_concurrency": 6})
Six leaves headroom under the limit of 8 for retries and other traffic. If you stream agent output to users, remember that a streamed request holds its slot until the stream ends. Set max_retries on the model object so short 429 bursts are absorbed with backoff instead of crashing the run.
Debugging an agent that misbehaves
When an agent goes wrong, the cause is nearly always visible in the message list, so print it. Log each tool call with its arguments and the result you returned, plus the X-Request-Id response header for any request you may need to ask support about. Most failures fall into a few patterns.
- The model never calls a tool. The docstring is vague, or the task does not seem to need one. Make the system prompt say when tools are required, or force the first step with
tool_choice. - It calls the same tool again and again. The tool returns something the model cannot use, such as an empty string. Return an explicit message like "no results, try a different key".
- Arguments are malformed. Use simple types, short descriptions per argument, and validate inside the tool. Return the validation error as text.
- The run gets slow and expensive. The context is growing with long tool outputs. Truncate them before appending.
A low temperature, around 0.0 to 0.3, makes tool selection steadier. Raise it only for steps that write creative text. And keep in mind that models run by independent providers differ in how well they follow tool schemas, so test your own tools and prompts instead of assuming a result from another model carries over.
Safe habits for agents that act on the world
An agent that can only read notes is harmless. One that can send messages, write files or call paid services needs guardrails, and those are your code's job, not the model's. Give each tool the narrowest permission it needs. Ask for human confirmation before any action that cannot be undone. Log every call. Keep API keys for third-party services out of the prompt, and keep your own key in an environment variable on the server.
The same applies to content rules. The model is tuned to answer without content refusals for lawful adult use, so the limits of your product come from your design. Sexual content involving minors is never allowed. Add whatever further rules your audience needs, and enforce them in code around the model.
What an agent run costs
Prices are $0.15 per 1M input tokens and $0.50 per 1M output tokens. Agents are input-heavy, because every step resends the growing message list. Suppose a run takes 6 model calls, averaging 3,000 input tokens and 300 output tokens each.
- Input: 6 x 3,000 = 18,000 tokens, which is 0.018 x $0.15 = $0.0027.
- Output: 6 x 300 = 1,800 tokens, which is 0.0018 x $0.50 = $0.0009.
- Total: $0.0036 per run.
A thousand runs cost $3.60. The levers are the same as for any long-context work: keep tool outputs short, cap the loop, and trim old messages. The context window of 100,000 tokens covers prompt plus completion, so very long runs still fit, but they cost more with each step.
Billing is prepaid with no subscription, and failed or refused requests are not charged. Top-ups start at $20. See the pricing page for bonus tiers. For the raw API details behind this tutorial, the quickstart and the integration guide cover authentication, streaming and error handling.
More guides
Questions and answers
Does LangChain work with this API?
Yes. ChatOpenAI accepts a base_url, so you point it at the OpenAI-compatible endpoint and set the model to uncensored.
Does the model support tool calling?
Yes. The API accepts tools and tool_choice, streams tool_calls, and takes results as messages with role tool.
How do I stop an agent from looping forever?
Cap the number of iterations in your loop, as in the example above, and return tool errors as text so the model can adjust instead of retrying blindly.
What happens if I send too many requests?
You receive HTTP 429 with error code rate_limited or concurrency. Lower your concurrency, set max_retries and back off.
Can an agent use images or embeddings?
Not through this API. It is text only, with no image, audio or video generation, no embeddings and no fine-tuning.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.