跳到正文
DEV Community· cv-by-jd.com·· 52 分鐘前AI 評分64

選擇 LLM 框架:CV by JD 團隊為何從 BAML 轉用 LangChain 和 LangGraph,以及兩項會悄悄丟失資料的預設行為

Choosing an LLM framework: why we left BAML for LangChain, and two defaults that silently dropped our output

AI 導讀

CV by JD 團隊因每次請求需要支援多個模型、驗證輸出及在失敗後回退,從 BAML 轉用 LangChain 的聊天模型類別與 LangGraph 的 StateGraph,並只採用所需部分。

正文

Picking an LLM framework usually starts with "which one has the nicest API". We learned to start with a different question: what does your request actually need to do between the user's click and the answer? This post covers how that question moved us from BAML to LangChain and LangGraph, how we chose, and two framework defaults that silently dropped output once we'd switched.

The situation

I'm the founder of CV by JD. You upload your resume, paste a job description, and chat with an assistant that rewrites the resume for that job.

Every chat turn returns one structured response. It includes the assistant's reply, a flag saying whether the resume changed, the full rewritten resume as Markdown, and a few other fields. Simplified, a good response looks like this:

{
  "reply": "I've tailored your summary and two bullets to the role.",
  "resume_updates": { "has_updates": true },
  "output_resume_markdown": "# Jane Doe\n## Summary\n..."
}

The resume field is the biggest part of every response. Often it's several thousand tokens.

Here's where the framework sits. Everything in the middle box runs on our server for every chat message:

 User's message
       │
       ▼
 ┌───────────────────────────────────────────────────────┐
 │ Our server                                            │
 │   build the prompt ─▶ call a model ─▶ check the answer │
 │                          ▲                  │         │
 │                          └── try the next ◀─┘ bad?    │
 │                              model                    │
 └───────────────────────────────────────────────────────┘
       │
       ▼
 Reply + updated resume shown to the user

An LLM framework is the library that handles the boxes in the middle: talking to the model providers, shaping prompts, parsing answers and, in some frameworks, the loop itself.

How we got here

We started on BAML, a tool for writing LLM prompts and their expected output types in its own small language. With BAML you describe each LLM function and its output types in BAML's own language, and a code generator produces a typed TypeScript client. For "one prompt in, one typed object out", it's very pleasant. The types flow all the way through and parsing is handled for you.

As the product grew, each request started needing more than one prompt in and one object out:

  • Several providers. We wanted an ordered list of backup models: if the first fails or returns something unusable, try the next, ideally from a different provider. At the time that meant four models from four providers, including Google's Gemini and OpenAI.
  • A loop, not a call. A real chat turn became: call a model, check the output, and if it's bad, try the next model in the chain with a note on why the first one failed.
  • A build step for every prompt change. Each edit meant regenerating the client, and the generator had to run in CI and in our deploy too.

