https://www.boundaryml.com logo
🟡 Python PDF Extraction Code Sample Request
# questions
d
hi, Can someone please provide a sample code for extracting data from PDF file ? I am not sure how to create a BAML file for PDF extraction and get the resultant output as json. I am using Python. Thanks in advance.
v
hey @deepu_07113! You can just use a
pdf
type!
d
hi @Vaibhav (BAML 🐑) it didnt work for me. Here is my baml file for pdf extraction.
> // This function jumps straight into generating the graph from a pdf input (like pdf page). > function PDFExtractorGraph(pf: pdf) -> CytoscapeJSON { > client OllamaLlama3 > prompt #" > You're an expert at graph data analytics and visualizations. > Create a graph visualization of all important nodes and relationships (edges) for the given input. > > {{ ctx.output_format}} > > INPUT: > {{ input }}` > "# > }
here is my python code for calling the baml-client
> pathurl = pathlib.Path(path).as_uri() > pdf_content = Pdf.from_url(pathurl)
> res1 = b.PDFExtractorGraph(pdf_content)
path is where i am passing the pdf file
v
ah! pdfs need to be sent as base64!
urls need to be publically resolveable URLs as model providers require that
d
hi @Vaibhav (BAML 🐑) thank you. So if i understand it correctly, i need to (1) convert the pdf into base64 using a python function and then pass it to the function as below right?
v
yep!
d
base64_bytes = ase64.b64encode(pdf_bytes) base64_string = base64_bytes.decode('utf-8')
base64in = Pdf.from_base64(base64_string ) res1 = b.PDFExtractorGraph(base64in)
i still need to pass base64 to Pdf.from_base64() and use this to pass to b.PDFExtractorGraph(base64in)
can you please verify and confirm above @Vaibhav (BAML 🐑)
v
yep!
d
hi @Vaibhav (BAML 🐑) sorry but i couldn't make it to work. I am sharing my code here for your reference and request if you could take a look and let me know what is going wrong. I always get an empty json as output
Also i am attaching the pdf screenshot here from which i am trying to get the values
v
Can you share the pdf as well?
d
hi @Vaibhav (BAML 🐑) as it is a company material, i am not in a position to share the actual pdf 🙁
v
got it, let me send you some example repo as well
d
sure
you're using the
input
variable in your prompt. but only
mypdf
exists.
have you tried the vscode playground yet?
that will likely help you debug this stuff much faster
d
oh thank you!, let me try. Also will try vscode and check
btw @Vaibhav (BAML 🐑) after making the chage (mypdf), i got a new error
Copy code
---REQUEST OPTIONS---
    model: "llama3"
    ---ERROR (Unspecified error code: 400)---
    Request failed with status code: 400 Bad Request. {"error":{"message":"invalid message format","type":"invalid_request_error","param":null,"code":null}}
Traceback (most recent call last):
  File "C:\baml\baml-neo4j\src\01_Extract_Market_Highlights.py", line 32, in <module>
    extract_pdf_content(filepath)
  File "C:\baml\baml-neo4j\src\01_Extract_Market_Highlights.py", line 26, in extract_pdf_content
    res1 = b.ExtractMarketHighlightsInfo(base64in)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\baml\baml-neo4j\src\baml_client\sync_client.py", line 135, in ExtractMarketHighlightsInfo
    return typing.cast(types.MarketHighlightsInfo, result.cast_to(types, types, stream_types, False, __runtime__))
                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
baml_py.internal_monkeypatch.BamlClientHttpError: BamlClientHttpError(client_name=OllamaLlama3, message=Request failed with status code: 400 Bad Request. {"error":{"message":"invalid message format","type":"invalid_request_error","param":null,"code":null}}, status_code=400, detailed_message=LLM client "OllamaLlama3" failed with status code: Unspecified error code: 400
Message: Request failed with status code: 400 Bad Request. {"error":{"message":"invalid message format","type":"invalid_request_error","param":null,"code":null}})
v
yep, are you sure the ollam llama3 model accepts pdfs?
d
hmm not sure.
v
most things (aside from the major llm providers) sadly don't support native PDF
and require you to convert PDF -> image
we sadly haven't yet gotten around to doing that within baml yet natively for you 🙁
d
oh ok. Thanks for letting me know this. Any good python framework that can convert pdf to image?
v
https://github.com/ai-that-works/ai-that-works/blob/8efd8cc86dd190da109e68a7016662896b3adbcb/2025-09-30-dyanmic-schemas/backend/server.py#L161
Copy code
python
from pdf2image import convert_from_bytes
from PIL import Image as PILImage
from baml_py import Image

def convert_to_base64(img: PILImage):
    buffered = io.BytesIO()
    img.save(buffered, format="JPEG")
    return Image.from_base64(base64=base64.b64encode(buffered.getvalue()).decode("utf-8"), media_type="image/jpeg")


file_content = await file.read()
images = convert_from_bytes(file_content)
baml_images = [convert_to_base64(img) for img in images]
then you can pass in an array of
image[]
instead of
pdf
type into your function
d
thank you very much!
v
good luck 🙂
and thanks for trying baml
d
its a fantastic framework @Vaibhav (BAML 🐑)
v
any favorite parts?
or what made you try it in the first place
(even with all this pdf headache 😂 )
d
actually i was exploring the option of building a graphRAG quickly and came across the option of using BAML + Kuzu for building a quick prototype
and the simplicity of it ( explaining using different llm models for different tasks) and determinism is what made me feel attractive
i heard your video that you are coming up with agentic approach. looking forward to it
d
currently tried langchain/langgraph based agent and using MCP for some of the POC i am doing but agentic approach in baml is something that i am keen to try
v
(of course backed by real code ^^)
d
hi @Vaibhav (BAML 🐑) pdf conversion to image and extracting from image works! Just a note here- it is not able to extract correct values with open source llm-llama3 and i had to use GPT-4o
v
Amazing!
You def will need to do more schema engineering and image processing to use open source models compared to the smarter 4o model