A Local 27B Model Builds a 5,816-Entity Knowledge Graph from a 120-Chapter Classic
Currently working on DocFlow, a full-stack hands-on project that combines Agent, RAG, and knowledge graphs. Tested to support 100-person real-time collaboration, with Word (DOCX) and PDF import; the Agent can retrieve material, rewrite documents, and manipulate tables. Behind it sits a main Agent that coordinates, sub-Agents that verify in parallel and double-check results, along with automatic context compression, long/short-term memory, and task recovery. RAG covers parent-child chunking, BM25 + vector hybrid retrieval, RRF fusion, reranking, and original text citation tracing. Suitable for those who want to dig into source code and build AI applications hands-on.
Also compiled 80 Agent development articles, 72 RAG articles, and 70 knowledge graph articles, 222 in total, from fundamentals to engineering practice. Pair them with the source code to learn by doing. Add me on WeChat yunmz777 to learn more about the project and accompanying materials and discuss AI development together.
On a MacBook Pro with an M5 Pro and 48 GB unified memory, we ran a knowledge graph for all 120 chapters of Dream of the Red Chamber locally. The original text came from Project Gutenberg ebook #24264. A local processing script called Ollama, and the resulting graph was published to the DocFlow desktop client. From import to publication took about 12 hours 27 minutes.
The actual UI showed 5,816 entities and 5,165 relations, filterable by type such as characters, places, or events, and searchable by name from the left panel. The published archive also recorded 1,951 attributes and 10,145 source-text evidence passages that had passed location checks.
We wanted to test a retrieval path with this classic: first connect facts scattered across chapters, let the Agent find material along relations, then return to the source text with citations. Jia Baoyu and Zhen Baoyu were a test point: their names are close, and if the graph building merged them into the same node, queries could mix their life stories into a single answer.
How a knowledge graph records a fact with provenance
Chapter 23 describes the characters moving into Grand View Garden, including "Xue Baochai lived at Heng Wu Yuan, Lin Daiyu lived at Xiao Xiang Guan". Turning this passage into a graph yields two relations pointing to the respective residences; the same passage is later used to test the local model.
| Start entity | Relation | Target entity | Source evidence |
|---|---|---|---|
| Xue Baochai | resides in | Heng Wu Yuan | Xue Baochai lived at Heng Wu Yuan |
| Lin Daiyu | resides in | Xiao Xiang Guan | Lin Daiyu lived at Xiao Xiang Guan |
Each row's first three columns form a directed triple, pointing from person to residence. A person's age and other details can be stored as entity attributes, while the residence relation keeps both the Chapter 23 provenance and the exact sentence. When you find that Lin Daiyu lived in Xiao Xiang Guan, you can read back the account of moving into the garden to confirm which arrangement this relation corresponds to.
From chapter text to a traceable graph
In Dream of the Red Chamber, the same person has multiple names, and different people may share one name. Add to that the mixture of narration, speculation, and real account, so every model result needs to be checked against the source text. We split the process into three phases so each candidate relation has a bounded text range to check before entering the graph.
- Segment the text by chapter. The local
Qwen3.8-27Bextracts characters, places, events, relations, and attributes from fragments, while retaining the source text evidence for each candidate fact. For formal requests, thinking mode is off, context is configured at 32K, and the prompt plus model output must leave room when segmenting. - Review candidates and evidence. Check both parties' identity, relation direction, and whether the text supports the conclusion. Two names appearing together only means they are mentioned in the same passage. When conflicts arise, return to the relevant chapter; fix what can be corrected and leave cases with insufficient support as pending.
- Align identities across chapters. Merge records of the same person that have sufficient evidence, and keep separate records for still-ambiguous people. After publication, you can find the corresponding evidence from an entity or relation and trace back to the chapter.
During acceptance testing, we checked the identity and provenance of Jia Baoyu and Zhen Baoyu separately. In the formal archive, the two have separate records, and chapters 114 and 115 retain evidence useful for telling them apart. We also looked up the residence relation between Li Wan and Daoxiang Village in the desktop client, and the relation's provenance locates to Chapter 23.
Tracing from graph to source text reveals identity confusion, wrong relation direction, and misattributed evidence; tracing from source text to graph reveals important facts that were missed. The numbers at the top record processing and publication scale; a full-accuracy assessment of the graph still needs source samples covering different chapters, relation types, and entity categories.
How text retrieval and graph queries cooperate
Text RAG uses keyword, vector, or hybrid retrieval to find relevant fragments from the book, good for finding exact dialogue lines and surrounding plot. Graph queries first pin down an entity, then follow relations to find related people, places, and events, good for chasing threads scattered across chapters. Microsoft's GraphRAG local query places structured graph data and associated source text together into the model's query context.
For example, to find where Heng Wu Lord lives, first follow the alias to Xue Baochai, then follow the residence relation to Heng Wu Yuan. In Chapter 37, when the Crab Apple Poetry Society was formed, Li Wan gave Xue Baochai the alias Heng Wu Lord; Chapter 23 records Xue Baochai moving into Heng Wu Yuan. The two passages each support the person's identity and residence. Text retrieval can also search the two clues separately, then combine the evidence.
To decide whether a graph is worth adding, use the same batch of cross-chapter questions to compare both retrieval flows: check whether evidence is missed, whether a person is misidentified, whether provenance can be located, and log query latency and graph construction/maintenance costs.
Choosing a model that runs locally
Formal graph construction and the deployment re-test below both used qwen3.8:27b-mlx. The local model package is about 18 GB, with weights primarily in NVFP4 quantization. The raw 27B model, estimated at 2 bytes per parameter, would need about 54 GB of BF16 weights; just the weights already exceed this machine's unified memory. The quantized model still needs room for the system, context cache, and runtime compute, so actual memory usage should be measured at the target context and concurrency settings.
Context is easy to underestimate. Taking the model's 16 full-attention layers, 4 KV heads per layer, and head dimension 256, assume 2 bytes per cache element for a single request; at a full 32,768 tokens, this KV cache alone is about 2 GiB. The remaining hybrid-attention state, cache precision, runtime backend, and concurrency also affect actual usage, so we first test a single request, then increase context gradually.
| Device condition | Where to start trying |
|---|---|
| 8–12 GB unified memory | Use qwen3.5:2b to verify the API and extraction format |
| 16–24 GB unified memory | Start with qwen3.5:4b, then try 9B quantized if there is headroom |
| 32–48 GB unified memory | Try qwen3.8:27b-mlx on Apple Silicon, start with 4K and single request, then increase context |
| Windows or Linux discrete GPU | 24 GB VRAM can run qwen3.8:27b-q4_K_M single request with short context |
The table lists starting points for model selection; this full run used 48 GB unified memory and a 32K request configuration. When changing models, first compare missed extraction, wrong extraction, and evidence location using the same chapter, then look at speed and memory headroom.
Confirm which port Ollama is listening on
After installing and starting Ollama on a Mac, check the default port. The three commands below respectively check the listening process, the Ollama API on the port, and the already-downloaded models. If searching the default port returns nothing, use lsof -nP -a -c ollama -iTCP -sTCP:LISTEN to list listeners, then confirm one by one with the version API. If the service has OLLAMA_HOST set, point subsequent requests to the actual address.
lsof -nP -iTCP:11434 -sTCP:LISTEN
curl -fsS http://127.0.0.1:11434/api/version
OLLAMA_HOST=127.0.0.1:11434 ollama list
On this Mac, lsof's LISTEN pointed to 127.0.0.1:11434, and /api/version at the same address returned 0.40.16. ollama list showed qwen3.8:27b-mlx, meaning the model package was installed; whether it is loaded requires further checking.
If the tag is missing from the list, you can also point the pull command explicitly at the service you just verified.
OLLAMA_HOST=127.0.0.1:11434 ollama pull qwen3.8:27b-mlx
On Windows, run Get-NetTCPConnection -State Listen -LocalPort 11434 in PowerShell, then use curl.exe to check the version. On Linux, use ss -ltnp 'sport = :11434' to inspect listeners, and change the model name in inference requests to a tag downloaded on that machine.
Send requests to the same port and verify the model
Port 11434 is where Ollama serves applications. The same port accepts requests for different models, selected by the model field in the request body. This formal build used http://127.0.0.1:11434/api/chat with qwen3.8:27b-mlx. To confirm the app uses the same service and model, check both values in the configuration and request logs.
Save the request body below as UTF-8 encoded request.json. To check actual runtime state, this re-test uses the same passage from Chapter 23, keeping the formal build's num_ctx: 32768. For a first run or a tighter memory machine, fill in 4096 first.
{
"model": "qwen3.8:27b-mlx",
"messages": [{
"role": "user",
"content": "从《红楼梦》原文提取居住关系,返回 JSON 对象,包含 entities 字符串数组和 relations 对象数组。每条关系提供 subject、predicate、object、evidence,主体是人物,客体是住处,predicate 固定为 居住于。实体名称沿用原文字形,evidence 逐字摘自原文。原文:薛寶釵住了蘅蕪苑,林黛玉住了瀟湘館"
}],
"format": "json",
"stream": false,
"think": false,
"keep_alive": "2m",
"options": {"temperature": 0, "num_ctx": 32768}
}
Send the request from the directory containing the file, then inspect the model name and completion status in the response, and parse the relations in message.content. Below, jq displays the result; if you don't have it, just inspect response.json directly.
base=http://127.0.0.1:11434
curl -fsS "$base/api/chat" --json @request.json -o response.json
jq '{model, done}' response.json
jq -c '.message.content | fromjson | .relations[]' response.json
The response shows model as qwen3.8:27b-mlx, done as true, and the two residence relations point Xue Baochai to Heng Wu Yuan and Lin Daiyu to Xiao Xiang Guan, with evidence verbatim found in the input fragment from Chapter 23.
When integrating an app, JSON Schema can further constrain fields, but whether a relation holds still needs to be checked against the source text, especially for mismatches among subject, object, and the evidence fragment.
In Windows PowerShell, the same request can be sent with curl.exe -fsS http://127.0.0.1:11434/api/chat --json "@request.json" -o response.json.
Check whether the model is loaded and the actual context
Immediately after the request, run ollama ps, or query /api/ps on the same port. The short-request example set keep_alive: "2m", so you can see the model state before it unloads.
OLLAMA_HOST=127.0.0.1:11434 ollama ps
curl -fsS http://127.0.0.1:11434/api/ps | jq '.models[] | {name, context_length}'
Under the same configuration, ollama ps shows RUNNER as mlx and CONTEXT as 32768; /api/ps on the same port returns the same model name and context length. PROCESSOR shows 100% GPU, meaning the model is fully on the GPU; actual utilization needs separate measurement.
If ollama list has a model but ollama ps doesn't, send a request first, then check while the model is still in memory. If you changed num_ctx and still see an old value, wait for the current instance to idle unload, then send a request under the new setting. After a short request passes, pick one chapter to check person identities, relations, and provenance, then expand the scope.
How much time and how many tokens the whole book took
The published archive records 806 successful model calls, including extraction and review; debugging, replay, and later Agent/Q&A are counted separately.
| Stage | Successful calls | Input tokens | Output tokens |
|---|---|---|---|
| Extraction | 597 | 2,154,294 | 1,288,659 |
| Review | 209 | 825,930 | 244,404 |
| Total | 806 | 2,980,224 | 1,533,063 |
The ~12 hours 27 minutes is actual elapsed time from import to publication, including all graph-building workflow stages; it cannot be used directly to compute model generation speed. To estimate how much time a different machine or model would save, fix one chapter, extraction rules, and context, and record model-call and post-processing time separately.
To convert the same input/output token counts into cloud costs, estimate with deepseek-flash RMB prices as of November 23, 2026, assuming all input cache misses. Beijing time Monday-Friday 9:00-12:00 and 14:00-18:00 are peak, Chinese statutory holidays are excluded, and requests crossing time windows are billed per their respective window.
| Time window | Per 1M input tokens | Per 1M output tokens | Estimated for this usage |
|---|---|---|---|
| Idle | ¥1 | ¥4 | ¥9.11 |
| Peak | ¥2 | ¥8 | ¥18.22 |
After switching to a real service, tokenization, output length, cache hit rate, and retries can all change, and extraction quality must be re-verified on the same text. We chose local to hand the graph-building source text to a model on our own machine; adjusting rules afterward lets us re-run directly. The tradeoff is local compute usage and batch-processing time.
Summary
From a short sentence to 120 chapters, acceptance criteria must scale with the task. For short sentences, first check service address, model tag, runtime config, and structured output; for a whole chapter, check missed extraction, names that collide across people, and whether evidence can be located; only then run at batch scale. The published graph gives the Agent cross-document relation clues, while the source text remains the basis for judging whether each conclusion holds.