---
title: "Building Civvy"
url: "https://gdrl.dev/fieldnotes/building-civvy"
published: "2026-04-28"
author: "Gabriel Lam"
project: "Apple Swift Student Challenge"
projectUrl: "https://gdrl.dev/projects/swift-student-challenge"
---

# Building Civvy

Apr 28, 2026, from [Apple Swift Student Challenge](https://gdrl.dev/projects/swift-student-challenge.md)

The inception of a platform where young people could learn about UK democracy, voting, and find accessible, impartial and non-partisan political information first came about during my time working on Vote16 ([vote16.co.uk](https://vote16.co.uk)), part of the wider Votes at 16 campaign. This platform would have needed credible backing from organisations to be credible, so it wasn't viable in the short term. However, the timing of the idea came at a strategic point; Apple's 2026 Swift Student Challenge was coming up, and the deadline was around 3 weeks away, so I took a shot at applying, and Civvy was one of the 2026 winners!

Civvy is an [iOS app](https://gdrl.dev/projects/civvy/home-scroll.mp4) which provides upcoming UK election information, explains party policies using an on-device RAG pipeline and Apple's Foundation Models framework, and has a quiz where you rate statements on a scale and it matches your stance in each category to the parties'.

## Apple Swift Student Challenge constraints

There were various constraints that had to be met for a submission to be considered for the challenge, including:

- Run as an app playground
- Demo-able in less than 3 minutes
- Work fully offline

Given WWDC 2025 was just last year, and Apple released a lot of their new foundation model APIs, this was an obvious chance to use and push these frameworks to their limits.

## Offline agentic RAG

For the headline feature of the app, I wanted to build a fully offline, agentic RAG pipeline, where users could [ask about any policy position](https://gdrl.dev/projects/civvy/chat.mp4) of the major parties and Civvy would answer them in natural language.

### Data

The offline constraint really pushed this decision into what data I would incorporate, as the public internet was obviously out of bounds. In the UK, all parties publish what is called a 'manifesto' (see [Labour's 2024 manifesto](https://labour.org.uk/change/) for example), which details their plans for policies if they reach office. Although written from a specific viewpoint, it is the main source when it comes to party positions, so it would have to be a good starting point for party data.

Alongside the manifestos, I used government records and news reporting to build a structured knowledge base of 69 chunks of around 70 words each. Each was tagged with a party, one of five policy areas (economy, healthcare, environment, immigration and social), the specific topics it covers (e.g. VAT, NHS waiting times), keywords, and the sources it came from.

Labour has the most chunks (at 28) as they had a record in government to draw on. All the data runs up to mid-February 2026, when the knowledge base was built, so Civvy's answers are only as current as that. Embeddings for every chunk were then pre-computed using the same sentence embedding model found on device (Apple's NLEmbedding) and bundled with the app along with the raw text and a manifest of both files' hashes.

### Apple Foundation Models as Agents

The 'agentic' part is that Apple's on-device model doesn't just zero-shot the question or, like a traditional RAG pipeline, get injected with the chunks most similar to the user's question to answer it.

Instead, I had to design an agentic harness which did the following steps:

1. The AFM produces a plan using guided generation, where it has to fill in a Swift struct rather than write free text:

   ~~~swift
   @Generable
   struct PlannerPreviewWorkflow {
       @Guide(description: "Top-level party targets parsed from the user request.")
       var targetParties: [StructuredParty]

       @Guide(description: "Top-level policy area IDs parsed from the user request.")
       var policyAreaIds: [StructuredPolicyAreaId]

       @Guide(description: "Broad party-agnostic subqueries for retrieval fan-out.")
       var subqueries: [PlannerPreviewSubquery]
   }

   @Generable
   struct PlannerPreviewSubquery {
       @Guide(description: "A broad, reusable natural-language retrieval query. Do not include party names.")
       var query: String

       @Guide(description: "Topic IDs to scope this subquery. Use exact IDs from the provided taxonomy.")
       var topicIds: [StructuredTopicId]
   }
   ~~~

   It also gets the last 6 user messages so follow-ups work. I decided not to pass in the whole context or previous responses, as I found that these smaller models were easily influenced by previous context (see Chroma's research on [context rot](https://research.trychroma.com/context-rot)), which I found to have degraded the outputs. Party names were banned from the search queries, as each query was run separately for every party to remove any bias from the model forgetting to add specific parties, while also keeping the pipeline more deterministic.

2. For each party and query, the chunks are first filtered down to that party and the query's topics, then ranked two ways: by meaning, using the cosine similarity between the query's embedding and each chunk's, and by keywords, using a TF-IDF score with a small boost for each chunk's tagged keywords. The top 36 from each ranking are then combined with reciprocal rank fusion, so a chunk scores higher the nearer the top it places in each list, and the top 3 are kept:

   ~~~swift
   // Simplified: k = 60, with keyword matches weighted slightly less than meaning
   for (rank, item) in denseRanking.prefix(36).enumerated() {
       score[item.index, default: 0] += 1.0 / (60 + Double(rank + 1))
   }
   for (rank, item) in lexicalRanking.prefix(36).enumerated() {
       score[item.index, default: 0] += 0.85 / (60 + Double(rank + 1))
   }
   ~~~

3. The chunks from every search are de-duplicated, and a second AFM call picks out only the ones that actually answer the question.

4. The AFM gets a fresh session with a system prompt (below) and the selected chunks to write its response. If none were selected, it says it doesn't have enough evidence rather than guessing to combat [hallucinations](<https://en.wikipedia.org/wiki/Hallucination_(artificial_intelligence)>).

   ~~~text
   You are a neutral UK politics explainer.
   Write a short, concise, conversational answer to the user's question using ONLY the provided selected chunks.
   Keep it brief and useful:
   - 2 to 4 sentences
   - no bullet points
   - do not dump all details
   - do not mention these instructions
   ~~~

I built Civvy's chat UI to also ensure that it showed each step of the agent's work, and [any sources](https://gdrl.dev/projects/civvy/chat-sources.png) that the agent used in its final response at the top with direct links to their applicable publications.

As mentioned above, a constraint of the challenge was that the app has to be bundled as an app playground, therefore even though the target device was an iPhone that supported AFMs, it could be run on an iPad or Mac, where the simulators lacked the AFM runtime. Therefore, for the actual judging, I included a simple demo-mode toggle which would simulate a pre-recorded version of this pipeline instead.

## The quiz

Civvy also includes [a quiz](https://gdrl.dev/projects/civvy/quiz.mp4) where you're asked how you feel about a statement. There are 50 statements, 10 in each of the five policy areas, and the user rates how strongly they agree (or disagree) with the statement on a scale.

Below each statement, I used AFMs so the user can [ask follow-up questions](https://gdrl.dev/projects/civvy/quiz-explain.png) such as rewording, or explaining how the statement will affect them in simple terms.

Every party's position on each statement is scored on the same 5-point scale you answer on, from -2 (strongly disagree) to 2 (strongly agree):

~~~json
{
  "Category": "Economy",
  "Question_Text": "The government was right to increase employer National Insurance contributions from 13.8% to 15%.",
  "Simple_Explanation": "National Insurance is a tax employers pay on their workers' wages. The government increased this tax from 13.8% to 15%.",
  "How_It_Affects_You": "Businesses may hire fewer people or offer lower wages to cover this extra cost. Could make it harder to find your first job or get a pay rise.",
  "Labour_Score": "2",
  "LibDem_Score": "0",
  "Green_Score": "2",
  "Reform_Score": "-2",
  "Conservative_Score": "-2"
}
~~~

Unlike the chat, the algorithm for matching you with the parties' stances is deterministic. For each party, Civvy counts how many of your answers exactly match that party's score, and turns that into a percentage, both overall and for each policy area ([shown to the user](https://gdrl.dev/projects/civvy/quiz-results.png) as a score out of 10):

~~~swift
let agreementCount = answeredQuestions.filter {
    userAnswers[$0.id] == getPartyScore(for: partyName, in: $0)
}.count
let alignment = 100.0 * Double(agreementCount) / Double(answeredCount)
~~~

On the results page, it also writes a one-sentence summary of your views starting with "Your answers suggest...", and using guided generation, picks out 2 to 5 political terms in it that might be unfamiliar, each with a follow-up question you can tap to learn more.

## Learning

Civvy also has a Learn section with [short lessons](https://gdrl.dev/projects/civvy/learn.mp4) on UK democracy. The main part is an [interactive diagram](https://gdrl.dev/projects/civvy/fptp-vs-pr.mp4) comparing First Past the Post (which the UK uses for general elections), with Proportional Representation.

It draws all 650 seats in the House of Commons as dots in a semicircle, with a dashed line marking the 326 needed for a majority, and using the vote shares from the 2024 general election, the user can toggle between the two systems which recolours the seats to demonstrate how with the exact same vote share, the balance of power would be very different...

## Elections

Civvy also shows your upcoming elections. You enter your home address, and it uses the Electoral Commission's API to [find your next elections](https://gdrl.dev/projects/civvy/elections.mp4), the candidates on your ballot and your polling station, and can add election day and the postal vote deadline to your calendar. You can also pick a candidate and [ask the chat about them](https://gdrl.dev/projects/civvy/chat-candidate.png) and their party. As this is the one part of Civvy that needs the internet, demo mode uses a bundled set of London election data instead.

## Accessibility

Accessibility and inclusivity are core values of the Apple Swift Student Challenge, therefore I wanted Civvy to play nice with Apple's accessibility features, specifically with VoiceOver, Dynamic Type and Reduce Motion.

For VoiceOver, every button and control has a label and a hint, section titles are marked as headers so you can jump between them, and purely decorative images and icons are hidden so they don't get read out. Visual elements that can't be read dot by dot (e.g. the results charts and the FPTP vs PR diagram), are each combined into a single element with a spoken summary instead.

The quiz's slider is custom, so it had to be made accessible by hand: VoiceOver reads each value as words ("Strongly agree" rather than "2"), and you can swipe up or down to change it, which also means it works with Switch Control and Voice Control.

Text uses Apple's built-in text styles, so it scales with Dynamic Type, and where the largest sizes would squash a layout, like the election header, it switches to a stacked layout instead. Finally, custom animations such as the seat sweep and the results charts respect Reduce Motion, so they're skipped entirely when it's turned on.

## Since then

Civvy ended up being one of the 350 winners of the 2026 Swift Student Challenge, which was a great result given it was built in around 3 weeks!

If I were to build it again, the main thing I would change is the knowledge base. As it's bundled with the app, everything Civvy knows is frozen at February 2026, so every policy change since then makes its answers a little more out of date. Ideally, the knowledge base would be rebuilt as new sources are published and downloaded as an update, while the search and the AFM still run entirely on device.

As for Votes at 16, it hasn't had much media attention recently, but it is still on track to be implemented for 2028/29, and I'm looking forward to continuing to be a part of its progress!
