A platform for community discussion. Free, open, simple.
# frozen_string_literal: true
require_relative "endpoint_compliance"
class OpenAiMock < EndpointMock
def response(content, tool_call: false)
message_content =
if tool_call
{ tool_calls: [content] }
else
{ content: content }
end
{
id: "chatcmpl-6sZfAb30Rnv9Q7ufzFwvQsMpjZh8S",
object: "chat.completion",
created: 1_678_464_820,
model: "gpt-3.5-turbo-0301",
usage: {
prompt_tokens: 8,
completion_tokens: 12,
total_tokens: 499,
},
choices: [
{ message: { role: "assistant" }.merge(message_content), finish_reason: "stop", index: 0 },
],
}
end
def stub_response(prompt, response_text, tool_call: false)
WebMock
.stub_request(:post, "https://api.openai.com/v1/chat/completions")
.with(body: request_body(prompt, tool_call: tool_call))
.to_return(status: 200, body: JSON.dump(response(response_text, tool_call: tool_call)))
end
def stream_line(delta, finish_reason: nil, tool_call: false)
message_content =
if tool_call
{ tool_calls: [delta] }
else
{ content: delta }
end
+"data: " << {
id: "chatcmpl-#{SecureRandom.hex}",
object: "chat.completion.chunk",
created: 1_681_283_881,
model: "gpt-3.5-turbo-0301",
choices: [{ delta: message_content }],
finish_reason: finish_reason,
index: 0,
}.to_json
end
def stub_raw(chunks, body_blk: nil)
stub = WebMock.stub_request(:post, "https://api.openai.com/v1/chat/completions")
stub.with(body: body_blk) if body_blk
stub.to_return(status: 200, body: chunks)
end
def stub_streamed_response(prompt, deltas, tool_call: false, skip_body_check: false)
chunks =
deltas.each_with_index.map do |_, index|
if index == (deltas.length - 1)
stream_line(deltas[index], finish_reason: "stop_sequence", tool_call: tool_call)
else
stream_line(deltas[index], tool_call: tool_call)
end
end
chunks = (chunks.join("\n\n") << "data: [DONE]").split("")
mock = WebMock.stub_request(:post, "https://api.openai.com/v1/chat/completions")
if !skip_body_check
mock = mock.with(body: request_body(prompt, stream: true, tool_call: tool_call))
end
mock.to_return(status: 200, body: chunks)
yield if block_given?
end
def tool_deltas
[
{ id: tool_id, function: {} },
{ id: tool_id, function: { name: "get_weather", arguments: "" } },
{ id: tool_id, function: { arguments: "" } },
{ id: tool_id, function: { arguments: "{" } },
{ id: tool_id, function: { arguments: " \"location\": \"Sydney\"" } },
{ id: tool_id, function: { arguments: " ,\"unit\": \"c\" }" } },
]
end
def tool_response
{
id: tool_id,
function: {
name: "get_weather",
arguments: { location: "Sydney", unit: "c" }.to_json,
},
}
end
def tool_id
"tool_0"
end
def tool_payload
{
type: "function",
function: {
name: "get_weather",
description: "Get the weather in a city",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "the city name",
},
unit: {
type: "string",
description: "the unit of measurement celcius c or fahrenheit f",
enum: %w[c f],
},
},
required: %w[location unit],
},
},
}
end
def request_body(prompt, stream: false, tool_call: false)
model
.default_options
.merge(messages: prompt)
.tap do |b|
if stream
b[:stream] = true
b[:stream_options] = { include_usage: true }
end
b[:tools] = [tool_payload] if tool_call
end
.to_json
end
end
RSpec.describe DiscourseAi::Completions::Endpoints::OpenAi do
subject(:endpoint) { described_class.new(model) }
fab!(:user)
fab!(:model, :llm_model)
let(:echo_tool) do
{
name: "echo",
description: "echo something",
parameters: [{ name: "text", type: "string", description: "text to echo", required: true }],
}
end
let(:tools) { [echo_tool] }
let(:open_ai_mock) { OpenAiMock.new(endpoint) }
let(:compliance) do
EndpointsCompliance.new(self, endpoint, DiscourseAi::Completions::Dialects::ChatGpt, user)
end
let(:image100x100) { plugin_file_from_fixtures("100x100.jpg") }
let(:upload100x100) do
UploadCreator.new(image100x100, "image.jpg").create_for(Discourse.system_user.id)
end
def minimal_pdf_content
<<~PDF
%PDF-1.4
1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj
2 0 obj<< /Type /Pages /Count 1 /Kids [3 0 R] >>endobj
3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>endobj
4 0 obj<< /Length 44 >>stream
BT /F1 12 Tf 72 720 Td (Hello PDF) Tj ET
endstream
endobj
xref
0 5
0000000000 65535 f
0000000010 00000 n
0000000060 00000 n
0000000111 00000 n
0000000200 00000 n
trailer<< /Size 5 /Root 1 0 R >>
startxref
268
%%EOF
PDF
end
def build_pdf_upload
SiteSetting.authorized_extensions = "*"
file = Tempfile.new(%w[test-pdf .pdf])
file.binmode
file.write(minimal_pdf_content)
file.rewind
UploadCreator.new(file, "document.pdf").create_for(Discourse.system_user.id)
ensure
file.close! if file
end
before { enable_current_plugin }
def stub_audited_completion(text, finish_reason: "stop", streaming: false)
usage = {
prompt_tokens: 10,
completion_tokens: 5,
completion_tokens_details: {
reasoning_tokens: 4,
},
}
response =
if streaming
"data: #{{ choices: [{ delta: { content: text }, finish_reason: finish_reason }] }.to_json}\n\n" +
"data: #{{ choices: [], usage: usage }.to_json}\n\ndata: [DONE]\n\n"
else
{
choices: [{ message: { content: text }, finish_reason: finish_reason }],
usage: usage,
}.to_json
end
open_ai_mock.stub_raw(response)
end
it "resets stop reasons, usage, and an unfinished decoder across retried streaming attempts" do
response = instance_double(Net::HTTPResponse, code: "200")
reads = 0
allow(response).to receive(:read_body) do |&block|
reads += 1
if reads == 1
block.call(
"data: #{{ choices: [{ delta: {}, finish_reason: "length" }], usage: { prompt_tokens: 10, completion_tokens: 0, completion_tokens_details: { reasoning_tokens: 7 } } }.to_json}\n\ndata: {\"choices\":",
)
raise EOFError, "Unexpected EOF"
end
block.call(
"data: #{{ choices: [{ delta: { content: "Recovered answer" }, finish_reason: "stop" }] }.to_json}\n\ndata: [DONE]\n\n",
)
end
http = instance_double(Net::HTTP)
allow(http).to receive(:request).and_yield(response)
allow(FinalDestination::HTTP).to receive(:start).and_yield(http)
endpoint.stubs(:sleep_before_retry)
emitted = []
endpoint.perform_completion!(
compliance.dialect(prompt: compliance.generic_prompt),
user,
) { |partial| emitted << partial }
expect(emitted).to eq(["Recovered answer"])
expect(AiApiAuditLog.last).to have_attributes(
completion_state: AiApiAuditLog::CompletionState::COMPLETE,
stop_reason: "stop",
reasoning_tokens: nil,
)
end
describe "completion state" do
it "classifies non-streaming normal text" do
stub_audited_completion("Answer", finish_reason: "stop")
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user)
expect(AiApiAuditLog.last).to have_attributes(
completion_state: AiApiAuditLog::CompletionState::COMPLETE,
stop_reason: "stop",
reasoning_tokens: 4,
response_tokens: 5,
)
end
it "classifies non-streaming limited text" do
stub_audited_completion("Partial", finish_reason: "length")
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user)
expect(AiApiAuditLog.last).to have_attributes(
completion_state: AiApiAuditLog::CompletionState::TRUNCATED,
stop_reason: "length",
reasoning_tokens: 4,
response_tokens: 5,
)
end
it "classifies non-streaming blank output" do
stub_audited_completion(" ", finish_reason: "length")
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user)
expect(AiApiAuditLog.last).to have_attributes(
completion_state: AiApiAuditLog::CompletionState::EMPTY,
stop_reason: "length",
reasoning_tokens: 4,
response_tokens: 5,
)
end
it "classifies non-streaming structured empty objects" do
stub_audited_completion("{}", finish_reason: "length")
params = {
response_format: {
json_schema: {
schema: {
properties: {
message: {
type: "string",
},
},
},
},
},
}
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user, params)
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::EMPTY)
end
it "classifies non-streaming structured broken JSON" do
stub_audited_completion("{broken", finish_reason: "length")
params = {
response_format: {
json_schema: {
schema: {
properties: {
message: {
type: "string",
},
},
},
},
},
}
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user, params)
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::TRUNCATED)
end
it "classifies non-streaming structured a finished incomplete JSON prefix" do
stub_audited_completion("{", finish_reason: "length")
params = {
response_format: {
json_schema: {
schema: {
properties: {
message: {
type: "string",
},
},
},
},
},
}
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user, params)
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::TRUNCATED)
end
it "classifies streamed normal text" do
stub_audited_completion("Answer", finish_reason: "stop", streaming: true)
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user) { |partial| }
expect(AiApiAuditLog.last).to have_attributes(
completion_state: AiApiAuditLog::CompletionState::COMPLETE,
stop_reason: "stop",
reasoning_tokens: 4,
response_tokens: 5,
)
end
it "classifies streamed limited text" do
stub_audited_completion("Partial", finish_reason: "length", streaming: true)
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user) { |partial| }
expect(AiApiAuditLog.last).to have_attributes(
completion_state: AiApiAuditLog::CompletionState::TRUNCATED,
stop_reason: "length",
reasoning_tokens: 4,
response_tokens: 5,
)
end
it "classifies streamed blank output" do
stub_audited_completion(" ", finish_reason: "length", streaming: true)
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user) { |partial| }
expect(AiApiAuditLog.last).to have_attributes(
completion_state: AiApiAuditLog::CompletionState::EMPTY,
stop_reason: "length",
reasoning_tokens: 4,
response_tokens: 5,
)
end
it "classifies streamed structured empty objects" do
stub_audited_completion("{}", finish_reason: "length", streaming: true)
params = {
response_format: {
json_schema: {
schema: {
properties: {
message: {
type: "string",
},
},
},
},
},
}
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user, params) { |partial| }
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::EMPTY)
end
it "classifies streamed structured broken JSON" do
stub_audited_completion("{broken", finish_reason: "length", streaming: true)
params = {
response_format: {
json_schema: {
schema: {
properties: {
message: {
type: "string",
},
},
},
},
},
}
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user, params) { |partial| }
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::TRUNCATED)
end
it "classifies streamed structured a finished incomplete JSON prefix" do
stub_audited_completion("{", finish_reason: "length", streaming: true)
params = {
response_format: {
json_schema: {
schema: {
properties: {
message: {
type: "string",
},
},
},
},
},
}
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user, params) { |partial| }
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::TRUNCATED)
end
it "classifies disable_streaming replay using the processed non-streaming output" do
model.update!(provider_params: { disable_streaming: true })
open_ai_mock.stub_raw(
{ choices: [{ message: { content: "Partial" }, finish_reason: "length" }] }.to_json,
)
emitted = []
endpoint.perform_completion!(
compliance.dialect(prompt: compliance.generic_prompt),
user,
) { |partial| emitted << partial }
expect(emitted).to eq(["Partial"])
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::TRUNCATED)
end
it "leaves failed requests unclassified and records only final-attempt metadata after a retry" do
endpoint.stubs(:sleep_before_retry)
stub_request(:post, model.url).to_return(
{ status: 500, body: "Server error" },
{
status: 200,
body: { choices: [{ message: { content: "Answer" }, finish_reason: "stop" }] }.to_json,
},
)
endpoint.perform_completion!(compliance.dialect(prompt: compliance.generic_prompt), user)
expect(AiApiAuditLog.last).to have_attributes(
completion_state: AiApiAuditLog::CompletionState::COMPLETE,
stop_reason: "stop",
reasoning_tokens: nil,
)
expect(AiApiAuditLog.last.request_attempts.map { |attempt| attempt["status"] }).to eq(
[500, 200],
)
stub_request(:post, model.url).to_return(status: 500, body: "Server error")
stub_const(DiscourseAi::Completions::Endpoints::Base, :TRANSIENT_ERROR_RETRY_DELAYS, []) do
expect {
endpoint.perform_completion!(compliance.dialect(prompt: compliance.generic_prompt), user)
}.to raise_error(DiscourseAi::Completions::Endpoints::Base::CompletionFailed)
end
expect(AiApiAuditLog.last).to have_attributes(
completion_state: nil,
stop_reason: nil,
reasoning_tokens: nil,
)
end
it "bounds unexpected provider stop reasons before persisting" do
reason = "x" * 100
stub_audited_completion("Answer", finish_reason: reason)
endpoint.perform_completion!(compliance.dialect(prompt: compliance.generic_prompt), user)
expect(AiApiAuditLog.last.stop_reason).to eq(reason.first(50))
end
it "preserves successful cancellation settlement while leaving completion state unknown" do
partial = "A long partial answer with more than one token"
payload = {
choices: [{ delta: { content: partial } }],
usage: {
prompt_tokens: 10,
completion_tokens: 1,
},
}
open_ai_mock.stub_raw("data: #{payload.to_json}\n\n")
execution =
DiscourseAi::Completions::ExecutionContext.new(
work_budget: DiscourseAi::Completions::TurnWorkBudget.new(limit: 4000),
)
cancel = DiscourseAi::Completions::CancelManager.new
model
.to_llm
.generate(
"Input",
user: user,
execution_context: execution,
cancel_manager: cancel,
) { |fragment| cancel.cancel! }
expect(AiApiAuditLog.last).to have_attributes(
completion_state: nil,
response_status: 200,
response_tokens: 1,
)
# Cancelled streams settle as incomplete: exposed output wins over an
# early usage snapshot.
expect(execution.work_budget.used).to eq(
DiscourseAi::Completions::Llm.proxy(model).tokenizer.size(partial),
)
end
end
describe "DNS SRV endpoints" do
let(:domain) { "_openai._tcp.example.com" }
let(:resolved_url) { "https://llm.example.com:8443" }
let(:response_body) { { choices: [{ message: { content: "hello" } }] }.to_json }
before do
resource = Resolv::DNS::Resource::IN::SRV.new(1, 1, 8443, "llm.example.com")
Resolv::DNS
.any_instance
.stubs(:getresources)
.with(domain, Resolv::DNS::Resource::IN::SRV)
.returns([resource])
Discourse.cache.delete("dns_srv_lookup:#{domain}")
end
it "uses the configured path" do
model.update!(url: "srv://#{domain}/custom/chat/completions")
request =
stub_request(:post, "#{resolved_url}/custom/chat/completions").to_return(
status: 200,
body: response_body,
)
DiscourseAi::Completions::Llm.proxy(model).generate("test", user: user)
expect(request).to have_been_requested
end
it "uses the fallback path when no path is configured" do
request =
stub_request(:post, "#{resolved_url}/v1/chat/completions").to_return(
status: 200,
body: response_body,
)
["srv://#{domain}", "srv://#{domain}/"].each do |url|
model.update!(url: url)
DiscourseAi::Completions::Llm.proxy(model).generate("test", user: user)
end
expect(request).to have_been_requested.twice
end
end
describe "max tokens for reasoning models" do
it "uses max_completion_tokens for reasoning models" do
model.update!(name: "o3-mini", max_output_tokens: 999)
llm = DiscourseAi::Completions::Llm.proxy(model)
prompt =
DiscourseAi::Completions::Prompt.new(
"You are a bot",
messages: [type: :user, content: "hello"],
)
response_text = <<~RESPONSE
data: {"id":"chatcmpl-B2VwlY6KzSDtHvg8pN1VAfRhhLFgn","object":"chat.completion.chunk","created":1739939159,"model":"o3-mini-2025-01-31","service_tier":"default","system_fingerprint":"fp_ef58bd3122","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"finish_reason":null}],"usage":null}
data: {"id":"chatcmpl-B2VwlY6KzSDtHvg8pN1VAfRhhLFgn","object":"chat.completion.chunk","created":1739939159,"model":"o3-mini-2025-01-31","service_tier":"default","system_fingerprint":"fp_ef58bd3122","choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}],"usage":null}
data: {"id":"chatcmpl-B2VwlY6KzSDtHvg8pN1VAfRhhLFgn","object":"chat.completion.chunk","created":1739939159,"model":"o3-mini-2025-01-31","service_tier":"default","system_fingerprint":"fp_ef58bd3122","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":null}
data: {"id":"chatcmpl-B2VwlY6KzSDtHvg8pN1VAfRhhLFgn","object":"chat.completion.chunk","created":1739939159,"model":"o3-mini-2025-01-31","service_tier":"default","system_fingerprint":"fp_ef58bd3122","choices":[],"usage":{"prompt_tokens":22,"completion_tokens":203,"total_tokens":225,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":192,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}
data: [DONE]
RESPONSE
body_parsed = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body: ->(body) { body_parsed = JSON.parse(body) },
).to_return(body: response_text)
result = +""
llm.generate(prompt, user: user, max_tokens: 1000) { |chunk| result << chunk }
expect(result).to eq("hello")
expect(body_parsed["max_completion_tokens"]).to eq(999)
llm.generate(prompt, user: user, max_tokens: 100) { |chunk| result << chunk }
expect(body_parsed["max_completion_tokens"]).to eq(100)
llm.generate(prompt, user: user) { |chunk| result << chunk }
expect(body_parsed["max_completion_tokens"]).to eq(999)
end
end
describe "repeat calls" do
it "can properly reset context" do
llm = DiscourseAi::Completions::Llm.proxy(model)
tools = [
{
name: "echo",
description: "echo something",
parameters: [
{ name: "text", type: "string", description: "text to echo", required: true },
],
},
]
prompt =
DiscourseAi::Completions::Prompt.new(
"You are a bot",
messages: [type: :user, id: "user1", content: "echo hello"],
tools: tools,
)
response = {
id: "chatcmpl-9JxkAzzaeO4DSV3omWvok9TKhCjBH",
object: "chat.completion",
created: 1_714_544_914,
model: "gpt-4-turbo-2024-04-09",
choices: [
{
index: 0,
message: {
role: "assistant",
content: nil,
tool_calls: [
{
id: "call_I8LKnoijVuhKOM85nnEQgWwd",
type: "function",
function: {
name: "echo",
arguments: "{\"text\":\"hello\"}",
},
},
],
},
logprobs: nil,
finish_reason: "tool_calls",
},
],
usage: {
prompt_tokens: 55,
completion_tokens: 13,
total_tokens: 68,
},
system_fingerprint: "fp_ea6eb70039",
}.to_json
stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(body: response)
result = llm.generate(prompt, user: user)
tool_call =
DiscourseAi::Completions::ToolCall.new(
id: "call_I8LKnoijVuhKOM85nnEQgWwd",
name: "echo",
parameters: {
text: "hello",
},
)
expect(result).to eq(tool_call)
stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(
body: { choices: [message: { content: "OK" }] }.to_json,
)
result = llm.generate(prompt, user: user)
expect(result).to eq("OK")
end
end
describe "max tokens remapping" do
it "remaps max_tokens to max_completion_tokens for reasoning models" do
model.update!(name: "o3-mini")
llm = DiscourseAi::Completions::Llm.proxy(model)
body_parsed = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body: ->(body) { body_parsed = JSON.parse(body) },
).to_return(status: 200, body: { choices: [{ message: { content: "hello" } }] }.to_json)
llm.generate("test", user: user, max_tokens: 1000)
expect(body_parsed["max_completion_tokens"]).to eq(1000)
expect(body_parsed["max_tokens"]).to be_nil
end
end
describe "forced tool use" do
it "can properly force tool use" do
llm = DiscourseAi::Completions::Llm.proxy(model)
tools = [
{
name: "echo",
description: "echo something",
parameters: [
{ name: "text", type: "string", description: "text to echo", required: true },
],
},
]
prompt =
DiscourseAi::Completions::Prompt.new(
"You are a bot",
messages: [type: :user, id: "user1", content: "echo hello"],
tools: tools,
tool_choice: "echo",
)
response = {
id: "chatcmpl-9JxkAzzaeO4DSV3omWvok9TKhCjBH",
object: "chat.completion",
created: 1_714_544_914,
model: "gpt-4-turbo-2024-04-09",
choices: [
{
index: 0,
message: {
role: "assistant",
content: nil,
tool_calls: [
{
id: "call_I8LKnoijVuhKOM85nnEQgWwd",
type: "function",
function: {
name: "echo",
arguments: "{\"text\":\"h<e>llo\"}",
},
},
],
},
logprobs: nil,
finish_reason: "tool_calls",
},
],
usage: {
prompt_tokens: 55,
completion_tokens: 13,
total_tokens: 68,
},
system_fingerprint: "fp_ea6eb70039",
}.to_json
body_json = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body: proc { |body| body_json = JSON.parse(body, symbolize_names: true) },
).to_return(body: response)
result = llm.generate(prompt, user: user, max_tokens: 1000)
expect(body_json[:tool_choice]).to eq({ type: "function", function: { name: "echo" } })
# we expect this not to be remapped on older non reasoning models
expect(body_json[:max_tokens]).to eq(1000)
log = AiApiAuditLog.order(:id).last
expect(log.request_tokens).to eq(55)
expect(log.response_tokens).to eq(13)
expect(log.duration_msecs).not_to be_nil
expected =
DiscourseAi::Completions::ToolCall.new(
id: "call_I8LKnoijVuhKOM85nnEQgWwd",
name: "echo",
parameters: {
text: "h<e>llo",
},
)
expect(result).to eq(expected)
stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(
body: { choices: [message: { content: "OK" }] }.to_json,
)
result = llm.generate(prompt, user: user)
expect(result).to eq("OK")
end
end
describe "structured outputs" do
it "falls back to best-effort parsing on broken JSON responses" do
prompt = compliance.generic_prompt
deltas = ["```json\n{ message: 'hel", "lo' }"]
model_params = {
response_format: {
json_schema: {
schema: {
properties: {
message: {
type: "string",
},
},
},
},
},
}
read_properties = []
open_ai_mock.with_chunk_array_support do
# skip body check cause of response format
open_ai_mock.stub_streamed_response(prompt, deltas, skip_body_check: true)
dialect = compliance.dialect(prompt: prompt)
endpoint.perform_completion!(dialect, user, model_params) do |partial|
read_properties << partial.read_buffered_property(:message)
end
end
expect(read_properties.join).to eq("hello")
end
end
describe "disabled tool use" do
it "can properly disable tool use with :none" do
llm = DiscourseAi::Completions::Llm.proxy(model)
tools = [
{
name: "echo",
description: "echo something",
parameters: [
{ name: "text", type: "string", description: "text to echo", required: true },
],
},
]
prompt =
DiscourseAi::Completions::Prompt.new(
"You are a bot",
messages: [type: :user, id: "user1", content: "don't use any tools please"],
tools: tools,
tool_choice: :none,
)
response = {
id: "chatcmpl-9JxkAzzaeO4DSV3omWvok9TKhCjBH",
object: "chat.completion",
created: 1_714_544_914,
model: "gpt-4-turbo-2024-04-09",
choices: [
{
index: 0,
message: {
role: "assistant",
content: "I won't use any tools. Here's a direct response instead.",
},
logprobs: nil,
finish_reason: "stop",
},
],
usage: {
prompt_tokens: 55,
completion_tokens: 13,
total_tokens: 68,
},
system_fingerprint: "fp_ea6eb70039",
}.to_json
body_json = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body: proc { |body| body_json = JSON.parse(body, symbolize_names: true) },
).to_return(body: response)
result = llm.generate(prompt, user: user)
# Verify that tool_choice is set to "none" in the request
expect(body_json[:tool_choice]).to eq("none")
expect(result).to eq("I won't use any tools. Here's a direct response instead.")
end
end
describe "parameter disabling" do
it "excludes disabled parameters from the request" do
model.update!(provider_params: { disable_top_p: true, disable_temperature: true })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(
status: 200,
body: { choices: [{ message: { content: "test response" } }] }.to_json,
)
dialect = compliance.dialect(prompt: compliance.generic_prompt)
# Request with parameters that should be ignored
endpoint.perform_completion!(dialect, user, { top_p: 0.9, temperature: 0.8, max_tokens: 100 })
# Verify disabled parameters aren't included
expect(parsed_body).not_to have_key(:top_p)
expect(parsed_body).not_to have_key(:temperature)
# Verify other parameters still work
expect(parsed_body).to have_key(:max_tokens)
expect(parsed_body[:max_tokens]).to eq(100)
end
end
describe "image support" do
it "can handle images" do
model = Fabricate(:llm_model, vision_enabled: true)
model.update!(allowed_attachment_types: %w[pdf])
model.reload
expect(model.allowed_attachment_types).to eq(%w[pdf])
llm = DiscourseAi::Completions::Llm.proxy(model)
prompt =
DiscourseAi::Completions::Prompt.new(
"You are image bot",
messages: [type: :user, id: "user1", content: ["hello", { upload_id: upload100x100.id }]],
)
encoded = prompt.encoded_uploads(prompt.messages.last)
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [message: { content: "nice pic" }] }.to_json)
completion = llm.generate(prompt, user: user)
expect(completion).to eq("nice pic")
expected_body = {
model: "gpt-4-turbo",
messages: [
{ role: "system", content: "You are image bot" },
{
role: "user",
content: [
{ type: "text", text: "hello" },
{
type: "image_url",
image_url: {
url: "data:#{encoded[0][:mime_type]};base64,#{encoded[0][:base64]}",
},
},
],
name: "user1",
},
],
}
expect(parsed_body).to eq(expected_body)
end
it "can handle pdf documents via input_file nodes" do
model = Fabricate(:llm_model, vision_enabled: true)
model.update!(allowed_attachment_types: %w[pdf])
llm = DiscourseAi::Completions::Llm.proxy(model)
pdf_upload = build_pdf_upload
prompt =
DiscourseAi::Completions::Prompt.new(
"You are pdf bot",
messages: [type: :user, id: "user1", content: ["hello", { upload_id: pdf_upload.id }]],
)
encoded = prompt.encoded_uploads(prompt.messages.last, allow_documents: true)
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [message: { content: "thanks" }] }.to_json)
completion = llm.generate(prompt, user: user)
expect(completion).to eq("thanks")
expected_body = {
model: "gpt-4-turbo",
messages: [
{ role: "system", content: "You are pdf bot" },
{
role: "user",
content: [
{ type: "text", text: "hello" },
{
type: "file",
file: {
filename: "document.pdf",
file_data: "data:#{encoded[0][:mime_type]};base64,#{encoded[0][:base64]}",
},
},
],
name: "user1",
},
],
}
expect(parsed_body).to eq(expected_body)
end
end
describe "#perform_completion!" do
context "when using XML tool calls format" do
let(:xml_tool_call_response) { <<~XML }
<function_calls>
<invoke>
<tool_name>get_weather</tool_name>
<parameters>
<location>Sydney</location>
<unit>c</unit>
<is_it_hot>true</is_it_hot>
</parameters>
</invoke>
</function_calls>
XML
let(:weather_tool) do
{
name: "get_weather",
description: "get weather",
parameters: [
{ name: "location", type: "string", description: "location", required: true },
{ name: "unit", type: "string", description: "unit", required: true, enum: %w[c f] },
{ name: "is_it_hot", type: "boolean", description: "is it hot" },
],
}
end
it "counts streamed XML-only tool output as visible" do
model.update!(provider_params: { disable_native_tools: true })
response =
"data: #{{ choices: [{ delta: { content: xml_tool_call_response }, finish_reason: "stop" }] }.to_json}\n\ndata: [DONE]\n\n"
open_ai_mock.stub_raw(response)
emitted = []
endpoint.perform_completion!(
compliance.dialect(prompt: compliance.generic_prompt(tools: [weather_tool])),
user,
) { |partial| emitted << partial }
expect(emitted.grep(DiscourseAi::Completions::ToolCall).map(&:name)).to eq(["get_weather"])
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::COMPLETE)
end
it "parses XML tool calls" do
response = {
id: "chatcmpl-6sZfAb30Rnv9Q7ufzFwvQsMpjZh8S",
object: "chat.completion",
created: 1_678_464_820,
model: "gpt-3.5-turbo-0301",
usage: {
prompt_tokens: 8,
completion_tokens: 13,
total_tokens: 499,
},
choices: [
{
message: {
role: "assistant",
content: xml_tool_call_response,
},
finish_reason: "stop",
index: 0,
},
],
}.to_json
endpoint.llm_model.update!(provider_params: { disable_native_tools: true })
body = nil
open_ai_mock.stub_raw(response, body_blk: proc { |inner_body| body = inner_body })
dialect = compliance.dialect(prompt: compliance.generic_prompt(tools: [weather_tool]))
tool_call = endpoint.perform_completion!(dialect, user)
body_parsed = JSON.parse(body, symbolize_names: true)
expect(body_parsed[:tools]).to eq(nil)
expect(body_parsed[:messages][0][:content]).to include("<function_calls>")
expect(AiApiAuditLog.last.completion_state).to eq(AiApiAuditLog::CompletionState::COMPLETE)
expect(tool_call.name).to eq("get_weather")
expect(tool_call.parameters).to eq({ location: "Sydney", unit: "c", is_it_hot: true })
end
end
context "when using regular mode" do
context "with simple prompts" do
it "completes a trivial prompt and logs the response" do
compliance.regular_mode_simple_prompt(open_ai_mock)
end
end
context "with tools" do
it "returns a function invocation" do
compliance.regular_mode_tools(open_ai_mock)
end
end
end
it "falls back to non-streaming mode when streaming is disabled" do
model.update!(provider_params: { disable_streaming: true })
response = {
id: "chatcmpl-123",
object: "chat.completion",
created: 1_677_652_288,
choices: [
{
message: {
role: "assistant",
content: "Hello there",
},
index: 0,
finish_reason: "stop",
},
],
}
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: response.to_json)
chunks = []
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user) { |chunk| chunks << chunk }
expect(parsed_body).not_to have_key(:stream)
expect(chunks).to eq(["Hello there"])
end
describe "when using streaming mode" do
context "with simple prompts" do
it "completes a trivial prompt and logs the response" do
compliance.streaming_mode_simple_prompt(open_ai_mock)
end
it "recovers automatically from a bad payload" do
called = false
# this should not happen, but lets ensure nothing bad happens
# the row with test1 is invalid json
raw_data = <<~TEXT.strip
d|a|t|a|:| |{|"choices":[{"delta":{"content":"test,"}}]}
data: {"choices":[{"delta":{"content":"test|1| |,"}}]
data: {"choices":[{"delta":|{"content":"test2 ,"}}]}
data: {"choices":[{"delta":{"content":"test3,"}}]|}
data: {"choices":[{|"|d|elta":{"content":"test4"}}]|}
data: [D|ONE]
TEXT
chunks = raw_data.split("|")
open_ai_mock.with_chunk_array_support do
open_ai_mock.stub_raw(chunks)
partials = []
endpoint.perform_completion!(compliance.dialect, user) { |partial| partials << partial }
called = true
expect(partials.join).to eq("test,test2 ,test3,test4")
end
expect(called).to be(true)
end
end
it "supports gpt-5, remaps max_tokens, passes reasoning effort, and uses developer message" do
model.update!(name: "gpt-5")
prompt =
DiscourseAi::Completions::Prompt.new(
"You are a bot",
messages: [type: :user, content: "hello"],
)
dialect = compliance.dialect(prompt: prompt)
body_parsed = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |body|
body_parsed = JSON.parse(body)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "ok" } }] }.to_json)
endpoint.perform_completion!(
dialect,
user,
{ max_tokens: 321, reasoning: { effort: "low" } },
)
expect(body_parsed["model"]).to eq("gpt-5")
expect(body_parsed["max_completion_tokens"]).to eq(321)
expect(body_parsed["max_tokens"]).to be_nil
expect(body_parsed["reasoning"]).to eq({ "effort" => "low" })
expect(body_parsed["messages"].first["role"]).to eq("developer")
expect(body_parsed["messages"].first["content"]).to eq("You are a bot")
end
it "supports gpt-6, remaps max_tokens, and uses developer message" do
model.update!(name: "gpt-6.1-sol")
prompt =
DiscourseAi::Completions::Prompt.new(
"You are a bot",
messages: [type: :user, content: "hello"],
)
dialect = compliance.dialect(prompt: prompt)
body_parsed = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |body|
body_parsed = JSON.parse(body)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "ok" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { max_tokens: 321 })
expect(body_parsed["model"]).to eq("gpt-6.1-sol")
expect(body_parsed["max_completion_tokens"]).to eq(321)
expect(body_parsed["max_tokens"]).to be_nil
expect(body_parsed["messages"].first["role"]).to eq("developer")
expect(body_parsed["messages"].first["content"]).to eq("You are a bot")
end
context "with tools" do
it "returns a function invocation" do
compliance.streaming_mode_tools(open_ai_mock)
end
it "emits every tool call when a streamed event contains multiple calls" do
event = {
choices: [
{
index: 0,
delta: {
content: "Searching\n",
tool_calls: [
{
index: 0,
id: "call_sam",
function: {
name: "search",
arguments: '{"search_query":"sam"}',
},
},
{
index: 1,
id: "call_dan",
function: {
name: "search",
arguments: '{"search_query":"dan"}',
},
},
],
},
finish_reason: "tool_calls",
},
],
}
open_ai_mock.stub_raw("data: #{event.to_json}\n\ndata: [DONE]\n\n")
dialect = compliance.dialect(prompt: compliance.generic_prompt(tools: tools))
response = []
endpoint.perform_completion!(dialect, user) { |partial| response << partial }
expect(response.first).to eq("Searching\n")
tool_calls = response.drop(1)
expect(tool_calls.map(&:id)).to eq(%w[call_sam call_dan])
expect(tool_calls.map(&:parameters)).to eq(
[{ search_query: "sam" }, { search_query: "dan" }],
)
expect(tool_calls).to all(have_attributes(partial: false))
end
it "properly handles multiple tool calls" do
raw_data = <<~TEXT.strip
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"role":"assistant","content":null},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_3Gyr3HylFJwfrtKrL6NaIit1","type":"function","function":{"name":"search","arguments":""}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"se"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"arch_"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"query\\""}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":": \\"D"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"iscou"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"rse AI"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" bot"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\\"}"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_H7YkbgYurHpyJqzwUN4bghwN","type":"function","function":{"name":"search","arguments":""}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\\"qu"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"ery\\":"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":" \\"Disc"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"ours"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"e AI "}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"bot2\\"}"}}]},"logprobs":null,"finish_reason":null}]}
data: {"id":"chatcmpl-8xjcr5ZOGZ9v8BDYCx0iwe57lJAGk","object":"chat.completion.chunk","created":1709247429,"model":"gpt-4-0125-preview","system_fingerprint":"fp_91aa3742b1","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]}
data: [DONE]
TEXT
open_ai_mock.stub_raw(raw_data)
response = []
dialect = compliance.dialect(prompt: compliance.generic_prompt(tools: tools))
endpoint.perform_completion!(dialect, user) { |partial| response << partial }
tool_calls = [
DiscourseAi::Completions::ToolCall.new(
name: "search",
id: "call_3Gyr3HylFJwfrtKrL6NaIit1",
parameters: {
search_query: "Discourse AI bot",
},
),
DiscourseAi::Completions::ToolCall.new(
name: "search",
id: "call_H7YkbgYurHpyJqzwUN4bghwN",
parameters: {
query: "Discourse AI bot2",
},
),
]
expect(response).to eq(tool_calls)
end
it "properly handles newlines" do
response = <<~TEXT.strip
data: {"id":"chatcmpl-ASngi346UA9k006bF6GBRV66tEJfQ","object":"chat.completion.chunk","created":1731427548,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_159d8341cc","choices":[{"index":0,"delta":{"content":":\\n\\n"},"logprobs":null,"finish_reason":null}],"usage":null}
data: {"id":"chatcmpl-ASngi346UA9k006bF6GBRV66tEJfQ","object":"chat.completion.chunk","created":1731427548,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_159d8341cc","choices":[{"index":0,"delta":{"content":"```"},"logprobs":null,"finish_reason":null}],"usage":null}
data: {"id":"chatcmpl-ASngi346UA9k006bF6GBRV66tEJfQ","object":"chat.completion.chunk","created":1731427548,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_159d8341cc","choices":[{"index":0,"delta":{"content":"ruby"},"logprobs":null,"finish_reason":null}],"usage":null}
data: {"id":"chatcmpl-ASngi346UA9k006bF6GBRV66tEJfQ","object":"chat.completion.chunk","created":1731427548,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_159d8341cc","choices":[{"index":0,"delta":{"content":"\\n"},"logprobs":null,"finish_reason":null}],"usage":null}
data: {"id":"chatcmpl-ASngi346UA9k006bF6GBRV66tEJfQ","object":"chat.completion.chunk","created":1731427548,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_159d8341cc","choices":[{"index":0,"delta":{"content":"def"},"logprobs":null,"finish_reason":null}],"usage":null}
TEXT
open_ai_mock.stub_raw(response)
partials = []
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user) { |partial| partials << partial }
expect(partials).to eq([":\n\n", "```", "ruby", "\n", "def"])
end
it "uses proper token accounting" do
response = <<~TEXT.strip
data: {"id":"chatcmpl-9OZidiHncpBhhNMcqCus9XiJ3TkqR","object":"chat.completion.chunk","created":1715644203,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_729ea513f7","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],"usage":null}|
data: {"id":"chatcmpl-9OZidiHncpBhhNMcqCus9XiJ3TkqR","object":"chat.completion.chunk","created":1715644203,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_729ea513f7","choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}],"usage":null}|
data: {"id":"chatcmpl-9OZidiHncpBhhNMcqCus9XiJ3TkqR","object":"chat.completion.chunk","created":1715644203,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_729ea513f7","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}|
data: {"id":"chatcmpl-9OZidiHncpBhhNMcqCus9XiJ3TkqR","object":"chat.completion.chunk","created":1715644203,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_729ea513f7","choices":[],"usage":{"prompt_tokens":20,"completion_tokens":9,"total_tokens":29}}|
data: [DONE]
TEXT
chunks = response.split("|")
open_ai_mock.with_chunk_array_support do
open_ai_mock.stub_raw(chunks)
partials = []
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user) { |partial| partials << partial }
expect(partials).to eq(["Hello"])
log = AiApiAuditLog.order("id desc").first
expect(log.request_tokens).to eq(20)
expect(log.response_tokens).to eq(9)
end
end
it "uses proper token accounting with cached tokens" do
response = <<~TEXT.strip
data: {"id":"chatcmpl-cached","object":"chat.completion.chunk","created":1715644203,"model":"gpt-4o-2024-05-13","choices":[],"usage":{"prompt_tokens":25,"completion_tokens":10,"total_tokens":35,"prompt_tokens_details":{"cached_tokens":5}}}|
data: [DONE]
TEXT
chunks = response.split("|")
open_ai_mock.with_chunk_array_support do
open_ai_mock.stub_raw(chunks)
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user) { |partial| }
log = AiApiAuditLog.order("id desc").first
# request_tokens should be prompt_tokens (25) - cached_tokens (5) = 20
expect(log.request_tokens).to eq(20)
expect(log.cache_read_tokens).to eq(5)
expect(log.response_tokens).to eq(10)
end
end
it "uses proper token accounting with top-level cache usage" do
response = <<~TEXT.strip
data: {"id":"chatcmpl-cached","object":"chat.completion.chunk","created":1715644203,"model":"gpt-4o-2024-05-13","choices":[],"usage":{"prompt_tokens":25,"completion_tokens":10,"total_tokens":35,"prompt_cache_hit_tokens":5,"prompt_cache_miss_tokens":20}}|
data: [DONE]
TEXT
chunks = response.split("|")
open_ai_mock.with_chunk_array_support do
open_ai_mock.stub_raw(chunks)
dialect = compliance.dialect(prompt: compliance.generic_prompt)
endpoint.perform_completion!(dialect, user) { |partial| }
log = AiApiAuditLog.order("id desc").first
expect(log.request_tokens).to eq(20)
expect(log.cache_read_tokens).to eq(5)
expect(log.response_tokens).to eq(10)
end
end
it "properly handles multiple params in partial tool calls" do
# this is not working and it is driving me nuts so I will use a sledghammer
# text = plugin_file_from_fixtures("openai_artifact_call.txt", "bot")
path = File.join(__dir__, "../../../fixtures/bot", "openai_artifact_call.txt")
text = File.read(path)
partials = []
open_ai_mock.with_chunk_array_support do
open_ai_mock.stub_raw(text.scan(/.*\n/))
dialect = compliance.dialect(prompt: compliance.generic_prompt(tools: tools))
endpoint.perform_completion!(dialect, user, partial_tool_calls: true) do |partial|
partials << partial.dup
end
end
expect(partials.compact.length).to eq(134)
params =
partials
.map { |p| p.parameters if p.is_a?(DiscourseAi::Completions::ToolCall) && p.partial? }
.compact
lengths = {}
params.each do |p|
p.each do |k, v|
if lengths[k] && lengths[k] > v.length
expect(lengths[k]).to be > v.length
else
lengths[k] = v.length
end
end
end
audit_log = AiApiAuditLog.order("id desc").first
expect(audit_log.cache_read_tokens).to eq(33)
end
it "properly handles spaces in tools payload and partial tool calls" do
raw_data = <<~TEXT.strip
data: {"choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"func_id","type":"function","function":{"name":"go|ogle","arg|uments":""}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "{\\""}}]}}]}
data: {"ch|oices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "query"}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "\\":\\""}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "Ad"}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "a|b"}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "as"}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": |"| "}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "9"}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "."}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"argume|nts": "1"}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": "\\"}"}}]}}]}
data: {"choices": [{"index": 0, "delta": {"tool_calls": []}}]}
data: [D|ONE]
TEXT
chunks = raw_data.split("|")
open_ai_mock.with_chunk_array_support do
open_ai_mock.stub_raw(chunks)
partials = []
dialect = compliance.dialect(prompt: compliance.generic_prompt(tools: tools))
endpoint.perform_completion!(dialect, user, partial_tool_calls: true) do |partial|
partials << partial.dup
end
tool_call =
DiscourseAi::Completions::ToolCall.new(
id: "func_id",
name: "google",
parameters: {
query: "Adabas 9.1",
},
)
expect(partials.last).to eq(tool_call)
progress = partials.map { |p| p.parameters[:query] }
expect(progress).to eq(["Ad", "Adabas", "Adabas 9.", "Adabas 9.1"])
end
end
end
end
end
describe "reasoning effort payload format" do
let(:prompt) { compliance.generic_prompt }
let(:dialect) { compliance.dialect(prompt: prompt) }
it "uses reasoning_effort field for standard API" do
model.update!(provider_params: { reasoning_effort: "low" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:reasoning_effort]).to eq("low")
expect(parsed_body).not_to have_key(:reasoning)
end
it "accepts none as reasoning_effort" do
model.update!(provider_params: { reasoning_effort: "none" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:reasoning_effort]).to eq("none")
end
it "accepts xhigh as reasoning_effort" do
model.update!(provider_params: { reasoning_effort: "xhigh" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:reasoning_effort]).to eq("xhigh")
end
it "collapses minimal to low since some models reject it outright" do
model.update!(name: "gpt-5")
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "minimal" })
expect(parsed_body[:reasoning_effort]).to eq("low")
end
it "strips temperature and top_p when reasoning_effort is set" do
model.update!(provider_params: { reasoning_effort: "low" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { temperature: 0.7, top_p: 0.9 })
expect(parsed_body[:reasoning_effort]).to eq("low")
expect(parsed_body).not_to have_key(:temperature)
expect(parsed_body).not_to have_key(:top_p)
end
it "uses per-call thinking effort and maps max to xhigh for allowlisted models" do
model.update!(name: "gpt-5.5-2026-04-24", provider_params: { reasoning_effort: "low" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "max", temperature: 0.7 })
expect(parsed_body[:reasoning_effort]).to eq("xhigh")
expect(parsed_body).not_to have_key(:temperature)
end
it "uses native max effort for GPT-5.6" do
model.update!(name: "gpt-5.6-sol")
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "max" })
expect(parsed_body[:reasoning_effort]).to eq("max")
end
it "maps none to low for GPT-6 Astra, which does not support none" do
model.update!(name: "gpt-6-astra")
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "none" })
expect(parsed_body[:reasoning_effort]).to eq("low")
end
it "maps none to low for GPT-6.1 Sol snapshots, which do not support none" do
model.update!(name: "gpt-6.1-sol-2026-09-01", provider_params: { reasoning_effort: "none" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:reasoning_effort]).to eq("low")
end
it "keeps none for GPT-6 Sol, which supports none" do
model.update!(name: "gpt-6-sol")
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "none" })
expect(parsed_body[:reasoning_effort]).to eq("none")
end
%w[gpt-4.1-mini gpt-35-turbo].each do |model_name|
it "omits per-call efforts for #{model_name}, which does not reason" do
model.update!(name: model_name)
bodies = []
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
bodies << JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "none" })
endpoint.perform_completion!(dialect, user, { thinking_effort: "medium" })
expect(bodies.map { |body| body.key?(:reasoning_effort) }).to eq([false, false])
end
end
it "sends a per-call none to reasoning models" do
model.update!(name: "gpt-5-mini")
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "none" })
expect(parsed_body[:reasoning_effort]).to eq("none")
end
it "uses native max effort for GPT-6 Astra" do
model.update!(name: "gpt-6-astra")
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "max" })
expect(parsed_body[:reasoning_effort]).to eq("max")
end
it "uses native max effort for future OpenAI models by default" do
model.update!(name: "gpt-5.7")
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user, { thinking_effort: "max" })
expect(parsed_body[:reasoning_effort]).to eq("max")
end
it "passes max through for Azure deployments with opaque names" do
azure_url = "https://test.openai.azure.com/openai/v1/chat/completions"
model.update!(
provider: "azure",
name: "production-deployment",
url: azure_url,
provider_params: {
reasoning_effort: "max",
},
)
parsed_body = nil
stub_request(:post, azure_url).with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:reasoning_effort]).to eq("max")
end
it "reserves OpenAI recommended output room for reasoning when no token cap is configured" do
model.update!(name: "gpt-5")
prepared_params = endpoint.prepare_model_params(thinking_effort: "high")
expect(prepared_params[:reserved_output_tokens]).to eq(25_000)
end
it "uses the model output limit as the reasoning output reservation when configured" do
model.update!(name: "gpt-5", max_output_tokens: 12_000)
prepared_params = endpoint.prepare_model_params(thinking_effort: "high")
expect(prepared_params[:reserved_output_tokens]).to eq(12_000)
end
it "does not reserve output room when reasoning is explicitly disabled" do
prepared_params = endpoint.prepare_model_params(thinking_effort: "none")
expect(prepared_params).not_to have_key(:reserved_output_tokens)
end
it "reserves output room when none maps to low on GPT-6.1 Sol" do
model.update!(name: "gpt-6.1-sol")
prepared_params = endpoint.prepare_model_params(thinking_effort: "none")
expect(prepared_params[:reserved_output_tokens]).to eq(25_000)
end
it "treats standard reasoning mode as a no-op for Chat Completions" do
model.update!(provider_params: { reasoning_mode: "standard" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body).not_to have_key(:reasoning)
expect(parsed_body).not_to have_key(:reasoning_effort)
end
it "omits reasoning parameters when not configured" do
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body).not_to have_key(:reasoning)
expect(parsed_body).not_to have_key(:reasoning_effort)
end
end
describe "service_tier payload" do
let(:prompt) { compliance.generic_prompt }
let(:dialect) { compliance.dialect(prompt: prompt) }
it "includes service_tier when set to auto" do
model.update!(provider_params: { service_tier: "auto" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:service_tier]).to eq("auto")
end
it "includes service_tier when set to flex" do
model.update!(provider_params: { service_tier: "flex" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:service_tier]).to eq("flex")
end
it "includes service_tier when set to priority" do
model.update!(provider_params: { service_tier: "priority" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:service_tier]).to eq("priority")
end
it "omits service_tier when set to default" do
model.update!(provider_params: { service_tier: "default" })
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body).not_to have_key(:service_tier)
end
it "omits service_tier when not configured" do
parsed_body = nil
stub_request(:post, "https://api.openai.com/v1/chat/completions").with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body).not_to have_key(:service_tier)
end
it "includes service_tier for azure provider" do
model.update!(
provider: "azure",
url:
"https://test.openai.azure.com/openai/deployments/gpt-4/chat/completions?api-version=2024-02-15-preview",
provider_params: {
service_tier: "priority",
},
)
parsed_body = nil
stub_request(
:post,
"https://test.openai.azure.com/openai/deployments/gpt-4/chat/completions?api-version=2024-02-15-preview",
).with(
body:
proc do |req_body|
parsed_body = JSON.parse(req_body, symbolize_names: true)
true
end,
).to_return(status: 200, body: { choices: [{ message: { content: "test" } }] }.to_json)
endpoint.perform_completion!(dialect, user)
expect(parsed_body[:service_tier]).to eq("priority")
end
end
end