AI Coding Agent API: Tool Calling Step by Step
An ai coding agent api needs three things from the endpoint: tool calling, a long context window and predictable limits. This guide wires a working agent loop to an OpenAI-compatible URL, with code you can paste and run.
Updated


Key points
- The agent loop is plain chat completions: send tools, run the calls the model returns, send results back as role tool.
- Streamed tool_calls arrive in fragments; accumulate arguments by index before parsing JSON.
- Cap loop steps, truncate tool output and respect 8 concurrent requests per full key.
- Everything works with the standard OpenAI SDK by changing base URL and key.
What an agent needs from the API
An agent is a loop. The model reads a task, decides to call a tool, your code runs it, the result goes back, and the model decides what to do next. The API only has to do the model step well. For an ai coding agent api that means function calling in the OpenAI format, a context window big enough to hold files and logs, and limits that do not choke a loop that fires many calls in a row.
This endpoint is OpenAI-compatible and serves one model, uncensored. It supports tools, tool_choice, streamed tool_calls and results sent back as role: "tool". The context window is 100,000 tokens, prompt and completion together. The base URL is https://api.codingllmapi.com/v1 and auth is a standard Bearer key. Get a key on the API key page; new accounts can claim a $0.50 trial in one click.
One honest note: the model is an independent open-weight model, not an official product of any big lab, and tool-call quality varies by model. Test your own tools before trusting an unattended run.
Define tools the model can actually use
A tool is a JSON schema plus a function in your code. Good schemas are small. Use one verb per tool, plain parameter names and a one-sentence description that says when to call it. Typical coding tools: read_file, write_file, run_tests, search_code, list_dir.
Three habits help more than any prompt trick:
- Mark required parameters. The model skips optional ones more often than you expect.
- Return errors as text. If a path does not exist, return
"error: no such file"and let the model correct itself. - Keep tool output short. Return the last 3,000 characters of a test log, not the whole thing.
For tool_choice, "auto" lets the model decide whether to call a tool or answer. Pass a specific function to force one call, for example when step one must always be reading the failing test. Use "none" for the final summary turn if you want to stop it from calling anything more.
A complete agent loop in Python
The loop below fixes a failing test. It sends one tool, runs whatever the model asks for, appends the result with the matching tool_call_id, and stops when the model answers without a tool call or after 8 steps.
import json, subprocess
from openai import OpenAI
client = OpenAI(base_url="https://api.codingllmapi.com/v1", api_key="YOUR_KEY")
tools = [{
"type": "function",
"function": {
"name": "run_tests",
"description": "Run the project's test suite and return the output.",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string", "description": "Test file or folder"}},
"required": ["path"],
},
},
}]
def run_tests(path):
p = subprocess.run(["pytest", "-x", "-q", path], capture_output=True, text=True)
return (p.stdout + p.stderr)[-3000:]
messages = [
{"role": "system", "content": "You fix failing tests. Use tools, then explain the fix."},
{"role": "user", "content": "tests/test_parser.py fails. Find out why."},
]
for step in range(8):
resp = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = resp.choices[0].message
messages.append(msg)
if not msg.tool_calls:
print(msg.content)
break
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = run_tests(**args)
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
Two details trip people up. First, append the assistant message itself (with its tool_calls) before the tool results, or the next request is malformed. Second, arguments is a JSON string, so parse it, and wrap the parse in a try block in production in case the model emits broken JSON. If parsing fails, send the error back as the tool result and let it retry.
Streaming tool calls
Streaming gives you live output and lower perceived latency, which matters for a terminal agent. With stream: true, tool calls arrive as fragments: the first chunk carries the call id and function name, later chunks carry slices of the arguments string. Merge them by index and parse only after the stream ends.
# client = OpenAI(base_url="https://api.codingllmapi.com/v1", api_key="YOUR_KEY")
calls = {}
stream = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, stream=True
)
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
if delta.content:
print(delta.content, end="", flush=True)
for tc in delta.tool_calls or []:
slot = calls.setdefault(tc.index, {"id": "", "name": "", "args": ""})
slot["id"] = tc.id or slot["id"]
if tc.function:
slot["name"] = tc.function.name or slot["name"]
slot["args"] += tc.function.arguments or ""
After the loop finishes, json.loads(slot["args"]) for each slot, run the tools, and append results exactly as before. Usage is reported at the end of the stream, so you can log token counts per step.
One limit to remember: a streamed request holds its concurrency slot until the stream closes. If your agent opens a stream and forgets to read it to the end, that slot stays busy.
Limits, retries and cost control
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. An agent running sequentially rarely hits either, but parallel sub-agents can. When you exceed a limit the API returns HTTP 429 with the error code rate_limited (per minute) or concurrency (too many at once). A temporary overload also returns 429, with a Retry-After: 5 header. Sleep for that long and retry with a short exponential backoff.
Cost depends on how much context each step resends. At $0.15 per 1M input tokens and $0.50 per 1M output tokens, a 20-step run averaging 22,000 input tokens per call and 500 output tokens per call costs about $0.071 (440,000 x $0.15 / 1M = $0.066, plus 10,000 x $0.50 / 1M = $0.005). Failed or refused requests are not charged. For the wider cost picture see pricing.
Guardrails for unattended runs
Agents do real damage when left alone. A few rules that cost nothing:
- Step cap. The example stops at 8. Pick a number, and make hitting it a visible failure.
- Allowlist commands. A
run_teststool that takes a path is safer than ashelltool that takes any string. - Sandbox writes. Work in a throwaway git branch or a container, and review the diff yourself.
- Log every call. Store the request id from the
X-Request-Idheader with each step so you can trace a bad run. - Compress history. When the transcript passes a size you choose, summarize old steps and drop the raw output.
If you are building a bot rather than a terminal agent, the Discord coding bot guide covers the same loop inside a chat service. The full parameter list is in the API docs.
More guides
Making answers feel better
Once the basic loop works, a few small changes improve it a lot.
- Stream the answer. Pass
stream=Trueand edit the bot's message every second or so with the text so far. Do not edit on every token, because Discord applies its own rate limits to message edits. A streamed request holds its concurrency slot until it ends, so keep the semaphore around the whole stream. - Use slash commands. A command like
/askavoids the mention parsing and does not need the Message Content intent at all, which also makes the bot easier to verify later if it grows past a small number of servers. - Per-user history. Key the history by channel and user if several people ask unrelated questions in one channel.
- Tune the system prompt. Name the languages your community uses, ask for short answers, and tell the model to ask a clarifying question when the problem is vague. Prompt changes are free and often beat model changes.
- Lower the temperature. For code, values between 0.2 and 0.4 give steadier results than the default.
Troubleshooting the usual failures
When a new bot stays silent, the cause is almost always one of the items below. Check them in this order.
- The bot is online but never replies. The Message Content intent is off in the developer portal, or
intents.message_content = Trueis missing from the code. Both must be set. - It replies in some channels only. The bot lacks permission to read or send messages in the others. Check the channel's permission overrides, not only the server-wide role.
- Every reply is a "busy" message. You are probably hitting a 429. Print the exception body once. If the code says
rate_limited, you passed the per-minute cap of 300 requests on a full key or 60 on a trial key. If it saysconcurrency, lower the semaphore size. - An authentication error appears at the first call. The LLM key is missing from the environment of the process that runs the bot. A key exported in one terminal tab is not visible to a service started elsewhere.
- The answer is cut off. The
max_tokens=900in the sample stops long replies. Raise it, or remove it, sincemax_tokensis optional and the completion may use the rest of the window. - The bot answers its own messages. That loop happens if you drop the
message.author.botcheck. Keep it.
For debugging, log the X-Request-Id value for each call. With the OpenAI SDK you can read it from the raw response by calling llm.chat.completions.with_raw_response.create(...) and then reading .headers. If you contact support about a specific failure, that ID lets them find the exact request.
What this costs to run
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, with no subscription. Take a typical exchange: the system prompt plus twelve history entries make about 2,500 input tokens, and the answer is about 400 tokens.
Input: 2,500 x $0.15 / 1,000,000 = $0.000375. Output: 400 x $0.50 / 1,000,000 = $0.0002. One answer costs about $0.000575. A community that asks 500 questions in a day would spend 500 x $0.000575 = $0.2875, a little under thirty cents. Your numbers will differ with longer code pastes, so log resp.usage for a week and read the real averages. The pricing page shows the top-up options: any whole amount from $20 to $500, with +5% from $50, +10% from $100 and +15% from $200, paid by crypto.
To limit abuse, add a per-user cooldown and a cap on question length. Those two checks protect your balance better than anything else you can add.
Hosting and safety notes
The bot is a long-running process. A small virtual machine or a container host is enough, since the heavy work happens on the API side. Run it under a process manager so it restarts after a crash, and keep both tokens in environment variables or a secrets store, never in the repository.
Think about what your server allows. The model is tuned to answer without content refusals for lawful adult use, so it will discuss security testing or edgy fiction that a stricter assistant might refuse. If your community includes younger members, set rules in the system prompt, restrict the bot to specific channels, and remember that Discord's own terms apply to your bot too. Content sexualizing minors is forbidden on this API without exception.
Full parameter details, such as stop, seed and tool calling, are in the API docs. If you want the bot to run code or read repositories, tool calling is the route, and you decide which functions the model may request. For programming-focused use of this model, see the page about the uncensored AI model for coding.
More guides
Questions and answers
Does the endpoint support OpenAI-style function calling?
Yes. Send tools and tool_choice in the request, read tool_calls from the response, and return results as messages with role tool and the matching tool_call_id.
Can I stream tool calls?
Yes. Tool calls stream as fragments; join the arguments strings by index and parse the JSON after the stream ends.
Which model ID do I use?
Use uncensored with the base URL https://api.codingllmapi.com/v1. A GET to /v1/models lists what is available.
How many agents can run in parallel?
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Get API key