Last reviewed: 2026-08-10
Direct answer
Run the OpenAI Agents SDK through CometAPI by giving the SDK an AsyncOpenAI client whose key and base URL come from server-side environment variables. Then select Chat Completions explicitly, name a current CometAPI model explicitly, and make an explicit tracing decision before the first agent run.
The CometAPI quick-start documentation
specifies an HTTPS base host of api.cometapi.com, a /v1 base path, environment-based key handling, and a current model ID chosen from its model catalog. The OpenAI Agents SDK Models guide
explains that the SDK supports both Responses and Chat Completions models and defaults to the Responses path. The OpenAI Agents SDK Configuration guide
documents custom AsyncOpenAI clients, set_default_openai_api, and tracing controls.
That makes the safe minimum configuration explicit: CometAPI receives the model request through Chat Completions, while the SDK does not try to export traces with the CometAPI credential.
import asyncio
import json
import logging
import os
import time
from urllib.parse import urlparse
from agents import (
Agent,
Runner,
set_default_openai_api,
set_default_openai_client,
set_tracing_disabled,
)
from openai import AsyncOpenAI
logger = logging.getLogger('cometapi_agent')
def require_env(name: str) -> str:
value = os.getenv(name)
if not value:
raise RuntimeError(f'Missing required environment variable: {name}')
return value
async def run_agent() -> int:
started = time.monotonic()
fields = {
'event': 'cometapi_agent_run',
'outcome': 'started',
'api_surface': 'chat_completions',
'base_url_host': 'unverified',
'model': 'unverified',
}
try:
base_url = require_env('COMETAPI_BASE_URL')
parsed = urlparse(base_url)
fields['base_url_host'] = parsed.hostname or 'invalid'
if (
parsed.scheme != 'https'
or parsed.hostname != 'api.cometapi.com'
or parsed.path.rstrip('/') != '/v1'
):
raise RuntimeError(
'COMETAPI_BASE_URL does not match the documented HTTPS host and /v1 path'
)
model = require_env('COMETAPI_MODEL')
fields['model'] = model
client = AsyncOpenAI(
api_key=require_env('COMETAPI_KEY'),
base_url=base_url,
)
set_default_openai_client(client, use_for_tracing=False)
set_default_openai_api('chat_completions')
set_tracing_disabled(True)
agent = Agent(
name='Concise assistant',
instructions='Answer in one short sentence and do not call tools.',
model=model,
)
result = await Runner.run(
agent,
'Name one practical reason to test an API integration with a fixed prompt.',
)
except Exception as exc:
status_code = getattr(exc, 'status_code', None)
fields.update(
{
'outcome': 'error',
'duration_ms': round((time.monotonic() - started) * 1000),
'error_type': type(exc).__name__,
'http_status': status_code if isinstance(status_code, int) else None,
}
)
logger.error(json.dumps(fields, sort_keys=True))
return 1
fields.update(
{
'outcome': 'success',
'duration_ms': round((time.monotonic() - started) * 1000),
'output_present': bool(result.final_output),
}
)
logger.info(json.dumps(fields, sort_keys=True))
print(result.final_output)
return 0
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(message)s')
raise SystemExit(asyncio.run(run_agent()))
Set COMETAPI_BASE_URL, COMETAPI_MODEL, and COMETAPI_KEY in the process environment before running the script. Use the documented base URL, choose a current Chat Completions model ID, and load the key from a protected server-side secret store or local environment. Do not put the key in the source file, command history, logs, screenshots, or a repository.
Who this is for
This guide is for Python developers who already have a CometAPI account and want a small Agents SDK integration with one agent and a plain text result. It is also useful for operators who need an observable smoke test before adding tools, handoffs, structured output, or streaming.
The example deliberately selects Chat Completions. If the model or feature you need requires Responses, review the Chat Completions and Responses comparison before changing the API surface.
Key takeaways
- Configure the custom client before the first
Runner.runcall. The SDK resolves its default client lazily, so startup is the clearest place to establish the boundary. - Keep the base URL, model ID, and credential outside the code. Validate the scheme, host, and base path without logging the complete configuration.
- Select
chat_completionsexplicitly. The Agents SDK otherwise defaults to Responses, which may produce a route or feature mismatch with an OpenAI-compatible provider path. - Set
use_for_tracing=Falseand disable tracing for this minimal setup. Model traffic and trace export are separate concerns. - Log metadata, not payloads. A model ID, API surface, duration, status, and exception class are normally enough for first-pass triage.
- Start with text only. Add tools or structured output only after verifying that the selected model and provider path support them.
Sources checked
The following public sources were refetched for this guide:
- CometAPI quick start establishes the base URL components, server-side key handling, Python client pattern, and requirement to choose a current model ID.
- OpenAI Agents SDK Models establishes the Responses and Chat Completions model paths, the default Responses behavior, non-OpenAI provider considerations, and feature-compatibility warnings.
- OpenAI Agents SDK Configuration
establishes custom
AsyncOpenAIconfiguration,set_default_openai_client,set_default_openai_api, tracing separation, and sensitive-log controls.
Together, these sources cover the gateway contract, SDK model surface, client setup, and tracing boundary. No package-version claim is required for the implementation; pin and record the dependency version that your own deployment tests.
Contract details to verify
Treat the integration as three contracts rather than one opaque agent call.
First, verify the gateway contract. COMETAPI_BASE_URL must use HTTPS, the documented host, and the /v1 base path. COMETAPI_MODEL must be a current model ID that is appropriate for Chat Completions. COMETAPI_KEY must exist in the server-side environment, but its value must never enter a log record.
Second, verify the SDK contract. Call set_default_openai_client and set_default_openai_api before any agent run. The model set on Agent should be the same model shown in the operator log. The initial prompt should request plain text and avoid tools so the first test measures the client and model path, not optional capabilities.
Third, verify the observability contract. The sample records these sanitized fields:
eventoutcomeapi_surfacebase_url_hostmodelduration_mserror_typehttp_statusoutput_present
Do not record the key, complete request headers, prompt text, model output, tool arguments, raw error bodies, or environment dumps. The OpenAI configuration source notes that diagnostic settings can expose model or tool data. Keep the SDK’s model-data and tool-data logging protections enabled, and do not enable verbose logging casually in a shared environment.
Happy path workflow
- Confirm the model ID against the current CometAPI catalog and confirm that it is intended for Chat Completions.
- Load the three required environment variables through the deployment system. Check presence, not values.
- Run the script once with the fixed, non-sensitive prompt.
- Require a zero exit status,
outcomeequal tosuccess, the expected model and API surface, andoutput_presentequal totrue. - Read the returned sentence separately from the structured operator log. Do not copy it into telemetry by default.
- Repeat the same fixed probe after dependency, model, routing, or environment changes so results remain comparable.
Error path workflow
- If preflight fails locally, correct the missing or invalid environment setting before making another request.
- If the request reaches the SDK and fails, retain only the exception class, numeric HTTP status when available, selected model, API surface, and duration.
- Check tracing configuration first when an authentication error appears outside the expected model call. The SDK documentation identifies tracing as a separate client path; this example disables it.
- Check the API surface when the status or error indicates a missing route. A default Responses request sent to a Chat Completions-only path can produce a route-style failure.
- Recheck the current model ID when the gateway rejects the selected model. Do not substitute a guessed alias during incident handling.
- Reduce the request to plain text when a tool or structured-output feature fails. Reintroduce one capability at a time after checking support.
- Do not place configuration errors, unsupported features, or deterministic client errors into an unbounded retry loop.
Failure modes
The SDK sends a Responses request. The Agents SDK uses Responses by default. If the selected provider path expects Chat Completions, the result can be a missing-route error or a similar compatibility failure. Keep set_default_openai_api('chat_completions') before the first call for this article’s contract.
Tracing uses the wrong credential boundary. Setting a custom model client does not automatically make that credential appropriate for OpenAI trace export. A tracing authentication failure can occur even when model routing is otherwise correct. The example separates the model client from tracing and disables trace export.
The model ID and API surface do not match. CometAPI’s quick start tells readers to choose a current model ID and notes that some coding or reasoning models may require Responses. A valid catalog entry is not automatically valid for every endpoint family.
A Responses-only feature reaches Chat Completions. The Models guide identifies features that are specific to Responses and warns that providers can differ in structured-output, multimodal, and tool support. A plain text smoke test can succeed while a later tool or schema request fails. Treat each added capability as a separate contract test.
The process configures the client too late. The SDK resolves its default client when it first needs one. If an earlier code path triggers a model call, later global configuration may not describe the client that already ran. Configure once during startup, before concurrent work begins.
Logs become a second data leak. Raw exception text, request headers, prompts, tool arguments, and outputs can contain sensitive material. The sample intentionally records only bounded metadata and suppresses raw exception messages from the normal operator log.
A placeholder model reaches production. The source documentation uses a generic model placeholder because catalog entries change. Make missing or placeholder model configuration a deployment failure rather than silently choosing a different model.
For a broader request-level validation sequence, use the CometAPI Chat Completions smoke-test guide .
FAQ
Do I need a separate OpenAI credential for this example?
The model call shown here uses the CometAPI credential through the custom client. Tracing is disabled, so the example does not export traces through the SDK’s default OpenAI tracing path. If you later enable that exporter, configure its credential separately according to the SDK configuration guide rather than reusing the model-routing credential by assumption.
Can I omit set_default_openai_api?
Only if you intentionally want the default Responses path and have verified that the selected CometAPI model and endpoint support it. This tutorial promises a Chat Completions integration, so leaving the API shape implicit would weaken the contract.
Which model ID should I put in COMETAPI_MODEL?
Use a current CometAPI catalog ID that supports the Chat Completions workflow you are testing. The supplied evidence does not justify hard-coding one universal model ID. Keep the value configurable and revalidate it before deployments that change models.
Can I enable tools immediately?
Start without tools. Once the text-only call passes, check the selected model and provider path for the exact tool behavior you need, add one tool, and test both its success and rejection paths. Do the same for structured output and multimodal input.
Should the application retry every failure?
No. Missing environment values, an incorrect base path, a wrong API surface, an unsupported feature, and an invalid model selection require configuration or code changes. Retry only failures your policy classifies as transient, with explicit limits and observable outcomes.
Is printing final_output the same as logging it?
No. The sample prints the result for an interactive smoke test but keeps it out of the structured operator log. In an application, send the result only to its intended consumer and decide separately whether any retention is justified.
Reader next step
Create the script in a clean Python environment, load the documented base URL, a current Chat Completions model ID, and the CometAPI credential through protected environment configuration, then run the fixed happy-path probe. Before committing configuration, review how to keep CometAPI keys out of repositories .
Once the plain text run succeeds and the sanitized log is usable, test one intentional error, confirm that no payload or credential appears in logs, and only then add tools, structured output, streaming, or a Responses-based model path.