Newsletter Curator Project Breakdown
An autonomous AI newsletter curation agent using Gmail API, Gemini LLM scoring, Qdrant semantic memory, dynamic vector rules, and Telegram delivery.
Being interested in both data science and finance, I have always tried to keep up with industrial trends and the latest news by subscribing to newsletters and reading blogs. However, the problem was that I ended up with too many newsletters to read, and too little time to decide which one was relevant and interesting to me. This project solves that problem for me: It first pulls unread newsletters/blogs from my inbox and scores them based on my interest profile. This score is then blended based on my previous feedback (thumbs down/thumbs up), before sending me the top 5 articles that I would be interested to read through Telegram every morning.
These are some of the takeaways that I got from this project:
- A zero-shot LLM is a good start, but feedback is what makes the system tailored and personal. Blending the system’s LLM score with an embedding based preference signal, with the blend weight ramping up as feedback accumulates avoided the issue of a cold start and any abrupt changes in behaviour.
- Self-updating rules need guardrails to ensure it doesn’t affect performance. I learnt this when an exclusion detector clustered 66 articles that I disliked, and produced a new rule called “industry news and product drops”. This was far broader than my actual dislikes and contradicted one of my own interest domains.
- An agent is only worth its cost where judgement pays. A fixed workflow is cheaper, more predictable, and easier to debug. I kept the backbone deterministic and used an agent only when the LLM was uncertain about certain scores, with hard limits, read-only tools and a fallback to the first-pass score.
- Measuring recommendation quality was harder than I expected. Only delivered items receive feedback, so I could only measure precision and ranking quality, without recall.
Initial challenges faced
Newsletter curation had its own set of challenges, because they are generally nested MIME emails full of tracking links, boilerplate code and ads, with their text written by third parties. In case of malicious intent, some articles might even contain instructions aimed at an LLM/agent, and so it must be treated as data only and not instructions. Additionally, on the very first day of deployment my system had no labels yet and had to work from a written interest profile alone and was only able to learn from behavior later. One of the hardest challenges I faced was the free tier limits that were available. I was not paying for anything and had to ensure that the system degrades gracefully if the APIs ever hit their rate limit and that the model/agents stay within the free-tier limit.

Ingestion & Cleaning
The pipeline reads unread emails carrying a “newsletters” label through the Gmail API, authenticated with a OAuth token that is refreshed every 7 days. Each email’s MIME tree is walked recursively to find a HTML body. The HTML is converted to readable text with Trafilatura, with BeautifulSoup as fallback, while MIME-encoded subject lines are decoded.
Before any paid call is made, the cleaned text is hashed with SHA-256 and checked against Supabase. A duplicated is marked read and skipped, so repeated issues cost nothing.
To find the story article link, every link with long enough anchor text is ranked by fuzzy similarity to the subject. Sponsor links and navigation links are removed with a blocklist, redirects are resolved and tracking parameters are stripped. If nothing usable is found, it returns nothing instead of guessing.
Scoring with the LLM
The interest profile was first written as a small JSON file with weighted domains (fintech and payments, applied AI/ML engineering, quantitative finance, tech industry news), example headlines that interested me and a list of exclusions. This interest profile is injected into the scoring prompt together with the subject, sender and the first 4000 characters of the newsletter.
The model is instructed to return JSON only, with a score between 0 to 1, a short reasoning and a 3-bullet point summary. The response is validated in code (score in range, summary and reasoning present) before it can reach the database. Failures are retried twice with a linear backoff of 20 and 40 seconds, because immediately re-hitting a rate limit only burns more quota. As a safety guardrail, the prompt tells the model that the newsletter text may contain embedded instructions and must be treated purely as content to evaluate.

