Skip to main content

Integrate Morpheus Inference API with OpenAI Python SDK

Learn how to integrate the Morpheus Inference API with OpenAI’s official Python SDK. This guide covers basic chat completions, streaming responses, tool calling, and async operations.

Overview

The Morpheus Inference API is fully OpenAI-compatible. Simply point the official OpenAI Python SDK to the Morpheus base URL and start building.
Base URL: https://api.mor.org/api/v1

Prerequisites

Before you begin, ensure you have:
  • Python 3.8+ installed on your system
  • A Morpheus API key from app.mor.org
  • Basic knowledge of Python and async/await patterns
  • Familiarity with REST APIs
1

Create a Morpheus API Key

Visit app.mor.org and sign in to create your API key.
  1. Navigate to the API Keys section
  2. Click “Create API Key” and provide a name
  3. Copy your API key immediately (it won’t be shown again)
Store your API key securely. Never commit it to version control or expose it in publicly accessible code.
2

Install the OpenAI Python SDK

Install the official OpenAI Python library:
Verify installation by running pip show openai to see the installed version.
3

Configure Environment Variables

Create a .env file in your project root or set environment variables:
.env
For better security, use environment variables instead of hardcoding API keys:
Never commit your API key to version control. Add .env to your .gitignore file.

Basic Integration

Setting Up the Client

Configure the OpenAI client to use the Morpheus Inference API by setting a custom base_url:
setup.py
The only difference from using the standard OpenAI client is the base_url parameter. All other functionality remains the same.

Available Models

Query the available models using the Morpheus API:
list_models.py
Popular models available through Morpheus:
  • llama-3.3-70b:web - Meta’s Llama 3.3 with web search capabilities
  • llama-3.3-70b - Meta’s Llama 3.3 base model
  • qwen3-235b:web - Qwen 3 with web search capabilities
  • qwen3-235b - Qwen 3 base model
Model availability may vary based on provider availability in the Morpheus marketplace. The API automatically routes to the highest-rated provider for your selected model. The :web suffix indicates models optimized for web browsing tasks.

Text Generation

Basic Chat Completions

Use the chat.completions.create() method for standard, non-streaming text generation:
basic_chat.py

Streaming Responses

For real-time output, enable streaming to receive tokens as they’re generated:
streaming_chat.py
Streaming provides a better user experience by showing output immediately rather than waiting for the entire response.

Asynchronous Operations

Async Client Setup

Use the AsyncOpenAI client for concurrent operations and async/await patterns:
async_client.py

Async Streaming

Combine async operations with streaming for efficient, concurrent request handling:
async_streaming.py
Async operations are ideal for handling multiple concurrent requests efficiently, making your application more responsive.

Tool Calling

Enable your AI models to execute functions and interact with external systems through tool calling.

Defining Tools

Define tools using JSON schemas to specify available functions:
tools_definition.py

Using Tools with Chat Completions

Integrate tools with chat completions to enable function calling:
tool_calling.py

Complete Tool Calling Example

Here’s a complete example with error handling and streaming:
complete_tool_example.py
Always provide clear, detailed descriptions for your tools and parameters. This helps the model understand when and how to use each function.

Advanced Configuration

Custom Timeouts and Retries

Configure timeouts and retry behavior for production applications:
config.py

Token Usage Tracking

Monitor token consumption and costs:
token_tracking.py

Error Handling

Implement robust error handling for production deployments:
error_handling.py

Context Manager Pattern

Use context managers for automatic resource cleanup:
context_manager.py

Troubleshooting

Cause: Network issues, firewall restrictions, or server unavailability.Solution:
  • Check your internet connection
  • Verify the base URL is correct: https://api.mor.org/api/v1
  • Increase timeout values for slower connections
  • Ensure your firewall allows HTTPS connections
Cause: Invalid or missing API key.Solution:
  • Verify your API key is correct
  • Ensure the API key is properly loaded from environment variables
  • Check that the key hasn’t been deleted from your Morpheus account
Cause: Incorrect tool schema, missing function implementations, or model limitations.Solution:
  • Verify tool schemas match the JSON Schema specification
  • Ensure all required parameters are marked correctly
  • Provide detailed descriptions for tools and parameters
  • Test with different models (llama-3.3-70b often performs better)
Cause: Network interruption, timeout, or model completion.Solution:
  • Check the finish_reason in the response
  • Implement error handling for streams
  • Use appropriate timeout values
Cause: Requested model is not available or misspelled.Solution:
  • List available models first
  • Use exact model names including suffixes (:web)
  • Check model availability in the marketplace
Cause: Incorrect async/await usage or event loop issues.Solution:
  • Use AsyncOpenAI instead of OpenAI
  • Properly await all async operations
  • Run async functions with asyncio.run()

Best Practices

Use environment variables

Always store API keys in environment variables, never hardcode them in your source code.

Implement retry logic

Use the built-in max_retries parameter or implement custom retry logic for production applications.

Monitor token usage

Track token consumption to understand your application’s resource needs and optimize prompts.

Handle errors gracefully

Implement comprehensive error handling to provide good user experiences when API calls fail.

Use async for concurrency

Leverage AsyncOpenAI for applications that need to handle multiple concurrent requests.

Validate tool schemas

Test tool calling implementations thoroughly and provide clear descriptions for reliable function execution.

Example Applications

Command-Line Chat Application

A simple command-line chat interface:
cli_chat.py

Batch Processing Script

Process multiple prompts efficiently:
batch_processor.py

Next Steps

Explore Models

Browse all available models in the Morpheus marketplace and their capabilities.

OpenAI Python Docs

Explore the complete OpenAI Python SDK documentation for advanced features.

API Reference

Complete API documentation for all Morpheus Gateway endpoints and parameters.

Vercel AI SDK

Learn how to integrate Morpheus with Vercel’s AI SDK for frontend applications.

Summary

You’ve successfully integrated the Morpheus Inference API with OpenAI’s Python SDK! Key takeaways:
OpenAI Compatibility: Morpheus works seamlessly with the official OpenAI Python SDK by using a custom base_url
Flexible Deployment: Use synchronous or asynchronous clients based on your application needs
Streaming Support: Real-time streaming responses work identically to OpenAI’s API
Tool Calling: Define and execute custom functions with JSON schema-based tool definitions
The combination of Morpheus’s decentralized AI inference and the OpenAI Python SDK’s robust features enables you to build powerful AI applications without infrastructure costs or vendor lock-in.