Principle:A616567126 GPT WEB JAVA OpenAI Chat Completions
| 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
ChatImgCompletionwith image messages)
Practical Guide
The repository implements this in ChatGPTStream and ChatCompletion:
ChatGPTStream.streamChatCompletion(messages, listener, type, req, imgMessages)— selects model, builds ChatCompletion or ChatImgCompletion, calls the streaming overloadChatGPTStream.streamChatCompletion(chatCompletion, listener)— serializes to JSON, creates OkHttp request, opens EventSourceAbstractStreamListener.onEvent()— parses each SSE event, extracts delta content, callsonMsg()ChatCompletion.checkTokens()— validates token count before sending (throws if exceeds limit)
Related Pages
Implemented By
- Implementation:A616567126_GPT_WEB_JAVA_ChatGPTStream
- Implementation:A616567126_GPT_WEB_JAVA_GptController
- Implementation:A616567126_GPT_WEB_JAVA_ChatCompletion
- Implementation:A616567126_GPT_WEB_JAVA_TokensUtil