Problem: LLM Context Window and Streaming Data
A typical scenario: a user dictates a lecture or pastes a 100-page PDF. The LLM takes the text but the context window overflows — the response cuts off or ignores the middle. Or a meeting transcript streams in, and a summary is needed immediately after. We solve these problems on iOS and Android with map-reduce summarization, live transcription, and structured output. We use Swift 5.9, Kotlin, Flutter 3.x, gpt-4o, Core Data, and Room. Our solutions include adaptive chunking, parallel processing, and local caching of summaries for offline access. Experience — over 50 projects with AI integration.
For example, for one EdTech client, we implemented live lecture summarization: 30-second audio fragments are processed by SpeechRecognizer, and the accumulated transcript is summarized with a rolling window every 2000 words. The result — structured notes available 5 minutes after the lecture. The key technique is map-reduce: split the document into chunks of 2500 tokens with 200-token overlap, summarize in parallel, then reduce into a final summary. This allows processing documents up to 500 pages without losing coherence.
How Map-Reduce Summarization Solves the Long Document Problem
gpt-4o supports 128k tokens of context, but running the entire document through every time is expensive and slow. The standard pattern — MapReduce:
- Split the document into chunks of 2000–3000 tokens with ~200-token overlap
- Summarize each chunk independently (map)
- Summarize the list of summaries into a final summary (reduce)
More about chunking parameters
In practice, the chunk size depends on the model: for gpt-4o-mini, 3000 tokens is optimal, for gpt-3.5-turbo — 2000. The 200-token overlap ensures no sentence is broken at chunk boundaries.
// iOS
func summarizeDocument(_ text: String) async throws -> String {
let chunks = chunkText(text, maxTokens: 2500, overlap: 200)
// Parallel summarization of chunks
let partialSummaries = try await withThrowingTaskGroup(of: String.self) { group in
for chunk in chunks {
group.addTask { try await self.summarizeChunk(chunk) }
}
var results = [String]()
for try await result in group { results.append(result) }
return results
}
// Final reduce
let combined = partialSummaries.joined(separator: "\n\n")
return try await summarizeChunk(combined, isFinal: true)
}
func chunkText(_ text: String, maxTokens: Int, overlap: Int) -> [String] {
// ~4 characters = 1 token for Russian text (approximate)
let chunkSize = maxTokens * 3
let overlapSize = overlap * 3
var chunks = [String]()
var start = text.startIndex
while start < text.endIndex {
let end = text.index(start, offsetBy: chunkSize, limitedBy: text.endIndex) ?? text.endIndex
chunks.append(String(text[start..<end]))
guard let nextStart = text.index(start, offsetBy: chunkSize - overlapSize, limitedBy: text.endIndex) else { break }
start = nextStart
}
return chunks
}
withThrowingTaskGroup allows parallel execution of tasks for each chunk. For 10 chunks, this is 5–7 times faster than sequential processing.
Why Structured Output Improves UX
Summaries can be of several types. Prompts for each:
| Type | Prompt Instruction |
|---|---|
| Brief summary | «Summarize in 3-5 sentences. Key points only.» |
| Bullets | «Extract 5-8 key points as bullet list. Each point = one idea.» |
| Mind-map JSON | «Return JSON: {title, branches: [{topic, subtopics: []}]}» |
| Q&A | «Generate 5 questions and answers based on the text.» |
| Action items | «Extract only action items and deadlines. Format: - [Task]: [Deadline/Owner]» |
For structured output, we use response_format: { type: "json_object" } in the OpenAI API — the model must return valid JSON without a markdown wrapper.
let requestBody: [String: Any] = [
"model": "gpt-4o-mini",
"messages": messages,
"response_format": ["type": "json_object"],
"temperature": 0.2
]
Live Transcription: Real-Time Audio Processing
If the source is a microphone (lecture recording, meeting), the summary builds on top of transcription. The flow:
AVAudioEngine → 30-second fragments → SpeechRecognizer (Whisper API or native SFSpeechRecognizer) → accumulated transcript → summarization with rolling window.
// Summarize every 5 minutes of transcript with overlap
class LiveSummaryEngine {
private var transcript = ""
private var lastSummaryLength = 0
func onNewTranscript(_ chunk: String) {
transcript += " " + chunk
// Summarize new block when ~2000 words accumulated
let wordCount = transcript.split(separator: " ").count
if wordCount - lastSummaryLength > 2000 {
Task { await summarizeNewBlock() }
lastSummaryLength = wordCount
}
}
private func summarizeNewBlock() async {
let newContent = transcript.components(separatedBy: " ")
.dropFirst(max(0, lastSummaryLength - 200)) // overlap 200 words
.joined(separator: " ")
let summary = try? await llmService.summarize(newContent)
await MainActor.run { appendToNotes(summary ?? "") }
}
}
On Android, use SpeechRecognizer + MediaRecorder with chunking by RECOGNIZER_RESULT_STABILITY.
Where to Store Summaries?
Summaries must be available offline and support search. On iOS — Core Data or SwiftData with full-text index via NSPersistentStoreDescription with SQLite FTS5. According to Apple documentation, FTS5 full-text index speeds up search by 10x. On Android — Room with @Fts4 or @Fts5 annotation.
Semantic search (by meaning, not words) — via vector embeddings stored locally in SQLite-VSS or on the server via pgvector. For mobile apps, server-side embedding search with cached results is sufficient.
Step-by-Step Implementation Plan
- Requirements analysis: determine content type (text/audio), frequency, need for offline access.
- Model selection:
gpt-4o-minifor speed,gpt-4ofor complex cases. - Implement chunking and summarization: use map-reduce with parallel tasks.
- Integrate transcription: connect AVAudioEngine/SpeechRecognizer on iOS or SpeechRecognizer on Android.
- Configure storage: choose Core Data or Room with FTS for search.
- Testing: run on real data, verify summarization quality.
Each stage is accompanied by architectural documentation and source code. We also train your team on AI features and provide a warranty of up to 6 months after delivery.
What's Included
- Architecture and API integration documentation
- Source code with comments and tests
- Repository access (Git) and CI/CD pipeline
- Team training (2 sessions)
- 6-month warranty support
Estimated Timelines
| Task | Timeframe |
|---|---|
| Basic API summarization | 2–3 days |
| Map-reduce + multiple output formats | 1.5 weeks |
| Live summarization with transcription | 3–4 weeks |
Cost is calculated individually after project analysis. Time savings on materials preparation for one project reached 80%.
Our Experience and Guarantees
We specialize in mobile development with AI for over 6 years. We have completed 50+ projects, including apps with document summarization, speech-to-text, and live transcription. We use a modern stack: Swift 5.9, Kotlin, Flutter 3.x, OpenAI API, Firebase, Core Data, Room. We guarantee compliance with App Store Review Guidelines and Google Play Policy.
Contact us — we'll assess your project. Order end-to-end development and get a consultation on your use case.







