<?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 Nishant Choudhary on Medium]]></title>
        <description><![CDATA[Stories by Nishant Choudhary on Medium]]></description>
        <link>https://medium.com/@codepoetn?source=rss-1ace73d3cbf7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Sz1qhrRnjHfamAahG_y7Pw.png</url>
            <title>Stories by Nishant Choudhary on Medium</title>
            <link>https://medium.com/@codepoetn?source=rss-1ace73d3cbf7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:04:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codepoetn/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[Build a Gmail Agent with Scalekit, LangChain, Flask, & Claude]]></title>
            <link>https://medium.com/@codepoetn/gmail-ai-agent-development-guide-e9ea7d683926?source=rss-1ace73d3cbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ea7d683926</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agent-development]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Nishant Choudhary]]></dc:creator>
            <pubDate>Mon, 11 May 2026 07:37:45 GMT</pubDate>
            <atom:updated>2026-05-11T08:02:41.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-AxrW4HTLSx12IP7GwCkg.gif" /><figcaption>Gmail AI Agent Development</figcaption></figure><blockquote><em>I built an agent, and thought, why not publish an unfiltered guide to building agents with real errors, real fixes, and every concept explained. Anyway, my medium has been lying dormant for long. If you find any gaps in the content for beginner agent developers, please do point out in the comments, I’ll fix it.</em></blockquote><p><strong>Gmail Agent Stack:</strong></p><p>Python 3.13 · LangChain 1.2 · <a href="https://scalekit.com/">Scalekit</a> (AgentKit) · Flask · Claude Sonnet 4</p><p>(If you’re unaware of flask, no worries, you’ll still be able to follow through the guide if you’re well versed with Python)</p><h3>Context, a.k.a What to Expect From This Gmail Agent Development Guide</h3><p>This guide walks you through <strong>building a production-grade Gmail agent</strong> — a <strong>conversational interface</strong> where <em>a user can ask in plain English</em> to <strong>search emails, read content, apply labels, trash messages, </strong>and<strong> get inbox stats</strong>. I repeat, User just asks the agent to do something in plain english, and the agent handles everything internally. That means, the user never sees a message ID, an API parameter, or a token.</p><p><em>What makes this guide different?</em></p><p>It’s built from a real development session, including every error that came up, every wrong assumption made, and every concept that needed clarification. If you’ve tried to build an agent like this before and hit walls, this is the guide for you.</p><h3>What you’ll build?</h3><p>A Flask web app with a chat interface. The <strong>user connects their Gmail account once via OAuth</strong>, then chats with an agent that can:</p><ul><li>Search emails with full Gmail query syntax</li><li>Read full email body content</li><li>Browse threads and conversations</li><li>Find emails with attachments</li><li>Apply labels (including creating new ones)</li><li>Move emails to trash</li><li>Mark emails as spam</li><li>Get inbox stats and top senders</li><li>Look up contacts</li></ul><p>This is what you’ll end up with:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7BisneGTx9k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7BisneGTx9k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7BisneGTx9k%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3847914a477e82ed49568d0a328e708/href">https://medium.com/media/e3847914a477e82ed49568d0a328e708/href</a></iframe><h3>Gmail Agent Development Architecture:</h3><pre>User (Browser) → Flask App → LangChain Agent (Claude)<br>                                      ↓<br>                             Scalekit AgentKit → Gmail API</pre><pre>Scalekit handles: OAuth flow, token storage, token refresh, API proxy, tool execution</pre><h3>Prerequisites:</h3><ul><li>Python 3.10+</li><li>A <strong>Scalekit account</strong> (free tier works)</li><li>An <strong>Anthropic API key</strong></li><li>A Gmail account to test with</li><li>Basic Python knowledge</li></ul><blockquote><em>ℹ️ </em><strong><em>Google Cloud</em></strong></blockquote><blockquote><em>You do </em><strong><em>not</em></strong><em> need Google Cloud for development. Scalekit provides its own Google OAuth credentials so you can test immediately. Google Cloud is only needed when going to production with your own branding.</em></blockquote><h3>Gmail Agent Development Tech Stack:</h3><h4>1. Claude (claude-sonnet-4)</h4><p>The LLM brain of the agent. Handles all reasoning — understanding the user’s intent, deciding which tools to call, chaining multiple tool calls, and formatting the response in plain English. We use claude-sonnet-4-20250514 via langchain-anthropic.</p><h4>2. LangChain 1.x</h4><p>LangChain went through a major breaking API change at version 1.0. The old AgentExecutor and create_tool_calling_agent are removed. The new API is create_agent from langchain.agents, which wraps LangGraph under the hood. You invoke it with a messages list and get back a messages list.</p><blockquote><em>⚠️ </em><strong><em>Breaking Change</em></strong></blockquote><blockquote><em>If you see </em><em>ImportError: cannot import name &#39;AgentExecutor&#39; or </em><em>cannot import name &#39;create_react_agent&#39; — you&#39;re on LangChain 1.x. The correct import is </em><em>from langchain.agents import create_agent.</em></blockquote><h4>3. Scalekit (AgentKit)</h4><p>Scalekit is the auth and connector layer. It does three things for us:</p><ol><li><strong>OAuth orchestration</strong> — handles the entire Gmail OAuth flow, token exchange, and storage. Your app never touches a token.</li><li><strong>Token vault</strong> — stores tokens per user, auto-refreshes before expiry.</li><li><strong>Tool execution + API proxy</strong> — two ways to call Gmail: via named tools (execute_tool) or via a raw proxy (actions.request) that auto-injects the user&#39;s token.</li></ol><h4>Scalekit’s default credentials vs BYOC:</h4><p>When you create a Gmail connection in Scalekit, by default it uses <strong>Scalekit’s own Google OAuth app</strong>. This means:</p><ul><li>No Google Cloud setup needed</li><li>Works immediately for testing</li><li>Scalekit’s app name appears on the consent screen (not yours)</li><li>Scalekit controls which scopes are available</li></ul><p><strong>BYOC (Bring Your Own Credentials)</strong> means you register your own Google OAuth app and paste the credentials into Scalekit. This is needed for production — your app name on the consent screen, your scope control.</p><h3>Gmail Agent Development Project Setup:</h3><h4>Folder structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*X8x0QQdGaJKpWfkaPqZ-ww.png" /><figcaption>Project Structure for Agent development</figcaption></figure><p>gmail-agent/ <br>├── <strong>app.py</strong> # Flask app — routes, session, chat endpoint <br>├── <strong>agent.py</strong> # LangChain agent — tools, system prompt, history <br>├── <strong>requirements.txt </strong><br>├── <strong>.env</strong> # secrets — never commit this <br>├── <strong>.gitignore</strong> <br>├── <strong>auth/</strong> <br>│ ├── __init__.py <br>│ └── <strong>scalekit_auth.py</strong> # Scalekit client, auth link, connection status <br>├── <strong>tools/ </strong><br>│ ├── __init__.py <br>│ └── <strong>gmail_tools.py</strong> # all Gmail tools <br>├── <strong>templates/</strong> <br>│├── <strong>index.html</strong> # chat interface <br>│└── <strong>connect.html</strong> # Gmail connect page</p><h4>Python Package Installations</h4><pre>mkdir gmail-agent &amp;&amp; cd gmail-agent                     # creates a folder gmail-agent in your current directory and moves into it.<br>python -m venv .venv &amp;&amp; source .venv/bin/activate.      #starts a virtual environment<br><br>pip install langchain langchain-anthropic <br>            langchain-core langgraph <br>            flask <br>            python-dotenv <br>            scalekit-sdk-python <br>            google-auth google-auth-oauthlib<br>            google-api-python-client                   # You&#39;ve to install all these packages/libraries from your terminal in your virtual environment</pre><blockquote><em>⚠️ </em><strong><em>Common Mistake</em></strong></blockquote><blockquote><em>The pip package is </em><em>scalekit-sdk-python, </em><strong><em>not</em></strong><em> </em><em>scalekit-sdk. The latter doesn&#39;t exist and gives a &quot;no matching distribution&quot; error. Sometimes, claude/gemini will suggest you to install </em><em>scalekit-sdk but it’s not correct. Always use </em><em>scalekit-sdk-python .</em></blockquote><h4>Environment variables (.env)</h4><p>.env file will have SCALEKIT-ENV-URL , SCALEKIT-CLIENT-ID , SCALEKIT-CLIENT-SECRET; and you can get all of this only after <a href="https://auth.scalekit.com/a/auth/signup">registering on <strong>Scalekit</strong></a>, of course. It’s very easy, hardly 20 - 3 0 seconds is all it takes.</p><pre># You&#39;ll get these from Scalekit — register on https://auth.scalekit.com/a/auth/signup -&gt; from scalekit&#39;s dashboard → Developers → Settings → API Credentials<br>SCALEKIT_ENV_URL=https://yourenv.scalekit.dev    # ensure there is no trailing slash<br>SCALEKIT_CLIENT_ID=skc_xxxxxxxxxx<br>SCALEKIT_CLIENT_SECRET=sks_xxxxxxxxxx<br><br># Gmail connection name - this must match exactly what you named it in Scalekit dashboard<br>GMAIL_CONNECTION_NAME=MY_GMAIL<br># This you&#39;ll get from Anthropic&#39;s console<br>ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxx<br># Flask - generate once: python -c &quot;import secrets; print(secrets.token_hex(32))&quot;<br>FLASK_SECRET_KEY=your-generated-secret-key</pre><p>Critical: FLASK_SECRET_KEY</p><p>Never use app.secret_key = secrets.token_hex(32) — this regenerates on every restart, invalidating all session cookies and causing <strong>403 Forbidden</strong> errors. Generate it once, store it in .env, and never change it. <em>Why is this important?</em> Once you’ve verified the gmail OAuth using Scalekit, you app remains connected; so, you avoid connecting everytime you have an app iteration during development phase. Also, just a tip, in case, you need to disconnect Gmail from your Slack app, you’ll have to clear cookies for the app — you can do that right from the address bar in chrome browser.</p><h4>Git Ignore (.gitignore)</h4><p>Your .gitignore file should never commit environment variable files or misc files like virtual environment files or __pycache__. This is important to avoid others from discovering and exploiting your API keys and Scalekit credentials.</p><pre>.env<br>.venv/<br>__pycache__/<br>*.pyc</pre><h3>1. Scalekit Setup</h3><h4>a. Create a Scalekit account</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IU7fAW_hvoiSO4mQANcapg.png" /><figcaption><a href="https://auth.scalekit.com/a/auth/signup">https://auth.scalekit.com/a/auth/signup</a></figcaption></figure><p>Sign up on <a href="https://app.scalekit.com/">scalekit.com</a> by entering your work email. Verify email OTP, and fill in the details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQQ7BmKuZn_A1hXpCBvWzw.png" /><figcaption>Scalekit’s Post Login Screen</figcaption></figure><p>On the next screen, choose “<strong>connect my agents to apps</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wowOITJbsE60gh795060pw.png" /></figure><p>That’s it. You’re ready to get started with Scalekit. Dev environment is auto setup for you. As easy as that.</p><p>Now, from the Scalekit’s dashboard, <strong>click</strong> on ‘Settings’ from the left navigation panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*Til2OYO1UQSk199xgxeo7w.png" /><figcaption>Scalekit’s navigation panel</figcaption></figure><h4>b. Get API credentials</h4><p><strong>Settings → API Credentials </strong>tab will have SCALEKIT-ENV-URL , SCALEKIT-CLIENT-ID , SCALEKIT-CLIENT-SECRET. Copy all three from there.</p><ul><li><strong>Environment URL</strong> will look like <a href="https://yourapp.scalekit.dev/">https://yourapp.scalekit.dev</a></li><li><strong>Client ID</strong> will look likeskc_123...</li><li><strong>Client Secret</strong> — will be masked as asterisk, you’ll have copy button.</li></ul><p>Paste all three into your .env.</p><blockquote><em>🚨 </em><strong><em>Invalid Domain Error</em></strong></blockquote><blockquote><em>If you get </em><em>ScalekitNotFoundException: invalid domain in request — your </em><em>SCALEKIT_ENV_URL is wrong. Common causes: trailing slash, </em><em>http:// instead of </em><em>https://, or still a placeholder value. The URL must be something like </em><em>https://yourenv.scalekit.dev from your scalekit’s </em><strong>Settings → API Credentials </strong>tab <em>with nothing after </em><em>.dev.</em></blockquote><h4>c. Create a Gmail connection in the dashboard</h4><p>Left sidebar → <strong>AgentKit → Connections → Create Connection</strong> → select <strong>Gmail</strong> → click <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqxuzD2b3lB6yiM_kWddlA.png" /><figcaption>Choose Gmail to connect your Gmail.</figcaption></figure><p>In the <strong>Connection Name</strong> field, type MY_GMAIL. Click Save.</p><p>After successful connection, it would show like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lv7JkMGlCadmX60sFu9-uA.png" /><figcaption>Gmail Connector Connected in Scalekit</figcaption></figure><p>Add to your .env: GMAIL_CONNECTION_NAME=MY_GMAIL</p><blockquote><em>⚠️ </em><strong><em>Connection Name is Case-Sensitive</em></strong></blockquote><blockquote><em>The connection name in your code must match the dashboard </em>exactly<em>. If the dashboard shows </em><em>MY_GMAIL and your code passes </em><em>my_gmail, every API call will fail silently.</em></blockquote><h4>How the auth flow actually works for your agent with Scalekit</h4><p>For this Gmail Agent Development Tutorial, Scalekit’s OAuth flow does <strong>not</strong> redirect back to your Gmail app automatically after the user authorizes. Here’s the full flow:</p><ol><li>Your flask app calls get_authorization_link(); Scalekit generates a magic link, which opens up in a new tab.</li><li>User opens the link, lands on Google’s consent screen</li><li>User authorizes → Google redirects to <strong>Scalekit’s</strong> callback URL (not yours)</li><li>Scalekit exchanges the code for tokens and stores them in its vault</li><li>Scalekit shows its own success page</li><li>The connected account status becomes ACTIVE</li></ol><p><strong>Your app has no callback to handle.</strong> Scalekit manages the entire OAuth exchange. The correct pattern is to open the auth link in a new tab, then give the user a “I’ve authorized — continue” button that takes them back to your app, where you check the connected account status.</p><p>Note: The UI of the demo is not flawless, you’ve to hide the authorize button automatically when the user is connected. And your app must also ship a disconnect button. But that’s web development logic. This tutorial is about agent development parts. So, we skip all the nitty-gritty, and just focus on what’s necessary to get up production-ready Gmail agent.</p><p>Anyway, here’s the crux of this section:</p><blockquote><em>ℹ️ </em><strong><em>No Redirect Parameter</em></strong></blockquote><blockquote><em>get_authorization_link() does not accept a </em><em>success_redirect_uri or </em><em>redirect_uri parameter for AgentKit flows. Attempts to pass one are silently ignored. The success page is Scalekit&#39;s hosted UI — by design.</em></blockquote><h3>2. Gmail connector tools</h3><p><a href="https://docs.scalekit.com/agentkit/connectors/gmail/">Scalekit’s Gmail connector</a> exposes exactly 8 named tools callable via execute_tool. Use the exact names below — any typo causes a silent failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*239Tem_YTr_1o-Z6hxCwmw.png" /><figcaption>Scalekit’s Gmail Agent Tools</figcaption></figure><p>Tool name | What it does<br>gmail_fetch_mailsSearch/fetch emails with Gmail query syntax<br>gmail_get_message_by_idGet full content of one email by ID <br>gmail_get_thread_by_idGet all messages in a thread <br>gmail_list_threadsList threads with search filters <br>gmail_list_draftsList draft emails<br>gmail_get_attachment_by_idDownload an attachment by ID <br>gmail_get_contactsFetch user&#39;s contact list<br>gmail_search_peopleSearch contacts by name/email</p><h4>Write operations via proxy — custom Gmail agent tools</h4><p>Scalekit’s Gmail connector does <strong>not</strong> yet include tools for labeling, trashing, or marking spam. so, we will create that using API proxy. These are done via actions.request() — This is <strong>Scalekit&#39;s proxy API, which auto-injects the user&#39;s OAuth token into raw Gmail REST API calls</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0unhwyaNAlaMSKEkqRvHQ.png" /><figcaption>Gmail Agent Tools</figcaption></figure><h4>The message ID problem, and the solution</h4><p>A naive Gmail agent would expose message IDs to the user and ask them to provide one when labeling or trashing. This completely defeats the purpose of a conversational agent.</p><p>The correct pattern: <strong>the agent always searches first, gets IDs internally, then acts.</strong> The user says “label emails from Rahul as URGENT,” the agent calls apply_label with search_query=&#39;from:Rahul&#39;, which internally searches for matching emails, gets their IDs, and applies the label. The user never sees an ID.</p><h3>3. The LangChain Agent</h3><h4>LangChain 1.x API</h4><p>In LangChain 1.x, the agent is created with create_agent and invoked with a messages list:</p><pre>from langchain.agents import create_agent<br>agent = create_agent(<br>    model=llm,<br>    tools=tools,<br>    system_prompt=&quot;Your system prompt here&quot;,<br>)<br>result = agent.invoke({&quot;messages&quot;: history})<br>ai_reply = result[&quot;messages&quot;][-1].content</pre><h4>System prompt design</h4><p>The system prompt does the heavy lifting. It must tell the agent:</p><ul><li>Its capabilities (so it can answer “what can you do?”)</li><li>When to ask before acting (write ops) vs act immediately (read ops)</li><li>Never to expose IDs to the user</li><li>How to handle pagination</li><li>How to chain tools (search → act)</li><li>The user_id to pass to every tool call</li></ul><h4>Conversation history</h4><p>LangChain 1.x doesn’t have built-in session memory in create_agent. We maintain it ourselves with a simple dict keyed by session ID:</p><pre>_histories: dict[str, list] = {}<br><br>def chat(user_id, message, session_id):<br>    if session_id not in _histories:<br>        _histories[session_id] = []<br>    history = _histories[session_id]<br>    history.append(HumanMessage(content=message))<br>    result = agent.invoke({&quot;messages&quot;: history})<br>    _histories[session_id] = result[&quot;messages&quot;]   # save full history<br>    return result[&quot;messages&quot;][-1].content</pre><h3>4. The Flask App</h3><h4>Session management</h4><p>Flask uses a signed cookie for sessions. The signing key is app.secret_key. If this changes between restarts (which it does if you use secrets.token_hex(32) inline), every existing session cookie becomes invalid and Flask returns a 403.</p><blockquote><em>✅ </em><strong><em>Fix</em></strong></blockquote><blockquote><em>Generate the key once: </em><em>python -c &quot;import secrets; print(secrets.token_hex(32))&quot;, and Store in </em><em>.env as </em><em>FLASK_SECRET_KEY. Use </em><em>app.secret_key = os.getenv(&quot;FLASK_SECRET_KEY&quot;).</em></blockquote><h4>HTML in Python strings — the SyntaxWarning</h4><p>Putting HTML with JavaScript inside a Python triple-quoted string causes SyntaxWarning: invalid escape sequence for any regex or JS escape sequences like \s, \n, \d. Python interprets the backslash as a Python escape.</p><blockquote><em>✅ </em><strong><em>Fix</em></strong></blockquote><blockquote>We move all HTML into <em>templates/</em> and use <em>render_template()</em>. Flask&#39;s Jinja2 template engine handles the files natively — no Python string escaping issues.</blockquote><h4>The chat endpoint</h4><p>The chat interface uses fetch() for all message sending — no page reloads. The /chat route accepts JSON in, returns JSON out:</p><pre># JS sends: { &quot;message&quot;: &quot;show my unread emails&quot; }<br># Flask returns: { &quot;response&quot;: &quot;Here are your 5 unread emails...&quot; }<br># Or on error: { &quot;error&quot;: &quot;Gmail not connected&quot; }<br><br>python app.py<br># Visit http://localhost:5000 → Connect Gmail → chat</pre><h3>Final Code</h3><p>Every file, complete and copy-pasteable. These are the exact final working versions for developing a Gmail Agent with conversational interface and Agent Auth flow.</p><p><strong>app.py</strong></p><pre>import os<br>import secrets<br>from flask import Flask, request, jsonify, redirect, session, render_template<br>from auth.scalekit_auth import get_or_create_account, get_auth_link, is_connected<br>from agent import chat<br>from dotenv import load_dotenv<br><br>load_dotenv()<br>app = Flask(__name__)<br>app.secret_key = os.getenv(&quot;FLASK_SECRET_KEY&quot;)<br>@app.route(&quot;/&quot;)<br>def index():<br>    user_id = session.get(&quot;user_id&quot;)<br>    connected = bool(user_id and is_connected(user_id))<br>    return render_template(&quot;index.html&quot;, connected=connected)<br>@app.route(&quot;/auth/login&quot;)<br>def login():<br>    user_id = session.get(&quot;user_id&quot;)<br>    if not user_id:<br>        user_id = secrets.token_urlsafe(16)<br>        session[&quot;user_id&quot;] = user_id<br>    account = get_or_create_account(user_id)<br>    if account.status == &quot;ACTIVE&quot;:<br>        return redirect(&quot;/&quot;)<br>    auth_url = get_auth_link(user_id)<br>    return render_template(&quot;connect.html&quot;, auth_url=auth_url)<br>@app.route(&quot;/auth/disconnect&quot;)<br>def disconnect():<br>    session.clear()<br>    return redirect(&quot;/&quot;)<br>@app.route(&quot;/chat&quot;, methods=[&quot;POST&quot;])<br>def chat_route():<br>    user_id = session.get(&quot;user_id&quot;)<br>    if not user_id or not is_connected(user_id):<br>        return jsonify({&quot;error&quot;: &quot;Gmail not connected.&quot;}), 401<br>    data = request.get_json()<br>    message = (data or {}).get(&quot;message&quot;, &quot;&quot;).strip()<br>    if not message:<br>        return jsonify({&quot;error&quot;: &quot;Empty message.&quot;}), 400<br>    try:<br>        response = chat(user_id, message, session_id=user_id)<br>        return jsonify({&quot;response&quot;: response})<br>    except Exception as e:<br>        return jsonify({&quot;error&quot;: str(e)}), 500<br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=False, port=5000)</pre><p><strong>agent.py</strong></p><pre>import os<br>from dotenv import load_dotenv<br>from langchain.agents import create_agent<br>from langchain_anthropic import ChatAnthropic<br>from langchain_core.messages import HumanMessage<br>from tools.gmail_tools import (<br>    search_emails,<br>    get_email_body,<br>    get_thread,<br>    list_threads,<br>    fetch_emails_with_attachments,<br>    get_contacts,<br>    search_contacts,<br>    get_inbox_stats,<br>    apply_label,<br>    trash_email,<br>    mark_as_spam,<br>)<br><br>load_dotenv()<br>llm = ChatAnthropic(model=&quot;claude-sonnet-4-20250514&quot;, temperature=0)<br>tools = [<br>    search_emails,<br>    get_email_body,<br>    get_thread,<br>    list_threads,<br>    fetch_emails_with_attachments,<br>    get_contacts,<br>    search_contacts,<br>    get_inbox_stats,<br>    apply_label,<br>    trash_email,<br>    mark_as_spam,<br>]<br>SYSTEM_PROMPT = &quot;&quot;&quot;You are a smart, conversational Gmail assistant. The user talks<br>to you in plain English - you handle all technical details internally.<br>## YOUR CAPABILITIES<br>When asked what you can do, tell the user:<br>1. **Search emails** - by sender, subject, keyword, date, label, or any combination<br>2. **Read email content** - open and read the full body of any email<br>3. **Browse conversations** - see full email threads grouped together<br>4. **Emails with attachments** - filter emails that have files attached<br>5. **Look up contacts** - find people in the user&#39;s Google contacts<br>6. **Apply labels** - tag emails with any label (URGENT, WORK, FOLLOW-UP, etc.)<br>7. **Trash emails** - move emails to trash (one at a time, always with confirmation)<br>8. **Mark as spam** - report emails as spam (always with confirmation)<br>9. **Inbox stats** - unread count, top senders, morning briefing<br>## RULES<br>**On first message**, greet the user, show capabilities, and ask what they&#39;d like to do.<br>**Read operations** (search, read, threads, attachments, contacts, stats):<br>act immediately - no confirmation needed.<br>**Write operations** (label, trash, spam):<br>always confirm with the user before calling the tool. Tell them which emails<br>will be affected.<br>**Email count:** When the user asks to see emails without specifying a number,<br>ask how many they want. When fetching, pass that exact number as max_results.<br>**Pagination:** If results include has_more=true, tell the user there are more<br>results and ask if they want to see the next page. Use next_page_token in the<br>follow-up search_emails call.<br>**Never expose message IDs or thread IDs.** Resolve everything by searching<br>first. The user says &quot;label emails from Rahul as URGENT&quot; - call apply_label<br>with search_query=&#39;from:Rahul&#39;, label_name=&#39;URGENT&#39;. Done.<br>**To read an email body:** call search_emails first to get the ID, then call<br>get_email_body with that ID. Never ask the user for an ID.<br>**Summarization:** call search_emails, then get_email_body for relevant ones,<br>then write a clean human-readable summary. Never show raw JSON.<br>**Response formatting:**<br>- Email lists: numbered, show Subject + From + Date<br>- Stats: brief paragraph<br>- Confirmations: name the specific email subject and sender<br>- Never show raw JSON, IDs, or technical fields<br>The user_id for ALL tool calls is: {user_id}&quot;&quot;&quot;<br>_histories: dict[str, list] = {}<br>def chat(user_id: str, message: str, session_id: str) -&gt; str:<br>    if session_id not in _histories:<br>        _histories[session_id] = []<br>    history = _histories[session_id]<br>    history.append(HumanMessage(content=message))<br>    agent = create_agent(<br>        model=llm,<br>        tools=tools,<br>        system_prompt=SYSTEM_PROMPT.format(user_id=user_id),<br>    )<br>    result = agent.invoke({&quot;messages&quot;: history})<br>    all_messages = result[&quot;messages&quot;]<br>    ai_reply = all_messages[-1].content<br>    _histories[session_id] = all_messages<br>    return ai_reply</pre><p><strong>scalekit_auth.py</strong></p><pre>import os<br>import scalekit.client<br>from dotenv import load_dotenv<br><br>load_dotenv()<br>client = scalekit.client.ScalekitClient(<br>    client_id=os.getenv(&quot;SCALEKIT_CLIENT_ID&quot;),<br>    client_secret=os.getenv(&quot;SCALEKIT_CLIENT_SECRET&quot;),<br>    env_url=os.getenv(&quot;SCALEKIT_ENV_URL&quot;),<br>)<br>connection_name = os.getenv(&quot;GMAIL_CONNECTION_NAME&quot;)<br>def get_or_create_account(user_id: str):<br>    response = client.actions.get_or_create_connected_account(<br>        connection_name=connection_name,<br>        identifier=user_id,<br>    )<br>    return response.connected_account<br>def get_auth_link(user_id: str) -&gt; str:<br>    link_response = client.actions.get_authorization_link(<br>        connection_name=connection_name,<br>        identifier=user_id,<br>    )<br>    return link_response.link<br>def is_connected(user_id: str) -&gt; bool:<br>    account = get_or_create_account(user_id)<br>    return account.status == &quot;ACTIVE&quot;</pre><p><strong>gmail_tools.py</strong></p><pre>import os<br>import json<br>import base64<br>from langchain_core.tools import tool<br>from dotenv import load_dotenv<br>import scalekit.client<br><br>load_dotenv()<br>client = scalekit.client.ScalekitClient(<br>    client_id=os.getenv(&quot;SCALEKIT_CLIENT_ID&quot;),<br>    client_secret=os.getenv(&quot;SCALEKIT_CLIENT_SECRET&quot;),<br>    env_url=os.getenv(&quot;SCALEKIT_ENV_URL&quot;),<br>)<br>connection_name = os.getenv(&quot;GMAIL_CONNECTION_NAME&quot;)<br>def _get_connected_account_id(user_id: str) -&gt; str:<br>    response = client.actions.get_or_create_connected_account(<br>        connection_name=connection_name,<br>        identifier=user_id,<br>    )<br>    return response.connected_account.id<br>def _get_body_text(payload: dict) -&gt; str:<br>    mime = payload.get(&quot;mimeType&quot;, &quot;&quot;)<br>    if mime == &quot;text/plain&quot;:<br>        data = payload.get(&quot;body&quot;, {}).get(&quot;data&quot;, &quot;&quot;)<br>        if data:<br>            return base64.urlsafe_b64decode(data + &quot;==&quot;).decode(&quot;utf-8&quot;, errors=&quot;replace&quot;)<br>    for part in payload.get(&quot;parts&quot;, []):<br>        result = _get_body_text(part)<br>        if result:<br>            return result<br>    return &quot;&quot;<br>def _ensure_label(user_id: str, label_name: str) -&gt; str:<br>    labels_resp = client.actions.request(<br>        connection_name=connection_name,<br>        identifier=user_id,<br>        path=&quot;/gmail/v1/users/me/labels&quot;,<br>    ).json()<br>    labels = labels_resp.get(&quot;labels&quot;, [])<br>    existing = next((l for l in labels if l[&quot;name&quot;].upper() == label_name.upper()), None)<br>    if existing:<br>        return existing[&quot;id&quot;]<br>    created = client.actions.request(<br>        connection_name=connection_name,<br>        identifier=user_id,<br>        path=&quot;/gmail/v1/users/me/labels&quot;,<br>        method=&quot;POST&quot;,<br>        body={&quot;name&quot;: label_name.upper()},<br>    ).json()<br>    return created[&quot;id&quot;]<br># ── SCALEKIT CONNECTOR TOOLS (execute_tool) ──────────────────────────────<br>@tool<br>def search_emails(user_id: str, query: str, max_results: int = 50, page_token: str = &quot;&quot;) -&gt; str:<br>    &quot;&quot;&quot;Search Gmail using Gmail search syntax. Examples: &#39;is:unread&#39;,<br>    &#39;from:someone@example.com&#39;, &#39;subject:invoice&#39;, &#39;has:attachment&#39;,<br>    &#39;after:2024/01/01&#39;. Combine: &#39;is:unread from:boss@company.com&#39;.<br>    Returns subjects, senders, dates, and IDs for chaining. Supports pagination.&quot;&quot;&quot;<br>    ca_id = _get_connected_account_id(user_id)<br>    tool_input = {&quot;query&quot;: query, &quot;max_results&quot;: max_results}<br>    if page_token:<br>        tool_input[&quot;page_token&quot;] = page_token<br>    response = client.actions.execute_tool(<br>        tool_name=&quot;gmail_fetch_mails&quot;,<br>        connected_account_id=ca_id,<br>        tool_input=tool_input,<br>    )<br>    data = response.data or {}<br>    messages = data.get(&quot;messages&quot;, [])<br>    next_token = data.get(&quot;nextPageToken&quot;, &quot;&quot;)<br>    if not messages:<br>        return json.dumps({&quot;results&quot;: [], &quot;message&quot;: &quot;No emails found.&quot;})<br>    results = [{<br>        &quot;id&quot;: msg.get(&quot;id&quot;, &quot;&quot;),<br>        &quot;thread_id&quot;: msg.get(&quot;threadId&quot;, &quot;&quot;),<br>        &quot;subject&quot;: msg.get(&quot;subject&quot;, &quot;(no subject)&quot;),<br>        &quot;from&quot;: msg.get(&quot;from&quot;, &quot;?&quot;),<br>        &quot;date&quot;: msg.get(&quot;date&quot;, &quot;?&quot;),<br>        &quot;snippet&quot;: msg.get(&quot;snippet&quot;, &quot;&quot;),<br>    } for msg in messages]<br>    return json.dumps({<br>        &quot;results&quot;: results,<br>        &quot;next_page_token&quot;: next_token,<br>        &quot;count&quot;: len(results),<br>        &quot;has_more&quot;: bool(next_token),<br>    })<br>@tool<br>def get_email_body(user_id: str, message_id: str) -&gt; str:<br>    &quot;&quot;&quot;Get the full content of an email by its message ID.<br>    Use after search_emails. Never ask the user for the ID - get it from search results.&quot;&quot;&quot;<br>    ca_id = _get_connected_account_id(user_id)<br>    response = client.actions.execute_tool(<br>        tool_name=&quot;gmail_get_message_by_id&quot;,<br>        connected_account_id=ca_id,<br>        tool_input={&quot;message_id&quot;: message_id, &quot;format&quot;: &quot;full&quot;},<br>    )<br>    data = response.data or {}<br>    payload = data.get(&quot;payload&quot;, {})<br>    body = _get_body_text(payload)<br>    headers = {h[&quot;name&quot;]: h[&quot;value&quot;] for h in payload.get(&quot;headers&quot;, [])}<br>    return json.dumps({<br>        &quot;subject&quot;: headers.get(&quot;Subject&quot;, &quot;(no subject)&quot;),<br>        &quot;from&quot;: headers.get(&quot;From&quot;, &quot;?&quot;),<br>        &quot;to&quot;: headers.get(&quot;To&quot;, &quot;?&quot;),<br>        &quot;date&quot;: headers.get(&quot;Date&quot;, &quot;?&quot;),<br>        &quot;body&quot;: body[:3000] if body else data.get(&quot;snippet&quot;, &quot;&quot;),<br>        &quot;truncated&quot;: len(body) &gt; 3000 if body else False,<br>    })<br>@tool<br>def get_thread(user_id: str, thread_id: str) -&gt; str:<br>    &quot;&quot;&quot;Get all messages in an email thread. thread_id comes from search_emails results.<br>    Never ask the user for it.&quot;&quot;&quot;<br>    ca_id = _get_connected_account_id(user_id)<br>    response = client.actions.execute_tool(<br>        tool_name=&quot;gmail_get_thread_by_id&quot;,<br>        connected_account_id=ca_id,<br>        tool_input={&quot;thread_id&quot;: thread_id, &quot;format&quot;: &quot;metadata&quot;,<br>                    &quot;metadata_headers&quot;: [&quot;Subject&quot;, &quot;From&quot;, &quot;Date&quot;, &quot;To&quot;]},<br>    )<br>    data = response.data or {}<br>    messages = data.get(&quot;messages&quot;, [])<br>    results = []<br>    for msg in messages:<br>        headers = {h[&quot;name&quot;]: h[&quot;value&quot;] for h in msg.get(&quot;payload&quot;, {}).get(&quot;headers&quot;, [])}<br>        results.append({&quot;from&quot;: headers.get(&quot;From&quot;, &quot;?&quot;),<br>                        &quot;date&quot;: headers.get(&quot;Date&quot;, &quot;?&quot;),<br>                        &quot;snippet&quot;: msg.get(&quot;snippet&quot;, &quot;&quot;)})<br>    return json.dumps({&quot;message_count&quot;: len(results), &quot;messages&quot;: results})<br>@tool<br>def list_threads(user_id: str, query: str = &quot;in:inbox&quot;, max_results: int = 10) -&gt; str:<br>    &quot;&quot;&quot;List email threads matching a query. Default shows inbox.<br>    Supports Gmail search syntax.&quot;&quot;&quot;<br>    ca_id = _get_connected_account_id(user_id)<br>    response = client.actions.execute_tool(<br>        tool_name=&quot;gmail_list_threads&quot;,<br>        connected_account_id=ca_id,<br>        tool_input={&quot;query&quot;: query, &quot;max_results&quot;: max_results},<br>    )<br>    data = response.data or {}<br>    threads = data.get(&quot;threads&quot;, [])<br>    if not threads:<br>        return &quot;No threads found.&quot;<br>    return json.dumps({<br>        &quot;threads&quot;: [{&quot;thread_id&quot;: t.get(&quot;id&quot;, &quot;&quot;), &quot;snippet&quot;: t.get(&quot;snippet&quot;, &quot;&quot;)}<br>                    for t in threads],<br>        &quot;count&quot;: len(threads),<br>        &quot;next_page_token&quot;: data.get(&quot;nextPageToken&quot;, &quot;&quot;),<br>    })<br>@tool<br>def fetch_emails_with_attachments(user_id: str, max_results: int = 20) -&gt; str:<br>    &quot;&quot;&quot;Fetch emails that have file attachments.&quot;&quot;&quot;<br>    ca_id = _get_connected_account_id(user_id)<br>    response = client.actions.execute_tool(<br>        tool_name=&quot;gmail_fetch_mails&quot;,<br>        connected_account_id=ca_id,<br>        tool_input={&quot;query&quot;: &quot;has:attachment&quot;, &quot;max_results&quot;: max_results},<br>    )<br>    data = response.data or {}<br>    messages = data.get(&quot;messages&quot;, [])<br>    if not messages:<br>        return &quot;No emails with attachments found.&quot;<br>    return json.dumps({&quot;results&quot;: [{<br>        &quot;id&quot;: msg.get(&quot;id&quot;, &quot;&quot;),<br>        &quot;subject&quot;: msg.get(&quot;subject&quot;, &quot;(no subject)&quot;),<br>        &quot;from&quot;: msg.get(&quot;from&quot;, &quot;?&quot;),<br>        &quot;date&quot;: msg.get(&quot;date&quot;, &quot;?&quot;),<br>    } for msg in messages], &quot;count&quot;: len(messages)})<br>@tool<br>def get_contacts(user_id: str, max_results: int = 20) -&gt; str:<br>    &quot;&quot;&quot;Fetch the user&#39;s Google contacts list.&quot;&quot;&quot;<br>    ca_id = _get_connected_account_id(user_id)<br>    response = client.actions.execute_tool(<br>        tool_name=&quot;gmail_get_contacts&quot;,<br>        connected_account_id=ca_id,<br>        tool_input={&quot;max_results&quot;: max_results},<br>    )<br>    data = response.data or {}<br>    contacts = data.get(&quot;connections&quot;, [])<br>    if not contacts:<br>        return &quot;No contacts found.&quot;<br>    results = []<br>    for c in contacts:<br>        names = c.get(&quot;names&quot;, [{}])<br>        emails = c.get(&quot;emailAddresses&quot;, [{}])<br>        results.append({<br>            &quot;name&quot;: names[0].get(&quot;displayName&quot;, &quot;?&quot;) if names else &quot;?&quot;,<br>            &quot;email&quot;: emails[0].get(&quot;value&quot;, &quot;?&quot;) if emails else &quot;?&quot;,<br>        })<br>    return json.dumps({&quot;contacts&quot;: results, &quot;count&quot;: len(results)})<br>@tool<br>def search_contacts(user_id: str, query: str) -&gt; str:<br>    &quot;&quot;&quot;Search for a person in Google contacts by name or email.&quot;&quot;&quot;<br>    ca_id = _get_connected_account_id(user_id)<br>    response = client.actions.execute_tool(<br>        tool_name=&quot;gmail_search_people&quot;,<br>        connected_account_id=ca_id,<br>        tool_input={&quot;query&quot;: query},<br>    )<br>    data = response.data or {}<br>    people = data.get(&quot;results&quot;, [])<br>    if not people:<br>        return f&quot;No contacts found matching &#39;{query}&#39;.&quot;<br>    results = []<br>    for p in people:<br>        person = p.get(&quot;person&quot;, {})<br>        names = person.get(&quot;names&quot;, [{}])<br>        emails = person.get(&quot;emailAddresses&quot;, [{}])<br>        results.append({<br>            &quot;name&quot;: names[0].get(&quot;displayName&quot;, &quot;?&quot;) if names else &quot;?&quot;,<br>            &quot;email&quot;: emails[0].get(&quot;value&quot;, &quot;?&quot;) if emails else &quot;?&quot;,<br>        })<br>    return json.dumps({&quot;results&quot;: results})<br>@tool<br>def get_inbox_stats(user_id: str) -&gt; str:<br>    &quot;&quot;&quot;Get inbox overview: unread count and top senders. Good for morning briefing.&quot;&quot;&quot;<br>    ca_id = _get_connected_account_id(user_id)<br>    unread_resp = client.actions.execute_tool(<br>        tool_name=&quot;gmail_fetch_mails&quot;,<br>        connected_account_id=ca_id,<br>        tool_input={&quot;query&quot;: &quot;is:unread in:inbox&quot;, &quot;max_results&quot;: 500},<br>    )<br>    unread_messages = (unread_resp.data or {}).get(&quot;messages&quot;, [])<br>    sender_counts: dict[str, int] = {}<br>    for msg in unread_messages[:20]:<br>        sender = msg.get(&quot;from&quot;, &quot;?&quot;)<br>        sender_counts[sender] = sender_counts.get(sender, 0) + 1<br>    top_senders = sorted(sender_counts.items(), key=lambda x: x[1], reverse=True)[:5]<br>    return json.dumps({<br>        &quot;unread&quot;: len(unread_messages),<br>        &quot;top_unread_senders&quot;: [{&quot;sender&quot;: s, &quot;count&quot;: c} for s, c in top_senders],<br>    })<br># ── PROXY TOOLS - write ops not in Scalekit connector ────────────────────<br>@tool<br>def apply_label(user_id: str, search_query: str, label_name: str) -&gt; str:<br>    &quot;&quot;&quot;Apply a label to emails matching a search query. Searches first -<br>    user never provides message IDs. Creates label if it doesn&#39;t exist.<br>    Applies to up to 10 matching emails.&quot;&quot;&quot;<br>    list_resp = client.actions.request(<br>        connection_name=connection_name, identifier=user_id,<br>        path=&quot;/gmail/v1/users/me/messages&quot;,<br>        query_params={&quot;q&quot;: search_query, &quot;maxResults&quot;: 10},<br>    ).json()<br>    messages = list_resp.get(&quot;messages&quot;, [])<br>    if not messages:<br>        return f&quot;No emails found matching &#39;{search_query}&#39;. Label not applied.&quot;<br>    label_id = _ensure_label(user_id, label_name)<br>    applied = []<br>    for msg in messages:<br>        detail = client.actions.request(<br>            connection_name=connection_name, identifier=user_id,<br>            path=f&quot;/gmail/v1/users/me/messages/{msg[&#39;id&#39;]}&quot;,<br>            query_params={&quot;format&quot;: &quot;metadata&quot;, &quot;metadataHeaders&quot;: [&quot;Subject&quot;]},<br>        ).json()<br>        headers = {h[&quot;name&quot;]: h[&quot;value&quot;] for h in detail.get(&quot;payload&quot;, {}).get(&quot;headers&quot;, [])}<br>        client.actions.request(<br>            connection_name=connection_name, identifier=user_id,<br>            path=f&quot;/gmail/v1/users/me/messages/{msg[&#39;id&#39;]}/modify&quot;,<br>            method=&quot;POST&quot;, body={&quot;addLabelIds&quot;: [label_id]},<br>        )<br>        applied.append(headers.get(&quot;Subject&quot;, &quot;(no subject)&quot;))<br>    return f&quot;Applied label &#39;{label_name}&#39; to {len(applied)} email(s):\n&quot; + &quot;\n&quot;.join(f&quot;- {s}&quot; for s in applied)<br>@tool<br>def trash_email(user_id: str, search_query: str) -&gt; str:<br>    &quot;&quot;&quot;Move ONE email matching the search query to trash.<br>    Only moves one to avoid accidents. Always confirm with user first.&quot;&quot;&quot;<br>    list_resp = client.actions.request(<br>        connection_name=connection_name, identifier=user_id,<br>        path=&quot;/gmail/v1/users/me/messages&quot;,<br>        query_params={&quot;q&quot;: search_query, &quot;maxResults&quot;: 1},<br>    ).json()<br>    messages = list_resp.get(&quot;messages&quot;, [])<br>    if not messages:<br>        return f&quot;No email found matching &#39;{search_query}&#39;. Nothing trashed.&quot;<br>    msg_id = messages[0][&quot;id&quot;]<br>    detail = client.actions.request(<br>        connection_name=connection_name, identifier=user_id,<br>        path=f&quot;/gmail/v1/users/me/messages/{msg_id}&quot;,<br>        query_params={&quot;format&quot;: &quot;metadata&quot;, &quot;metadataHeaders&quot;: [&quot;Subject&quot;, &quot;From&quot;]},<br>    ).json()<br>    headers = {h[&quot;name&quot;]: h[&quot;value&quot;] for h in detail.get(&quot;payload&quot;, {}).get(&quot;headers&quot;, [])}<br>    client.actions.request(<br>        connection_name=connection_name, identifier=user_id,<br>        path=f&quot;/gmail/v1/users/me/messages/{msg_id}/trash&quot;,<br>        method=&quot;POST&quot;,<br>    )<br>    return f&quot;Moved to trash: &#39;{headers.get(&#39;Subject&#39;, &#39;?&#39;)}&#39; from {headers.get(&#39;From&#39;, &#39;?&#39;)}.&quot;<br>@tool<br>def mark_as_spam(user_id: str, search_query: str) -&gt; str:<br>    &quot;&quot;&quot;Mark emails matching a search query as spam. Up to 5 at a time.<br>    Always confirm with user first.&quot;&quot;&quot;<br>    list_resp = client.actions.request(<br>        connection_name=connection_name, identifier=user_id,<br>        path=&quot;/gmail/v1/users/me/messages&quot;,<br>        query_params={&quot;q&quot;: search_query, &quot;maxResults&quot;: 5},<br>    ).json()<br>    messages = list_resp.get(&quot;messages&quot;, [])<br>    if not messages:<br>        return f&quot;No emails found matching &#39;{search_query}&#39;.&quot;<br>    marked = []<br>    for msg in messages:<br>        detail = client.actions.request(<br>            connection_name=connection_name, identifier=user_id,<br>            path=f&quot;/gmail/v1/users/me/messages/{msg[&#39;id&#39;]}&quot;,<br>            query_params={&quot;format&quot;: &quot;metadata&quot;, &quot;metadataHeaders&quot;: [&quot;Subject&quot;]},<br>        ).json()<br>        headers = {h[&quot;name&quot;]: h[&quot;value&quot;] for h in detail.get(&quot;payload&quot;, {}).get(&quot;headers&quot;, [])}<br>        client.actions.request(<br>            connection_name=connection_name, identifier=user_id,<br>            path=f&quot;/gmail/v1/users/me/messages/{msg[&#39;id&#39;]}/modify&quot;,<br>            method=&quot;POST&quot;,<br>            body={&quot;addLabelIds&quot;: [&quot;SPAM&quot;], &quot;removeLabelIds&quot;: [&quot;INBOX&quot;]},<br>        )<br>        marked.append(headers.get(&quot;Subject&quot;, &quot;(no subject)&quot;))<br>    return f&quot;Marked {len(marked)} email(s) as spam:\n&quot; + &quot;\n&quot;.join(f&quot;- {s}&quot; for s in marked)</pre><p><strong>templates/index.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>&lt;title&gt;Gmail Agent&lt;/title&gt;<br>&lt;link href=&quot;https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&amp;family=DM+Mono:wght@400;500&amp;family=DM+Sans:wght@300;400;500&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;style&gt;<br>  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }<br>  :root {<br>    --bg: #0d0d0f; --surface: #16161a; --border: #2a2a35;<br>    --accent: #c8f55a; --accent-dim: #a8d43a; --text: #e8e8ec;<br>    --text-muted: #7a7a8a; --user-bubble: #1e2a10; --user-border: #3a5020;<br>    --agent-bubble: #16161a; --agent-border: #2a2a35; --radius: 16px;<br>  }<br>  html, body { height: 100%; }<br>  body { background: var(--bg); color: var(--text); font-family: &#39;DM Sans&#39;, sans-serif;<br>    font-weight: 300; display: flex; flex-direction: column; align-items: center; min-height: 100vh; }<br>  header { width: 100%; max-width: 760px; padding: 24px 24px 0;<br>    display: flex; align-items: center; justify-content: space-between; }<br>  .logo { font-family: &#39;Instrument Serif&#39;, serif; font-style: italic;<br>    font-size: 22px; color: var(--text); letter-spacing: -0.3px; }<br>  .logo span { color: var(--accent); }<br>  .status-pill { display: flex; align-items: center; gap: 7px; font-size: 12px;<br>    font-family: &#39;DM Mono&#39;, monospace; color: var(--text-muted);<br>    background: var(--surface); border: 1px solid var(--border);<br>    padding: 5px 12px; border-radius: 99px; }<br>  .status-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--text-muted); }<br>  .status-dot.connected { background: var(--accent); box-shadow: 0 0 6px var(--accent); }<br>  .connect-btn { font-size: 12px; font-family: &#39;DM Mono&#39;, monospace; color: var(--accent);<br>    background: transparent; border: 1px solid var(--accent); padding: 5px 14px;<br>    border-radius: 99px; cursor: pointer; text-decoration: none;<br>    transition: background 0.15s, color 0.15s; }<br>  .connect-btn:hover { background: var(--accent); color: var(--bg); }<br>  .chat-wrap { width: 100%; max-width: 760px; flex: 1; display: flex;<br>    flex-direction: column; padding: 24px 24px 0; overflow: hidden; }<br>  #messages { flex: 1; overflow-y: auto; display: flex; flex-direction: column;<br>    gap: 16px; padding-bottom: 16px; scrollbar-width: thin;<br>    scrollbar-color: var(--border) transparent; }<br>  .empty-state { flex: 1; display: flex; flex-direction: column; align-items: center;<br>    justify-content: center; gap: 12px; color: var(--text-muted);<br>    text-align: center; padding: 60px 0; }<br>  .empty-state .big { font-family: &#39;Instrument Serif&#39;, serif; font-style: italic;<br>    font-size: 32px; color: var(--text); }<br>  .empty-state .sub { font-size: 14px; line-height: 1.6; max-width: 340px; }<br>  .suggestions { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; margin-top: 8px; }<br>  .suggestion { font-size: 12px; font-family: &#39;DM Mono&#39;, monospace; color: var(--text-muted);<br>    border: 1px solid var(--border); padding: 6px 14px; border-radius: 99px;<br>    cursor: pointer; background: transparent; transition: border-color 0.15s, color 0.15s; }<br>  .suggestion:hover { border-color: var(--accent); color: var(--accent); }<br>  .msg { display: flex; flex-direction: column; max-width: 88%; animation: fadeUp 0.2s ease; }<br>  .msg.user { align-self: flex-end; align-items: flex-end; }<br>  .msg.agent { align-self: flex-start; align-items: flex-start; }<br>  @keyframes fadeUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }<br>  .bubble { padding: 12px 16px; border-radius: var(--radius); font-size: 14px;<br>    line-height: 1.65; white-space: pre-wrap; word-break: break-word; }<br>  .msg.user .bubble { background: var(--user-bubble); border: 1px solid var(--user-border);<br>    border-bottom-right-radius: 4px; color: var(--accent);<br>    font-family: &#39;DM Mono&#39;, monospace; font-size: 13px; }<br>  .msg.agent .bubble { background: var(--agent-bubble);<br>    border: 1px solid var(--agent-border); border-bottom-left-radius: 4px; }<br>  .bubble strong { color: var(--accent); font-weight: 500; }<br>  .bubble em { color: var(--text-muted); font-style: italic; }<br>  .bubble .email-row { display: flex; flex-direction: column; gap: 2px;<br>    padding: 8px 0; border-bottom: 1px solid var(--border); }<br>  .bubble .email-row:last-child { border-bottom: none; padding-bottom: 0; }<br>  .bubble .email-row:first-child { padding-top: 0; }<br>  .bubble .email-from { font-size: 12px; color: var(--text-muted); font-family: &#39;DM Mono&#39;, monospace; }<br>  .bubble .email-subject { font-size: 14px; color: var(--text); }<br>  .msg-label { font-size: 11px; font-family: &#39;DM Mono&#39;, monospace;<br>    color: var(--text-muted); margin-bottom: 4px; padding: 0 4px; }<br>  .typing-indicator { display: flex; align-items: center; gap: 5px; padding: 14px 16px;<br>    background: var(--agent-bubble); border: 1px solid var(--agent-border);<br>    border-radius: var(--radius); border-bottom-left-radius: 4px; width: fit-content; }<br>  .typing-dot { width: 6px; height: 6px; border-radius: 50%;<br>    background: var(--text-muted); animation: typingBounce 1.2s infinite; }<br>  .typing-dot:nth-child(2) { animation-delay: 0.2s; }<br>  .typing-dot:nth-child(3) { animation-delay: 0.4s; }<br>  @keyframes typingBounce {<br>    0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }<br>    30% { transform: translateY(-5px); opacity: 1; }<br>  }<br>  .input-bar { width: 100%; max-width: 760px; padding: 16px 24px 28px;<br>    position: sticky; bottom: 0;<br>    background: linear-gradient(to top, var(--bg) 80%, transparent); }<br>  .input-row { display: flex; align-items: flex-end; gap: 10px;<br>    background: var(--surface); border: 1px solid var(--border);<br>    border-radius: var(--radius); padding: 10px 10px 10px 16px;<br>    transition: border-color 0.15s; }<br>  .input-row:focus-within { border-color: var(--accent); }<br>  #input { flex: 1; background: transparent; border: none; outline: none;<br>    color: var(--text); font-family: &#39;DM Sans&#39;, sans-serif; font-size: 14px;<br>    font-weight: 300; resize: none; max-height: 120px; line-height: 1.5; padding: 2px 0; }<br>  #input::placeholder { color: var(--text-muted); }<br>  #send-btn { width: 34px; height: 34px; border-radius: 10px; background: var(--accent);<br>    border: none; cursor: pointer; display: flex; align-items: center;<br>    justify-content: center; flex-shrink: 0; transition: background 0.15s, transform 0.1s; }<br>  #send-btn:hover { background: var(--accent-dim); }<br>  #send-btn:active { transform: scale(0.93); }<br>  #send-btn:disabled { opacity: 0.35; cursor: not-allowed; }<br>  #send-btn svg { color: var(--bg); }<br>  .not-connected-bar { text-align: center; padding: 12px; font-size: 13px; color: var(--text-muted); }<br>  .not-connected-bar a { color: var(--accent); text-decoration: none; border-bottom: 1px solid var(--accent); }<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;header&gt;<br>  &lt;div class=&quot;logo&quot;&gt;gmail&lt;span&gt;.&lt;/span&gt;agent&lt;/div&gt;<br>  {% if connected %}<br>    &lt;div class=&quot;status-pill&quot;&gt;<br>      &lt;div class=&quot;status-dot connected&quot;&gt;&lt;/div&gt;<br>      Gmail connected<br>    &lt;/div&gt;<br>  {% else %}<br>    &lt;a href=&quot;/auth/login&quot; class=&quot;connect-btn&quot;&gt;Connect Gmail&lt;/a&gt;<br>  {% endif %}<br>&lt;/header&gt;<br>&lt;div class=&quot;chat-wrap&quot;&gt;<br>  &lt;div id=&quot;messages&quot;&gt;<br>    &lt;div class=&quot;empty-state&quot; id=&quot;empty-state&quot;&gt;<br>      &lt;div class=&quot;big&quot;&gt;What&#39;s in your inbox?&lt;/div&gt;<br>      &lt;div class=&quot;sub&quot;&gt;Ask me to summarize emails, find urgent ones, or apply labels.&lt;/div&gt;<br>      &lt;div class=&quot;suggestions&quot;&gt;<br>        &lt;button class=&quot;suggestion&quot; onclick=&quot;suggest(this)&quot;&gt;What can you do?&lt;/button&gt;<br>        &lt;button class=&quot;suggestion&quot; onclick=&quot;suggest(this)&quot;&gt;Show my unread emails&lt;/button&gt;<br>        &lt;button class=&quot;suggestion&quot; onclick=&quot;suggest(this)&quot;&gt;Emails with attachments&lt;/button&gt;<br>        &lt;button class=&quot;suggestion&quot; onclick=&quot;suggest(this)&quot;&gt;Give me inbox stats&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;input-bar&quot;&gt;<br>  {% if connected %}<br>  &lt;div class=&quot;input-row&quot;&gt;<br>    &lt;textarea id=&quot;input&quot; rows=&quot;1&quot; placeholder=&quot;Ask about your emails…&quot; autocomplete=&quot;off&quot;&gt;&lt;/textarea&gt;<br>    &lt;button id=&quot;send-btn&quot; onclick=&quot;sendMessage()&quot;&gt;<br>      &lt;svg width=&quot;16&quot; height=&quot;16&quot; viewBox=&quot;0 0 24 24&quot; fill=&quot;none&quot; stroke=&quot;currentColor&quot;<br>           stroke-width=&quot;2.5&quot; stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot;&gt;<br>        &lt;line x1=&quot;22&quot; y1=&quot;2&quot; x2=&quot;11&quot; y2=&quot;13&quot;&gt;&lt;/line&gt;<br>        &lt;polygon points=&quot;22 2 15 22 11 13 2 9 22 2&quot;&gt;&lt;/polygon&gt;<br>      &lt;/svg&gt;<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>  {% else %}<br>  &lt;div class=&quot;not-connected-bar&quot;&gt;<br>    &lt;a href=&quot;/auth/login&quot;&gt;Connect your Gmail account&lt;/a&gt; to get started.<br>  &lt;/div&gt;<br>  {% endif %}<br>&lt;/div&gt;<br>&lt;script&gt;<br>var messagesEl = document.getElementById(&#39;messages&#39;);<br>var inputEl = document.getElementById(&#39;input&#39;);<br>var sendBtn = document.getElementById(&#39;send-btn&#39;);<br>var emptyState = document.getElementById(&#39;empty-state&#39;);<br>if (inputEl) {<br>  inputEl.addEventListener(&#39;input&#39;, function() {<br>    inputEl.style.height = &#39;auto&#39;;<br>    inputEl.style.height = Math.min(inputEl.scrollHeight, 120) + &#39;px&#39;;<br>  });<br>  inputEl.addEventListener(&#39;keydown&#39;, function(e) {<br>    if (e.key === &#39;Enter&#39; &amp;&amp; !e.shiftKey) { e.preventDefault(); sendMessage(); }<br>  });<br>}<br>function suggest(btn) {<br>  if (inputEl) { inputEl.value = btn.textContent; sendMessage(); }<br>}<br>function escHtml(str) {<br>  return str.replace(/&amp;/g, &#39;&amp;amp;&#39;).replace(/&lt;/g, &#39;&amp;lt;&#39;).replace(/&gt;/g, &#39;&amp;gt;&#39;);<br>}<br>function formatResponse(text) {<br>  if (text.indexOf(&#39;From:&#39;) !== -1 &amp;&amp; text.indexOf(&#39;Subject:&#39;) !== -1) {<br>    var lines = text.split(&#39;\n&#39;).filter(function(l) { return l.trim(); });<br>    var emailLines = lines.filter(function(l) {<br>      return l.indexOf(&#39;From:&#39;) !== -1 &amp;&amp; l.indexOf(&#39;Subject:&#39;) !== -1;<br>    });<br>    var otherLines = lines.filter(function(l) {<br>      return !(l.indexOf(&#39;From:&#39;) !== -1 &amp;&amp; l.indexOf(&#39;Subject:&#39;) !== -1);<br>    });<br>    var html = &#39;&#39;;<br>    if (otherLines.length) {<br>      html += &#39;&lt;div style=&quot;margin-bottom:12px&quot;&gt;&#39; + escHtml(otherLines.join(&#39; &#39;)) + &#39;&lt;/div&gt;&#39;;<br>    }<br>    emailLines.forEach(function(line) {<br>      var fromMatch = line.match(/From:[ ]*([^|]+)/);<br>      var subjectMatch = line.match(/Subject:[ ]*(.+)/);<br>      var from = fromMatch ? fromMatch[1].trim() : &#39;&#39;;<br>      var subject = subjectMatch ? subjectMatch[1].trim() : &#39;&#39;;<br>      html += &#39;&lt;div class=&quot;email-row&quot;&gt;&#39;<br>        + &#39;&lt;div class=&quot;email-subject&quot;&gt;&#39; + escHtml(subject) + &#39;&lt;/div&gt;&#39;<br>        + &#39;&lt;div class=&quot;email-from&quot;&gt;&#39; + escHtml(from) + &#39;&lt;/div&gt;&#39;<br>        + &#39;&lt;/div&gt;&#39;;<br>    });<br>    return html;<br>  }<br>  return escHtml(text)<br>    .replace(/\*\*([^*]+)\*\*/g, &#39;&lt;strong&gt;$1&lt;/strong&gt;&#39;)<br>    .replace(/\*([^*]+)\*/g, &#39;&lt;em&gt;$1&lt;/em&gt;&#39;)<br>    .replace(/\n/g, &#39;&lt;br&gt;&#39;);<br>}<br>function addMessage(role, text) {<br>  if (emptyState) emptyState.style.display = &#39;none&#39;;<br>  var wrap = document.createElement(&#39;div&#39;);<br>  wrap.className = &#39;msg &#39; + role;<br>  var label = document.createElement(&#39;div&#39;);<br>  label.className = &#39;msg-label&#39;;<br>  label.textContent = role === &#39;user&#39; ? &#39;you&#39; : &#39;agent&#39;;<br>  wrap.appendChild(label);<br>  var bubble = document.createElement(&#39;div&#39;);<br>  bubble.className = &#39;bubble&#39;;<br>  if (role === &#39;agent&#39;) { bubble.innerHTML = formatResponse(text); }<br>  else { bubble.textContent = text; }<br>  wrap.appendChild(bubble);<br>  messagesEl.appendChild(wrap);<br>  messagesEl.scrollTop = messagesEl.scrollHeight;<br>}<br>function showTyping() {<br>  var wrap = document.createElement(&#39;div&#39;);<br>  wrap.className = &#39;msg agent&#39;; wrap.id = &#39;typing&#39;;<br>  var label = document.createElement(&#39;div&#39;);<br>  label.className = &#39;msg-label&#39;; label.textContent = &#39;agent&#39;;<br>  wrap.appendChild(label);<br>  var indicator = document.createElement(&#39;div&#39;);<br>  indicator.className = &#39;typing-indicator&#39;;<br>  indicator.innerHTML = &#39;&lt;div class=&quot;typing-dot&quot;&gt;&lt;/div&gt;&lt;div class=&quot;typing-dot&quot;&gt;&lt;/div&gt;&lt;div class=&quot;typing-dot&quot;&gt;&lt;/div&gt;&#39;;<br>  wrap.appendChild(indicator);<br>  messagesEl.appendChild(wrap);<br>  messagesEl.scrollTop = messagesEl.scrollHeight;<br>}<br>function removeTyping() {<br>  var t = document.getElementById(&#39;typing&#39;);<br>  if (t) t.remove();<br>}<br>function sendMessage() {<br>  if (!inputEl || !sendBtn) return;<br>  var text = inputEl.value.trim();<br>  if (!text || sendBtn.disabled) return;<br>  inputEl.value = &#39;&#39;; inputEl.style.height = &#39;auto&#39;;<br>  sendBtn.disabled = true;<br>  addMessage(&#39;user&#39;, text);<br>  showTyping();<br>  fetch(&#39;/chat&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify({ message: text })<br>  })<br>  .then(function(res) { return res.json(); })<br>  .then(function(data) {<br>    removeTyping();<br>    if (data.error) { addMessage(&#39;agent&#39;, &#39;⚠ &#39; + data.error); }<br>    else { addMessage(&#39;agent&#39;, data.response); }<br>  })<br>  .catch(function() {<br>    removeTyping();<br>    addMessage(&#39;agent&#39;, &#39;⚠ Something went wrong. Try again.&#39;);<br>  })<br>  .finally(function() {<br>    sendBtn.disabled = false;<br>    if (inputEl) inputEl.focus();<br>  });<br>}<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>templates/connect.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;meta charset=&quot;UTF-8&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>&lt;title&gt;Connect Gmail&lt;/title&gt;<br>&lt;link href=&quot;https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&amp;family=DM+Mono:wght@400;500&amp;family=DM+Sans:wght@300;400;500&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;<br>&lt;style&gt;<br>  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }<br>  :root { --bg: #0d0d0f; --accent: #c8f55a; --text: #e8e8ec; --text-muted: #7a7a8a; }<br>  body { background: var(--bg); color: var(--text); font-family: &#39;DM Sans&#39;, sans-serif;<br>    font-weight: 300; display: flex; flex-direction: column; align-items: center;<br>    justify-content: center; min-height: 100vh; gap: 20px; text-align: center; padding: 24px; }<br>  .logo { font-family: &#39;Instrument Serif&#39;, serif; font-style: italic;<br>    font-size: 28px; color: var(--text); margin-bottom: 8px; }<br>  .logo span { color: var(--accent); }<br>  p { font-size: 14px; color: var(--text-muted); max-width: 340px; line-height: 1.6; }<br>  .btn { display: inline-block; background: var(--accent); color: #0d0d0f; border: none;<br>    padding: 10px 28px; border-radius: 99px; font-size: 14px;<br>    font-family: &#39;DM Mono&#39;, monospace; cursor: pointer; text-decoration: none;<br>    transition: background 0.15s; }<br>  .btn:hover { background: #a8d43a; }<br>  .btn-secondary { background: transparent; color: var(--accent); border: 1px solid var(--accent); }<br>  .btn-secondary:hover { background: var(--accent); color: #0d0d0f; }<br>  .divider { color: var(--text-muted); font-size: 12px; }<br>&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div class=&quot;logo&quot;&gt;gmail&lt;span&gt;.&lt;/span&gt;agent&lt;/div&gt;<br>  &lt;p&gt;Click below to connect your Gmail account. A new tab will open for authorization.&lt;/p&gt;<br>  &lt;a href=&quot;{{ auth_url }}&quot; target=&quot;_blank&quot; class=&quot;btn&quot;&gt;Connect Gmail&lt;/a&gt;<br>  &lt;span class=&quot;divider&quot;&gt;—&lt;/span&gt;<br>  &lt;p&gt;After authorizing in the new tab, click below to continue.&lt;/p&gt;<br>  &lt;a href=&quot;/&quot; class=&quot;btn btn-secondary&quot;&gt;I&#39;ve authorized — continue&lt;/a&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>requirements.txt</strong></p><pre>langchain<br>langchain-anthropic<br>langchain-core<br>langgraph<br>flask<br>python-dotenv<br>scalekit-sdk-python<br>google-auth<br>google-auth-oauthlib<br>google-api-python-client<br>gunicorn</pre><p>To run the Gmail Agent:</p><pre>python app.py<br># Visit http://localhost:5000 → Connect Gmail → chat</pre><h3>Common Errors You Might Hit during the Gmail Agent development using Langchain, Scalekit, Flask, Claude — and the Fixes</h3><p>These are some common errors, when you try to build agents using LLM code generators.</p><ul><li><strong>ImportError: cannot import name ‘AgentExecutor’ from ‘langchain.agents’</strong></li></ul><p><strong>Cause:</strong> LangChain 1.0 removed AgentExecutor entirely.</p><p>Fix: Replace with from langchain.agents import create_agent. The new API takes model, tools, and system_prompt directly.</p><ul><li><strong>ImportError: cannot import name ‘create_react_agent’ from ‘langchain.agents’</strong></li></ul><p><strong>Cause:</strong> create_react_agent was moved and renamed in LangChain 1.x. The function shown in the dir() output is create_agent.</p><p>Fix: from langchain.agents import create_agent. Verify available names: python -c &quot;import langchain.agents; print(dir(langchain.agents))&quot;</p><ul><li><strong>ERROR: Could not find a version that satisfies the requirement scalekit-sdk</strong></li></ul><p><strong>Cause:</strong> The package name on PyPI is different from the SDK name.</p><p>Fix: pip install scalekit-sdk-python (not scalekit-sdk). The import remains from scalekit import ScalekitClient.</p><ul><li><strong>AttributeError: ‘NoneType’ object has no attribute ‘encode’</strong></li></ul><p><strong>Cause:</strong> ENCRYPTION_KEY environment variable not set. This was from an earlier architecture that used Fernet encryption to store tokens locally. After switching to Scalekit&#39;s token vault, this code was no longer needed but imports remained.</p><p>Fix: Delete storage/token_store.py and all imports from it. Scalekit handles token storage — you don&#39;t need local encryption.</p><ul><li><strong>AttributeError: ‘ActionClient’ object has no attribute ‘get_token’</strong></li></ul><p><strong>Cause:</strong> get_token() doesn&#39;t exist on the Scalekit actions client.</p><p>Fix: Use execute_tool() for Scalekit&#39;s 8 named tools, or actions.request() as a proxy for raw Gmail API calls. Both auto-inject the user&#39;s token — you never fetch it yourself.</p><ul><li><strong>ScalekitNotFoundException: invalid domain in request</strong></li></ul><p><strong>Cause:</strong> SCALEKIT_ENV_URL is malformed. Common issues: trailing slash, wrong protocol, still a placeholder value, or quotes around the value in .env.</p><p>Fix: Value must be exactly https://yourenv.scalekit.dev — nothing after .dev, https:// protocol, no quotes.</p><ul><li><strong>403 Forbidden on </strong><a href="http://127.0.0.1:5000/"><strong>http://127.0.0.1:5000/</strong></a><strong> after app restart</strong></li></ul><p><strong>Cause:</strong> app.secret_key = secrets.token_hex(32) regenerates on every restart, invalidating existing session cookies. Flask can&#39;t decode the old cookie with the new key.</p><p>Fix: Generate key once, store in .env as FLASK_SECRET_KEY, use app.secret_key = os.getenv(&quot;FLASK_SECRET_KEY&quot;). To clear old cookies: Firefox → address bar lock icon → Clear cookies and site data.</p><ul><li><strong>SyntaxWarning: invalid escape sequence ‘\s’ in app.py</strong></li></ul><p><strong>Cause:</strong> JavaScript regex patterns like /From:\s*/ inside a Python triple-quoted string — Python interprets \s as an invalid escape sequence.</p><p>Fix: Move HTML to templates/index.html and use render_template(). Or replace \s with [ ] (space character class) in the regex.</p><ul><li><strong>ReferenceError: sendMessage is not defined</strong></li></ul><p><strong>Cause:</strong> JavaScript inside a Python multiline string breaks when the string contains unescaped newlines or characters that Python interprets before the JS engine sees them. The script block fails to parse, so none of the functions are defined.</p><p>Fix: Move all HTML and JS to proper template files in templates/. Never put JS in Python triple-quoted strings.</p><ul><li><strong>Stuck on Scalekit success page after OAuth in you flask agent app, i.e., no redirect back to app</strong></li></ul><p><strong>Cause:</strong> Scalekit AgentKit does not redirect back to your app after OAuth. It handles the token exchange internally and shows its own success page. The get_authorization_link() method does not accept a redirect URI parameter for this flow.</p><p>Fix: Open the auth link in a new tab. Show the user a “I’ve authorized — continue” button that takes them back to your app. Check connected account status on return.</p><h3>Next Steps: Going to Production (BYOC)</h3><p>When you’re ready for production — your app name on the Google consent screen, your own scope control — you need to switch from Scalekit’s default credentials to your own.</p><h3>Google Cloud setup (for going to production)</h3><ol><li>Create a Google Cloud project</li></ol><p>Go to <a href="https://console.cloud.google.com/">console.cloud.google.com</a>. Click the project dropdown → <strong>New Project</strong>. Name it and create it. Make sure it’s selected in the dropdown.</p><p>2. Enable the Gmail API</p><p><strong>APIs &amp; Services → Library</strong> → search “Gmail API” → click it → <strong>Enable</strong>.</p><p>3. Configure Google Auth Platform</p><p>Go to <strong>Menu → Google Auth Platform → Branding</strong>. If you see “not configured yet”, click <strong>Get Started</strong> and complete the wizard:</p><ul><li>App name, support email, developer contact</li><li>Audience: <strong>External</strong></li><li>Scopes: add gmail.readonly, gmail.labels, gmail.modify</li><li>Test users: add your Gmail address</li></ul><blockquote><em>⚠️ </em><strong><em>Token Expiry in Testing Mode</em></strong></blockquote><blockquote><em>While publishing status is “Testing”, tokens expire after 7 days. You’ll need to re-authorize. This is fine for development. Publish the app to remove this restriction.</em></blockquote><p>4. Create OAuth credentials</p><p><strong>Google Auth Platform → Clients → + Create Client</strong> → Web application.</p><p>First, get the Scalekit redirect URI: in the Scalekit dashboard, go to <strong>AgentKit → Connections → MY_GMAIL → Use your own credentials</strong>. Copy the redirect URI — it looks like https://yourenv.scalekit.dev/sso/v1/oauth/&lt;id&gt;/callback.</p><p>Add that URI to <strong>Authorized redirect URIs</strong> in Google Cloud. Create the client. Copy the Client ID and Client Secret — the secret is only shown once.</p><p>5. Add credentials to Scalekit</p><p>In the Scalekit dashboard → <strong>AgentKit → Connections → MY_GMAIL</strong> → enter your Google Client ID, Client Secret, and scopes. Save.</p><p>Disconnect and reconnect Gmail in your app — the new OAuth flow uses your credentials and your scopes.</p><h3>DOs and DON’Ts</h3><h4>DOs</h4><ul><li>Store FLASK_SECRET_KEY in .env — never generate it inline</li><li>Put all HTML in templates/ — never in Python strings</li><li>Use execute_tool for Scalekit&#39;s 8 connector tools</li><li>Use actions.request() only for write ops not in the connector</li><li>Confirm with the user before every write operation (label, trash, spam)</li><li>Let the agent resolve IDs internally — never expose them to users</li><li>Add .env, .venv/, __pycache__/ to .gitignore</li><li>Set debug=False in Flask even locally</li><li>Request minimum scopes needed (readonly before modify)</li></ul><h4>DON’Ts</h4><ul><li>Never commit .env to version control</li><li>Don’t use scalekit-sdk — the correct package is scalekit-sdk-python</li><li>Don’t pass a redirect URI to get_authorization_link() — AgentKit doesn&#39;t support it</li><li>Don’t put JS inside Python triple-quoted strings — escaping conflicts will break your app</li><li>Don’t use Scalekit’s default credentials for production — switch to BYOC</li><li>Don’t bulk trash or spam without limiting to 1–5 emails per operation</li><li>Don’t hardcode API keys anywhere in code</li></ul><h3>Cleanup Checklist</h3><p>When you want to fully tear this down:</p><ul><li>Revoke Gmail access: <a href="https://myaccount.google.com/permissions">myaccount.google.com/permissions</a> → remove your app</li><li>Delete connected account in Scalekit: <strong>AgentKit → Connections → MY_GMAIL</strong> → delete</li><li>Delete your Scalekit environment from the dashboard</li><li>Rotate your ANTHROPIC_API_KEY in the Anthropic console if ever exposed</li><li>Delete the Google Cloud project (removes OAuth credentials, API access, quota)</li><li>Delete your local project folder and .venv</li><li>Remove the app from any deployment service (Render, Railway, Fly.io)</li><li>Clear browser cookies for 127.0.0.1:5000 (Firefox: address bar lock icon → Clear cookies)</li></ul><p>Built with Python 3.13 · LangChain 1.2 · Scalekit AgentKit · Flask · Claude Sonnet 4</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ea7d683926" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get clients as a freelance writer?]]></title>
            <link>https://medium.com/@codepoetn/how-to-get-clients-as-a-freelance-writer-78c342a4bfec?source=rss-1ace73d3cbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/78c342a4bfec</guid>
            <category><![CDATA[make-money-online]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[career-advice]]></category>
            <dc:creator><![CDATA[Nishant Choudhary]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 22:14:42 GMT</pubDate>
            <atom:updated>2026-02-12T22:14:42.667Z</atom:updated>
            <content:encoded><![CDATA[<p>For me freelancing wasn’t something that I planned and ventured into.</p><p>It just happened.</p><p>Initially, I had no idea about how freelancers find client.</p><p>And everyone claimed to know the secrets to finding freelance clients. And they wanted me to buy their course.</p><p>Some of them wanted $2, some $49, and some wanted $999 for the course. No complaints. Spoiler: most of these courses don’t work. Okay, I want to say “NONE OF THESE COURSES WORK,” but I’ll settle with ‘most.’</p><p>If you observe, these courses are created by digital hackers who don’t actively freelance but want to rake in money by robbing your pocket.</p><p>I say ‘robbing’ because you won’t get any value in return.</p><p>These creators see ‘courses’ as a way to print money, and not as a way to educate and empower learners. So, what they do is basically cash your fears, and not fuel your aspirations.</p><p>Having said that, I settled with ‘most’ over ‘none,’ because some courses about finding freelance clients are useful. However, it is finding the needle in the haystack. The road to identifying such creators has a lot of variables involved- one important variable is how actively the course creator freelances, and 2, do they get regular real testimonials from real account on platforms like LinkedIn, Fiverr, Guru, Upwork, etcetera? Any platform and any review that you feel is fake is actually fake.</p><p>Okay, one last thing before we hop on to the list of things that work to get freelancing clients, I want you to remember that <strong>RESULTS TAKE TIME… so, be patient</strong>. If you’re visiting this page with hope of getting overnight clients…nope that’s not happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YP3bPq7s2T6YJzgLBVkyPw.png" /><figcaption>Source: GrowthRomeo/Gemini</figcaption></figure><h3>The first client</h3><p>Out of desperation, I wanted to find freelance client. I joined lot of junk communities. I don’t know where from the client came, but it was for freelance blog writing. I was a college passout desperately looking for sources to make money, and jumped onto the opportunity. He (the client) must have discovered me through some group. But what a horrible client he was, damn! He made me write. But he didn’t pay me. When I asked for payment, He ghosted.</p><p><strong>Tip 1 to find freelance client:</strong> First client was not accidental. You’ve to think where can you be visible such that people who need your help will come to you. Be present everywhere. Visibility sells. The more you’re visible, the more the chances that people will come to you when they seek help. Join active groups (offline/online), make noise about yourself, let people know and feel your existence.</p><p><strong>Takeaway (with a pinch of salt): </strong>There are a$$holes everywhere, and you’ll meet them. So, learn to identify them early on, and develop the muscles needed to deal with them.</p><h3>The next client, another client, and one more client</h3><p>When I accepted that I’ve been cheated, I felt horrible, but I made an extremely good decision while I was furious about that cheater guy- I published my blog elsewhere. I thought, why let that a$$ get away with my content. So, I posted the article on a free publishing platform. Honestly, it wasn’t that good a piece. But it helped me in my developer job hunt. And after that, it helped me win trust of people that even after being a developer, I can write good content.</p><p>Someone saw my post, offered me something more challenging, and I accepted it again. I was doubtful and wanted to give up, but I didn’t because this client trusted me and was constantly supporting me. First article for this client did really well, they came with a freelance engagement proposition that I couldn’t say ‘no&#39; to. Did some good work for this client. And requested to add my author details, which they obliged with.</p><p>Next 3 clients came from the work I did for this company.</p><p><strong>Tip 2 to find freelance clients:</strong> Whatever projects you take up, do the work really well because <strong>your work is your first impression in freelancing</strong>. Your work is your 24x7 sales guy. And let people know that it’s your work. Unless, you’ve signed an NDA for ghostwriting, you can always claim the work to be yours.</p><p><strong>Takeaway (with a pinch of salt): </strong>This approach is akin to ‘referral’ marketing, or ‘word of mouth’ marketing, and may take months to finally start yielding results for you.</p><h3>Finding high-paying freelance clients</h3><p>Ah, first of all, touchwood. OMG, I don’t remember how long I’ve been highly underpaid. Given a choice, I would want to be a horrible writer who is highly overpaid, than being an awesome writer who is highly underpaid. I consider myself an average writer who was underpaid. It’s fortunate that the first guy ghosted me. Because if he had not, I’d be working with him, and I’d have never understood the high-paying dynamics of freelancing. After my first few clients. I started to raise price. I was very afraid early on, thinking I’d lose potential clients this way. But later, when I was earning enough, I realised that now I can afford to negotiate and lose the deals. The opposite happened. I seldom had to negotiate with well-paying clients. They always agreed instantly in a way where I used to feel “Am I quoting enough?” But for me, it was enough. So yeah, I gradually started getting high-paying clients. And had to part my ways with the low paying ones. All smoothly. No bumpers. No problem discontinuing with any of the clients.</p><p><strong>Tip 3 for finding freelance clients: </strong>Always be looking to up-skill and improve your craft, and ask your employers who is availing your freelancer services to match your actual market value. If they do not agree, you can start eyeing better opportunities.</p><p><strong>Takeaway (with a pinch of salt): </strong>This approach doesn’t mean that you cut chords with earlier clients. Nope. Keep them. However. request them to revisit engagement economics. Behavior goes a long way in business, and freelancing is a one person business.</p><h3>Building a pipeline of freelance clients</h3><p>Once you’ve basic level of earning. You can now start investing in building your social currency– Presence on Twitter/LinkedIn.</p><p>Understand that freelancing is not like SaaS or IT where companies can wait for 2–3 months for employees to join, it is more like urgent phone call that “You’re needed now.” So, you’ll lose a lot of potential clients. But that shouldn’t deter you from building your social presence. Especially on LinkedIn because there you can do both- attract and approach at scale.</p><p>Yep, this is where you don’t have to be dependent on intangible inbound, rather, rely more on tangible inbound and meticulously formulated outbound workflows — ads, email, etcetera.</p><h3>The last leg to find freelance client</h3><p>Make account on freelance platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78c342a4bfec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 day startup — basics for beginners]]></title>
            <link>https://medium.com/@codepoetn/7-day-startup-basics-for-beginners-14292e51fc64?source=rss-1ace73d3cbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/14292e51fc64</guid>
            <category><![CDATA[start-business]]></category>
            <category><![CDATA[book-summary]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[business-books]]></category>
            <category><![CDATA[7-day-startup]]></category>
            <dc:creator><![CDATA[Nishant Choudhary]]></dc:creator>
            <pubDate>Sat, 30 Oct 2021 12:01:12 GMT</pubDate>
            <atom:updated>2021-12-25T04:52:28.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKOG6rPyHS1E0MKJy76mxw.jpeg" /></figure><h3>7 day startup — basics for a beginner</h3><p>Hey!</p><p>I’ve got something special for you today.</p><p><em>Guess, guess..</em></p><p>– Actionable lessons from <strong><em>The 7 day startup</em></strong>.</p><p>Yes, I read <em>the book by Dan Norris</em>, “The 7 Day Startup”. And so, I thought of writing a<strong> summary for the 7 Day startup</strong>. But then, I dropped the idea. Because business book summaries are everywhere... aren’t they?</p><p>Instead of sharing <em>the 7 day startup book summary</em>, I thought why not share with you a framework that they can use to <strong>launch your startup in just 7 steps</strong>, maybe in less than 7 days ;)</p><p>From ideation to <a href="https://www.codewave.com/">building website and app for your idea</a>, I’ve tried to cover all aspects. Yes, the framework is inspired from the 7 day startup book, and these steps are ridiculously simple/obvious. It’s a no brainer framework, in-fact, most of us the steps mentioned in this article would appear as obvious steps to start a business.</p><p><strong>Note: This article is for you if you’re at a very beginner level, and have no clue about how you should start your business or launch your startup idea.</strong></p><p>You must be thinking, “are you kidding me? I’ve been <strong>thinking of starting-up</strong> for years now and yet I don’t <em>own a business</em>. And you’re telling me that I can <strong><em>launch my startup in just 7 days</em>?</strong>”.</p><p><strong>Well, umm… yeah!</strong></p><p>That’s true.</p><p>You can launch your startup in just seven days. After reading the book or this blog, and implementing the insights shared, you too shall be in the mindset that you can startup in mere 7 days.</p><p>So, if you’ve the intent to start, <strong><em>let’s get grinding</em></strong>.</p><h3>The 7 day startup book summary</h3><p>Before we share the seven baby steps to starting up in 7 days, it’s critical that you get in the right mindset.</p><p>Neither the author, nor I want you to be distracted or confused when you are pursuing your dream <a href="https://growthromeo.com/">business ideas</a>, rather I would request/plead you to put forward your best effort, a well calculated, aware, conscious, intent-led <strong>focused effort</strong>.</p><p><strong>Focused efforts involve constantly scrutinizing your actions, relentlessly chasing your customers, taking measurable actions to improve your product, process, and culture, and of-course prioritizing those efforts which yield best results for your business.</strong></p><p>The goal is to grow your business.</p><ol><li><strong>Focused Efforts –</strong></li></ol><ul><li>Relentlessly chase your customers.</li><li>Take Measurable Actions.</li><li>Prioritize the efforts yielding best results.</li></ul><p><strong>You shall be questioning,</strong></p><p><strong>Why is focused effort necessary?</strong></p><p>Often newbie entrepreneurs get caught-up in the ego-trap.</p><p>We as humans always have some bias associated with all the decisions we take.</p><p>Suppose, we have to market our product ‘P’ and we have multiple channels to promote the product.</p><p>Let’s say, the channels are channel ‘A’, channel ‘B’ and channel ‘C’.</p><p>Also, let’s assume channel ‘C’ is your favorite channel and you’re all gaga about it BUT it’s channel ‘B’ which is converting the most number of customers for your product ‘P’.</p><p>So, <a href="https://www.linkedin.com/in/codepoetn">a good business consultant</a> suggests you not to gravitate towards channel ‘C’ but instead focus on optimizing your customer acquisition efforts by focusing on channel ‘B’.</p><p>Now, there is another possibility. Maybe, you too know channel ‘B’ is yielding better results as of now but you strongly believe that channel ‘C’ could really fire-up once it crosses certain limitations or thresholds.</p><p>In that case, if this belief is not biased, you should decide whether you want to persist on your gut feeling or take a safer route.</p><p>Remember, risk appetite &amp; decision making abilities are something that differentiates an entrepreneur from average people.</p><p>So, take measured &amp; unbiased decisions.</p><p>Next, it’s good and kind of compulsory as an entrepreneur to be in the mindset of taking actions.</p><p><strong>2. Take Actions</strong></p><p>To understand this better, ask yourself these questions –</p><p>Would just thinking about business ideas build your business? Or do you need to take action?</p><p>You, my dear hustler, you are smart enough, and you already have the answers. You have to take actions in order to validate and build your ideas into businesses. So,</p><ul><li>Stop Thinking About Ideas</li><li>Start Building Ideas</li></ul><h3>What can you do to start bringing your ideas to life?</h3><p>Start <strong>talking</strong> to prospects i.e., potential customers in your circle to assess your <a href="https://growthromeo.com/startup-business-ideas/">startup business idea</a>. See, if they are paying for any similar product/service that you are planning for.</p><p>Make sure that you are not biased while assessing a <a href="https://growthromeo.com/profitable-business-ideas/">profitable business idea</a>.</p><p>Remember, there is a big &amp; clear difference between someone <strong>subscribing to your free emails</strong> and someone <strong>subscribing to your monthly subscription plans</strong>. The point is, don’t be biased when you are assessing your business idea on the ground. Choose your business KPIs wisely.</p><p>One important note, please do not take <strong>feedback</strong> from anyone who doesn’t already use/own a similar product or service. Do not listen to opinions, listen to experiences.</p><p>There is a thin line of difference in <strong>mindset</strong> between <strong>successful</strong> entrepreneurs and filthy successful entrepreneurs.</p><p>Highly successful entrepreneurs are <strong>passionate</strong> about growing their business. They invest a major chunk of profits back into the business to scale it to the next level.</p><p>So, if you gain initial traction, revenue and profit, do not go crazy with celebrations. Celebrate, but in a calculated and responsible way. But first, invest back into your business. Grow your business revenue and profits to insane levels.</p><p>Lastly, do not over burn yourself with startup stress. Entrepreneurship is not that easy, else everyone would have been an entrepreneur. It is rewarding but sometimes really stressful and frustrating as well. You must prioritize your physical, mental as well as financial health too. Remember, your own personal happiness is equally critical for your business success.</p><h3>The framework To Startup In 7 Days</h3><ul><li><strong>Brainstorm Ideas</strong></li></ul><p>This would make you laugh. Please don’t. I told you already, the steps mentioned here are a no-brainer.</p><p>Anyways, I have to share because in business we do not assume, we play by the rules (occasionally break them too).</p><p>On day one of seven, you have to brainstorm on <a href="https://growthromeo.com/startup-business-ideas/">startup business ideas</a> you would like to pursue. You might already be on day one, if you have been thinking about startup or <a href="https://growthromeo.com/category/business-ideas/">business ideas</a> for a while.</p><p>All you need to do is give your <a href="https://growthromeo.com/unique-business-ideas/">unique business idea</a> a thorough thought, gain some clarity and confidence about one-single idea and be relentless in pursuing it.</p><ul><li><strong>Decide on MVP</strong></li></ul><p>Next, once you have clarity on the <a href="https://growthromeo.com/best-business-ideas-india/">best business idea</a> for you or at least a <strong>business domain </strong>on a broad level, you need to take up a pen &amp; paper or some digital doodling tool and draw up a <strong>minimal viable product for your startup idea</strong>, with minimal features to launch.</p><p>Remember, if <a href="https://growthromeo.com/online-business-ideas/">online business ideas</a> like Facebook (now rebranded to Meta) were started the way it is now, it would have been really complex for people to understand how exactly to use it. Facebook might not have been as successful as it is now if it was launched with all the features at once. In-fact, Facebook and several other startups were not launched with the intent or idea of what it became over the time.</p><p>Instagram was a check-in app but transitioned into image sharing social network.</p><p>Facebook was a university app but it became a social network.</p><p>Amazon was an ecommerce site that used to sell only books, but today it is into almost every business.</p><p>Similarly, with Google, Paytm, and others.</p><p>So, do not wait to launch a polished product, just <strong>doodle up the MVP</strong> and launch it to test the market. After you have good signs about the feasibility of the business, go aggressive and iteratively build your business.</p><ul><li><strong>Register a business name &amp; domain</strong></li></ul><p>Registering the name for your business might not be that great a leap but at-least it’s a baby step and it gets counted. <strong>Buy a domain.</strong></p><p>When you take actions, no matter how small they are, you get tempted and excited to take further actions. Kind of that law, a body in motion, stays in motion… So, go ahead and <strong>register a good marketable domain name</strong>. Here’s a resource to help you <strong>brainstorm on a good business name</strong>.</p><ul><li><strong>Build a Website</strong></li></ul><p>It’s damn easy to <strong>build a website</strong> these days, you can use <strong>no-code website development platforms</strong> like <em>wordpress, shopify,</em> etc. to develop your website without having to understand or write even a single line of code.</p><p>Website building frameworks like drupal, magento etc are useful to <strong>build customized websites</strong> but you do need some acquaintance with coding to use these website development platforms.</p><p>You can also <a href="https://www.codewave.com/"><strong>outsource your website development</strong></a> if you have the right budget. Countries like India are a <em>great outsourcing destination</em> for website and mobile app development. <strong>Top IT outsourcing cities in India</strong> are Bangalore, Delhi NCR, Pune, Chennai, Hyderabad, Mumbai, and Kolkata.</p><p>You may also <strong>consider learning javascript</strong> or python to <em>code your own website</em>. For outsourcing, you need a budget of around <strong>USD 10–20k</strong> for developing the MVP and working version of the product.</p><ul><li><strong>Plan your marketing</strong></li></ul><p>Once you have your website up &amp; running, start reaching out to your immediate customers. Plan out innovative methodologies to boost your visibility and pitch to your prospects.</p><p>Remember, just planning out is of no use. <strong>Implement those marketing plans.</strong></p><p>Use social media, your friends &amp; family circle, networking events, communities, online ads and whatsoever you can to get to your customers. Be obsessed about it.</p><ul><li><strong>Measure signups, revenue, evaluate costs, resources etc.,</strong></li></ul><p>Once you start gaining some traction for your idea in terms of number of customers, revenue growth etc. Start analyzing and measuring input/output equations. Take data-led decisions to grow your startup.</p><ul><li><strong>Launch a startup. Keep an eye on the competitor.</strong></li></ul><p>Now, having a great system and attitude in place you can fully launch your startup, <strong>plan on hiring</strong>, <strong>pitching investors</strong> and <strong>scaling your business</strong> to unprecedented heights.</p><p>Thanks for reading this, but we shall be more happy if you really start taking actions, and explore your options. If you purchased your domain, planned out marketing, gained some traction or just want to share with the world and the growth community about your actions and business — drop a comment.</p><h3>Need help in launching your business?</h3><p>If you seek help with website or app development, <a href="https://www.linkedin.com/in/codepoetn">reach out to me</a> for a brainstorming session. Visit <a href="https://insights.codewave.com/">Codewave Insights</a> where you find detailed articles on Tech, Design, and Culture to grow you organization.</p><p>Soon, I’ll be sharing a lot more resources to <strong>start and grow your business</strong>. I’ll put up videos on <strong>how to brainstorm on new business Ideas</strong> to <strong>launch your own startups</strong>, <strong>how to spot growth opportunities</strong> for your startup business, <strong>how to register your domain</strong>, <strong>how to plan your marketing </strong>as well as <strong>resources on pitching your startup idea to investors</strong> for funding.</p><h3>Connect with me!</h3><p>Follow <a href="https://www.linkedin.com/in/codepoetn">me</a> on any social platform where you’re most active — T<a href="https://www.twitter.com/codepoetn">witter</a>, L<a href="https://www.linkedin.com/in/codepoetn">inkedin</a>, F<a href="https://www.facebook.com/codepoetn/">acebook</a>, I<a href="https://www.instagram.com/codepoetn_">nstagram</a>, or Y<a href="https://www.youtube.com/c/codepoetn">outube</a>. Following on social platforms would mean you’ll get to discover content that I share on a regular basis during your leisure.</p><p>I personally prefer subscribing to newsletter to never miss an update from them, but I don’t have one. Will share soon, after setting up a proper newsletter.</p><p>I love <em>consuming and creating</em> effective business resources which are easy to follow and implement, business book summaries that are helpful, and brainstorming sessions to share tech and business experiences/knowledge. All this enables me to <strong>consult you effectively for scaling your business to greater heights</strong>.</p><p>Explore <a href="https://insights.codewave.com/">Codewave Insights</a> to discover interesting <strong>tech insights </strong>and some really good business growth resources.</p><p>Stay safe &amp; keep growing!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14292e51fc64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrape Job Postings From Indeed : Automated]]></title>
            <link>https://medium.com/@codepoetn/scrape-job-postings-from-indeed-automated-f2bed0f6e571?source=rss-1ace73d3cbf7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2bed0f6e571</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scraping]]></category>
            <dc:creator><![CDATA[Nishant Choudhary]]></dc:creator>
            <pubDate>Wed, 30 Dec 2020 07:21:24 GMT</pubDate>
            <atom:updated>2021-12-25T05:01:47.999Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scrape Job Postings From Indeed : Automated Scraping</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Nd2f4wODjXWnx5NnMCsK9A.jpeg" /><figcaption>Data scraping Automation</figcaption></figure><blockquote>The US bureau of labor statistics reported in November, <strong><em>10 Million US citizens are looking for Job</em></strong><em>.</em></blockquote><p>Jobs are on a rebound as economies across the globe recovers from the Covid trauma. Pandemic plummeted the hiring industry in the US from <strong>$150 Bn to $119 Bn in 2020</strong>. Trends were similar across the globe. But good news is layoffs are no more making headlines and <strong><em>staffing firms observe an upsurge in hiring, training &amp; recruitment</em></strong>.</p><p>In such an environment, the rise of <strong><em>niche job boards</em></strong> is an obvious outcome and a brilliant <a href="https://growthromeo.com/startup-business-ideas/">startup idea</a> as well. Job boards smoothens job search experience for candidates and also helps talent boards in <strong>finding right talent at scale</strong>. From politics focused job boards to remote working, <strong><em>job aggregator websites &amp; applications are a hot trend right now</em></strong>. And as far as we could see in the future, we only see an uptrend.</p><p>This insight is written with an intent to be your go-to guide for <strong>building a killer and robust Indeed.com job scraper using Octoparse</strong>. We start with a <em>job scraping</em> refresher and then jump to practical demonstration of <strong>scraping job postings from Indeed</strong>.</p><h3><strong>Insight Content :</strong></h3><ol><li>Job Scraping Indeed — What, Why, Who, How ?</li><li>What’s needed to scrape indeed jobs?</li><li>Main steps for building the indeed job scraper</li><li>Using Octoparse to build the indeed job scraper</li><li>What is Octoparse &amp; how to start scraping?</li></ol><h3><strong>Job Scraping Indeed</strong></h3><p>You can scrape jobs not just from indeed but from any number of job boards and enterprise career pages including <strong><em>Monster, Linkedin, Glassdoor, Angel and Naukri</em></strong>. But for this article we cater specifically to approaches for <strong>scraping job listings from Indeed</strong>.</p><h3><strong>What job data shall be scraped from Indeed.com ?</strong></h3><p>Any data that helps in narrowing down the job search to a particular niche and intersects with your business domain should ideally be scraped. Generally, following data-points are collected -</p><ul><li>Job Title</li><li>Date Posted</li><li>Job Location</li><li>Hiring Organization</li><li>Job Description</li><li>Employment Type</li><li>Base Salary</li><li>Valid Through</li><li>Job Url</li><li>Job Source</li></ul><h3><strong>Why to scrape jobs from Indeed ?</strong></h3><p>You may consider <a href="https://www.codewave.com/services">automating job scraping from Indeed to build efficient job data ETL pipelines</a>. Usually, <strong>job scraping use cases</strong> fall in four verticals -</p><ul><li>Build your own niche-focused job aggregator website — a good part-time <a href="https://growthromeo.com/online-business-ideas/">online business idea</a></li><li>Market research to stay on top of industrial trends and stay competitor-aware</li><li>Finding right job opportunities for an individual/group</li><li>Additionally, sales teams of staff augmentation and staff training teams can use this to generate leads for their services.</li></ul><h3><strong>Who should scrape indeed jobs &amp; how ?</strong></h3><p>Enterprises who need to track or manage several thousands of job postings across industry verticals, job boards and company career pages should leverage <a href="https://www.linkedin.com/in/codepoetn"><strong>automated job scraping</strong></a>. Individuals with small scale requirements too can build their own job scrapers with or without technical programming expertise. How? <strong>Indeed jobs can be scraped using out of the box screen-scraping solutions, cloud-scraping solutions, custom written scripts or commercial scraping services</strong>.</p><h3><strong>What is needed to scrape indeed jobs?</strong></h3><p>There are two ways to <strong>feed your job data centric application</strong> -</p><h4>Hire Scraping <a href="http://upwork.com/">Talent</a> or <a href="https://www.codewave.com/">Agency</a></h4><p>If Indeed’s website structure is not changing consistently then avoid building an inhouse scraping talent pool as it’s a cost-intensive affair. Consider <strong>freelancers</strong> who <a href="https://www.linkedin.com/in/codepoetn">charge $25 - $50 an hour <strong>for building custom scrapers</strong></a>. <strong>Agencies </strong>shall be preferred for <strong>large scale, quick to market scraping needs</strong> and if the target website is extremely sophisticated and tough to scrape. <a href="https://www.codewave.com/">Good agencies starts offerings at $50/hour</a>.</p><p>Overall, both hiring approaches are <strong>effective</strong> if you have the right budget.</p><p>In-house team building is effective when you have a data-centeric business and necessary knowledge to manage entire workflow. It involves a steep learning curve if data scraping is new to your enterprise.</p><h4>Use A <a href="https://www.octoparse.com/">Scraping Tool</a></h4><p>SaaS based job scraping tools are an affordable and sustainable option for enterprises who have relatively moderate complexity scraping needs. These tools enable enterprises to create scraping logic visually or use pre-built templates to scrape major websites. Costs are affordable if you do proper research before choosing an efficient commercial scraping tool. As per our research, you can start job scraping from as low as $100/month for 100k data points.</p><h3><strong>Main steps for building the indeed job scraper</strong></h3><h4><strong>Step 1 — Define your job data requirements</strong></h4><p>At this stage you need to lay down the structure of the job database. Decide upon the data points you seek. Also, find out how often you need to scrape jobs from Indeed.</p><h4><strong>Step 2 — Choose your scraping methodology (In-house, agency or tool)</strong></h4><p>Based on your data requirements, see which scraping approach best suits your requirements as well as job data scraping budget.</p><h4><strong>Step 3 — Setup the job data extraction pipeline</strong></h4><p>If you’ve decided on in-house scraping, you would need an expert scraping developer, a devops guy to set up the pipeline, a testing engineer to check data quality and a data wrangler for cleaning and formatting the raw data. To cut costs, you may look for guys with multiple aforementioned skills.</p><p>If you decide to go with an agency, you only need to worry about financial burdens and maybe daily calls to stay updated with the progress.</p><p>If you choose leveraging scraping tools, you will need to set up a visual data extraction flow.</p><h4><strong>Step 4 — Iteratively improve the entire process, if possible.</strong></h4><p>Sometimes, website structure changes and focused-scraping scripts needs to be updated. Yes, even in case of visual scraping flow set-up.</p><h3><strong>Using Octoparse to build the indeed job scraper</strong></h3><p>Now, we’ll demonstrate how easy it is to “scrape job listings from Indeed” using Octoparse. Let’s build a scalable, automated indeed job scraper, one step at a time.</p><h3><strong><em>Method 1 : Scraping Indeed Jobs Using Pre-Built Task Templates</em></strong></h3><h4><strong>Step 1 : Getting started with Octoparse</strong></h4><p>If you’re new to Octoparse,</p><ul><li><a href="https://www.octoparse.com/signup">Register here</a> and</li><li>Download their <strong><em>scraping automation software</em></strong> for <a href="https://www.octoparse.com/download/windows">windows</a> or <a href="https://www.octoparse.com/download/mac">mac</a>.</li><li>Install it on your system and</li><li>Finally, login using your credentials.</li></ul><h4><strong>Step 2</strong> : <strong>Using Pre-built Indeed task templates</strong></h4><ul><li>On the home screen, you’ll find the following two options.</li><li>Advanced Mode Task is for building <strong>custom data scraping</strong> pipelines.</li></ul><p>For method 1 of “<strong>Indeed job scraping</strong>” demo, we shall click on the “Task Templates +Task” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*o7zytR-Wxi_d52T-fNXJrA.png" /><figcaption>Octoparse Home Screen Post Login</figcaption></figure><ul><li>This shows us pre-built available templates to scrape websites. For your convenience, Indeed Job Scraper is included.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*YWQ9d11sIYcuuwJxffsHsA.png" /><figcaption>Pre-Built Scraping Templates On Octoparse</figcaption></figure><ul><li>If pre-built templates are not sufficient, You may always custom build your scrapers. We demonstrate building “<strong>custom Indeed job scraper</strong>” in method 2.</li><li>For task templates method, let’s click on “Indeed” to open “Indeed Job scraping template” -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*hBVmvOENqy7UtA-DX87k_g.png" /><figcaption>Using Indeed Job Scraper Pre-Built Template</figcaption></figure><ul><li>Next you get three Indeed specific templates. Let’s chose the third one to scrape US jobs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*AZuqb-mKr7CzzbLW1I0DxA.png" /><figcaption>Indeed Scraping Templates</figcaption></figure><ul><li>In the next screen, you can see a set of parameters which the template will scrape.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*6XoLC2w0nTdWlnZ9_JJiXg.png" /><figcaption>Job Data to be Scraped from Indeed</figcaption></figure><ul><li>Scroll to the bottom of the screen to see a button “use template”, click on it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*KH3_gMS3e-VvolAm4QL9cg.png" /><figcaption>Finalize The Job Scraper Template</figcaption></figure><ul><li>Next, enter your target url in the “Enter Urls” option on the left and click on the “save and run” button towards the bottom right to start “Indeed job scraping”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*Iu_5llaA2v77ZBAyhfFMBA.png" /><figcaption>Save &amp; Run The Indeed Scraper</figcaption></figure><h4><strong>Step 3 : Run the indeed job scraper and export data</strong></h4><ul><li>When you click on “save and run”, Octoparse scraping automation solution asks you where you want to save the data. You can “<strong><em>save data Locally as well as in the Cloud</em></strong>”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*xRiphNIFl_ngyCZP3Y5G9A.png" /><figcaption>Saving the scraped Job Data From Indeed</figcaption></figure><p>The scraper starts scraping and you can see the data visually on screen. <strong>You can download the scraped data</strong> in JSON, CSV or XLS. Here is a glimpse of how scraped job data from Indeed looks like -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*nwZIPeGpZeFScE69m3soWQ.png" /><figcaption>Job Data Scraped From Indeed</figcaption></figure><p>For aesthetic brevity, the cells have been trimmed from the right. Lastly, you can stop scraping if need be and export the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*0Q8AXMPe5ElUVRcnXhWY0Q.png" /><figcaption>Exporting Scraped Job Data</figcaption></figure><h3><strong><em>METHOD 2 — Custom Scraping Indeed Job Data Using Octoparse</em></strong></h3><h4><strong>Step 1</strong> : <strong>Getting started with Octoparse</strong></h4><p>If you’re new to Octoparse,</p><ul><li><a href="https://www.octoparse.com/signup">Register here</a> and</li><li>Download their <strong><em>scraping automation software</em></strong> for <a href="https://www.octoparse.com/download/windows">windows</a> or <a href="https://www.octoparse.com/download/mac">mac</a>.</li><li>Install it on your system and</li><li>Finally, login using your credentials.</li></ul><h4><strong>Step 2</strong> : <strong>Using Pre-built Indeed task templates</strong></h4><ul><li>On the home screen, you’ll find the following two options.</li><li>Task Template is for leveraging <strong>pre-built data scraping</strong> templates. We demonstrated that above for “scraping Indeed Jobs”.</li></ul><p>For method 2 of “<strong>Indeed job scraping</strong>” demo, we shall click on the “Advanced Mode +Task” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*o7zytR-Wxi_d52T-fNXJrA.png" /><figcaption>Custom Indeed Job Scraping</figcaption></figure><ul><li>This takes us to a screen where we can enter the start url of the target website from which we need to scrape data. In our case it’ll be a “Indeed hospital job listing in Melbourne” page url. -</li></ul><p><a href="https://au.indeed.com/jobs?q=Hospital&amp;l=Melbourne+VIC&amp;sort=date"><strong>https://au.indeed.com/jobs?q=Hospital&amp;l=Melbourne+VIC&amp;sort=date</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*SAiEPlAzFh-OpWQQTwydcA.png" /><figcaption>Indeed Melbourne Hospital Jobs</figcaption></figure><ul><li>At the bottom, click on the “Save URL” button to go to the template building screen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*SsBte7BWyKYcrg-GOEfP2A.png" /><figcaption>Saving the job scraper starting URL</figcaption></figure><p><strong>Now we create the following flow -</strong></p><ul><li><strong>Go to job listing page and scrape jobs on page 1</strong></li><li><strong>Paginate Repeat</strong></li></ul><ol><li>Go to next page -</li><li>Scrape jobs</li></ol><h4><strong>Step 3: Creating the template -</strong></h4><ul><li>On the landing page (indeed starting url), scroll down and discover the pagination links. Write down an Xpath to the next page in pagination-</li></ul><p><strong>//ul[@class=’pagination-list’]//*[contains(@aria-current,”true”)]/ancestor::li/following-sibling::li[1]/a/span</strong></p><ul><li>We also need xpath to job titles link. So using chrome devtools, we write that xpath too -</li></ul><p><strong>//div[contains(@class,”jobsearch-SerpJobCard”)]/h2[contains(@class,”title”)]/a</strong></p><ul><li>Now click on the pagination element, it may automatically select all pagination items.</li><li>On the right action tips helper, click on the option “loop click single element”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*ovDQlRP5Ek9-L3kq9HKFYA.png" /><figcaption>Octoparse Pagination Setup for scraping Jobs</figcaption></figure><ul><li>This will create a pagination flow in your template as shown below -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*bWz7n3q3QsLoZ-VNJfEnTA.png" /><figcaption>Indeed Job Scraping Pagination</figcaption></figure><ul><li>Next, click on the Pagination loop. Advanced option gets reflected on the left half of the screen. Add Xpath for identifying the next pagination link as shown below -</li></ul><p><strong>//ul[@class=’pagination-list’]//*[contains(@aria-current,”true”)]/ancestor::li/following-sibling::li[1]/a/span</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*0iF7eW0Yreu6KKpIBi0lcg.png" /><figcaption>indeed pagination using xpath</figcaption></figure><ul><li>Click on Ok</li><li>Now, again click on pagination square. And in the job listing section click on “Title of any of the Job”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*19vAU0MqSWe_0iLAS5jQhA.png" /><figcaption>Job Posts Scraping Template Setup</figcaption></figure><ul><li>Click again on any of the job title, and then from the action tips helper select “loop click each element”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*MR5NIRh23kL7IRhXC9yDzw.png" /><figcaption>Selecting Multiple Job Posts to automate scraping</figcaption></figure><ul><li>Again in the advanced section for this template item, add an xpath, as we did before for pagination -</li></ul><p><strong>//div[contains(@class,”jobsearch-SerpJobCard”)]/h2[contains(@class,”title”)]/a</strong></p><ul><li>Also, add an AJAX Timeout of 3s or more. This is because the job details are loaded as AJAX and involves some delay.</li><li>Next select all the data points from Job data. For brevity of the demo, we keep it restricted to five, as shown below -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*eHzCeM9SZYOeAY-NfG4XDg.png" /><figcaption>Labelling Scraped Data from Indeed</figcaption></figure><ul><li>You may edit the labels, in the previous screen itself or you can click on the workflow item and edit as shown below -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*sV_pZj2GSVsxuVix_re8JA.png" /><figcaption>labelling scraped data</figcaption></figure><ul><li>Save the template. The complete template looks like this -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*16vb5r57ZK0UNUtd0wOjyQ.png" /><figcaption>Final Indeed Scraping Template In Octoparse</figcaption></figure><h4><strong>Step 4: Extracting the data and saving it.</strong></h4><ul><li>Click on the “<strong>start extraction</strong>” button at the top of template -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*60Cm3ATBb3SVrRViOS7rgQ.png" /><figcaption>Saving the template befor job data extraction</figcaption></figure><ul><li>Choose the extraction type. You can extract locally, in cloud or you may also create an API. for our demo, we click on “Local Extraction” button -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*exXe80kt84miQqke" /><figcaption>Local data Extraction, Cloud Data Extraction Using Octoparse</figcaption></figure><ul><li>As soon as you click on <strong>“Local Extraction”</strong>. It starts scraping indeed job data. <strong>Woohoo!!!!!</strong></li><li>Wait, data exporting is still not done. So, the scraping screen looks as shown below. Observe The number of pages already scraped, and the data being extracted.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XgdNFo_hU44U-Cy1" /><figcaption>Fouth Page Indeed Job Data Scraping</figcaption></figure><ul><li>The scraping continues, unless it reaches the end of job listings or you manually click on “Stop” button at the bottom.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*efre_VOsxLNtcDws" /></figure><ul><li>Now, let’s click on Export Data.</li></ul><h4>Octoparse provides us data in different formats -</h4><ol><li>CSV</li><li>JSON</li><li>XLS</li><li>HTML</li><li>Direct export to database</li></ol><ul><li>We clicked on JSON and saved the data in “HJM data.json” file. Opening it locally with Notepad -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*g9zQBo4iHF2lDdHN" /><figcaption>JSON view of scraped job data</figcaption></figure><p>For brevity, we restricted to only five data points but you can as many data points as required for your job data scraping use-case.</p><h3><strong><em>Conclusion : Indeed Job Scraping</em></strong></h3><p>Scraping job data from Indeed using Octoparse is a cakewalk. As demonstrated it hardly takes five minutes to get started. Getting started with Octoparse is EASY AND FREE. Scaling up with Octoparse is very flexible and affordable. So, what are you waiting for? Go build that terrific job solution idea you have in your head. If you seek help, am always there ;)</p><p>For <a href="https://www.linkedin.com/in/codepoetn"><strong><em>custom python scrapy indeed scraper script development</em></strong></a> reach out to me on <a href="https://www.linkedin.com/in/codepoetn">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2bed0f6e571" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>