Skip to main content

What This Example Shows

  • Using the Swarms API as a drop-in OpenAI replacement with zero code changes beyond base_url and api_key
  • Non-streaming and streaming completions
  • Multi-turn conversations with conversation history
  • Sending images (multimodal / vision)
  • Multi-loop agent reasoning via max_loops
  • Discovering available models with client.models.list() (GET /v1/models)
  • The Responses API with client.responses.create() (POST /v1/responses)
  • Error handling with SDK-native exception classes
  • Working examples in Python, TypeScript, Go, and Rust
This endpoint uses the standard OpenAI request/response schema. Any existing OpenAI SDK code works by changing two config values. See the API Reference for the full schema.

Prerequisites

Set your API key as an environment variable:

1. Basic Chat Completion

The simplest usage — send a message, get a response.

Expected Output


2. Streaming Responses

Stream the response as it’s generated for a better user experience on longer outputs.

3. Multi-Turn Conversation (Chatbot)

Build a conversational chatbot by accumulating messages across turns.

4. Vision (Image Input)

Send an image alongside your prompt using the multimodal content format. Each image costs $0.25 per request, and images in earlier turns are attached and billed again whenever you resend the history.

5. Multi-Loop Reasoning

Use max_loops to let the agent iterate on its own output — useful for complex analysis, self-correction, or multi-step reasoning. Pass it via extra_body in the OpenAI SDK.
max_loops is a Swarms extension — not part of the OpenAI spec. Default is 1 (single pass). The agent runs the specified number of reasoning loops, refining its output each iteration.

6. Model Discovery

The SDK’s built-in model listing works too — GET /v1/models returns every model available to your account (filtered by subscription tier) in the standard OpenAI list format. Each entry also carries a pricing object with the model’s price per 1M input and output tokens (USD, 15% service fee included) and its price_source.
Prefer the native Swarms shape with a count? Use GET /v1/models/available, which returns one object per model with its model_name and price, or GET /v1/models/pricing?model_name=<model> for a single model — see Available Models. Both list endpoints return the same tier-filtered catalog.

7. Putting It All Together — Research Assistant

A complete example that combines system prompts, multi-turn conversation, and streaming to build a simple research assistant.

8. Responses API

Code written for OpenAI’s Responses API works with the same two config values. POST /v1/responses is non-streaming and text-only; see Responses API for the supported fields.

Environment Setup

Create a .env file in your project directory:

Next Steps