Route Standard OpenAI Requests to Your Local Ollama Server

FreeKeyAPIOpenAI · Updated 2026-11-24 · 12 min read

Computer monitor showing code for the Rust proxy server
The Rust proxy server runs efficiently on standard hardware.

Running large language models locally has become a practical alternative to cloud subscriptions, but most developer tools still expect the familiar OpenAI API structure. By intercepting those standard requests and redirecting them to a local instance, you can keep your existing codebase intact while gaining complete control over your data and inference costs. This guide walks you through creating a lightweight proxy server in Rust using the Axum framework to bridge the gap between proprietary ecosystems and open-source flexibility.

This proxy acts as a drop-in replacement, translating incoming HTTP calls into the format your local Ollama instance understands. You will set up streaming support, handle connection pooling, and deploy the solution using Docker Compose for reliable operation. The resulting architecture allows any application that speaks the OpenAI protocol to communicate with your local hardware, particularly useful for developers who want to experiment with open-weight models without managing complex API keys or paying per-token fees.

The FreeKeyAPIOpenAI service is not affiliated with OpenAI, and while this proxy focuses on local inference, it shares the same goal of providing accessible AI interfaces. You can use this setup alongside other services like the free keyless API or explore how ChatGPT subscription can be used as a free API. This approach is particularly valuable for those who want to understand the mechanics of API compatibility, similar to what makes an API truly portable, ensuring that your tools remain versatile regardless of the underlying model provider.

Frequently asked questions

What is an API proxy in this context?

An API proxy sits between your client application and the backend model server. It receives standard requests formatted for one service and translates them into the specific protocol required by another. In this case, it converts OpenAI-style JSON payloads into Ollama-compatible requests, allowing seamless integration without code changes.

How does Rust compare to Python for this proxy?

Rust offers superior performance and lower memory overhead compared to Python, making it ideal for high-throughput proxying. While Python scripts are easier to write for quick prototypes, Rust provides robust concurrency and faster response times, which is crucial when handling streaming data and multiple concurrent connections efficiently.

Which is better: Axum or Actix-web for streaming?

Axum is generally preferred for its ergonomic integration with Tokio and its built-in support for streaming responses via SSE. It simplifies the code required to handle chunked data and maintains a cleaner abstraction layer. Actix-web is also capable but requires more manual configuration for similar streaming scenarios.

How do you handle connection pooling for Ollama?

Connection pooling reuses existing TCP connections to the Ollama backend instead of establishing new ones for every request. This reduces latency and overhead. You should configure the reqwest client pool size based on your expected concurrency, ensuring you do not overwhelm the local model server while maximizing throughput.

Does the proxy support streaming responses?

Yes, the proxy can forward Server-Sent Events (SSE) from the backend to the client in real-time. This allows for immediate display of generated text, mimicking the behavior of cloud APIs. The proxy buffers chunks briefly if necessary but generally passes data through with minimal delay.

What is the difference between this and a standard gateway?

A standard gateway often routes traffic to multiple backends or handles authentication and rate limiting. This proxy is a direct translator focused on protocol compatibility. It does not add complex routing logic but ensures that the specific JSON structures and headers of the OpenAI API are correctly mapped to Ollama's expectations.

How does this affect privacy compared to cloud APIs?

Routing requests locally keeps your data within your own network or device. No prompts or generated responses are sent to third-party servers. This is critical for sensitive applications where data residency is a concern. The proxy ensures that only your local hardware processes the inference, eliminating external tracking.

Is this solution truly free of API costs?

Yes, aside from the electricity cost of running your local hardware, there are no per-token or subscription fees. You pay for the hardware once and run as many requests as your system can handle. This makes it economically viable for high-volume usage that would otherwise become expensive on cloud platforms.

Step by step

  1. Install Rust and Cargo — Install the Rust toolchain and create a new project directory. Add dependencies for Axum, reqwest, serde, and tokio to your Cargo.toml file to set up the necessary libraries for building the proxy server.
  2. Configure Axum Router — Define the main application routes, mapping /v1/chat/completions to your handler function. Ensure that the handler accepts JSON payloads and returns responses in the correct format, mimicking the standard OpenAI API structure.
  3. Implement Translation Logic — Write functions to translate OpenAI JSON payloads into Ollama-compatible requests. Map fields like messages, model, and parameters correctly. Handle edge cases and ensure that all required fields are present in the transformed payload.
  4. Deploy with Docker Compose — Create a Dockerfile and docker-compose.yml file. Build the Docker image and start the services. Verify that the proxy is running and responding to requests by sending a test request using curl or Postman.

Architecture Overview

The core architecture relies on a simple request-response cycle where the proxy intercepts HTTP POST requests destined for the standard OpenAI endpoints. These requests typically target the chat completions endpoint with a JSON payload containing messages, model names, and generation parameters. The proxy parses this JSON, extracts the relevant fields, and restructures them into the format that Ollama expects.

