Updated
Hermes Agent Python API: OpenAI SDK Setup and Tools
For a hermes agent python api setup, you only need the official openai package, this service's base URL and an API key. This page goes from a first call to an agent loop with tools.
Key points
- Install openai, then set base_url and api_key on the client.
- Stream with stream=True and read usage from the final chunk.
- Keep parallel calls at 8 or fewer on a full key, 2 on a trial key.
- Tool calling follows the standard OpenAI loop with role tool results.

First call in five lines
The service speaks the OpenAI chat completions protocol, so the standard Python package works unchanged. Install it, point it at the base URL, and pass your key. If you do not have a key yet, the API key page lets new accounts claim $0.50 of trial credit with no card.
pip install openai
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.hermesapi.cc/v1",
api_key=os.environ["HERMES_API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise research assistant."},
{"role": "user", "content": "List three risks of running an agent without a step limit."},
],
temperature=0.7,
)
print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens, resp.usage.completion_tokens)
That is the whole integration. The model ID is uncensored, the auth header is built for you from api_key, and the two usage numbers at the end are what you are billed for: $0.15 per 1M input tokens and $0.50 per 1M output tokens. The quickstart shows the same call in curl and Node if you want to compare.
The word agent means different things to different people. Here it means a loop: the model reads the conversation, optionally asks your code to run a function, receives the result, and continues until it can answer. Every piece of that loop is available through the chat completions endpoint, so you do not need a special framework to build one. The sections below add each piece. Frameworks can help once your agent grows, but they all end up making the same HTTP calls, so understanding the plain version first makes any framework easier to debug.
Configure it once with environment variables
If you use the official SDK in several scripts, set two environment variables and skip the constructor arguments. The Python SDK reads OPENAI_BASE_URL and OPENAI_API_KEY.
export OPENAI_BASE_URL="https://api.hermesapi.cc/v1"
export OPENAI_API_KEY="YOUR_API_KEY"
from openai import OpenAI
client = OpenAI() # base URL (https://api.hermesapi.cc/v1) and key come from the variables
models = client.models.list() # GET /v1/models
print([m.id for m in models.data]) # should include "uncensored"
The models call is a handy smoke test. It hits GET /v1/models and proves that your key and base URL are correct before you debug anything else. Two mistakes cause most first-run failures: leaving off the /v1 suffix on the base URL, and passing a model name from another provider. The model here is always uncensored.
The two methods the API offers are POST /v1/chat/completions and GET /v1/models. Anything else in the SDK, such as embeddings, image generation or the fine-tuning endpoints, is not available on this service, so a call to those will fail.
Streaming responses
For interactive tools, stream tokens as they are produced. Set stream=True and iterate. The final chunk carries token usage, and it has an empty choices list, so guard for that.
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a four-line status update for a build pipeline."}],
stream=True,
)
usage = None
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if getattr(chunk, "usage", None):
usage = chunk.usage
print()
if usage:
print("tokens:", usage.prompt_tokens, usage.completion_tokens)
One thing to remember about streaming is that the request occupies one of your concurrency slots until the stream ends. A full key allows 8 requests at once, a trial key allows 2. If your UI opens a stream and the user wanders off without closing it, that slot stays busy. Close the stream on cancel (stream.close()) so the slot is released.
Rate limits, 429s and retries
Limits on a full key are 300 requests per minute and 8 concurrent requests. A trial key gets 60 per minute and 2 concurrent. Every response includes X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency headers, so your code can read its own ceiling instead of hard-coding it.
When you go over, the API returns HTTP 429. The error code tells you which limit you hit: rate_limited means too many requests per minute, and concurrency means too many at once. Temporary overload also returns 429, with a Retry-After: 5 header. The OpenAI SDK retries a couple of times on its own and honours that header, and you can raise the number with OpenAI(max_retries=5). For an agent that must not drop a step, a small explicit wrapper is clearer:
import time
import openai
def ask(messages, attempts=6, **kwargs):
for attempt in range(attempts):
try:
return client.chat.completions.create(
model="uncensored", messages=messages, **kwargs
)
except openai.RateLimitError as e:
if attempt == attempts - 1:
raise
wait = float(e.response.headers.get("retry-after", 2 ** attempt))
print(f"429 ({e.code}), sleeping {wait}s")
time.sleep(wait)
Rejected requests are not charged, so retrying is safe for your balance. It still pays to avoid the problem in the first place by capping parallelism, which is the next section.
Running many requests in parallel
Agents that fan out, such as one call per document or per search result, hit the concurrency cap quickly. An asyncio semaphore keeps you under it without a retry storm.
import asyncio
from openai import AsyncOpenAI
aclient = AsyncOpenAI(
base_url="https://api.hermesapi.cc/v1",
api_key=os.environ["HERMES_API_KEY"],
)
sem = asyncio.Semaphore(8) # use 2 on a trial key
async def summarize(text):
async with sem:
r = await aclient.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Summarize in two sentences:\n" + text}],
max_tokens=200,
)
return r.choices[0].message.content
async def main(docs):
return await asyncio.gather(*(summarize(d) for d in docs))
results = asyncio.run(main(["first document...", "second document..."]))
With 8 slots and calls that take a few seconds each, you will stay far below 300 requests per minute, so the concurrency cap is the number that matters in practice. Set max_tokens when you know the answer is short. It is optional, since a completion can use whatever is left of the 100,000-token window, but a cap protects you from a runaway answer.
A tool-calling agent loop
Tool calling uses the tools and tool_choice parameters, returns tool_calls on the assistant message, and expects your results back as messages with role: "tool". Here is a complete loop with one tool, a clock:
import json
from datetime import datetime
from zoneinfo import ZoneInfo
def get_time(tz):
return datetime.now(ZoneInfo(tz)).isoformat(timespec="seconds")
TOOLS = {"get_time": get_time}
tool_specs = [{
"type": "function",
"function": {
"name": "get_time",
"description": "Current local time for an IANA time zone name.",
"parameters": {
"type": "object",
"properties": {"tz": {"type": "string", "description": "e.g. Asia/Tokyo"}},
"required": ["tz"],
},
},
}]
messages = [{"role": "user", "content": "What time is it in Tokyo right now?"}]
for step in range(5): # hard step limit
r = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tool_specs,
tool_choice="auto",
)
msg = r.choices[0].message
if not msg.tool_calls:
print(msg.content)
break
messages.append(msg)
for call in msg.tool_calls:
try:
args = json.loads(call.function.arguments)
result = TOOLS[call.function.name](**args)
except Exception as e:
result = f"tool error: {e}"
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": str(result),
})
Three habits keep this loop healthy. Put a hard cap on steps, as the range(5) does, so a confused model cannot spin forever and spend your credit. Parse arguments inside a try block, because any language model can occasionally emit arguments that are not valid JSON. And return errors as tool results instead of raising, which gives the model a chance to correct itself on the next turn.
Streaming works with tool calls too, which matters when you want a user interface to show progress while the agent works. The call arrives as tool_calls deltas that you stitch together by index before running the function.
Keeping state and fixing common errors
The API does not remember earlier calls, so an agent has to carry its own memory. In Python that is a list you append to: the system message first, then each user message, assistant reply and tool result in order. Pass the whole list every time. This is also why long-running agents get more expensive per step. Every step resends everything before it, and you pay $0.15 per 1M input tokens for that history. When the list grows large, summarise the oldest part and keep the recent steps as they are. The context window of 100,000 tokens is the hard ceiling for prompt plus completion.
When something fails, the cause is usually one of a few things. An AuthenticationError means the key is missing, mistyped, or still has quotes or whitespace around it from a copy and paste. A NotFoundError usually means the base URL lacks /v1 or the model name is wrong. A RateLimitError is the 429 case covered above. A BadRequestError can come from a body over the 8 MB limit or from malformed message objects, for example a tool message without its tool_call_id.
Failed or refused requests are not charged, so debugging does not eat your balance. If you need help with a specific failure, quote the X-Request-Id value when you write to the support page. For the rates behind the token counts in your logs, see the pricing page.
JSON mode and reading usage headers
When an agent step must produce structured data, enable JSON mode with response_format. Also say in the prompt that you want JSON and describe the keys, since the setting constrains the format but not your schema.
r = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "Reply with a JSON object with keys 'title' and 'tags' (list of strings)."},
{"role": "user", "content": "Classify: a guide to caching API responses."},
],
response_format={"type": "json_object"},
temperature=0,
)
data = json.loads(r.choices[0].message.content)
To read response headers such as X-Request-Id and X-Balance-USD, use the SDK's raw response wrapper, then parse the body as usual:
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "ping"}],
max_tokens=5,
)
print(raw.headers.get("X-Request-Id"), raw.headers.get("X-Balance-USD"))
completion = raw.parse()
Logging the request ID next to each agent step makes support questions much easier, and watching the balance header lets a long-running job stop itself before credit runs out. Sampling options such as temperature, top_p, stop, seed and the penalties are passed through, so use seed with a low temperature when you want repeatable test runs. The pricing page has the rates if you want to turn those token counts into dollars.
More guides
Questions and answers
Which Python package do I need?
The official openai package. Set base_url to https://api.hermesapi.cc/v1, pass your key as api_key, and use the model ID uncensored.
Does tool calling work?
Yes. Send tools and tool_choice, read tool_calls from the assistant message, and return results as messages with role tool. Streamed tool_calls are supported as well.
How many requests can I run in parallel?
A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 concurrent and 60 per minute. Extra requests get HTTP 429.
Can I get embeddings or images from the same client?
No. The service is text only. It offers chat completions and a models list, with no embeddings, image, audio or video endpoints.
Are my prompts used for training?
No. Prompts are not used for training.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.