Skip to content

listModels function does not work (at least not on openrouter) #167

@OpenSource03

Description

@OpenSource03

On OpenRouter, I tried following code:

import Foundation
import SwiftOpenAI

Task {
    let apiKey = "api-key"
    let service = OpenAIServiceFactory.service(
        apiKey: apiKey,
        overrideBaseURL: "https://openrouter.ai",
        proxyPath: "api",
        extraHeaders: [
            "HTTP-Referer": "<YOUR_SITE_URL>",
            "X-Title": "<YOUR_SITE_NAME>"
        ]
    )

    do {
        let models = try await service.listModels()
        print(models)
        print("Done")
    } catch {
        print("Failed to list models: \(error)")
    }
}

// Keep the program alive
RunLoop.main.run()

Apparently, it returns the following error:

Failed to list models: dataCouldNotBeReadMissingData(description: "Key \'object\' not found: No value associated with key CodingKeys(stringValue: \"object\", intValue: nil) (\"object\").codingPath: [CodingKeys(stringValue: \"data\", intValue: nil), _CodingKey(stringValue: \"Index 0\", intValue: 0)]")

This is not some sort of OpenRouter limitation, as the following Python code, for instance, properly returns the list:

import os
import requests
from openai import OpenAI

# Load your API keys from environment variables
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")

# --- OpenAI Models ---
def list_openai_models():
    client = OpenAI(
        api_key=OPENAI_API_KEY,
        base_url=OPENAI_BASE_URL
    )
    models = client.models.list()
    print("=== OpenAI Models ===")
    for model in models.data:
        print(model.id)


if __name__ == "__main__":
    if OPENAI_API_KEY:
        list_openai_models()
    else:
        print("Missing OPENAI_API_KEY")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions