<?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 Jeeva V on Medium]]></title>
        <description><![CDATA[Stories by Jeeva V on Medium]]></description>
        <link>https://medium.com/@jeeva.v910?source=rss-fd8989c71135------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-C_MNDkcDEz751ea</url>
            <title>Stories by Jeeva V on Medium</title>
            <link>https://medium.com/@jeeva.v910?source=rss-fd8989c71135------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:26:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeeva.v910/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[Building an AI Calendar Agent from Scratch — No Frameworks, Just Pure Python and Gemini]]></title>
            <link>https://medium.com/@jeeva.v910/building-an-ai-calendar-agent-from-scratch-no-frameworks-just-pure-python-and-gemini-9e65e79341c4?source=rss-fd8989c71135------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e65e79341c4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Jeeva V]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 04:41:04 GMT</pubDate>
            <atom:updated>2025-11-05T04:48:51.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI Calendar Agent from Scratch — No Frameworks, Just Pure Python and Gemini</h3><h3>Introduction</h3><p>Everyone’s talking about AI agents lately — little digital minds that can schedule meetings, summarize your inbox, and maybe even plan your weekend. Most tutorials show fancy frameworks doing the heavy lifting: LangChain, LlamaIndex, crewAI, you name it.<br>But underneath all that abstraction is something surprisingly simple — logic, reasoning, and function calls.</p><p>So here’s the question: can you build your own AI agent from scratch, without relying on any agentic framework, using only raw Python and an LLM?<br>Turns out, yes. And it’s cleaner than you’d expect.</p><p>This post walks you through how I built a fully functional AI Calendar Assistant using Google’s Gemini model and the Google Calendar API — no libraries, no shortcuts, and no magic middleware. Just reasoning, structure, and good design.</p><h3>Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lq6dXZjC9_80zQpZ7y50g.png" /></figure><h4>Setting Up Google Calendar Access (OAuth2 + Scopes)</h4><p>Step is where you set up your <strong>OAuth credentials</strong> and define <strong>scopes</strong>, which determine what your AI agent can actually do.</p><ol><li>Create a Google Cloud Project</li></ol><ul><li>To start, open the <a href="https://console.cloud.google.com/"><strong>Google Cloud Console</strong></a> and click the project dropdown at the top. Choose <strong>“New Project,”</strong> give it a name like <strong>AI-Calendar-Agent</strong>, and click <strong>Create</strong>. Once it’s ready, make sure your new project is selected in the top bar — that’s the workspace where you’ll enable APIs and add credentials.</li></ul><p>2. Enable the Google Calendar API</p><ul><li>In your Google Cloud project, go to <strong>APIs &amp; Services → Library</strong> from the left sidebar. Search for <strong>“Google Calendar API”</strong>, click on it, and hit <strong>Enable</strong> — this activates calendar access for your project so your Python agent can communicate with Google Calendar.</li></ul><p>3. Enable Calendar Auth Scope</p><ul><li>In the <a href="https://console.cloud.google.com/auth/overview"><strong>Google Cloud OAuth Overview</strong></a> page, open the sidebar and go to <strong>Data Access → Add or remove scopes</strong>. Choose <strong>Manually add scopes</strong>, paste https://www.googleapis.com/auth/calendar, and click <strong>Update</strong> to save it. Then, in the sidebar, go to <strong>Audience → Add users</strong> and add your own Google account as a <strong>test user</strong> — this step allows the app to access your calendar during development.</li></ul><p>4. Create OAuth 2.0 Credentials</p><ul><li>In your Google Cloud project, open <strong>APIs &amp; Services → Credentials</strong> from the sidebar. Click <strong>Create Credentials → OAuth client ID</strong>, and if prompted, set up the <strong>OAuth consent screen</strong> by choosing <strong>External</strong> (for testing), then entering your app name, support email, and developer contact email before clicking <strong>Save and Continue</strong>. After that, create your credentials by selecting <strong>Application type: Desktop app</strong>, naming it something like <strong>Python Calendar Agent</strong>, and clicking <strong>Create</strong> to finish.</li></ul><p>5. Download and rename it to credentials.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*BiG1XCjLjy3M3nJe56_dUg.png" /><figcaption>( Download JSON )</figcaption></figure><h4>Setting up the agent</h4><p>Create and activate a Python virtual environment and install the required packages</p><pre>python3 -m venv .venv<br>pip3 install google-genai pydantic \<br>google-api-python-client \<br>google-auth-httplib2 google-auth-oauthlib python-dotenv</pre><p>Obtain the Gemini API key from Google from <a href="https://aistudio.google.com/api-keys">AI Studio</a>. and add it in .env</p><pre>GEMINI_API_KEY=&quot;Your API Key Goes Here&quot;</pre><p>Create utility.py</p><pre>from termcolor import colored<br><br>import platform<br><br>def get_color_map():<br>    if platform.system().lower() != &quot;windows&quot;:<br>        color_map = {<br>            &quot;success&quot;: &quot;green&quot;,<br>            &quot;failure&quot;: &quot;red&quot;,<br>            &quot;status&quot;: &quot;light_green&quot;,<br>            &quot;code&quot;: &quot;light_blue&quot;,<br>            &quot;warning&quot;: &quot;yellow&quot;,<br>            &quot;output&quot;: &quot;cyan&quot;,<br>            &quot;info&quot;: &quot;cyan&quot;<br>        }<br>    else:<br>        color_map = {<br>            &quot;success&quot;: &quot;green&quot;,<br>            &quot;failure&quot;: &quot;red&quot;,<br>            &quot;status&quot;: &quot;light_green&quot;,<br>            &quot;code&quot;: &quot;light_blue&quot;,<br>            &quot;warning&quot;: &quot;yellow&quot;,<br>            &quot;output&quot;: &quot;cyan&quot;,<br>            &quot;info&quot;: &quot;black&quot;<br>        }<br>    return color_map<br><br>def pretty_print(text, color=&quot;info&quot;, no_newline=False):<br>    &quot;&quot;&quot;<br>    Print text with color formatting.<br><br>    Args:<br>        text (str): The text to print<br>        color (str, optional): The color to use. Defaults to &quot;info&quot;.<br>            Valid colors are:<br>            - &quot;success&quot;: Green<br>            - &quot;failure&quot;: Red <br>            - &quot;status&quot;: Light green<br>            - &quot;code&quot;: Light blue<br>            - &quot;warning&quot;: Yellow<br>            - &quot;output&quot;: Cyan<br>            - &quot;default&quot;: Black (Windows only)<br>    &quot;&quot;&quot;<br><br>    color_map = get_color_map()<br>    if color not in color_map:<br>        color = &quot;info&quot;<br>    print(colored(text, color_map[color]), end=&#39;&#39; if no_newline else &quot;\n&quot;)</pre><p>Create calender_services.py</p><p>Make the necessary import</p><pre>import os<br><br>from datetime import datetime<br>from typing import Annotated, Optional<br>from google.auth.transport.requests import Request<br>from google.oauth2.credentials import Credentials<br>from google_auth_oauthlib.flow import InstalledAppFlow<br>from googleapiclient.discovery import build<br>from googleapiclient.errors import HttpError<br>from schemas import Event, LoginResponse<br>from utility import pretty_print<br><br>SCOPES = [&quot;https://www.googleapis.com/auth/calendar&quot;]</pre><p>Lets Create Calendar Class</p><pre>class Calender():<br>    def __init__(self):<br>        self.authenticated = False<br>        self.creds = None<br>        self.services = None<br>        if os.path.exists(&quot;token.json&quot;):<br>            self.authenticated = True<br>            self.creds = Credentials.from_authorized_user_file(&quot;token.json&quot;, SCOPES)<br>            if self.creds and self.creds.expired and self.creds.refresh_token:<br>                self.creds.refresh(Request())<br>            self.services = build(&quot;calendar&quot;, &quot;v3&quot;, credentials=self.creds)<br>            <br>    def isAuthenticated(self):<br>        if os.path.exists(&quot;token.json&quot;):<br>            self.authenticated = True<br>        else:<br>            self.authenticated = False<br>        return self.authenticated<br><br>    def login(self) -&gt; LoginResponse:<br>        try:<br>            flow = InstalledAppFlow.from_client_secrets_file(<br>                &quot;credentials.json&quot;, SCOPES<br>            )<br>            self.creds = flow.run_local_server(port=0)<br>            with open(&quot;token.json&quot;, &quot;w&quot;) as token:<br>                token.write(self.creds.to_json())<br>            self.services = build(&quot;calendar&quot;, &quot;v3&quot;, credentials=self.creds)<br>            self.authenticated = True<br>            return {&quot;message&quot;: &quot;Authenticated Succesfully&quot;, &quot;success&quot;: True}<br><br>        except HttpError as http_err:<br>            return {&quot;message&quot;: f&quot;Authentication failed: Google API error ({http_err})&quot;, &quot;success&quot;: False}<br><br>        except Exception as ex:<br>            return {&quot;message&quot;: f&quot;Authentication failed: unexpected error ({ex})&quot;, &quot;success&quot;: False}</pre><ul><li>Initializes three member variables:</li><li>authenticated — a boolean showing whether you’re already logged in.</li><li>creds — holds your OAuth credentials object.</li><li>services — the API client object you’ll use to talk to Google Calendar.</li><li>When the file token.json is present in the working directory, At initialization, the class sets authenticated = True, then loads the credentials using Credentials.from_authorized_user_file(&quot;token.json&quot;, SCOPES).</li><li>If the credentials are expired and still have a valid refresh token, the code triggers creds.refresh(Request()) to get refreshed credentials. This automatic refresh flow aligns with how OAuth 2.0 works in the context of Google APIs: access tokens expire, but refresh tokens allow your app to obtain new ones without user intervention.</li><li>If token.json does <em>not</em> exist, the class leaves authenticated = False and services = None, . This clean separation ensures that the agent won’t attempt to call the Calendar API unless it is properly authenticated.</li></ul><p>Creating List Events Function</p><pre>class Calender():<br>    # Rest of the code from Above<br>    def list_events(<br>        self, <br>        end: Annotated[str, &quot;String in ISO 8601 format (with timezone offset) defining the upper bound for event start time. If the user does not specify this, default to one year after the start date.&quot;],<br>        calendar_id: Annotated[str, &quot;the calendar identifier, default &#39;primary&#39;&quot;] = &quot;primary&quot;,<br>        max_results: Annotated[int, &quot;maximum number of events to fetch.&quot;] = 50<br>    ) -&gt; Event | None:<br>        try:<br>            if not self.authenticated:<br>                res = self.login()<br>                if not res.success:<br>                    pretty_print(res.message, color=&quot;error&quot;)<br>                    return None<br>            now = datetime.now().isoformat()<br>            print(f&quot;Getting the Calender event: {end}&quot;)<br>            events_result = (<br>                self.services.events()<br>                .list(<br>                    calendarId=calendar_id,<br>                    timeMin=now+&quot;Z&quot;,<br>                    timeMax=end,<br>                    singleEvents=True,<br>                    orderBy=&quot;startTime&quot;,<br>                    maxResults=max_results<br>                )<br>                .execute()<br>            )<br>            events = events_result.get(&quot;items&quot;, [])<br>            if not events:<br>                print(&quot;No upcoming events found.&quot;)<br>                return None<br><br>            return events<br>        except HttpError as error:<br>            print(f&quot;An error occurred: {error}&quot;)</pre><ul><li>The Google Calendar API offers a RESTful interface (among other supported protocols) for calendar-related resources and operations. In particular its events.list endpoint allows you to query a calendar for events within certain time bounds (via parameters like timeMin and timeMax), filter or sort them (orderBy, singleEvents), paginate results (maxResults, pageToken), and retrieve key details of each event (like start time, end time, summary, attendees).</li></ul><p>Testing the function</p><pre>if __name__ == &quot;__main__&quot;:<br>    cal = Calender()<br>    print(cal.isAuthenticated())<br>    if not cal.isAuthenticated():<br>        cal.login()<br>    events = cal.list_events(&quot;2025-12-10T18:00:00Z&quot;)<br>    pretty_print(events, color=&quot;success&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcwKhicM6XaVzt7_4xnZBQ.png" /></figure><p>First time it will ask for the permission click on continue -&gt; in my case i have already accepted it</p><p>It Should Output like this:</p><pre>[{&#39;kind&#39;: &#39;calendar#event&#39;, &#39;etag&#39;: &#39;35243015300000046&#39;, &#39;id&#39;: &#39;cgpm....jgdhn70q6acr6cc&#39;, &#39;status&#39;: &#39;confirmed&#39;, &#39;htmlLink&#39;: &#39;https://www.google.com/calendar/event?eid=calid&#39;, &#39;created&#39;: &#39;2025-11-03T06:19:28.000Z&#39;, &#39;updated&#39;: &#39;2025-11-03T06:19:28.825Z&#39;, &#39;summary&#39;: &#39;Hey&#39;, &#39;creator&#39;: {&#39;email&#39;: &#39;jeeva.v910@gmail.com&#39;, &#39;self&#39;: True}, &#39;organizer&#39;: {&#39;email&#39;: &#39;jeeva.v910@gmail.com&#39;, &#39;self&#39;: True}, &#39;start&#39;: {&#39;dateTime&#39;: &#39;2025-11-05T04:30:00Z&#39;, &#39;timeZone&#39;: &#39;Asia/Kolkata&#39;}, &#39;end&#39;: {&#39;dateTime&#39;: &#39;2025-11-05T05:30:00Z&#39;, &#39;timeZone&#39;: &#39;Asia/Kolkata&#39;}, &#39;iCalUID&#39;: &#39;cgpm6cr4cpijib9lasdaqwdgdhn70q6acr6cc@google.com&#39;, &#39;sequence&#39;: 0, &#39;reminders&#39;: {&#39;useDefault&#39;: True}, &#39;eventType&#39;: &#39;default&#39;}]</pre><p>Creating Create Events Function</p><pre>class Calender():<br>    # Rest of the code from Above<br>    def create_event(self, calendar_id: str, event_data: dict) -&gt; dict:<br>        &quot;&quot;&quot;Create an event in the specified calendar.&quot;&quot;&quot;<br>        if not self.authenticated:<br>            res = self.login()<br>            if not res.success:<br>                pretty_print(res.message, color=&quot;error&quot;)<br>                return None<br><br>        try:<br>            event = self.services.events().insert(calendarId=calendar_id, body=event_data).execute()<br>            print(f&quot;Event created: {event.get(&#39;htmlLink&#39;)}&quot;)<br>            return {<br>                &quot;success&quot;: True,<br>                &quot;event_id&quot;: event.get(&quot;id&quot;),<br>                &quot;link&quot;: event.get(&quot;htmlLink&quot;),<br>                &quot;summary&quot;: event.get(&quot;summary&quot;),<br>                &quot;start&quot;: event.get(&quot;start&quot;),<br>                &quot;end&quot;: event.get(&quot;end&quot;)<br>            }<br>        except HttpError as e:<br>            print(f&quot;An error occurred: {e}&quot;)<br>            return {&quot;success&quot;: False, &quot;error&quot;: str(e)}</pre><ul><li>The events.insert endpoint of the Google Calendar API lets you add a new event to a specified calendar (calendarId) with a JSON body describing the event details (such as summary, start and end times, time zone) and then commits it to Google’s backend. According to the docs, specifying calendarId, body.event including start.dateTime and end.dateTime, and using the appropriate OAuth scope (https://www.googleapis.com/auth/calendar) are required.</li></ul><p>Testing the function</p><pre>if __name__ == &quot;__main__&quot;:<br>    cal = Calender()<br>    print(cal.isAuthenticated())<br>    if not cal.isAuthenticated():<br>        cal.login()<br>    event_data = {<br>        &quot;summary&quot;: &quot;Coffee with jeeva&quot;,<br>        &quot;description&quot;: None,<br>        &quot;location&quot;: None,<br>        &quot;start&quot;: {&quot;dateTime&quot;: &quot;2025-11-09T11:00:00Z&quot;, &quot;timeZone&quot;: &quot;Asia/Kolkata&quot;},<br>        &quot;end&quot;: {&quot;dateTime&quot;: &quot;2025-11-09T12:00:00Z&quot;, &quot;timeZone&quot;: &quot;Asia/Kolkata&quot;},<br>    }<br>    res = cal.create_event(calendar_id=&quot;primary&quot;, event_data=event_data)<br>    print(res)</pre><p>It Should Output like this:</p><pre>{&#39;success&#39;: True, &#39;event_id&#39;: &#39;5qccn2vl19hppfk&#39;, &#39;link&#39;: &#39;https://www.google.com/calendar/event?eid=NXFjY2.l....ZmsgamVldmEudjkxMEBt&#39;, &#39;summary&#39;: &#39;Coffee with jeeva&#39;, &#39;start&#39;: {&#39;dateTime&#39;: &#39;2025-11-09T11:00:00Z&#39;, &#39;timeZone&#39;: &#39;Asia/Kolkata&#39;}, &#39;end&#39;: {&#39;dateTime&#39;: &#39;2025-11-09T12:00:00Z&#39;, &#39;timeZone&#39;: &#39;Asia/Kolkata&#39;}}</pre><h4>Now Lets Jump To Making Agents</h4><p>For our agents to call the tools we need to provide the tool with description and required arguments</p><p>Create tools.py</p><pre>from google.genai import types<br><br>list_tool = {<br>    &quot;name&quot;: &quot;list_events&quot;,<br>    &quot;description&quot;: &quot;List events from now until end_date (exclusive) on the given calendar.&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>            &quot;end&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;String in ISO 8601 format (with timezone offset) defining the upper bound for event start time and ends with Z eg: 2025-12-10T18:00:00Z. If the user does not specify this, default to one year after the start date.&quot;,<br>            },<br>            &quot;calendar_id&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;the calendar identifier, default &#39;primary&#39;&quot;,<br>            },<br>            &quot;max_results&quot;: {<br>                &quot;type&quot;: &quot;integer&quot;,<br>                &quot;description&quot;: &quot;maximum number of events to fetch, Default 50.&quot;,<br>            },<br>        },<br>        &quot;required&quot;: [&quot;end&quot;, &quot;calendar_id&quot;, &quot;max_results&quot;],<br>    }<br>}<br><br>create_tool = {<br>    &quot;name&quot;: &quot;create_events&quot;,<br>    &quot;description&quot;: &quot;Create a new event on the specified date.&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>            &quot;summary&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;Title of the event specified by the user. if no title found on the user query Just return None.&quot;,<br>            },<br>            &quot;description&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;generate an small description of the event using the title. if no title found on the user query Just return None.&quot;,<br>            },<br>            &quot;location&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;Location of the event. Default None&quot;,<br>            },<br>            &quot;start&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;ISO 8601 with timezone offset ends with “Z” —The event’s start date and time (e.g., 2025-12-10T18:00:00Z). If not specified, defaults to today at 09:00 AM UTC..&quot;,<br>            },<br>            &quot;end&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;ISO 8601 with timezone offset ends with “Z” —The event’s end date and time (e.g., 2025-12-10T18:00:00Z). If not specified, defaults to today at one hour after start..&quot;,<br>            },<br>            &quot;calendar_id&quot;: {<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;description&quot;: &quot;the calendar identifier, default &#39;primary&#39;&quot;,<br>            },<br>            &quot;attendies&quot;: {<br>                &quot;type&quot;: &quot;array&quot;, <br>                &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                &quot;description&quot;: &quot;list of people emails who are attending&quot;,<br>            }<br>        },<br>        &quot;required&quot;: [&quot;summary&quot;, &quot;start&quot;, &quot;end&quot;],<br>    }<br>}<br><br>list_tool_fn = types.Tool(function_declarations=[list_tool])<br>create_tool_fn = types.Tool(function_declarations=[create_tool])<br><br>tools = [list_tool_fn, create_tool_fn]</pre><p>You’re telling the Gemini model that it has two <strong>tools</strong> available:</p><ul><li>One tool called <strong>“list_events”</strong> which asks for parameters like an end-time (end), which calendar (calendar_id) and how many events to fetch (max_results).</li><li>Another tool called <strong>“create_events”</strong> which takes things like summary, description, location, start, end, calendar_id, and attendies so it can create a new calendar event.</li></ul><p>These are declared using JSON-schema style definitions (name, description, parameters) so the model can pick <em>which</em> tool to call and <em>how</em> to call it. <a href="https://ai.google.dev/gemini-api/docs/function-calling">Google AI for Developers+2Google Cloud+2</a></p><p>Now Lets Create agents.py</p><p>Making necessary imports</p><pre>from schemas import *<br>from datetime import datetime<br>from google import genai<br>from dotenv import load_dotenv<br>from google.genai.types import GenerateContentConfig<br>from calender_service import Calender<br>from utility import pretty_print<br>from tools import tools<br>from typing import Annotated, Optional<br><br>load_dotenv()<br><br>llm = genai.Client()<br>model = &quot;gemini-2.5-pro&quot;<br>cal = Calender()</pre><p>Now Ensuring the user has the tokens to access the calendar</p><pre>def ensure_authenticated() -&gt; bool:<br>    if cal.isAuthenticated():<br>        return cal.authenticated<br>    cal.login()<br>    return True</pre><p>Now lets gaurd rail our agent (It prevents the agent from doing other tasks)</p><pre>def gaurdrail(user_query: str) -&gt; SecurityCheck:<br>    &quot;&quot;&quot;Check for ptompt injections&quot;&quot;&quot;<br><br>    completion = llm.models.generate_content(<br>        model=model,<br>        contents=user_query,<br>        config=GenerateContentConfig(<br>            system_instruction=&quot;Determine if this is a calendar event request. if its not related to the calendar event return is safe to false and give the risk flags&quot;,<br>            response_mime_type=&quot;application/json&quot;,<br>            response_schema=SecurityCheck<br>        )<br>    )<br><br>    res: SecurityCheck = completion.parsed<br>    print(res.is_safe)<br>    return res</pre><p>Functions to call the tools (These are the function we are gonna call if model desides on calling functions)</p><pre>def list_events(end_date: str, calendar_id: str = &quot;primary&quot;, max_results: int = 50) -&gt; list[Event]:<br>    print(&quot;Processing the user query for listing&quot;)<br>    cal = Calender()<br>    events = cal.list_events(end_date, calendar_id, max_results)<br>    return events<br><br>def create_event(<br>    title: Annotated[str, &quot;Event title given by the user&quot;],<br>    start_time: Annotated[str, &quot;String in ISO 8601 format (with timezone offset)&quot;],<br>    end_time: Annotated[str, &quot;String in ISO 8601 format (with timezone offset)&quot;],<br>    calendar_id: Annotated[str, &quot;the calendar identifier, default &#39;primary&#39;&quot;] = &quot;primary&quot;,<br>    description: Optional[Annotated[str, &quot;An small description about the event&quot;]] = &quot;&quot;,<br>    location: Optional[Annotated[str, &quot;Location of the event&quot;]] = &quot;&quot;,<br>    attendees: Optional[Annotated[list[str], &quot;list of attendee email addresses&quot;]] = None<br>) -&gt; dict:<br>    <br>    print(&quot;Processing create_event request&quot;)<br>    cal = Calender()<br><br>    event_data = {<br>        &quot;summary&quot;: title,<br>        &quot;description&quot;: description,<br>        &quot;location&quot;: location,<br>        &quot;start&quot;: {&quot;dateTime&quot;: start_time, &quot;timeZone&quot;: &quot;Asia/Kolkata&quot;},<br>        &quot;end&quot;: {&quot;dateTime&quot;: end_time, &quot;timeZone&quot;: &quot;Asia/Kolkata&quot;},<br>    }<br><br>    if attendees:<br>        event_data[&quot;attendees&quot;] = [{&quot;email&quot;: a} for a in attendees]<br><br>    result = cal.create_event(calendar_id, event_data)<br>    return result</pre><p>Now the Agent Itself</p><pre>def process_and_route_request(user_query: str) -&gt; str:<br>    &quot;&quot;&quot;Process the user request&quot;&quot;&quot;<br>    print(&quot;Processing the user query&quot;)<br>    today = datetime.now()<br>    date_content = f&quot;Today is {today.strftime(&#39;%A, %B %d, %Y&#39;)}.&quot;<br><br>    SYS_PROMPT = &quot;&quot;&quot;<br>        You are a calendar assistant agent who has access to a set of tools (functions) for managing a user’s calendar: creating events, listing events, updating events, deleting events.<br><br>        Your job is:<br>        1. Review the user’s request.<br>        2. Decide which tool best matches the user’s intent (e.g., “list_events” if they ask to show their upcoming events; “create_event” if they ask to schedule a meeting; “update_event” if they ask to change something; “delete_event” if they ask to remove something).<br>        3. If needed, extract the correct parameters for the chosen tool (e.g., end date, calendar_id, max_results for listing; title, start, end, participants for creation; event_id for update/delete).<br>        4. Invoke that tool by outputting a function call JSON (with the correct function name and arguments) for your system to execute.<br>        5. After the tool returns results, produce a user-friendly natural-language response that summarizes what happened or answers their query.<br><br>        Constraints &amp; good behaviour:<br>        - If the user’s request is ambiguous (e.g., “Show me tomorrow’s meeting” but user has more than one meeting tomorrow), ask a clarifying question instead of proceeding.<br>        - Avoid using a tool if the user’s request can be answered directly without it (e.g., “how many days until Friday?”).<br>        - Make sure missing parameters are requested (e.g., if the user didn’t provide a date/time, ask: “Which days and time would you like?”).<br>        - Assume current date/time context is given (the system may provide “Today is …”).<br>        - The tool names and arguments must exactly follow the declarations you provided in the tools list.<br><br>        Output instructions:<br>        - If you decide to call a tool: output exactly a JSON object with the function name and args, and no extra text.<br>        - After the tool execution returns, output natural-language explanation.<br>        - Do not combine tool invocation and explanation in the same JSON output. First tool call, then separate message.<br><br>        Start by reading the user’s request carefully and determine the correct tool to use or confirm if a direct answer is possible.<br>    &quot;&quot;&quot;<br><br>    completion = llm.models.generate_content(<br>        model=model,<br>        contents=f&quot;{date_content} {user_query}&quot;,<br>        config=GenerateContentConfig(<br>            system_instruction=SYS_PROMPT,<br>            tools=tools<br>        )<br>    )<br>    model_response = &quot;&quot;<br>    for function in completion.candidates[0].content.parts:<br>        call = function.function_call<br>        pretty_print(f&quot;Tool calls: \n {call}&quot;)<br>        if call:<br>            sys_prompt = (<br>                &quot;You are a calendar assistant. Use the events list and the user query to respond. &quot;<br>                &quot;If the user asked to list events, present them clearly. &quot;<br>                &quot;If they asked for something else, do not perform any action you do not support.&quot;<br>            )<br>            if call.name == &quot;list_events&quot;:<br>                end_date = call.args.get(&quot;end&quot;)<br>                calendar_id = call.args.get(&quot;calendar_id&quot;, &quot;primary&quot;)<br>                max_results = call.args.get(&quot;max_results&quot;, 50)<br>                pretty_print(f&quot;Entering the list call&quot;)<br>                raw_events = list_events(end_date, calendar_id, max_results)<br>                summary_lines = []<br>                events_summary = &quot;&quot;<br>                if raw_events:<br>                    for ev in raw_events:<br>                        summary = ev.get(&quot;summary&quot;, &quot;(no title)&quot;)<br>                        start   = ev.get(&quot;start&quot;, {}).get(&quot;dateTime&quot;) or ev.get(&quot;start&quot;, {}).get(&quot;date&quot;)<br>                        end     = ev.get(&quot;end&quot;,   {}).get(&quot;dateTime&quot;) or ev.get(&quot;end&quot;,   {}).get(&quot;date&quot;)<br>                        summary_lines.append(f&quot;- {summary} from {start} to {end}&quot;)<br><br>                    events_summary = &quot;\n&quot;.join(summary_lines) or &quot;No events found.&quot;<br>                else:<br>                    events_summary = &quot;No Events Found&quot;<br><br>                full_prompt = (<br>                    f&quot;User query: {user_query}\n&quot;<br>                    f&quot;Here are the next events in your calendar (up to {max_results}):\n&quot;<br>                    f&quot;{events_summary}\n\n&quot;<br>                    &quot;Based on the user request and the events, provide the best answer.&quot;,<br>                    date_content<br>                )<br>                completion = llm.models.generate_content(<br>                    model=model,<br>                    contents=full_prompt,<br>                    config=GenerateContentConfig(<br>                        system_instruction=sys_prompt,<br>                    )<br>                )<br>                model_response = completion.candidates[0].content.parts[0].text<br>            elif call.name == &quot;create_events&quot;:<br>                summary = call.args.get(&quot;summary&quot;)<br>                description = call.args.get(&quot;description&quot;, None)<br>                location = call.args.get(&quot;location&quot;, None)<br>                start = call.args.get(&quot;start&quot;)<br>                calendar_id = call.args.get(&quot;calendar_id&quot;, &quot;primary&quot;)<br>                end = call.args.get(&quot;end&quot;)<br>                attendies = call.args.get(&quot;attendies&quot;, [])<br>                res = create_event(summary, start, end, calendar_id, description, location, attendies)<br>                full_prompt = f&quot;Event response: {res} \n User Query: {user_query}&quot;<br>                completion = llm.models.generate_content(<br>                    model=model,<br>                    contents=full_prompt,<br>                    config=GenerateContentConfig(<br>                        system_instruction=sys_prompt,<br>                    )<br>                )<br>                model_response = completion.candidates[0].content.parts[0].text<br>                    <br>        else:<br>            pretty_print(&quot;Model didnt make any tool call&quot;, color=&quot;error&quot;)<br>    return model_response if model_response else &quot;Something went wrong&quot;</pre><ol><li>It receives a user’s natural language query (user_query: str) and adds a little context about the current date.</li><li>It builds a system prompt (SYS_PROMPT) telling the LLM (in this case Gemini) that it is a calendar assistant, knows about tools (create/list events), needs to decide which tool to invoke, and must ask questions if things are ambiguous.</li><li>It calls the LLM with the prompt + tool definitions, and checks if the LLM suggests a tool call (via function_call).</li><li>If the LLM chooses <strong>list_events</strong>, the code extracts parameters (end_date, calendar_id, max_results), calls list_events(...), gets raw events, builds a summary of them, then sends a follow-up LLM query asking it to generate a user-friendly response based on those events.</li><li>If the LLM chooses <strong>create_events</strong>, the code pulls out summary, description, location, start, end, calendar_id, attendies, calls create_event(...), receives result, then sends that result into the LLM to get a friendly response.</li><li>If no tool call is made, it prints an error.</li><li>Finally, it returns the natural-language response to the user.</li></ol><h4>Now the Orchestration of the agent</h4><pre>def Orchestration(user_query: str):<br>    gaurd_rail = gaurdrail(user_query)<br>    if not gaurd_rail.is_safe:<br>        pretty_print(f&quot;Warning: Agent stops the Process, potential prompt injection: {&#39; &#39;.join(gaurd_rail.risk_flags)}&quot;, color=&quot;warning&quot;)<br>        return<br>    pretty_print(&quot;Starting user request&quot;, color=&quot;info&quot;)<br>    parsed_query = process_and_route_request(user_query)<br>    pretty_print(parsed_query, color=&quot;success&quot;)<br><br>def main():<br>    auth = ensure_authenticated()<br>    if not auth:<br>        pretty_print(f&quot;Warning: Agent stops the Process, Complete the auth to continue&quot;, color=&quot;warning&quot;)<br>        return<br>    pretty_print(&quot;Passed Auth Check ✅&quot;)<br>    while True:<br>        query = input(&quot;Enter Your Calendar query enter quit to exit: \n&quot;)<br>        if query == &quot;quit&quot;:<br>            pretty_print(&quot;Process Stopped by user&quot;, color=&quot;error&quot;)<br>            break<br>        Orchestration(query)</pre><p>It should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*rMAJEEOq27aU3tpCpGjDwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*G19poHhBq59fpzMRMHIZbQ.png" /></figure><h3>conclusion</h3><p>You’ve mastered the full flow: <strong>input → reasoning → tool call → API execution → user-friendly output</strong>.</p><p>This core architecture is your new superpower. Now, <strong>go build on it!</strong> Try adding features like updating/deleting events, setting reminders, or integrating with other services.</p><p><strong>You’re not just following steps — you’re creating something powerful and unique.</strong> The potential is wide open!</p><p>Thanks For Reading 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e65e79341c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>