ballerinax/ai.genericmodelprovider Ballerina library

1.0.0

Overview

The generic model provider is an OpenAI-compatible model provider. It works with any LLM service that exposes an OpenAI-compatible Chat Completions API (/chat/completions).

Configure the service URL, API key and model name to use providers such as Groq, Together AI, Fireworks AI, xAI, Z.ai (GLM), OpenRouter, Mistral, vLLM, LM Studio and Ollama, without waiting for a dedicated connector.

Note: Only OpenAI-compatible APIs are supported. Services with a different API format (for example, the native Anthropic Messages API or the Gemini API) require their dedicated model provider.

The provider implements ai:ModelProvider, so it can be used with ai:Agent and generate of the ballerina/ai module.

How it adapts to different servers

OpenAI-compatible servers differ in small ways. Instead of requiring provider-specific settings, the provider:

  • Sends only the fields you set. It never sends fields that some servers reject (such as messages[].name, n, user or logprobs) and omits tools when there are none.
  • Sends max_tokens, and switches to max_completion_tokens if the server rejects max_tokens.
  • Forces the internal result tool in generate, and falls back to tool_choice: "auto" with an instruction if the server does not support forced tool choice. If the model does not support tools at all, generate uses JSON mode instead. If the model replies with text instead of a tool call, the JSON in the text is parsed.
  • Reads reasoning output from either reasoning_content or reasoning, removes inline <think> blocks from responses, and accepts tool call arguments as a JSON string or an object.

A fallback is used only when the server's error message states that the field or feature is unsupported, and it is remembered for the lifetime of the provider instance only after the fallback request succeeds. Each fallback is logged as a warning. To avoid the extra requests, set the matching compatibility field (for example, maxTokensField: MAX_COMPLETION_TOKENS for OpenAI reasoning models such as gpt-5).

Request cost: until the fallbacks are learned, a single generate call can send up to six billable requests: up to three structured-output strategies (forced tool choice, tool_choice: "auto", JSON mode), each of which may be retried once with the other max tokens field. chat sends at most two. Once a fallback is remembered, later calls on the same provider instance send one request. Setting the compatibility fields up front avoids the extra requests entirely.

Quickstart

Step 1: Import the module

Copy
import ballerina/ai;
import ballerinax/ai.genericmodelprovider;

Step 2: Initialize the model provider

Copy
configurable string apiKey = ?;

final ai:ModelProvider model = check new genericmodelprovider:ModelProvider(
    serviceUrl = "https://api.groq.com/openai/v1",
    modelType = "llama-3.3-70b-versatile",
    apiKey = apiKey
);

For a local server that does not require authentication, omit apiKey:

Copy
final ai:ModelProvider localModel = check new genericmodelprovider:ModelProvider(
    serviceUrl = "http://localhost:1234/v1",
    modelType = "qwen2.5-7b-instruct"
);

Step 3: Invoke chat completion

Copy
ai:ChatMessage[] chatMessages = [{role: "user", content: "hi"}];
ai:ChatAssistantMessage response = check model->chat(chatMessages, tools = []);

chatMessages.push(response);

Step 4: Generate structured output

Copy
type Summary record {|
    string title;
    string[] keyPoints;
|};

string text = "Ballerina is an open-source programming language for writing network-aware integrations.";
Summary summary = check model->generate(`Summarize the following text: ${text}`);

Step 5: Use with an agent

Copy
final ai:Agent agent = check new (
    systemPrompt = {role: "Assistant", instructions: "You are a helpful assistant."},
    model = model,
    tools = []
);

Authentication

The API key is sent as Authorization: Bearer <apiKey>. Omit apiKey for local servers that do not require authentication. Azure OpenAI is not covered by this provider; use the dedicated ballerinax/ai.azure provider.

Common service URLs

ServiceserviceUrlAPI key
Groqhttps://api.groq.com/openai/v1Required
Together AIhttps://api.together.ai/v1Required
Fireworks AIhttps://api.fireworks.ai/inference/v1Required
xAIhttps://api.x.ai/v1Required
Z.ai (GLM)https://api.z.ai/api/paas/v4Required
OpenRouterhttps://openrouter.ai/api/v1Required
Mistralhttps://api.mistral.ai/v1Required
vLLMhttp://localhost:8000/v1Only if the server is started with an API key
LM Studiohttp://localhost:1234/v1Not required by default
Ollamahttp://localhost:11434/v1Not required

Self-hosted servers (Ollama, vLLM, LM Studio): set compatibility = {structuredOutputMode: genericmodelprovider:JSON_SCHEMA}. These servers enforce the JSON schema while generating, which makes generate reliable even with small models. Ollama accepts but ignores a forced tool_choice, so the default tool-call strategy depends on the model choosing to call the tool with correct arguments, which small models often fail to do.

Use the serviceUrl up to, but excluding, /chat/completions. The model name is passed to the service as-is (e.g. meta-llama/Llama-3.3-70B-Instruct-Turbo for Together AI).

Compatibility configuration

All settings are optional. Use them only when a server needs a request shape that the provider cannot detect automatically, or to skip the first failed request when you already know what the server supports.

FieldDefaultDescription
maxTokensFieldAuto-detectedMAX_TOKENS or MAX_COMPLETION_TOKENS
toolChoiceModeAuto-detectedHow generate requests the result tool: FORCED, AUTO, or NONE (omit tool_choice)
structuredOutputModeTOOL_CALLHow generate obtains structured output: TOOL_CALL, JSON_SCHEMA (response_format), or JSON_OBJECT (JSON mode with the schema in the prompt). JSON_SCHEMA does not send strict: true, so whether the schema is enforced depends on the server: self-hosted servers such as vLLM and Ollama enforce it, while on OpenAI it is only guidance. The response is always validated against the expected type. A server that does not support json_schema causes a JSON_OBJECT retry on every call, so prefer JSON_OBJECT for such servers
systemRoleSYSTEMRole used for system messages: SYSTEM or DEVELOPER
extraHeaders{}Additional headers sent with every request
extraBody{}Additional top-level request fields (e.g. provider-specific parameters)
dropParams[]Top-level request fields that must never be sent
preserveReasoningContentfalseExperimental. Send reasoning content back with assistant tool-call messages (required by some thinking models such as DeepSeek in thinking mode). The reasoning is kept in memory by the provider instance, so it works only within one process lifetime and is reliable only for a single conversation per provider instance; it is omitted after a restart or when identical tool calls from different conversations make it ambiguous

Example: passing a provider-specific parameter (Z.ai thinking mode).

Copy
final ai:ModelProvider glmModel = check new genericmodelprovider:ModelProvider(
    serviceUrl = "https://api.z.ai/api/paas/v4",
    modelType = "glm-4.6",
    apiKey = zaiApiKey,
    compatibility = {
        extraBody: {thinking: {"type": "disabled"}}
    }
);

Import

import ballerinax/ai.genericmodelprovider;Copy

Other versions

1.0.0

Metadata

Released date: 1 day ago

Version: 1.0.0

License: Apache-2.0


Security

No known vulnerabilities in libraries

Checked on 2026-11-25 via OSV.dev


Compatibility

Platform: java21

Ballerina version: 2201.12.0

GraalVM compatible: Yes


Pull count

Total: 0

Current verison: 5


Weekly downloads


Source repository


Keywords

Agent

Model

Provider

Vendor/OpenAI Compatible

Area/AI & Machine Learning

Type/Model Provider

Type/Connector

Name/Generic Model Provider

Generic

OpenAI Compatible

Groq

Together AI

Fireworks

xAI

GLM

vLLM

LM Studio

Ollama


Contributors