Class OpenAIProvider

java.lang.Object
org.machanism.machai.ai.provider.AbstractAIProvider
org.machanism.machai.ai.provider.impl.OpenAIProvider
All Implemented Interfaces:
EmbeddingProvider, Genai
Direct Known Subclasses:
CodeMieProvider.OpenAIProviderExtension

public class OpenAIProvider extends AbstractAIProvider implements EmbeddingProvider
OpenAI-backed Genai implementation. <p>This provider adapts the Machai provider abstraction to the OpenAI Java SDK Responses API. It supports prompting, file inputs, tool/function calling, optional web search and MCP tools, and embedding generation. </p>

Configuration

Configuration values are read from the Configurator passed to AbstractAIProvider.init(String, Configurator).

  • chatModel (required): model identifier passed to the OpenAI Responses API, for example gpt-4.1 or gpt-4o.
  • OPENAI_API_KEY (required): API key used to authenticate with the OpenAI API.
  • OPENAI_BASE_URL (optional): base URL for OpenAI-compatible endpoints. If unset, the SDK default base URL is used.
  • GENAI_TIMEOUT (optional): request timeout in seconds. If missing, 0, or negative, the SDK default timeouts are used.
  • MAX_OUTPUT_TOKENS (optional): maximum number of output tokens. Defaults to 18000L.
  • MAX_TOOL_CALLS (optional): maximum number of tool calls the model may issue in a single response loop. A value of 0 leaves the limit unset.
  • WebSearchTool.type (optional): enables the built-in web search tool when present.
  • WebSearchTool.city (optional): city value for the web search user location.
  • WebSearchTool.country (optional): country value for the web search user location.
  • WebSearchTool.region (optional): region value for the web search user location.
  • MCP.url, MCP.label, MCP.description, MCP.authorization (optional): registers an MCP server tool.
  • MCP_1.url, MCP_1.label, MCP_1.description, MCP_1.authorization and similarly numbered groups (optional): registers additional MCP server tools.
  • Field Details

    • logger

      static org.slf4j.Logger logger
      Logger instance for this provider.
    • OPENAI_API_KEY

      public static final String OPENAI_API_KEY
      Configuration/environment key used by OpenAI-compatible clients to provide the API key.

      For CodeMie this value is set to the retrieved OAuth 2.0 access token.

      See Also:
    • OPENAI_BASE_URL_NAME

      public static final String OPENAI_BASE_URL_NAME
      Configuration/environment key used to override the OpenAI-compatible base URL.
      See Also:
    • toolMap

      final Map<com.openai.models.responses.Tool,ToolFunction> toolMap
      Maps tools to handler functions.
    • inputs

      final List<com.openai.models.responses.ResponseInputItem> inputs
      Accumulated request input items for the current conversation.
  • Constructor Details

    • OpenAIProvider

      public OpenAIProvider()
      Creates an OpenAI provider instance.
  • Method Details

    • addWebSearch

      protected void addWebSearch(String type, String city, String country, String region)
      Adds the built-in OpenAI web search tool when configured.
      Overrides:
      addWebSearch in class AbstractAIProvider
      Parameters:
      type - provider-specific web-search tool type/version
      city - optional user city
      country - optional user country
      region - optional user region
    • addMcpServer

      protected void addMcpServer(String name, String url, String authorization, String description)
      Adds one or more MCP server tools from configuration.
      Overrides:
      addMcpServer in class AbstractAIProvider
      Parameters:
      name - provider-visible MCP server label
      url - server endpoint URL
      authorization - optional authorization token/value
      description - optional human-readable description
    • addTool

      protected void addTool(String name, String description, ToolFunction function, ParamDescriptor... paramsDesc)
      Registers a function tool for the current provider instance.

      The paramsDesc entries must follow the format name:type:required:description. The parameter schema passed to OpenAI is a JSON Schema object of type object.

      Specified by:
      addTool in class AbstractAIProvider
      Parameters:
      name - tool function name
      description - tool description
      function - handler callback for tool execution
      paramsDesc - parameter descriptors in the format name:type:required:description
    • prompt

      public void prompt(String text)
      Adds a text prompt to the current request input.
      Specified by:
      prompt in interface Genai
      Overrides:
      prompt in class AbstractAIProvider
      Parameters:
      text - the prompt string
    • perform

      public String perform()
      Executes a request using the currently configured model, inputs, and tools.

      If the response contains tool calls, the provider executes the matching tool handlers and continues the conversation until a final text response is produced.

      Specified by:
      perform in interface Genai
      Returns:
      the final model response text, or null if no text was produced
    • call

      private com.openai.models.responses.Response call(com.openai.models.responses.ResponseCreateParams params)
    • parseResponse

      private String parseResponse(com.openai.models.responses.Response response)
      Parses the given response and handles function tool calls.

      Tool calls are executed via callFunction(ResponseFunctionToolCall). If tool calls are present, the method creates and sends a follow-up request with both the tool call and tool output attached, and repeats until the model returns a final message.

      Parameters:
      response - response object
      Returns:
      response string, potentially after one or more tool call iterations
    • handleFunctionCall

      private void handleFunctionCall(com.openai.models.responses.ResponseFunctionToolCall functionCall)
      Records a function call in the conversation, executes it, and appends the resulting function output item.
      Parameters:
      functionCall - the function call returned by the model
    • extractReasoningText

      private String extractReasoningText(com.openai.models.responses.ResponseOutputItem item)
      Extracts reasoning text from a response output item when present.
      Parameters:
      item - response output item
      Returns:
      reasoning text, or null when unavailable
    • firstNonBlankReasoning

      private String firstNonBlankReasoning(List<com.openai.models.responses.ResponseReasoningItem.Content> contents)
      Returns the first non-blank reasoning fragment.
      Parameters:
      contents - reasoning content fragments
      Returns:
      first non-blank reasoning text, or null when none exists
    • extractMessageText

      private String extractMessageText(com.openai.models.responses.ResponseOutputItem item)
      Extracts text content from a message output item.
      Parameters:
      item - response output item
      Returns:
      message text, or null when unavailable
    • createResponseBuilder

      private com.openai.models.responses.ResponseCreateParams createResponseBuilder(List<com.openai.models.responses.ResponseInputItem> inputs)
      Builds the request parameters for the OpenAI Responses API.
      Parameters:
      inputs - input items to send
      Returns:
      immutable request parameters
    • callFunction

      private Object callFunction(com.openai.models.responses.ResponseFunctionToolCall functionCall)
      Executes a function tool call by finding a registered tool with the same name and delegating to its handler.

      The handler is invoked with an Object[] of length 2:

      1. index 0: parsed JSON arguments as a Jackson JsonNode
      2. index 1: the configured AbstractAIProvider.setProjectDir(File) value
      Parameters:
      functionCall - call details
      Returns:
      result from function handler, or null if no matching tool is registered
      Throws:
      IllegalArgumentException - if the tool call arguments cannot be parsed
    • clear

      public void clear()
      Clears all accumulated inputs for the next request.
      Specified by:
      clear in interface Genai
      Overrides:
      clear in class AbstractAIProvider
    • getClient

      public com.openai.client.OpenAIClient getClient()
      Returns the underlying OpenAI client.
      Returns:
      OpenAI client
    • captureUsage

      protected void captureUsage(Optional<com.openai.models.responses.ResponseUsage> usage)
      Captures and records usage statistics from an optional ResponseUsage instance.

      If the provided usage is present, this method extracts input tokens, cached input tokens, and output tokens from the ResponseUsage object, constructs a new Usage record, and adds it to the UsageStatistics for the current chat model.

      Parameters:
      usage - an Optional containing the ResponseUsage details to record; if not present, no action is taken
    • embedding

      public List<Double> embedding(String text, long dimensions)
      Requests an embedding vector for the given input text.
      Specified by:
      embedding in interface EmbeddingProvider
      Parameters:
      text - input to embed
      dimensions - number of dimensions requested from the embedding model
      Returns:
      embedding as a list of double values, or null when text is null