Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Principle:A616567126 GPT WEB JAVA OpenAI Chat Completions

From Leeroopedia
Knowledge Sources
Domains NLP, LLM, API_Integration
Last Updated 2026-10-13 00:00 GMT

Overview

API pattern that sends conversation messages to OpenAI's Chat Completions endpoint with streaming enabled, receiving token-by-token responses via Server-Sent Events.

Description

OpenAI's Chat Completions API accepts a list of messages (system, user, assistant) and returns a model-generated response. With stream: true, the API returns incremental token deltas via SSE, allowing real-time display of the response as it generates.

This repository constructs ChatCompletion or ChatImgCompletion objects with messages, model name, temperature, and topP parameters. The model is selected based on the request type: GPT-3.5-TURBO-16K for type 3, GPT-4 for type 4, and GPT-4 Vision for type 5. The request is serialized to JSON and sent to the OpenAI API (or a reverse proxy) via OkHttp's EventSource.

Usage

Use this principle when:

  • Integrating with OpenAI's chat completions API
  • Supporting multiple GPT models (3.5, 4, Vision) with a unified interface
  • Streaming responses token-by-token to the client

Theoretical Basis

Chat Completions Request:

{
    "model": "gpt-3.5-turbo-16k",
    "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ],
    "temperature": 0.7,
    "top_p": 1.0,
    "stream": true
}

Streaming Response (SSE):

data: {"choices":[{"delta":{"content":"Hello"}}]}
data: {"choices":[{"delta":{"content":" world"}}]}
data: [DONE]

Model Selection:

  • Type 3 → gpt-3.5-turbo-16k
  • Type 4 → gpt-4
  • Type 5 → GPT-4 Vision (uses ChatImgCompletion with image messages)

Practical Guide

The repository implements this in ChatGPTStream and ChatCompletion:

  1. ChatGPTStream.streamChatCompletion(messages, listener, type, req, imgMessages) — selects model, builds ChatCompletion or ChatImgCompletion, calls the streaming overload
  2. ChatGPTStream.streamChatCompletion(chatCompletion, listener) — serializes to JSON, creates OkHttp request, opens EventSource
  3. AbstractStreamListener.onEvent() — parses each SSE event, extracts delta content, calls onMsg()
  4. ChatCompletion.checkTokens() — validates token count before sending (throws if exceeds limit)

Related Pages

Implemented By

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment