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)
  • 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.

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.
Prefer a plain list of model names with a count? Use the native Swarms endpoint GET /v1/models/available instead — see Available Models. Both 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.

Environment Setup

Create a .env file in your project directory:

Next Steps

  • API Reference — full request/response schema and field documentation
  • Agent Completions — the native Swarms endpoint with tools, MCP, and multi-loop support
  • Streaming — streaming with the native Swarms agent endpoint
  • Vision — more image/multimodal examples