https://www.boundaryml.com logo
🟑 Issues with Passing PDFs in GPT-5 using API
# questions
z
I'm having no luck passing in Pdfs with GPT-5, using either the chat or responses API. Can anyone provide me with a working example??
a
what error do you get? Do you use python or typescript
z
Hey, sorry I got pulled away. But yes, here is my code:
Copy code
// GPT-5 Client 
client<llm> CustomGPT5 {
  provider "openai-responses"
  options {
    model "gpt-5"
    api_key env.OPENAI_API_KEY
  }
}


// baml classes/functions
class SourceDocSummary {
    summary string
}

function SummarizeSourceDoc(doc: pdf) -> SourceDocSummary {
    client CustomGPT5
    prompt #"
        Summarize the following document in few paragraphs (roughly 3-6).  The summary should be as concise as possible while including all pertinent details.

        {{ doc }}

        {{ ctx.output_format }}
    "#
}

test SummarizeSourceDocTest {
    functions [SummarizeSourceDoc]
    args {
        doc {
            file "./test_images/sample_doc.pdf"
        }
    }
}
Copy code
// python usage
def stream_sourcedoc_summary(request, sourcedoc_id: int):
    """Stream a generated summary for a SourceDoc using BAML streaming."""
    sourcedoc = get_object_or_404(SourceDoc, id=sourcedoc_id)
    sd = cast(Any, sourcedoc)

    if not sd.url:
        return HttpResponseBadRequest("No PDF URL available for this SourceDoc")

    def event_stream() -> Iterator[bytes]:
        try:
            pdf = baml_py.Pdf.from_url(sd.url)
            stream = b.stream.SummarizeSourceDoc(pdf)

            begin_streaming = False

            last_len = 0
            for partial in stream:
                # partial is stream_types.SourceDocSummary with optional fields
                if not begin_streaming and partial.summary and not partial.summary.startswith("[json"):
                    begin_streaming = True

                if begin_streaming and partial.summary:
                    current_text = partial.summary
                    if current_text is None:
                        continue
                    if last_len < len(current_text):
                        chunk = current_text[last_len:]
                        last_len = len(current_text)
                        if chunk:
                            yield chunk.encode('utf-8')

            final_response = stream.get_final_response()
            
            if final_response.summary and last_len < len(final_response.summary):
                yield final_response.summary[last_len:].encode('utf-8')
            yield b"\n"
        except Exception as e:
            yield f"[error] {str(e)}\n".encode('utf-8')

    response = StreamingHttpResponse(event_stream(), content_type='text/plain; charset=utf-8')
    return _streaming_headers(response)
When using the OpenAI responses API, I get this response, indicating that either the doc wasn't actually sent in the request or it was in an incorrect place/format and it wasn't able to find it: > Please provide the document (text or images) so I can prepare a 3–6 paragraph, title-focused summary. I will include: Document Type and Sub-Type; Document, Recording, and Effective dates; all named parties with roles (e.g., grantor/grantee, mortgagor/mortgagee, assignor/assignee, lessor/lessee, affiant, trustee, beneficiary); full legal description(s); recording information (instrument number, book/page, county/state); consideration; operative clauses (conveyance language, warranties, reservations/exceptions, easements, releases, subordination, POA authority, survivorship, merger, assignment, assumption, modification, maturity/interest terms, due-on-sale, acceleration, cross-collateralization, trustee substitution, foreclosure notices); referencing prior instruments; exhibits/schedules; notary/acknowledgment; and any atypical provisions or defects (scrivener’s errors, gaps, missing exhibits, improper capacity, corrective/confirmatory language, re-recordings, conflicting parties, estates/trusts authority, homestead/joinder, marital status, death, bankruptcy, liens, UCCs, MERS, HOA/condo matters). If images are provided, ensure all pages (including exhibits) are included and legible.
When using the OpenAI chat API, I get this hard error:
Copy code
[error] BamlClientHttpError(client_name=CustomGPT5, message=Request failed with status code: 400 Bad Request, 
{
  "error": {
    "message": "Invalid value: 'file'. Supported values are: 'text', 'refusal', 'image_url', and 'input_audio'.",
    "type": "invalid_request_error",
    "param": "messages[0].content[1]",
    "code": "invalid_value"
  }
}, status_code=400)
The same exact code works with gemini models, so my guess is that the code isn't the problem? @aaronv (BAML)
a
yeah we'll take a look
z
thanks, really appreciate it!
v
@zooski1099 one thing you can do to test this is see the raw curl in the playground
that may make things a lot easier to debug
(traveling and on my phone, so can't check myself sadly atm)
z
ahhh, thanks for the tip! got it working with the standard openai client... fix was setting the role to user since system only accepts text (duh)
however, it's still not working when using the openai-responses client. not sure what i'm doing wrong. here is the updated function:
Copy code
function SummarizeSourceDoc(doc: pdf) -> SourceDocSummary {
    client CustomGPT5
    prompt #"
        {{ _.role("user") }}

        Summarize the following document in few paragraphs (roughly 3-6).  The summary should be as concise as possible while including all pertinent details.

        {{ doc }}

        {{ ctx.output_format }}
    "#
}
And the curl from the playground:
Copy code
curl -X POST 'https://api.openai.com/v1/responses' -H "authorization: Bearer $OPENAI_API_KEY" -H "content-type: application/json" -d "{
  \"model\": \"gpt-5\",
  \"input\": \"user: Summarize the following document in few paragraphs (roughly 3-6).  The summary should be as concise as possible while including all pertinent details. Answer in JSON using this schema:\n{\n  summary: string,\n}\"
}"
v
what error are you seeing?
so this is what i see,
openai
works, but
openai-responses
doesn't?
z
yep, exactly
when i used a more recent api key it works!
are you doing it on promptfiddle.com? or on your own machine?
promptfiddle.com doesn't yet support gpt-5
z
so to clarify,
openai
is now working and passing in the file correctly. for
openai-responses
, i'm not getting any api errors but it's not sending the file. and the curl reflects that:
Copy code
curl -X POST 'https://api.openai.com/v1/responses' -H "authorization: Bearer $OPENAI_API_KEY" -H "content-type: application/json" -d "{
  \"model\": \"gpt-5\",
  \"input\": \"user: Summarize the following document in few paragraphs (roughly 3-6).  The summary should be as concise as possible while including all pertinent details. Answer in JSON using this schema:\n{\n  summary: string,\n}\"
}"
and you can see my function does in fact include the file (in
doc
):
Copy code
function SummarizeSourceDoc(doc: pdf) -> SourceDocSummary {
    client CustomGPT5
    prompt #"
        {{ _.role("user") }}

        Summarize the following document in few paragraphs (roughly 3-6).  The summary should be as concise as possible while including all pertinent details.

        {{ doc }}

        {{ ctx.output_format }}
    "#
}

test SummarizeSourceDocTest {
    functions [SummarizeSourceDoc]
    args {
        doc {
            file "./test_images/McKenzie Handwritten Mortgage.pdf"
        }
    }
}
v
What version of BAML are you on?
also happy to hop on OH and chat over screenshare if it may be faster!
z
i was on version 0.204.0, but just upgraded to 0.205.0 and seeing the same thing for both
OH? (I feel like i'm about to have egg running down my face just asking)
v
office hours channel πŸ₯²
z
haha, gotcha
ok, let's try