Ollama uses a slightly different API structure, often requiring specific endpoints for chat and completion operations. The proxy maps the OpenAI model identifier to the local Ollama model name, ensuring that the correct weights are loaded. It also handles parameter translation, such as converting temperature and top-p values to match Ollama's expectations. This mapping layer is the key to achieving drop-in compatibility without modifying client code.

Request Translation Logic

The translation logic converts the OpenAI messages array into Ollama's conversation format. It maps system, user, and assistant roles correctly, ensuring that the context window is utilized efficiently. Parameters like max_tokens and stop sequences are also adjusted to match Ollama's specific constraints, preventing errors during inference.

Response Formatting

Responses from Ollama are formatted to match the OpenAI JSON structure. This includes wrapping the generated text in a choices array with a finish_reason field. Streaming chunks are prefixed with data: and followed by a newline, ensuring compatibility with standard SSE parsers. This precise formatting allows tools like curl, Postman, or custom scripts to work without modification.

import requests

# Example of a standard OpenAI-style request
response = requests.post(
    "http://localhost:8080/v1/chat/completions",
    json={
        "model": "llama3",
        "messages": [{"role": "user", "content": "Hello"}],
        "stream": True
    }
)

for line in response.iter_lines():
    if line:
        print(line.decode('utf-8'))

Setting Up the Rust Environment

Begin by installing Rust and Cargo, the standard package manager. Create a new project using cargo new ollama-proxy. Add the necessary dependencies to your Cargo.toml file, including axum for the web framework, reqwest for making HTTP requests to Ollama, serde for JSON serialization, and tokio for asynchronous runtime. These libraries provide a robust foundation for building a high-performance proxy.

Configure the project to support asynchronous I/O, which is essential for handling multiple concurrent requests efficiently. Axum integrates seamlessly with Tokio, allowing you to write clean, non-blocking code. Define the main application structure, setting up routes that match the standard OpenAI endpoints, such as /v1/chat/completions. This ensures that any client expecting the standard API will find the expected routes available.

Dependency Management

Carefully select dependency versions to avoid conflicts. Axum and reqwest have specific compatibility requirements. Using the latest stable versions ensures you benefit from performance improvements and bug fixes. Pinning versions in Cargo.lock guarantees consistent builds across different environments, which is crucial for reproducibility.

Project Structure

Organize your code into modules for routing, translation, and error handling. This separation of concerns makes the code easier to maintain and test. The routing module handles incoming requests, the translation module converts payloads, and the error handling module ensures that malformed requests return appropriate HTTP status codes.

[dependencies]
axum = "0.7"
reqwest = { version = "0.11", features = ["json", "stream"] }
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
Diagram of the proxy architecture
Requests flow through the proxy to the local Ollama instance.

Implementing the Proxy Server

The core logic involves creating an Axum handler that receives the incoming request. This handler parses the JSON body, extracts the messages and parameters, and constructs a new request payload for Ollama. The proxy then sends this new payload to the Ollama backend using reqwest. If the client requested streaming, the proxy sets up a stream listener to read chunks from the backend and forward them to the client.

Error handling is critical in a proxy. If the Ollama backend is down or returns an error, the proxy should relay that error to the client in a format they understand. This might involve converting Ollama's error JSON into an OpenAI-style error response. Consistent error formatting ensures that client applications can handle failures gracefully, whether the error originates from the proxy or the backend.

Handler Implementation

The handler function takes the request body as input and returns an Axum response. It uses serde to deserialize the JSON into a struct, transforms the data, and then serializes it back for the backend request. This process is straightforward but requires attention to detail to ensure all fields are correctly mapped.

Streaming Logic

For streaming, use reqwest's streaming capabilities to read the response body in chunks. Each chunk is then sent to the client with the appropriate SSE prefix. The loop continues until the stream ends, at which point a [DONE] message is sent to signal completion. This mimics the behavior of cloud APIs exactly.

async fn chat_completions(
    Json(payload): Json<OpenAIChatRequest>,
) -> impl IntoResponse {
    let ollama_payload = translate_to_ollama(payload);
    let response = reqwest::Client::new()
        .post("http://localhost:11434/v1/chat/completions")
        .json(&ollama_payload)
        .send()
        .await
        .unwrap();
    
    // Forward response...
}

Handling SSE and Streaming

Server-Sent Events (SSE) are a standard protocol for sending real-time data from server to client. In the context of LLMs, this allows for immediate display of generated text, improving the user experience significantly. The proxy must parse the SSE stream from Ollama and reformat it to match the OpenAI SSE format, which includes specific data prefixes and structure.

The implementation involves reading the response body line by line. Each line is checked for the data: prefix and then forwarded to the client. If the line indicates the end of the stream, a final data: [DONE] message is sent to signal completion. This ensures that clients expecting the standard OpenAI streaming behavior will work correctly without any modifications. It is crucial to handle edge cases, such as empty lines or malformed data, to prevent client errors.

SSE Protocol Details

The OpenAI SSE format requires each data line to start with data: followed by a JSON object. The proxy must ensure that this format is strictly maintained. Any deviation can cause client-side parsers to fail. Testing with standard tools like curl or Postman helps verify that the format is correct.

Error Propagation

