
Summary
Key points of this document
- The difficulty of continuously collecting public data from thousands of sites in a consistent manner.
- Focus on static HTML/PDF and define collection etiquette upfront.
- Technology Stack
Overview
When creating a system to continuously collect and utilize standardized public information, such as public notices and meeting minutes, from local government websites nationwide, the first hurdle is not AI accuracy. It's the varying DOM structures, character encodings, update frequencies across sites, and the boundary of "how much can AI be allowed to configure?" Here, we will organize the design that separates AI-assisted configuration generation from non-AI deterministic execution, which was adopted to stably run thousands of site collections daily, along with the reasons for the decisions and the trade-offs involved.
The difficulty of continuously collecting public data from thousands of sites in a consistent manner.
Each local government has its own independent website, with varying CMS products, update frequencies, and page structures. One local government might display a list of public notices in a table, another might only list links to PDFs, and yet another might build pages with JavaScript. Writing collection rules manually for each site, while feasible for dozens of sites, breaks down the moment it scales nationwide.
On the other hand, a design where AI makes all collection rule decisions on the fly is also unsustainable. LLMs produce inconsistent outputs even with the same input, and they are costly. If page structure interpretation is left to AI for every daily crawl, items that were retrieved one day might not be retrieved the next, leading to a lack of reproducibility and making downstream processes (notifications, dashboards) that use that information unreliable.
The subject of this discussion is a collection pipeline that gathers standardized public information, such as public notices and meeting minutes, from local government websites nationwide, and makes it searchable and subscribable for those who need it. We will not touch upon individual local government names or user organizations, but only discuss the collection design and the criteria for how and to what extent AI is used.
Focus on static HTML/PDF and define collection etiquette upfront.
As a starting point for the design, we limited the scope to static HTML and PDFs. SPA sites that require JavaScript execution are excluded. While technically possible with headless browsers, the high startup cost and failure rate are not viable for stable daily operation at the scale of thousands of sites. We prioritized covering the majority of content with static pages, excluding JS-dependent sites from the initial scope.
Collection etiquette was also fixed upfront as a design prerequisite, not an implementation detail. This includesrobots.txt respecting each site's robots.txt, spacing out requests to the same host, and executing collections during off-peak hours (late night to early morning). In many cases, the target is an official local government website not designed for large-scale access, and we treated it as a technical requirement not to burden their services for the sake of our collection.
Another prerequisite is the nature of the collected information. Public notices and meeting minutes issued by public institutions often fall outside the scope of copyright protection under Japanese copyright law, as they are mere factual reports or legal provisions/notifications. However, "not protected" does not mean "anything goes." We incorporated the mandatory inclusion of the source (local government name and a link to the original URL) not only as a legal consideration but also as a design requirement to ensure information reliability.
- Only static HTML/PDFs are targeted. JS-dependent sites are excluded from the initial scope.
- Adherence to robots.txt, spacing out access to the same host, and execution during late-night hours are fixed as collection etiquette.
- The inclusion of the source (sender name and original URL) is treated as both a legal and quality requirement.
Technology Stack
The collection and analysis infrastructure is standardized on TypeScript/Bun, with Hono as the API framework and Drizzle ORM building the schema on PostgreSQL. HTML parsing uses cheerio, PDF text extraction uses a dedicated parser library, and iconv-lite is adopted for decoding legacy Japanese character encodings. pgvector is used for approximate nearest neighbor search of embedded vectors, which is applied for pre-filtering collected text by similarity.
AI is used in only two places. One is to assist in generating the collection settings themselves (described later), and the other is for structured review to determine if the collected text is of interest to the user. In both cases, we design the system to always include mechanical checks, such as schema validation and dry-run execution, rather than blindly trusting the output of generative AI.
AI is placed on the configuration creation side and excluded from the execution system.
The core decision in this design is the boundary: "AI is allowed to generate collection settings, but AI is not allowed to intervene in the daily collection execution itself." Collection settings are defined as a declarative schema (an object type-validated with zod, etc.) consisting only of CSS selectors, regular expressions, and dictionary mappings. The execution engine was made into deterministic code that merely interprets these settings.
Without this separation, the page structure would be passed to the LLM for inference of extraction methods with each daily execution. While this might seem flexible, it actually leads to inexplicable fluctuations like "it worked correctly today but not yesterday," along with increased costs proportional to thousands of sites multiplied by daily calls. By separating setting generation and execution, the execution system becomes fully reproducible, and costs are incurred only "when new settings are created."
The idea of limiting AI's role to that of a "proposer" is a repeatedly effective way to draw boundaries when entrusting AI with processes that cannot be definitively verified, not just for collection pipelines. AI output is always reflected in the execution system only after it has either been approved by a human or passed mechanical verification (dry run, schema validation).
Separate templates and individual site differences into two layers to enable change tracking.
Collection settings have a two-layer structure: shared templates and individual site differences (overrides). Since many local government websites use one of a few CMS products, by preparing common templates per CMS unit and layout pattern, and only having site-specific differences as override settings, the cost of creating settings for sites with similar structures can be significantly reduced.
Settings are managed not by overwriting but by appending (revisions), leaving past revisions accessible. This is so that if collection results change from a certain day, it can later be determined whether the cause was a layout change on the site or a setting change. A collection infrastructure that does not retain a history of setting changes will have to rely on speculation to determine "when" and "why" something broke every time a fault is investigated.
- Two-layer structure: shared templates (CMS/layout unit presets) + individual site overrides.
- Settings are managed with append-only revisions, not overwrites, making past settings accessible.
For character encoding detection, abandon assumptions and use multi-stage fallback.
A certain number of local government websites are still delivered with legacy Japanese character encodings like Shift_JIS and EUC-JP, not just UTF-8. Initially, we designed with the premise that the standard string decoding mechanism of the execution environment would be sufficient, but these legacy encodings were not supported by the standard mechanism, and the problem manifested as garbled characters.
Ultimately, we prioritized the charset specification in the HTTP response header, then peeked into<meta charset> the HTML if that was absent, and if still undetectable, fell back to UTF-8. We settled on a configuration that inserts a dedicated library (iconv-lite) for decoding legacy encodings. The premise that "there's nothing but UTF-8 these days" does not hold true when dealing with public websites on a national scale.
This type of pitfall does not surface while testing with a small number of sites. It's a common risk across all collection infrastructures that it goes unnoticed during a pilot phase with a limited number of target sites and only becomes apparent when the collection scope is expanded. It's important to assume that exceptions are more likely to manifest in "mature" areas like character encoding when the target population becomes large.
AI-assisted setting generation prevents hallucinations and runaway behavior in three stages.
Manually writing collection settings for a new site from scratch is time-consuming, so we have a mechanism to support setting generation with AI. However, allowing AI to freely read pages and create settings carries the risk of generating non-existent URLs or selectors (hallucinating). Therefore, the generation process is divided into three stages, with mechanical guardrails at each stage.
In the first stage, we crawl the top page of the target site, pre-filter link candidates by keywords, and then have the LLM select URLs that are likely to be "lists of announcements or minutes" from those candidates. The important point here is to have the LLM choose from existing links, rather than generating new URLs. This alone prevents the typical failure of incorporating non-existent paths into the settings.
In the second stage, instead of passing the DOM structure of the target page directly to the LLM, we convert it into skeletal information by retaining only class names and tag structures and thinning out the text before passing it. This is partly to reduce token consumption, but more importantly, it aims to have the LLM propose selectors by looking only at structural patterns, without being swayed by noise in the main text. The content proposed here is assembled as a schema-validated declarative configuration object.
In the third stage, we immediately perform a dry run (actual extraction) using the generated settings, and only retain those that successfully extracted items as "proposals." Settings that fail to extract are discarded and not even presented to humans. Furthermore, the generated settings are not automatically deployed to production; by default, they go through an approval flow and are activated only after human confirmation.
- Step 1: Select candidate pages only from existing links to prevent URL hallucinations.
- Step 2: Pass only the DOM skeleton to save tokens and generate selectors that are not influenced by noise.
- Step 3: Perform dry run validation immediately after generation, and only retain settings that successfully extract data as proposals.
- Automatic application is off by default and is enabled only after human approval.
Gradually expand the collection scope with regional gates.
If nationwide collection is enabled all at once from the beginning, unexpected failures or heavier-than-expected loads can occur simultaneously, making it difficult to pinpoint the cause. Therefore, we have prepared a global allowlist that restricts daily collection targets to only "regions where collection is permitted," and we gradually expand the scope each time a new region is enabled.
This gate is not a performance bottleneck but an intentional safety valve. Its purpose is to allow the scope to be expanded while monitoring the quality of settings and failure rates. Regions outside this gate are not included in the collection target for the default daily schedule. We have introduced an asymmetry where only manual explicit triggers can temporarily bypass this gate.
Cost limits are enforced by reservations before invocation.
For features involving AI calls (setting generation support and content review), we have established a two-tiered quota: a daily limit per tenant and a daily limit for the entire system. Neither alone can prevent a specific tenant from exhaustively using up resources or prevent overall budget overruns, so we configured it to check both independently.
Quota determination is not done by aggregating actual costs after the call and then restricting; instead, it's a pre-reservation system where the "amount to be used" is provisionally secured before the call, and if it cannot be secured, the execution is not performed. Restricting after use often leads to a situation where "you realize you've exceeded the limit when it's too late," so a design that reserves the quota beforehand is safer operationally.
Refine collected text with embedding similarity search and structured AI review.
Having the LLM review the full text of all collected minutes and announcements every time is inefficient in terms of both cost and accuracy. Therefore, we employ a two-step approach: first, we pre-filter "candidates that are close to topics of interest" using similarity search with vector embeddings, and then only those candidates are subjected to the LLM's structured output review.
Generating embeddings itself is also costly, so instead of pre-generating them all at once for all regions and tenants, we designed it to generate them on demand only when a tenant selects that region for analysis. This is based on the idea of not pre-investing in data that may or may not be used.
Japanese administrative documents often mix dates written in the Japanese calendar (Reiwa, Heisei, Showa, etc.). Therefore, before processing the collected text, we insert a step to normalize date notations, including Japanese calendar dates, into a unified format. Locale-specific notation variations are subtle within the collection infrastructure, but if overlooked, they can quietly break downstream sorting and filtering.
Internal operational functions are separated into a location invisible to tenants.
Operational functions, such as approving collection settings and adjusting cost limits, are separated into an application exclusively for internal operators, distinct from the application for general users. Rather than simply hiding menus on the screen, we make them invisible from the configuration level by not registering them in the tenant's application list in the first place.
If permission checks rely solely on conditional branching for screen display, there remains a risk that operational functions could become visible to unintended users due to a single implementation error. Separating the application itself and placing it out of sight of users from the outset as a system component is more robust, as it prevents accidents from occurring.
Verification points: dry run, approval flow, gradual expansion
Unit tests alone are insufficient for verifying this infrastructure. Daily verification points include dry run verification to check if generated collection settings can correctly extract items from actual sites, confirmation that unapproved settings do not get mixed into production daily collections, and monitoring to ensure that failure rates do not spike immediately after expanding regional gates.
When enabling a new region, we thoroughly check collection results for several days while the number of target sites is small, confirm that there are no missing extractions or garbled characters, and then expand the scope. Expanding gradually with small checks is ultimately more efficient than enabling everything at once and discovering problems retrospectively.
Constraints not determined by technology alone: copyright and collection etiquette
Many announcements and minutes issued by public institutions may fall outside the scope of copyright protection under copyright law as mere transmissions of facts or similar to laws and notifications. However, this does not mean they can be "collected, freely processed, and redistributed." We incorporate the mandatory display of the source (name of the sender and original URL) into the output specifications of the collection pipeline, both as a legal requirement and as a quality requirement to allow users to verify the primary source of information.
Compliance with robots.txt and control of access intervals to the same host are also positioned as essential requirements for the collection engine, not as technical implementation details, but as an operational responsibility to avoid inconveniencing the target sites. Precisely because the information being collected is of high public interest, we believe that a certain degree of moderation is required in the behavior of the collecting party.
Conditions where this method is not suitable
This design is suitable for collecting routine public information consisting of static HTML/PDF, with an update frequency of about daily. Conversely, it is not suitable for sites that require dynamic rendering with JavaScript, or for notifications that require real-time updates (e.g., immediate reflection within minutes). This is because the premise of daily batch processing itself is a choice that prioritizes cost and stability at the expense of immediacy.
Furthermore, if the structure of target sites changes extremely frequently, maintenance costs for settings will remain high even with AI assistance. This method is effective in areas where the number of target sites is large, but the structural changes of individual sites themselves are not so frequent.
Summary: AI as a proposer, execution as deterministic
The key to continuously collecting public data from thousands of sites daily, while maintaining both cost-effectiveness and reproducibility, was not about making the AI as smart as possible. Instead, it was about limiting AI's involvement to the role of "suggesting settings" and fixing the actual execution system to a non-AI, deterministic mechanism. This draws a boundary where setting generation can fluctuate, but execution must not.
This concept, I believe, is a reusable decision-making axis when incorporating AI into business systems, not just for data collection infrastructure. Rather than directly feeding AI output as a final decision into the execution system, it's a practical design for long-term, stable AI utilization to always include mechanical verification points like schema validation and dry runs. This ensures that even if the AI makes a mistake, the entire execution system remains stable.


