<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shinichi Nakagawa on Medium]]></title>
        <description><![CDATA[Stories by Shinichi Nakagawa on Medium]]></description>
        <link>https://medium.com/@shinyorke?source=rss-38313bd339f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qUIn4NkNC59TySVw.</url>
            <title>Stories by Shinichi Nakagawa on Medium</title>
            <link>https://medium.com/@shinyorke?source=rss-38313bd339f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:36:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shinyorke/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bringing AI to Every Dugout — The Ambitious Quest to Build an AI Agent for All of Baseball]]></title>
            <link>https://shinyorke.medium.com/ai-agent-for-all-baseball-d79211b60380?source=rss-38313bd339f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79211b60380</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[baseball]]></category>
            <dc:creator><![CDATA[Shinichi Nakagawa]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 11:01:01 GMT</pubDate>
            <atom:updated>2026-03-30T11:01:01.053Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bringing AI to Every Dugout — The Ambitious Quest to Build an AI Agent for All of Baseball</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKmQYJFNK0zi1veiHRrEaQ.png" /></figure><p><em>An AI-powered baseball analysis web app that turns Statcast tracking data into natural-language scouting reports — including matchups that could never happen in real life.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCzmO7UWoRbU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCzmO7UWoRbU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCzmO7UWoRbU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc597111e1cd9943022238a76a5f1035/href">https://medium.com/media/cc597111e1cd9943022238a76a5f1035/href</a></iframe><h3>About the Author</h3><p>I’m Shinichi Nakagawa (shinyorke), an SRE in the Ai Workforce Division at <a href="https://layerx.co.jp/">LayerX</a>. Outside of work, I’ve been analyzing baseball data through a sabermetric lens since 2012, and I describe myself as a “Baseball AI Engineer.”</p><p>In 2018, I joined <a href="https://nextbase.co.jp/">NEXTBASE</a> — a sports science and IT venture whose mission is “INNOVATIONS FOR ALL ATHLETES” — as the founding Engineer/CTO, spending about 18 months building systems for NPB(Nippon Professional Baseball Organization) and MLB. I continue to work on baseball data infrastructure, performance prediction, and other challenges as a personal lifework. The Scouter 3, introduced in this article, is the culmination of that journey.</p><p>Links: <a href="https://github.com/Shinichi-Nakagawa">GitHub</a> / <a href="https://x.com/shinyorke">X (Twitter)</a> / <a href="https://shinyorke.hatenablog.com/">Blog</a> / <a href="https://www.linkedin.com/in/shinyorke/">LinkedIn</a></p><h3>Introduction</h3><p>When watching an MLB game, questions naturally arise: “What’s the historical matchup between this pitcher and batter?” or “What would happen if Shohei Ohtani faced Roki Sasaki?” Sites like Baseball Savant and Fangraphs offer enormous amounts of public data, but without sabermetrics knowledge, making sense of all those numbers is daunting.</p><p>That’s why I built <strong>The Scouter 3</strong> — a web application that uses an LLM (Large Language Model) as an AI Agent to explain Statcast tracking data in natural language.</p><h3>What This Article Covers</h3><p>The Scouter 3 is a web application that provides four analysis experiences in both Japanese and English: player search, AI report generation, deep-dive matchup analysis, and virtual matchup prediction. The most distinctive feature is <strong>virtual matchup prediction</strong>, which uses an LLM to simulate matchups between players who have never faced each other — or matchups that could never happen, like “Pitcher Shohei Ohtani vs. Batter Shohei Ohtani.”</p><p>This article is structured in four chapters:</p><ul><li><strong>Chapter 1: What Is The Scouter 3</strong> — For baseball fans. The four analysis experiences powered by an AI Agent. No technical background needed if you’re familiar with baseball data.</li><li><strong>Chapter 2: From PoC to Product</strong> — For PMs and engineers. The limitations of the Marimo PoC, prototype-driven development, and design management via Design Docs.</li><li><strong>Chapter 3: Tech Stack</strong> — For engineers. Architecture details of Next.js 15 + FastAPI + Vertex AI + GCP Cloud Run, CI/CD, and infrastructure.</li><li><strong>Chapter 4: Lessons Learned</strong> — For PMs and engineers. Three practical lessons from migrating a PoC to a production product.</li></ul><p>I’m not building this as a “side project.” I’m building it as a product that genuinely changes how people experience baseball. The current target users are intermediate-to-advanced fans and analysts familiar with sabermetrics, but the vision extends to commentators who need data-backed insights during live broadcasts, coaches planning their next at-bat strategy, and ultimately every person involved in baseball having an AI Agent at their side. In six weeks, I merged 27 PRs and built a codebase of approximately 35,200 lines across 202 files. The full scope of this ambition is laid out in the closing section.</p><h3>1. What Is The Scouter 3</h3><h3>1.1 Project Purpose</h3><p>The Scouter 3 is an AI-driven baseball analysis web application powered by MLB’s Statcast/Baseball Savant data. The “3” is a baseball metaphor — three strikes, three outs.</p><p>The project codename is <strong>Betts</strong>, after Mookie Betts. The underlying MLB statistics data API platform is named <strong>Zobrist</strong>, after Ben Zobrist. (Zobrist API is a personally developed MLB data API platform built on a serverless microservice architecture using Cloud Run + Cloud Pub/Sub, managed with Terraform. See my talk “<a href="https://speakerdeck.com/shinyorke/cloud-run-and-pubsub-with-terraform">Cloud Run and Cloud PubSub for Serverless Data Infrastructure 2024 with Terraform</a>” for details.) Both are quintessential utility players in MLB — versatile performers who excel at any position. Naming projects after utility players reflects my aspiration to build a platform that’s universally useful across any analysis scenario.</p><p>The target users are intermediate-to-advanced fans and analysts who understand advanced metrics like wOBA, xBA, BABIP, ISO, K%, and BB% (all sabermetric statistical indicators used on Baseball Savant and Fangraphs; see the <a href="https://www.fangraphs.com/library/">Fangraphs Glossary</a> for details) and routinely analyze MLB data. The app is designed for use cases like pre-game scouting, player evaluation, matchup analysis, and sourcing material for social media posts.</p><h3>1.2 Four Pages, Four Analysis Experiences</h3><p>The Scouter 3 consists of four pages that let users progressively drill down from player search to detailed analysis:</p><ul><li><strong>Top (Player Search)</strong> — Search by player name in Japanese or English + summary display</li><li><strong>Player Detail</strong> — AI report + stats tables + interactive chart visualization</li><li><strong>AI Matchup Analysis</strong> — Deep-dive into actual matchup data + AI matchup report</li><li><strong>Virtual Matchup Prediction</strong> — LLM simulation of hypothetical matchups</li></ul><h4>Top Page (Player Search)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDNNg_SJa3B31IKF95oFOg.png" /><figcaption>Top Page(Player Search)</figcaption></figure><p>The landing page. You can search for players in Japanese (kanji, hiragana, katakana) or English. Type “大谷翔平” and the LLM maps it to “Ohtani, Shohei,” displaying a summary card with seven key metrics: batting average, on-base percentage, slugging percentage, OPS, home runs, strikeouts, and walks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5BzS10n4o-bBkVThdBOcQ.png" /><figcaption>summary card with seven key metrics</figcaption></figure><h4>Player Detail Page</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdEnagExj1UfTkcm7a_zZw.png" /></figure><p>A page that provides a full-season overview of a player. At the top, an AI report is displayed across five sections (playing style, strengths and weaknesses, vs. RHP tendencies, vs. LHP tendencies, and overall assessment), delivered via Server-Sent Events (SSE) streaming section by section. Users can start reading the first section while the LLM is still generating the rest, reducing perceived wait time.</p><p>Stats and visualizations are organized in two tabs:</p><ul><li><strong>Stats</strong> — Four categories: basic stats, SABR metrics, pitch-type breakdown, and batted ball tendencies</li><li><strong>Visualization</strong> — Interactive charts powered by Plotly.js</li></ul><p>The visualization tab displays 8 chart types across 4 sub-tabs for pitchers (pitch distribution pie chart, velocity trends, pitch locations, release points, batted ball locations) and 4 chart types across 2 sub-tabs for batters (Barrel distribution, batted ball type distribution, batted ball locations). All charts support filtering by handedness (vs. R / vs. L / Overall).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4g13XuXST5kkmBi0d6uFqg.png" /><figcaption>Player Detail Page for Pitcher</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DiHz9GAN74KbjCH437LkGQ.png" /><figcaption>Player Detail Page for Batter</figcaption></figure><h4>AI Matchup Analysis Page</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fA2cZLiSOQw2Po8k6ZGDMw.png" /></figure><p>A page for deep-diving into actual matchup data. It extracts opponents from a player’s tracking data and displays a table with at-bats, batting average, home runs, strikeouts, walks, and pitches per plate appearance, with pagination and sorting.</p><p>Selecting a specific opponent reveals:</p><ul><li><strong>Matchup Summary</strong> — Counting stats + rate stats in two tables</li><li><strong>Pitch-Type Breakdown</strong> — Pitch count, batting average, K% by pitch type</li><li><strong>Tracking Visualization</strong> — Velocity trends, pitch locations, batted ball location charts</li><li><strong>Pitch-Type Comparison</strong> — Batting average vs. strikeout rate comparison chart</li><li><strong>AI Matchup Report</strong> — Three sections: overall analysis, pitch-type analysis, and recommended strategy</li></ul><p>The AI matchup report goes beyond simple data summaries. It includes specific strategic recommendations like “This batter has a low batting average against sliders, so building counts with sliders would be effective.”</p><h4>Virtual Matchup Prediction Page</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhwVbZnssjACVspeLsCDlA.png" /><figcaption>Virtual Matchup — Yoshinobu Yamamoto VS Shohei Ohtani</figcaption></figure><p>The most original feature of The Scouter 3 — an analysis experience that only an AI Agent can deliver. It uses an LLM to simulate hypothetical matchups between players who have never faced each other, or who could never face each other.</p><p>Example use cases:</p><ul><li><strong>Cross-league / rare matchups</strong> — Shohei Ohtani (Dodgers, NL) vs. Munetaka Murakami (White Sox, AL) or Kazuma Okamoto (Blue Jays, AL). How many times a year do they actually face each other? Interleague-only matchups like these can be predicted based on data.</li><li><strong>Same-team matchups</strong> — Shohei Ohtani vs. Yoshinobu Yamamoto. As Dodgers teammates, they’ll never face each other in a real game. But their Statcast data can fuel a “what if” prediction.</li><li><strong>Same-person pitcher vs. batter</strong> — <strong>Can Pitcher Shohei Ohtani get Batter Shohei Ohtani out?</strong> The ultimate hypothetical for a two-way player. The LLM receives both pitching tracking data and batting tracking data to calculate pitch-type advantage and predicted batting average.</li></ul><p>The “Ohtani vs. Ohtani” matchup can never happen in real baseball. But Statcast records Pitcher Ohtani’s complete pitch data and Batter Ohtani’s complete at-bat data separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaCtZGoEUobXPFA1QcvEHg.png" /><figcaption>Ohtani(Batter) VS Ohtani(Pitcher)</figcaption></figure><p>The AI Agent reads both datasets and provides analysis grounded in specific evidence, such as “Ohtani’s Sweeper (opponent batting average .180) vs. Batter Ohtani’s breaking ball batting average of .260.” Where human commentators would rely on subjective speculation, the AI Agent delivers data-driven analysis. That’s the unique value of an AI Agent.</p><p>The UI displays:</p><ul><li><strong>Tug-of-War Bar</strong> — A horizontal bar graph showing pitcher (blue) vs. batter (red) advantage. 55% or higher = pitcher advantage, 45% or lower = batter advantage, in between = even.</li><li><strong>Prediction Summary</strong> — Four metrics with prediction ranges: projected batting average, strikeout probability, walk probability, and extra-base hit probability.</li><li><strong>Pitch-Type Advantage Bars</strong> — Per-pitch-type advantage, e.g., “Sweeper: 75% pitcher advantage” or “4-Seam: 55% batter advantage.”</li><li><strong>AI Analysis Report</strong> — Five sections: overall prediction, pitch-type vulnerability analysis, recommended strategy, opponent threats, and projected scenarios.</li></ul><p>A mode selector lets users choose between “Serious Analysis” mode (objective, professional) and “Entertainment” mode (dramatic, fan-oriented narration). Same data, presented in different voices — tailored to the reader’s purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ICHxC8okvIeSbKDMAVlOSQ.png" /><figcaption>“Entertainment” mode</figcaption></figure><h3>1.3 Bilingual Support (Japanese/English)</h3><p>The Scouter 3 supports both Japanese and English. A JA/EN toggle in the header switches not only UI labels but also the language of AI-generated reports. Over 108 i18n keys are managed by a lightweight custom i18n system with no external library dependencies.</p><p>Japanese is the default language because the primary target audience is MLB fans and analysts based in Japan. English is provided as a secondary language for international users and for writing English articles.</p><h3>2. From PoC to Product — The Development Journey</h3><h3>2.1 Starting with a Marimo PoC</h3><p>The project started as a PoC built with Marimo, a reactive Python notebook framework. Combined with Google Cloud Vertex AI (Gemini 2.5 Flash), Polars, and Plotly, it validated:</p><ul><li>Natural language MLB statistics search</li><li>LLM-based Japanese query parsing and player name matching</li><li>Batter/pitcher statistics visualization</li><li>Automated player report generation (AI reports)</li><li>Matchup trend analysis and matchup report generation</li><li>Season selection (2023–2025)</li></ul><p>The PoC worked well enough as an interactive web interface for the developer’s own analysis. It was deployed on Cloud Run with an OAuth2 Proxy sidecar at betts-poc.shinyorke.info, with infrastructure managed by Terraform.</p><p>But the PoC had limitations.</p><h3>2.2 PoC Limitations and the Motivation for Productization</h3><p>Four issues became clear during PoC operation:</p><ul><li><strong>UI constraints</strong> — Marimo is a notebook environment with poor mobile support. Checking stats on a phone at the ballpark wasn’t feasible. Tab switching and accordion UIs were also difficult to implement.</li><li><strong>Performance</strong> — Server-side rendering meant every client-side filter or sort operation required a round trip to the server.</li><li><strong>i18n difficulty</strong> — The PoC only had a Japanese UI. Retrofitting multilingual support onto Marimo’s architecture was not straightforward.</li><li><strong>Scalability</strong> — All functionality was packed into a single Cloud Run service, making independent scaling of frontend and backend impossible.</li></ul><p>Based on these issues, I decided to do a full rebuild as a proper web application with Next.js + FastAPI, separating frontend and backend. The LLM logic validated in the PoC (player name matching, report generation, virtual matchup prediction) would be re-implemented in Python and ported to the FastAPI backend.</p><h3>2.3 Prototype-Driven Development</h3><p>For the rebuild, I first created an HTML/CSS/JS prototype. Using Tailwind CSS 3.x (CDN) and Plotly.js 2.35 without any build step, I validated the UI/UX for all four pages in the browser.</p><p>This “prototype → frontend” development flow had explicit rules:</p><ul><li>The prototype is the single source of truth for UI/UX design validation</li><li>Design changes are first validated in the prototype, then implemented in frontend (Next.js) after confirmation</li><li>The prototype’s HTML structure, CSS class names, and responsive design serve as the spec for frontend implementation</li><li>Color palette (CSS variables) and breakpoints are reflected in the frontend’s Tailwind configuration</li><li>Chart definitions maintain a 1:1 correspondence with frontend React components</li></ul><p>The prototype has 121 Playwright E2E tests to automatically verify that no regressions occur with each change. This maintains the prototype’s reliability as the “design source of truth” while preventing spec drift during the Next.js port.</p><h3>2.4 Design Docs for Design Management</h3><p>Each feature and phase’s design decisions were documented as Design Docs, following a naming convention (ISSUE#_YYYYMMDD_description.md) and linked to GitHub Issues. Key Design Docs include:</p><ul><li><strong>#11 LLM Backend API Design</strong> — Schema, data flow, SSE design, and caching strategy for 8 API endpoints</li><li><strong>#12 GCP Infrastructure Design</strong> — VPC, Cloud Run 2-service architecture, IAM, Artifact Registry, Cloud NAT</li><li><strong>#16 Backend Implementation Plan</strong> — FastAPI’s 4-layer architecture and phased implementation</li><li><strong>#17 Frontend Implementation Plan</strong> — Next.js 15 App Router file structure, Server/Client Component strategy, API Route proxy design</li><li><strong>#26 i18n Implementation</strong> — LanguageProvider (React Context) multilingual switching design</li><li><strong>#27 Terraform Infrastructure</strong> — VPC/IAM/Artifact Registry/Workload Identity foundation</li><li><strong>#28 CI/CD Pipeline</strong> — GitHub Actions GAR push + Terraform deploy flow</li><li><strong>#29 Cloud Run Deployment</strong> — OAuth2 Proxy sidecar configuration, Domain Mapping, production setup</li></ul><p>Documenting design decisions made it possible to look back at PoC decisions and clarify what to change and what to carry over into the product. Differences from the PoC (e.g., moving Zobrist API calls from Frontend to Backend) are explicitly recorded in a “Changes from RFP” section in each Design Doc.</p><h3>2.5 Development Scale</h3><p>The rebuild from PoC to product took approximately six weeks (February 14 — March 29, 2026). Repository activity during that period:</p><ul><li><strong>Commits:</strong> 45</li><li><strong>Merged PRs:</strong> 27</li><li><strong>Files managed:</strong> 202</li><li><strong>Total lines of code:</strong> ~35,200</li></ul><p>That’s roughly one PR merged every 1.5 days. Component breakdown:</p><ul><li><strong>frontend/</strong> — ~17,300 lines (largest; includes lockfile)</li><li><strong>docs/</strong> — ~5,000 lines (RFP + Design Docs)</li><li><strong>backend/</strong> — ~5,000 lines (Python + lockfile)</li><li><strong>prototype/</strong> — ~3,900 lines (HTML/CSS/JS)</li><li><strong>terraform/</strong> — ~960 lines (HCL)</li><li><strong>.github/</strong> — ~630 lines (CI/CD workflows)</li><li><strong>scripts/</strong> — ~46 lines (pre-commit hooks)</li></ul><p>Excluding lockfiles, the effective code volume is roughly 20,000 lines. The 5,000 lines of docs reflect the effort that went into thoroughly documenting the RFP and eight Design Docs.</p><p>Claude Code was used extensively during implementation, with OpenAI Codex and GitHub Copilot assisting with code review. Integrating AI coding tools into the development process made it possible for a solo developer to ship a product of this scale in six weeks.</p><p>The six weeks of development blended naturally into daily life. On weekday evenings, I designed and implemented the prototype at my regular izakaya (Japanese pub) over drinks. Every weekend, I focused on frontend and backend implementation at my local Starbucks, nursing an almond milk café mocha with light syrup. Some days I debugged while watching WBC Team USA games — which are broadcast in Japan from morning into the early afternoon. Building a baseball product while watching baseball. You can’t get better dogfooding than that.</p><h3>3. Tech Stack</h3><p>From here, I’ll detail The Scouter 3’s tech stack from an engineering perspective.</p><h3>3.1 Overall Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdzLarjF5YKxX4FLMXGIFg.png" /></figure><p>Two Cloud Run services are deployed within the same VPC. Backend access is restricted to VPC-internal traffic. The Frontend accepts external traffic and authenticates via OAuth2 Proxy. The Backend uses ingress: internal-only to accept only VPC-internal requests.</p><h3>3.2 Frontend — Next.js 15 + TypeScript</h3><p><strong>Framework selection</strong> — Next.js 15 (App Router) was chosen as the migration target from Marimo. Reasons: future optimization through Server Components, including SSR/SEO benefits, App Router’s flexible Server/Client Component model, and the maturity of the React ecosystem.</p><p><strong>Key libraries:</strong></p><ul><li><strong>Next.js 15 (App Router)</strong> + <strong>React 18</strong> + <strong>TypeScript</strong> — Routing, data fetching, rendering</li><li><strong>Tailwind CSS v4</strong> + <strong>@tailwindcss/typography</strong> — Styling. v4 uses @theme directives in CSS; no tailwind.config.ts needed</li><li><strong>Plotly.js</strong> (react-plotly.js + plotly.js-basic-dist-min) — Chart rendering. The basic distribution (~1MB) includes scatter/pie and meets project requirements. A full bundle (~3.5MB) is considered for future 3D chart needs</li><li><strong>react-markdown</strong> — Markdown rendering for AI reports</li><li><strong>Custom i18n</strong> (lib/i18n.ts + JSON dictionaries + LanguageProvider) — No external library. External i18n libraries were deemed overkill for 108+ keys across 4 pages</li></ul><p><strong>API Route proxy design</strong> — Frontend-to-Backend communication is unified through a single pattern: Next.js API Route (/app/api/v1/[...path]/route.ts) as a transparent proxy. The browser hits /api/v1/*, and the API Route forwards to the Backend&#39;s Cloud Run service URL.</p><pre>// frontend/src/app/api/v1/[...path]/route.ts<br>export async function GET(<br>  request: Request,<br>  { params }: { params: Promise&lt;{ path: string[] }&gt; },<br>) {<br>  const backendUrl = process.env.BACKEND_URL ?? &quot;http://localhost:8000&quot;;<br>  const { path } = await params;<br>  const url = new URL(request.url);<br>  const targetUrl = `${backendUrl}/api/v1/${path.join(&quot;/&quot;)}${url.search}`;</pre><pre>  const response = await fetch(targetUrl);<br>  return new Response(response.body, {<br>    status: response.status,<br>    headers: {<br>      &quot;Content-Type&quot;:<br>        response.headers.get(&quot;Content-Type&quot;) ?? &quot;application/json&quot;,<br>    },<br>  });<br>}</pre><pre>export async function POST(<br>  request: Request,<br>  { params }: { params: Promise&lt;{ path: string[] }&gt; },<br>) {<br>  const backendUrl = process.env.BACKEND_URL ?? &quot;http://localhost:8000&quot;;<br>  const { path } = await params;<br>  const url = new URL(request.url);<br>  const targetUrl = `${backendUrl}/api/v1/${path.join(&quot;/&quot;)}${url.search}`;</pre><pre>  const body = await request.text();<br>  const response = await fetch(targetUrl, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body,<br>  });</pre><pre>  const contentType =<br>    response.headers.get(&quot;Content-Type&quot;) ?? &quot;application/json&quot;;<br>  return new Response(response.body, {<br>    status: response.status,<br>    headers: { &quot;Content-Type&quot;: contentType },<br>  });<br>}</pre><p>That’s the entire core of the proxy. A catch-all route ([...path]) receives the path, forwards it to the Backend URL, and returns response.body (ReadableStream) as-is. SSE responses (text/event-stream) are transparently passed through with their Content-Type header, requiring zero special handling for streaming.</p><p>Benefits of this design:</p><ul><li><strong>Security</strong> — The Backend’s internal URL is never exposed to the browser</li><li><strong>No CORS</strong> — Same-origin communication eliminates CORS configuration</li><li><strong>Unified API calls</strong> — Both Client and Server Components call the same /api/v1/* path</li></ul><p>The tradeoff is one extra hop of latency for every request. Cloud Run’s request timeout can also affect long-lived SSE connections. Currently, the timeout is set to 60 seconds, and LLM report generation fits within that window. Serverless environments like Vercel may have stricter streaming timeout constraints, but this hasn’t been an issue on Cloud Run.</p><p><strong>Server vs. Client Components</strong> — The design intended page components (page.tsx) to be Server Components that fetch initial data and pass props to Client Components. However, the introduction of i18n (LanguageProvider = React Context) means all pages currently declare &quot;use client&quot;. Server Component migration is positioned as a future optimization. Plotly.js chart components reference window during module import, so they use next/dynamic + ssr: false to disable SSR.</p><h3>3.3 Backend — Python + FastAPI</h3><p><strong>Framework selection</strong> — FastAPI was chosen because the Vertex AI (Google Cloud) Python SDK is used for LLM integration. The PoC’s LLM logic from the Marimo app was re-implemented (not directly imported) into FastAPI.</p><p><strong>Key libraries:</strong></p><ul><li><strong>Python 3.14+</strong> + <strong>FastAPI</strong> + <strong>Pydantic v2</strong> — API framework. CamelModel (alias_generator) provides automatic camelCase ↔ snake_case conversion</li><li><strong>google-cloud-aiplatform</strong> (Vertex AI / Gemini 2.5 Flash) — LLM inference</li><li><strong>httpx</strong> — Async HTTP client for Zobrist API</li><li><strong>google-cloud-storage</strong> — GCS cache bucket access</li><li><strong>Polars</strong> — Data processing (carried over from PoC)</li><li><strong>Package manager:</strong> <strong>uv</strong> — Dependency management via lockfile (uv.lock)</li></ul><p><strong>4-layer architecture:</strong></p><ol><li><strong>Routing layer</strong> (api/) — HTTP request/response handling only. No business logic.</li><li><strong>Service layer</strong> (services/) — Business logic: player name matching, report generation, matchup prediction.</li><li><strong>Client layer</strong> (clients/) — External service communication: Vertex AI, Zobrist API, GCS/Local cache.</li><li><strong>Model layer</strong> (models/) — Pydantic schema definitions: request, response, internal types.</li></ol><p>Additionally, core/ holds cross-cutting infrastructure code (LLMClient Protocol, SSE helpers), and config/ handles environment variable management. os.getenv is only used within settings.py; direct use from other modules is prohibited, centralizing environment variable management in one place.</p><p><strong>DI (Dependency Injection) pattern</strong> — Shared resources are initialized during FastAPI’s lifespan event and stored in app.state. Implementation proceeded in four phases:</p><ul><li><strong>Phase A:</strong> Settings → enables health endpoint</li><li><strong>Phase B:</strong> + CacheBackend + ZobristClient → enables players, tracking, summary</li><li><strong>Phase C:</strong> + LLMClient → enables search, report/player</li><li><strong>Phase D:</strong> Full integration → enables report/matchup, predict/virtual</li></ul><p>This ordering is intentional. Phase A confirms deployment health, Phase B validates external API integration (Zobrist API), and Phase C introduces the LLM for the first time. Building up from fewest dependencies ensures each phase has working endpoints, enabling incremental deployment and verification.</p><p><strong>8 API endpoints</strong> — The Backend provides 8 endpoints in two response categories:</p><ul><li><strong>Data retrieval (5 endpoints, JSON)</strong> — Health check, player list, Japanese name search, tracking data, player summary</li><li><strong>AI report generation (3 endpoints, SSE)</strong> — Player AI report, matchup analysis AI report, virtual matchup prediction</li></ul><p>Data retrieval endpoints are JSON APIs that return immediate responses (Zobrist API proxying, LLM-based player name matching, etc.). AI report generation endpoints deliver section-by-section streaming via SSE, the same approach used in the PoC, enabling users to read earlier sections before the LLM finishes.</p><p><strong>Caching strategy</strong> — Every endpoint except health check has a cache parameter. Default is true (reads from GCS bucket cache); false bypasses the cache. This reduces LLM call costs and improves response times. The cache bucket has a 7-day lifecycle policy for automatic cleanup.</p><h3>3.4 Infrastructure — GCP + Terraform</h3><p><strong>Infrastructure as Code</strong> — All infrastructure is declaratively managed with Terraform (1.14+). A flat structure (no module splitting) was adopted, prioritizing simplicity at this service scale. Google Cloud Provider ~&gt; 6.0 is used.</p><p><strong>Key infrastructure components:</strong></p><ul><li><strong>Compute:</strong> Cloud Run × 2 (Frontend + Backend)</li><li><strong>Network:</strong> VPC + Subnet for internal traffic isolation (10.0.0.0/24)</li><li><strong>Network:</strong> Serverless VPC Access Connector for Cloud Run ↔ VPC (10.8.0.0/28)</li><li><strong>Network:</strong> Cloud Router + Cloud NAT for Backend → external API traffic</li><li><strong>Auth:</strong> OAuth2 Proxy v7.6.0 for end-user Google OAuth</li><li><strong>Auth:</strong> Workload Identity Federation for keyless GitHub Actions → GCP authentication</li><li><strong>IAM:</strong> 4 Service Accounts (frontend-sa / backend-sa / deploy-sa / admin-sa)</li><li><strong>AI/ML:</strong> Vertex AI (Gemini 2.5 Flash) for LLM inference</li><li><strong>Storage:</strong> GCS for cache store (7-day lifecycle)</li><li><strong>Secrets:</strong> Secret Manager for API keys and OAuth secrets</li><li><strong>Container:</strong> Artifact Registry for Docker image storage (retains latest 10)</li></ul><p><strong>VPC and network design</strong> — Backend egress routing varies by destination. Enabling Private Google Access on the subnet makes this differentiation possible:</p><ul><li><strong>Vertex AI / GCS Cache</strong> → Private Google Access (stays within Google’s private network)</li><li><strong>Zobrist API</strong> → Cloud NAT (traverses the public internet as an external REST API)</li></ul><p><strong>OAuth2 Proxy sidecar configuration</strong> — The same approach from the PoC was carried over directly, using Cloud Run v2 API’s multi-container feature:</p><ul><li><strong>OAuth2 Proxy v7.6.0</strong> — Ingress (auth gateway), port 8080, 0.5 CPU, 256Mi memory</li><li><strong>Next.js App</strong> — Sidecar (application), port 3000, 0.5 CPU, 512Mi memory</li></ul><p>OAuth2 Proxy reads client secrets from Secret Manager and authenticates via Google OAuth 2.0. Here’s an excerpt of the Terraform definition (secret-related environment variables omitted):</p><pre># terraform/cloud_run.tf (excerpt)<br>resource &quot;google_cloud_run_v2_service&quot; &quot;frontend&quot; {<br>  name     = &quot;betts-frontend&quot;<br>  location = var.gcp_region</pre><pre>  template {<br>    service_account = google_service_account.frontend.email<br>    timeout         = &quot;60s&quot;</pre><pre>    # OAuth2 Proxy container (ingress, port 8080)<br>    containers {<br>      name  = &quot;oauth2-proxy&quot;<br>      image = &quot;${local.gar_url}/oauth2-proxy:v7.6.0-amd64&quot;<br>      ports { container_port = 8080 }<br>      env { name = &quot;OAUTH2_PROXY_UPSTREAMS&quot;; value = &quot;http://localhost:3000&quot; }<br>      # ... OAuth config via Secret Manager references (omitted)<br>      resources { limits = { cpu = &quot;0.5&quot;; memory = &quot;256Mi&quot; } }<br>    }</pre><pre>    # Next.js container (sidecar, port 3000)<br>    containers {<br>      name  = &quot;betts-frontend&quot;<br>      image = &quot;${local.gar_url}/betts-frontend:${var.frontend_image_tag}&quot;<br>      env { name = &quot;BACKEND_URL&quot;; value = google_cloud_run_v2_service.backend.uri }<br>      resources { limits = { cpu = &quot;0.5&quot;; memory = &quot;512Mi&quot; } }<br>      depends_on = [&quot;oauth2-proxy&quot;]  # Sidecar starts after ingress container<br>    }</pre><pre>    vpc_access {<br>      connector = google_vpc_access_connector.connector.id<br>      egress    = &quot;ALL_TRAFFIC&quot;<br>    }<br>  }</pre><pre>  ingress = &quot;INGRESS_TRAFFIC_ALL&quot;<br>}</pre><p>The key point: OAuth2 Proxy is the ingress container (has ports block), while the Next.js app is a sidecar (no ports block). OAuth2 Proxy&#39;s UPSTREAMS points to http://localhost:3000, forwarding to the Next.js app within the same instance. BACKEND_URL is dynamically injected with the Backend&#39;s Cloud Run URI, reaching the Backend via VPC-internal communication.</p><h3>3.5 CI/CD — GitHub Actions + Terraform</h3><p><strong>Branch strategy</strong> — A three-tier model: feature/#123-xxx → main → prd. Merges to main use squash merge; merges from main → prd use merge commits (to enable per-release reverts).</p><p><strong>CI pipelines</strong> — Separated by component:</p><ul><li><strong>backend-ci.yml</strong> — ruff check → ruff format — check → ty check → pytest → Docker build → GAR push</li><li><strong>frontend-ci.yml</strong> — ESLint → Next.js build → vitest → Docker build → GAR push</li><li><strong>terraform-ci.yml</strong> — fmt → validate → plan (PR comment output)</li></ul><p><strong>CD pipeline</strong> — Triggered by merge commits to the prd branch. Three steps:</p><ol><li><strong>Change detection</strong> — Determines whether frontend/ or backend/ has changes</li><li><strong>Tag resolution</strong> — Changed components get the latest Git SHA short tag from GAR; unchanged components keep the current terraform state value</li><li><strong>Deploy</strong> — terraform apply updates Cloud Run, ensuring consistency between tf state and reality</li></ol><p><strong>Workload Identity Federation</strong> — GitHub Actions authenticates to GCP via keyless authentication using OIDC tokens, with no service account key generation.</p><ul><li>deploy-sa — GAR push only (roles/artifactregistry.writer)</li><li>admin-sa — Terraform plan/apply (roles/run.admin, roles/compute.networkAdmin, etc.)</li></ul><p><strong>Pre-commit hooks</strong> — Automatically run CI checks on changed components at commit time:</p><ul><li>backend/ → ruff check → ruff format --check → ty check → pytest</li><li>frontend/ → ESLint → Next.js build → vitest</li><li>terraform/ → terraform fmt -check → terraform validate</li><li>prototype/ → Playwright E2E tests (121 tests)</li></ul><h3>3.6 Brand Color and Design System</h3><p>A brief detour from tech stack: The Scouter 3’s visual identity uses <strong>forest teal (</strong><strong>#115e59, Tailwind </strong><strong>teal-800)</strong> as its primary color. This was chosen to differentiate from existing baseball data sites — Fangraphs (green), Baseball Reference (red), Baseball Savant (navy) — while also nodding to the Oakland Athletics&#39; team colors (green &amp; gold). I discovered sabermetrics through Michael Lewis&#39;s <em>Moneyball</em> and became an A&#39;s fan in the process. Having the color of the team where data analysis in baseball began embedded in the product is a personally satisfying detail.</p><p>Pitcher blue (#2563eb) and batter red (#dc2626) are used consistently throughout the application — in the Tug-of-War bar, AI matchup reports, and more. The color palette is centrally managed via CSS variables, with the prototype&#39;s css/style.css reflected 1:1 in the frontend&#39;s Tailwind configuration.</p><h3>4. Lessons Learned from PoC-to-Product Migration</h3><h3>4.1 Throw Away the Code, Keep the Design</h3><p>Direct import of PoC Marimo app code was prohibited as a project rule. This avoided carrying over Marimo-specific UI framework constraints and monolithic structure. Meanwhile, design decisions validated in the PoC (SSE streaming, GCS caching, OAuth2 Proxy sidecar architecture) were carried over to the product through Design Docs. The approach of “throw away the code, keep the design” led to a clean re-implementation.</p><h3>4.2 Making the Prototype the Source of Truth</h3><p>The static HTML/CSS/JS prototype was positioned as the design source of truth, with Next.js implementation required to conform to the prototype. This separated design discussions from implementation discussions, establishing a single reference point: “For UI specs, look at the prototype.” Playwright tests ensuring prototype quality were a critical pillar supporting this approach.</p><h3>4.3 Design Doc Accumulation Accelerates Development</h3><p>Creating 8 Design Docs created a durable record of why each design decision was made. In particular, explicitly recording differences from the PoC makes it immediately clear whether a new implementation intentionally follows or intentionally departs from existing PoC design. This will hold significant value for future maintenance and new team member onboarding.</p><h3>Closing</h3><p>The Scouter 3 is an AI agent for baseball analysis and commentary that combines MLB’s Statcast data with LLMs. It delivers four analysis experiences in both Japanese and English: natural-language player search, AI report generation, deep-dive matchup analysis, and virtual matchup simulation.</p><p>Technically, it’s built on Next.js 15 + FastAPI + Vertex AI (Gemini 2.5 Flash), with an OAuth2 Proxy sidecar Cloud Run 2-service architecture. Terraform Infrastructure as Code, GitHub Actions CI/CD pipelines, pre-commit hooks for quality assurance, and Design Docs for design management — the full suite of practices expected of a production-quality web application.</p><p>The three keys to a smooth PoC-to-product migration were: “throw away the code, keep the design,” “make the prototype the source of truth,” and “accumulate Design Docs.”</p><p>The combination of baseball data and AI still holds enormous potential. Future directions include:</p><ul><li><strong>Natural language query search</strong> — Answering questions like “Who were the left-handed batters who hit 30+ home runs last year?” by searching a database</li><li><strong>Real-time game data integration</strong> — Ingesting tracking data from live games to update matchup analysis and reports in real time</li><li><strong>Advanced prediction models</strong> — Incorporating pitch movement (horizontal/vertical break) and pitch tunneling (how similar the trajectory of different pitch types appears to the batter) to explain <em>why</em> a particular pitch type is hard to hit</li></ul><p>And the value The Scouter 3 aims to deliver extends beyond fan entertainment. AI-driven, data-backed analysis can provide a third-party perspective that augments human judgment. I want to realize a future where an AI Agent stands alongside everyone involved in baseball:</p><ul><li><strong>Commentators</strong> — Instantly referencing AI reports as supporting data when asked “What’s the historical trend for this matchup?” during a live broadcast</li><li><strong>Play-by-play announcers</strong> — Quickly grasping matchup context and pitch-type advantages to communicate to viewers before the next at-bat</li><li><strong>Coaches</strong> — Using data as evidence when telling a player “Your batting average against this pitcher’s Sweeper is .150 — lay off the first pitch”</li><li><strong>Fans</strong> — Watching a game at the ballpark while reading the matchup in front of them through data, deepening the enjoyment of baseball by one more level</li></ul><p>The Scouter 3 is the first step.</p><p>If this vision resonates with you, or if you’d like to build the future of baseball × AI together, please don’t hesitate to reach out — individuals and companies alike. Contact shinyorke via <a href="https://x.com/shinyorke">X (Twitter)</a> or <a href="https://www.linkedin.com/in/shinyorke/">LinkedIn</a>.</p><p><em>About the Author: I’m Shinichi Nakagawa (shinyorke), an SRE at LayerX and a baseball data analyst who has been working with sabermetrics since 2012. I build MLB data infrastructure and AI-powered analysis tools as a personal lifework. Find me on </em><a href="https://github.com/Shinichi-Nakagawa"><em>GitHub</em></a><em>, </em><a href="https://x.com/shinyorke"><em>X</em></a><em>, and </em><a href="https://www.linkedin.com/in/shinyorke/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79211b60380" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>