If the backend stream ends prematurely or returns an error, the proxy should forward this information to the client. This might involve sending a JSON error object in the SSE format. Proper error propagation ensures that clients can handle unexpected disconnections or backend failures gracefully.

while let Some(chunk) = response.chunk().await {
    let chunk_str = String::from_utf8_lossy(&chunk);
    for line in chunk_str.lines() {
        if line.starts_with("data: ") {
            // Forward to client
        }
    }
}
Developer typing code for the proxy
Developers can use standard tools to interact with the proxy.

Connection Pooling and Performance

Connection pooling reuses existing TCP connections to the Ollama backend, reducing the overhead of establishing new connections for each request. This is particularly important for high-throughput scenarios where many requests are sent in quick succession. By reusing connections, you reduce latency and conserve system resources, leading to better overall performance.

Configuring the pool size in reqwest is straightforward. You can set the max_idle_per_host and other pool parameters to optimize for your specific workload. A larger pool size allows for more concurrent requests but consumes more memory. Balance these factors based on your hardware capabilities and expected traffic patterns. Monitoring connection usage helps fine-tune these settings over time.

Pool Configuration

Use reqwest's builder to configure the pool size. Set max_idle_per_host to a value that matches your expected concurrency. Too small a pool may lead to connection delays, while too large a pool may waste memory. Benchmarking with your specific workload helps determine the optimal size.

Latency Optimization

Minimize the time spent in the proxy by avoiding unnecessary data copying or serialization. Use efficient data structures and avoid blocking calls. Profiling the proxy with tools like flame graphs can help identify bottlenecks and guide optimization efforts.

let client = reqwest::Client::builder()
    .pool_max_idle_per_host(10)
    .build()
    .unwrap();

Docker Compose Deployment

Deploying the proxy using Docker Compose simplifies management and ensures consistency across environments. Create a Dockerfile for your Rust proxy, using a multi-stage build to minimize the final image size. The first stage compiles the code, and the second stage copies only the binary into a lightweight base image like Alpine Linux.

Define a docker-compose.yml file that includes services for the proxy and Ollama. This allows you to start both services with a single command. Docker Compose also handles networking, making it easy for the proxy to communicate with Ollama using service names. This setup is ideal for development and small-scale production deployments.

Dockerfile Best Practices

Use a multi-stage build to reduce image size. Install only necessary dependencies in the final stage. This results in a smaller, faster-to-deploy image. Pin specific versions of dependencies to ensure reproducibility.

Compose Configuration

Define services in docker-compose.yml, specifying ports, environment variables, and dependencies. Use depends_on to ensure Ollama starts before the proxy. This prevents connection errors during startup.

version: '3.8'
services:
  proxy:
    build: .
    ports:
      - "8080:8080"
    environment:
      - OLLAMA_BASE_URL=http://ollama:11434
  ollama:
    image: ollama/ollama:latest
Server infrastructure for the proxy
The proxy can be deployed in various environments.

Testing and Validation

Thorough testing ensures that the proxy behaves correctly under various conditions. Start with simple requests to verify that the basic translation logic works. Send a standard OpenAI chat request and check that the response matches the expected format. Use tools like curl or Postman to inspect the raw HTTP responses.

Test streaming functionality by sending requests with the stream parameter set to true. Verify that the response is sent in chunks and that the [DONE] message is received at the end. Check that the data format matches the OpenAI SSE specification. Any deviation can cause client-side errors, so precise formatting is essential.

Unit Testing

Write unit tests for the translation logic to ensure that JSON payloads are correctly converted. Test edge cases, such as empty messages or unusual parameter values. This ensures that the proxy handles malformed input gracefully.

Integration Testing

Test the end-to-end flow by sending requests from a client application through the proxy to Ollama. Verify that the response is correct and that streaming works as expected. This validates the entire pipeline, from request to response.

curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "llama3", "messages": [{"role": "user", "content": "Hi"}], "stream": true}'

Monitoring and Maintenance

Monitoring the proxy provides insights into its performance and health. Log key metrics such as request count, latency, error rate, and token usage. These metrics help you identify trends and potential issues before they become critical. Integrate with monitoring tools like Prometheus or Grafana for real-time dashboards and alerting.

Regular maintenance ensures the proxy remains stable and efficient. Update dependencies to benefit from bug fixes and performance improvements. Monitor disk space and memory usage to prevent resource exhaustion. Regularly review logs to identify patterns that may indicate problems, such as repeated errors or unusual traffic spikes.

Log Analysis

Parse logs to extract metrics. Use tools like grep or awk to filter and aggregate data. Look for patterns in error messages to identify common failure modes. Automated log analysis can provide early warnings of potential issues.

Alerting Strategies

Set up alerts for critical events, such as high error rates or low disk space. Use email, Slack, or other notification channels to ensure that issues are addressed promptly. Proactive alerting helps maintain service reliability.

# Example log parsing
grep "error" /var/log/proxy.log | wc -l
Planning the proxy architecture
Planning ensures smooth integration with existing tools.
Try the free API

Test our keyless endpoint right now—no credit card, no signup required.

Read also