Semantic memory: learning from feedback
Every thumbs-up/thumbs-down is embedded (title + summary) with a Gemini embedding model, truncated to 768 dimensions to fit the Qdrant free-tier storage cap, and stored in a liked or a disliked collection. For a new candidate, the system embeds it and takes the average cosine similarity to its five nearest neighbors in each collection, rescaled to a 0 to 1 range. The semantic score is calculated by taking a baseline of 0.5 and adding half the difference between its similarity to liked and disliked stories, clipped to the 0-1 range, so 0.5 means no signal. The final score is
$$(1-W) \times \text{LLM score} + W \times \text{semantic score}$$
where W is the number of liked items divided by 100, capped at 0.4. without feedback, the weight W is 0 and the system relies purely on LLM scoring. The embedding signal comes in gradually as feedback accumulates. If Qdrant is unreachable the weight falls back to 0 for that run, so a feedback-store outage degrades quality rather than crashing the job.
Procedural memory: Exclusion Detector
Semantic memory adjusts score softly, while the exclusion detector turns repeated dislikes into a hard rule. At the start of each run it pulls every disliked vector from Qdrant, connects pair whose cosine similarity is at least 0.84, and treats each connected group of at least 3 articles as a cluster. The LLM is then asked to name each cluster in 3 to 6 words in the form of an exclusion list. New phrases are then added to the interest profile that the scoring prompt reads.
During a live run, the exclusion detector found a cluster of 66 disliked articles and wrote the rule “industry news and product drops”. That was far broader than what I disliked and contradicted one of my interests in the profile. As a result, the next three newsletters all received a score of 0.1 because they fell under the “industry news and product drops” category. This was one of the limitations of my project which uses single-link clustering, which chains loosely related items together. This taught me that learned rules should be constrained and reviewed consistently.
Agentic escalation
Items’ scores that fall between the range of 0.4 and 0.7 inclusive are the ones that the LLM is least sure about and are sent to an agent for review. This agent utilizes a Gemini function-calling loop with two tools: one fetches the full article, and the other looks up how similar the item is to stories I previously liked and disliked. The loop ends by submitting a verdict, a score and a short reasoning.
Below are the guardrails that I implemented for the agent:
Hard limits
The agent can only make four model calls per item at most, and two escalated items per run. On the final step, the model is forced to submit a verdict, so the loop always terminates instead of looping infinitely.
Read-only tools
The agent cannot write to the database, mark email read or send messages. Its only effect is a verdict that code validates and clamps to the 0-1 range.
Bound fetch tool
The fetch tool takes no URL argument and can only open the item’s own link, so text hidden inside a malicious newsletter cannot point it elsewhere. It also rejects private and loopback addresses.
Safe failure
Any error, invalid verdict or missing tool call returns nothing and the pipeline keeps the first-pass score.
Feature flag
The use of this agent is controlled by an environment variable and can be switched off without a code change.
Delivery and Feedback loop
Each morning, the top 5 recommendations are sent to Telegram. Generated text is HTML-escaped first, because a raw “&” or “<” in a summary makes Telegram reject the whole message. If any story fails to send, a failure alert is sent so a broken batch never just disappears. A digest_sent_at timestamp also guards against re-sending the same story twice.
Button taps (thumbs-up/thumbs-down) arrive at a small Flask webhook. It authenticates every request twice, with a secret in the URL path and Telegram’s own secret-token header. The Supabase write of the feedback is the source of truth, so it runs synchronously before Telegram gets its response, and only the slower embedding and Qdrant upsert runs in a background thread.
Reliability Designs
- Write-then-mark: An email is only marked read after its database insert is confirmed, so failures are retried on the next run
- Per-message isolate: 1 bad email never stops the batch
- Idempotency: Use of content-hash deduplication on ingestion and digest timestamp delivery
- Graceful degradation: Qdrant outages, failed URL extraction, a failed embedding or a failed agent run all fall back to a simpler behavior
Cost Management & Optimization
This project was designed to run entirely on free tiers, so a lot of the work went into avoiding calls rather than making them cheaper.
- Using the cheapest viable model: Scoring and cluster labelling used a small Gemini Flash-Lite model so that cost and behavior do not drift.
- Deduplication before spending anything: Before any LLM/embedding calls, the content-hash check runs first to ensure that there is no duplication of content, helping to save unnecessary calls.
- Skipping empty bodies before scoring
- Input truncation: Only the first 4000 characters of each newsletter are sent to bound tokens spent per call.
- Hard cap per run: Each execution is capped at 5 emails being processed, so any backlogs will not lead to surprise billings.
- Small, deterministic outputs: The LLM’s temperature is dialed down to prevent creative outputs, with responses being limited to a 3 bullet summary and JSON only format.
- Bounded retries with backoff
- Smaller embeddings: I chose to use 768 dimensions instead of 3072, which would have stretched the free-tier vector storage cap.
- Gradual semantic blend
- Using agents only when needed: The agent is only called within a range of 0.4-0.7, which shows that the model is unsure of how relevant the newsletter is. There is also a cap of 2 items per run and 4 model calls per item to ensure lowered costs.
- Off the hot path: Embedding on feedback runs in a background thread so the webhook responds fast.
- Top 5 digest: Only the top 5 items are delivered, which narrows down the articles to only the most relevant based on my interest profile.
Results & Metrics
I ran SQL queries measuring metrics such as recommendation accuracy, agent usage, agent accuracy and number of LLM calls per day. Overall, this newsletter system ranks well. When a liked and disliked item come from the same daily curated digest, the system ranked the liked article higher 93% of the time. Items scoring 0.6 or higher were liked 98.5% of the time, and items below 0.4 were liked about 10% of the time. Very few items were scored in the middle, which further shows that the system is decisive.
Like rate also falls from quickly from the most highly ranked article in the daily digest downwards. From 87% at position 1 to 73%, 47%, 18% and 7% between positions 2 to 5. This shows that the ranking of article relevance is meaningful, as just reading the top 3 articles ranked by the system would already cover most of the content that I’m interested in.
The feedback loop used by the system also works well, as the accuracy of the rankings were significantly lower in the earlier weeks at 0.733, but steadily increased to 0.88 as the amount of feedback received increased over the weeks.
Since this system was implemented not too long ago, it remains to see how well the agent works. However, the agent performance seems promising as it was directionally right on all the cases it was escalated to thus far. The agent escalated 9 border-line items in roughly 2 weeks, raising the final score of articles 5 times and lowering the final score 4 times. Out of all 9 cases, it correctly evaluated whether the article would be relevant to my interests.
Importantly, the costs of the system stayed small. Scoring costs one call per email (5 a day), and the agent added 0 to 7 calls on the days it ran, with a peak of 12 calls in one day. Agent costs are also further bounded with a cap of 2 escalated items per run and 4 steps per item, as mentioned previously.
Insights and Takeaways
The most useful lesson I took away from this project was that reliability and cost control mattered more than model choice. A cheap model with validation, caps and fallbacks did more for the system than any prompt tweak. Besides that, there are a few other points mentioned below:
- Design for partial failure: Idempotency, write-then-mark and graceful degradation meant that the system could fall in many places without losing an email or breaking the daily digest.
- Putting the source of truth on the synchronous path: Only non-critical work, like embedding, belongs in the background. A lost vector costs a little accuracy, but a lost thumbs-up would silently corrupt the training signal.
- Cost is mostly about what you avoid calling: Deduplication, truncation, hard caps and a small model contributed to majority of the costs savings.
- Use an agent where judgment pays, not everywhere: In this context, a fixed workflow is cheaper, more predictable and easier to debug. The agent is reserved for the uncertain cases where reading the full article or recalling past feedback can change the decision.
- Learning systems need guardrails and review: The exclusion detector showed how quickly an automatic learner can over-generalize. Constrained, reviewable rules are safer than fully automatic ones.