The loop (call a model, check the answer, try the next model if it's bad) was the deciding point. It's the core of every request, and it lived outside the framework, in our own code, wrapped around BAML.

The problem

Every change added more friction. Each new provider in the list meant more wrapper code around the generated client. Each new check on the output had to be written in our own code, outside the framework that was supposed to handle the request. And the code-generation step had to run in CI and in every deploy, one more thing that could break a release.

None of this was an outage. But the fallback chain and the output checks were exactly what we planned to build next, and each one would make the workarounds worse.

What we researched

We wrote down what our LLM layer actually had to do, in order:

  1. Build the prompt and context for this turn.
  2. Call a model, through any of several providers.
  3. Validate the response (required fields present, the resume not empty when it says it changed).
  4. On failure, move to the next model with a note about what went wrong.
  5. If every model fails, return a safe fixed response.
  6. Record what happened at each step.

Then we looked at the realistic ways to build that.

The options we found

Option Good Bad
Stay on BAML and keep the loop in our own code No migration The workarounds stay, and so does the generate step
Provider SDKs directly, with our own loop Nothing between us and the HTTP request We'd write and maintain glue code for every provider
Vercel AI SDK Clean API, good streaming support Our core need was an explicit, testable loop with several steps and branches, and we'd still be writing that loop ourselves
LangChain chat models plus LangGraph One model class works with any OpenAI-compatible endpoint. LangGraph makes the loop an explicit graph. A big framework, with a reputation for too much abstraction

What we chose, and why

We chose LangChain and LangGraph, but only a small slice of them.

From LangChain we use the chat model classes. Most providers copy OpenAI's API format, so ChatOpenAI, pointed at a different baseURL, covers most of them. We call each position in our list of backup models a tier, and a small factory function builds a model object from a tier's settings (model name, URL, API key).

From LangGraph we use StateGraph to make the loop explicit. LangGraph lets you write a workflow as a graph: each node is a function, and the edges say which node runs next, including looping back. Ours has five nodes: build context, call the model, validate, move to the next model, and return a safe fallback. Each node is a plain async function that takes the current state and returns an update, so we can unit-test every step without calling a model.

We don't use chains, agents, retrievers, memory classes or output parsers. Those add layers we didn't need. We only wanted help with the loop.

That's why LangChain and LangGraph beat the other options for us: the graph matches the shape of our request, and the model classes remove most of the provider glue. If our request were a single call to a single provider, I'd have used that provider's SDK directly.

The first default that lost data: structured output

Shortly after the move, error reports started showing turns like this one:

Assistant: I've updated your resume for this role.
Resume panel: (empty)

The model had returned a full resume. LangChain's structured-output helper handed it to us empty.

LangChain's withStructuredOutput(schema) is the obvious way to get typed JSON from a model. One model in our chain at the time was Gemini, and on Gemini this helper uses constrained decoding: the provider forces every generated token to fit your JSON schema as it writes. With our schema, the big resume field sometimes came back empty while has_updates said true. A z.union type elsewhere in the schema also broke Gemini's schema converter.

We looked at three ways to fix it:

Option Problem
Simplify the schema until constrained decoding behaves Behaviour still depends on each provider's implementation
Use tool calling to return the structure Same big field, same kind of risk, and different behaviour per provider
Ask for plain JSON mode and validate it ourselves We have to handle messy JSON, but we see and control everything

We chose the third option, which is close to how our BAML setup had parsed responses before the switch:

const raw = await model.invoke(messages, {
  response_format: { type: 'json_object' },
});
const text = raw.text; // .text returns only the answer, not any reasoning blocks

const stripped = text
  .replace(/^```

(?:json)?\s*\n?/i, '')
  .replace(/\n?

```\s*$/i, '');
const parsed = ResponseSchema.parse(JSON.parse(jsonrepair(stripped)));

jsonrepair fixes trailing commas, single quotes and other small mistakes models make. If the text has prose around the JSON, we pull out the first {...} block and try again. Zod still checks the shape, so we kept full type safety, without depending on each provider's constrained decoding.

The second default that lost data: options that never reached the request

OpenRouter, a service that gives you one API for many models, accepts request fields that OpenAI's API doesn't. One is reasoning, which limits how many tokens a model spends thinking before it answers. We passed reasoning as a call option and nothing happened. There was no error and no warning. The field simply never reached the request body.

ChatOpenAI only forwards fields it knows about. Anything else has to go through modelKwargs, which is merged into the request body unchanged:

modelKwargs: {
  reasoning: { enabled: true, max_tokens: 2048 },
  provider: { order: ['deepinfra/fp8', 'deepseek'], allow_fallbacks: true },
},

The provider field tells OpenRouter which hosting companies to prefer for this model. That's what made prompt caching work for us, as the OpenRouter post in this series explains. This behaviour can differ between versions of @langchain/openai, so check yours.

What you can take from this

  • Choose a framework by the shape of your request, not by its API. Write down the steps between the click and the answer, and pick the tool that matches them.
  • Use the smallest slice that helps. We use two pieces of LangChain, and that's been enough.
  • Be careful with structured-output helpers when you have a large free-text field. Their behaviour depends on the provider underneath, and big fields are where they fail first.
  • Look at the outgoing request body at least once. A framework can drop an option without telling you.
  • Keep validation in your own code, so a provider or framework change can't quietly change what "valid" means.

What's the smallest slice of LangChain you've found worth keeping? I suspect a lot of teams have landed somewhere similar.

來源:DEV Community · dev.to