Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/HOST_APP_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,15 @@ Coplan provides a REST API for programmatic access. Users create API tokens in t

Coplan inherits from your `::ApplicationController` for layout and middleware. The engine's nav bar will render a "Sign out" link if your app defines a `sign_out_path` route helper.

## AI failure diagnostics

Chat and transcription errors append the provider's error type, code and message,
including gateway-specific reasons and plain-string gateway errors. The combined
diagnostic is limited to 300 characters and normalized to one line. Only string
fields are included; request objects and other fields are omitted. Providers are
trusted to supply suitable diagnostic text. Malformed bodies fall back to the
existing transport error, and the original exception remains available as the cause.

## Configuration reference

```ruby
Expand Down
31 changes: 29 additions & 2 deletions engine/app/services/coplan/ai_providers/open_ai.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ class OpenAi
# models cap how much of this they will read.
MAX_PROMPT_LENGTH = 600

# Bound the complete appended diagnostic, including type and code.
MAX_ERROR_DETAIL = 300

def self.call(system_prompt:, user_content:, model: nil)
new(system_prompt:, user_content:, model:).call
end
Expand All @@ -36,7 +39,7 @@ def self.transcribe(file:, context: nil)

text.strip
rescue Faraday::Error => e
raise Error, "Transcription failed: #{e.message}"
raise Error, "Transcription failed: #{e.message}#{failure_detail(e)}"
end

# Whether server-side calls are possible at all. The voice control
Expand Down Expand Up @@ -92,7 +95,31 @@ def call

content
rescue Faraday::Error => e
raise Error, "Chat request failed: #{e.message}"
raise Error, "Chat request failed: #{e.message}#{self.class.failure_detail(e)}"
end

# Keep the provider's explanation, including gateway-specific reasons.
# Only the error's diagnostic fields are appended, never request data.
def self.failure_detail(error)
response = error.response
body = response[:body] if response.is_a?(Hash)
body = JSON.parse(body) if body.is_a?(String)
detail = body.is_a?(Hash) ? body["error"] : nil
detail = { "message" => detail } if detail.is_a?(String)
return "" unless detail.is_a?(Hash)

type, code, message = %w[type code message].map do |key|
value = detail[key]
next unless value.is_a?(String)

value.encode("UTF-8", invalid: :replace, undef: :replace)
.gsub(/[[:cntrl:]]/, " ").squish.truncate(MAX_ERROR_DETAIL).presence
end
label = [ type, code ].compact.join("/")
text = [ label.presence, message ].compact.join(": ").truncate(MAX_ERROR_DETAIL)
text.empty? ? "" : " (#{text})"
rescue JSON::ParserError
""
end

class Error < StandardError; end
Expand Down
142 changes: 142 additions & 0 deletions spec/services/ai_providers/open_ai_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,146 @@ def stub_chat
}.to raise_error(Coplan::AiProviders::OpenAi::Error, "OpenAI API key not configured")
end
end

shared_examples "bounded provider diagnostics" do |operation, prefix|
let(:mock_client) { instance_double(OpenAI::Client) }
let(:detail) do
{ "error" => { "type" => "invalid_request_error", "code" => "context_length_exceeded",
"message" => "This model supports at most 128000 tokens.",
"request" => { "content" => "private-plan-content", "api_key" => "sk-secret-key" } } }
end
let(:body) { detail }
let(:failure) { Faraday::BadRequestError.new("the server responded with status 400", { status: 400, body: body }) }

before do
allow(OpenAI::Client).to receive(:new).and_return(mock_client)
if operation == :chat
allow(mock_client).to receive(:chat).and_raise(failure)
else
audio = double("audio")
allow(mock_client).to receive(:audio).and_return(audio)
allow(audio).to receive(:transcribe).and_raise(failure)
end
end

def request
if operation == :chat
described_class.call(system_prompt: system_prompt, user_content: user_content)
else
described_class.transcribe(file: double("audio file"), context: "private context")
end
end

let(:operation) { operation }

it "keeps the provider explanation without appending other response fields" do
expect { request }.to raise_error(described_class::Error,
"#{prefix}: the server responded with status 400 (invalid_request_error/context_length_exceeded: This model supports at most 128000 tokens.)") { |error|
expect(error.cause).to equal(failure)
}
end

context "with a JSON body" do
let(:body) { detail.to_json }

it "keeps the same provider explanation" do
expect { request }.to raise_error(described_class::Error,
"#{prefix}: the server responded with status 400 (invalid_request_error/context_length_exceeded: This model supports at most 128000 tokens.)")
end
end

[ nil, "", "<html>Bad gateway</html>", "{broken", "null", "[]", '"error"', [],
{ "error" => nil }, { "error" => [] }, { "error" => {} }, { "error" => " \n " },
{ "error" => { "message" => { "prompt" => "private-plan-content" } } },
{ "error" => { "type" => [ "invalid_request_error" ], "code" => { "secret" => "value" } } },
{ "error" => { "type" => true, "code" => false, "message" => 123 } }
].each_with_index do |malformed_body, index|
context "with an unusable error body (#{index})" do
let(:body) { malformed_body }

it "falls back to the original status without masking the failure" do
expect { request }.to raise_error(described_class::Error, "#{prefix}: the server responded with status 400") { |error|
expect(error.cause).to equal(failure)
}
end
end
end

it "keeps gateway-specific error types, codes and messages" do
detail["error"] = { "type" => "gateway_request_error", "code" => "custom_limit", "message" => "Try a smaller request." }
expect { request }.to raise_error(described_class::Error,
"#{prefix}: the server responded with status 400 (gateway_request_error/custom_limit: Try a smaller request.)")
end

it "keeps a gateway's plain-string error" do
detail["error"] = "prompt too long"
expect { request }.to raise_error(described_class::Error, "#{prefix}: the server responded with status 400 (prompt too long)")
end

it "normalizes whitespace and control characters in every field" do
detail["error"] = { "type" => " gateway\nerror ", "code" => " custom\tlimit ", "message" => " Try\u0000 again. " }
expect { request }.to raise_error(described_class::Error,
"#{prefix}: the server responded with status 400 (gateway error/custom limit: Try again.)")
end

it "handles invalid string encoding in decoded gateway bodies" do
detail["error"] = { "message" => "bad \xFF response".force_encoding("UTF-8") }
expect { request }.to raise_error(described_class::Error,
"#{prefix}: the server responded with status 400 (bad \uFFFD response)")
end

%w[type code message].each do |field|
it "bounds an oversized #{field}" do
detail["error"] = { field => "x" * 10_000 }
expect { request }.to raise_error(described_class::Error,
"#{prefix}: the server responded with status 400 (#{'x' * 297}...)")
end
end

it "bounds the combined diagnostic" do
detail["error"] = { "type" => "t" * 100, "code" => "c" * 100, "message" => "m" * 100 }
expect { request }.to raise_error(described_class::Error) { |error|
suffix = error.message.delete_prefix("#{prefix}: the server responded with status 400")
expect(suffix.length).to eq(303)
expect(suffix).to end_with("...)")
}
end

context "when Faraday cannot parse the gateway response" do
let(:failure) do
connection = Faraday.new do |faraday|
faraday.response :raise_error
faraday.response :json
faraday.adapter :test do |stub|
stub.post("/failure") { [ 502, { "Content-Type" => "application/json" }, "<html>Bad gateway</html>" ] }
end
end
begin
connection.post("/failure")
rescue Faraday::ParsingError => error
error
end
end

it "preserves the parsing failure without raising a formatter error" do
expect(failure.response).to be_a(Faraday::Response)
expect { request }.to raise_error(described_class::Error, "#{prefix}: #{failure.message}") { |error|
expect(error.cause).to equal(failure)
}
end
end

it "handles errors without a response" do
allow(failure).to receive(:response).and_return(nil)
expect { request }.to raise_error(described_class::Error, "#{prefix}: the server responded with status 400")
end
end

describe "chat errors" do
include_examples "bounded provider diagnostics", :chat, "Chat request failed"
end

describe "transcription errors" do
include_examples "bounded provider diagnostics", :transcribe, "Transcription failed"
end
end
Loading