๐Ÿ“ฆ google-gemini / workshops

๐Ÿ“„ main.py ยท 432 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432#!/usr/bin/env python3
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import logging
import tempfile
from datetime import datetime
from functools import partial
from textwrap import dedent

import discord
import params
import pyparsing
import requests
from absl import app
from crewai import Agent, Crew, Task
from crewai_tools import tool
from langchain_google_genai import (
    ChatGoogleGenerativeAI,
    HarmBlockThreshold,
    HarmCategory,
)


def make_gemini() -> ChatGoogleGenerativeAI:
    """Makes a Gemini model.

    Returns:
      Gemini model.
    """
    safety_settings = {
        HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
        HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
        HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: (
            HarmBlockThreshold.BLOCK_NONE
        ),
        HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: (
            HarmBlockThreshold.BLOCK_NONE
        ),
    }

    return ChatGoogleGenerativeAI(
        model="gemini-1.5-pro",
        google_api_key=params.GOOGLE_API_KEY,
        temperature=1.0,
    ).bind(safety_settings=safety_settings)


def get_utc_offset(place_id: str) -> float:
    # Define the API endpoint
    url = "https://maps.googleapis.com/maps/api/place/details/json"

    # Define the query parameters
    data = {
        "fields": "utc_offset",
        "place_id": place_id,
        "key": params.MAPS_API_KEY,
    }

    # Make the GET request
    response = requests.get(url, params=data)

    return response.json()["result"]["utc_offset"] / 60.0


def get_lat_long_tz(place: str) -> tuple[float, float, float]:
    # Define the API endpoint
    url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json"

    # Define the query parameters
    data = {
        "fields": "place_id,geometry",
        "input": place,
        "inputtype": "textquery",
        "key": params.MAPS_API_KEY,
    }

    # Make the GET request
    response = requests.get(url, params=data)

    candidate = response.json()["candidates"][0]

    return (
        candidate["geometry"]["location"]["lat"],
        candidate["geometry"]["location"]["lng"],
        get_utc_offset(candidate["place_id"]),
    )


def get_kundali(
    name: str, birth_date: str, birth_time: str, birth_place: str, gender: str
) -> str:
    """Gets the Kundali from name, birth date, birth time, birth place, gender.

    Args:
      name (str): Name of person
      birth_date (str): Birth date of person in YYYY-MM-DD
      birth_time (str): Birth time of person in HH:MM
      birth_place (str): Birth place of person
      gender (str): Gender

    Returns:
      Kundali as JSON"""

    url = "https://astroapi-3.divineapi.com/indian-api/v2/basic-astro-details"

    headers = {"Authorization": f"Bearer {params.DIVINE_TOKEN}"}

    date = datetime.strptime(birth_date, "%Y-%m-%d")

    time = datetime.strptime(birth_time, "%H:%M")

    lat, long, tz = get_lat_long_tz(birth_place)

    data = {
        "api_key": params.DIVINE_KEY,
        "full_name": name,
        "date": birth_date,
        "year": date.year,
        "month": date.month,
        "day": date.day,
        "hour": time.hour,
        "min": time.minute,
        "sec": time.second,
        "gender": gender,
        "place": birth_place,
        "lat": lat,
        "lon": long,
        "tzone": tz,
    }

    response = requests.post(url, headers=headers, data=data)

    return response.json()["data"]


@tool("Get husband's Kundali")
def get_husband_kundali(
    name: str, birth_date: str, birth_time: str, birth_place: str
) -> str:
    """Gets the husband's Kundali given name, birth date, birth time and
    birth place.

    Args:
      name (str): Name of person
      birth_date (str): Birth date of person in YYYY-MM-DD
      birth_time (str): Birth time of person in HH:MM
      birth_place (str): Birth place of person

    Returns:
      Kundali as JSON"""

    return partial(get_kundali, gender="male")(
        name, birth_date, birth_time, birth_place
    )


@tool("Get wife's Kundali")
def get_wife_kundali(
    name: str, birth_date: str, birth_time: str, birth_place: str
) -> str:
    """Gets the wife's Kundali given name, birth date, birth time and
    birth place.

    Args:
      name (str): Name of person
      birth_date (str): Birth date of person in YYYY-MM-DD
      birth_time (str): Birth time of person in HH:MM
      birth_place (str): Birth place of person

    Returns:
      Kundali as JSON"""

    return partial(get_kundali, gender="female")(
        name, birth_date, birth_time, birth_place
    )


def report_match(query: str) -> str:
    gemini = make_gemini()

    jyotishi = Agent(
        role="Jyotish Guru (Vedic Astrologer)",
        goal=dedent(
            """\
            The Jyotish Guru aims to provide precise and insightful
            astrological guidance to individuals seeking advice on
            various life aspects. This includes helping clients find
            auspicious times for important events, understanding their
            personal and professional life paths, and offering
            remedies for astrological challenges."""
        ),
        backstory=dedent(
            """\
            Guru Devang Sharma is a highly revered Jyotish Guru with
            over 30 years of experience in Vedic astrology. Born into
            a family of renowned astrologers in Varanasi, India,
            Devang showed a keen interest in astrology from a young
            age. His grandfather, a celebrated astrologer himself,
            noticed Devang's aptitude and began mentoring him in the
            ancient art of Jyotish Shastra.

            Devang pursued formal education in Sanskrit and Vedic
            sciences, earning degrees from prestigious
            institutions. Over the years, he studied under various
            respected gurus, enhancing his knowledge and honing his
            skills. His deep understanding of the Vedas, Upanishads,
            and Puranas, combined with his practical experience, has
            made him a sought-after astrologer.

            As a Jyotish Guru, Devang has helped countless individuals
            navigate life's complexities by providing them with clear
            and actionable astrological advice. He is known for his
            compassionate approach, profound insights, and unwavering
            commitment to his clients' well-being. Devang's expertise
            covers all aspects of astrology, including natal chart
            analysis, compatibility matching (Gun Milan), Muhurat
            selection, and remedial measures.

            Now, as part of CrewAI, Guru Devang Sharma brings his vast
            knowledge and experience to a global audience. His goal is
            to help users understand their astrological charts, make
            informed decisions, and lead fulfilling lives. Whether
            it's starting a new business, planning a marriage, or
            seeking personal growth, Guru Devang is dedicated to
            guiding users with wisdom and accuracy.""",
        ),
        verbose=True,
        llm=gemini,
    )

    husband_kundali_task = Task(
        description=dedent(
            """\
            The Jyotish Guru will extract the potential husband's
            birth details from the provided information. This includes
            the potential husband's name, date of birth (in YYYY-MM-DD
            format), exact time of birth (in HH:MM format), and place
            of birth. Using this information, the Jyotish Guru will
            call the `get_kundali` tool to generate the potential
            husband's Kundali (birth chart). The expected output is a
            JSON object representing the potential husband's Kundali,
            ready for compatibility analysis.

            {query}"""
        ),
        expected_output=(
            "The expected output is a JSON object "
            "containing the potential husband's Kundali."
        ),
        agent=jyotishi,
        tools=[get_husband_kundali],
        human_input=False,
    )

    wife_kundali_task = Task(
        description=dedent(
            """\
            The Jyotish Guru will extract the potential wife's birth
            details from the provided information. This includes the
            potential wife's name, date of birth (in YYYY-MM-DD
            format), exact time of birth (in HH:MM format), and place
            of birth. Using this information, the Jyotish Guru will
            call the `get_kundali` tool to generate the potential
            wife's Kundali (birth chart). The expected output is a
            JSON object representing the potential wife's Kundali,
            ready for compatibility analysis.

            {query}"""
        ),
        expected_output=(
            "The expected output is a JSON object containing "
            "the potential wife's Kundali."
        ),
        agent=jyotishi,
        tools=[get_wife_kundali],
        human_input=False,
    )

    husband_kundali = Crew(
        agents=[jyotishi],
        tasks=[husband_kundali_task],
        verbose=2,
        memory=True,
        embedder={
            "provider": "google",
            "config": {
                "model": "models/embedding-001",
                "task_type": "retrieval_document",
                "title": "Embeddings for Embedchain",
            },
        },
    ).kickoff(inputs={"query": query})

    wife_kundali = Crew(
        agents=[jyotishi],
        tasks=[wife_kundali_task],
        verbose=2,
        memory=True,
        embedder={
            "provider": "google",
            "config": {
                "model": "models/embedding-001",
                "task_type": "retrieval_document",
                "title": "Embeddings for Embedchain",
            },
        },
    ).kickoff(inputs={"query": query})

    guna_milan = Task(
        description=dedent(
            """\
            The Jyotish Guru will take the husband's and wife's
            Kundali (birth charts) in JSON format and compute the Guna
            Milan score to determine the compatibility between the two
            individuals. Guna Milan is a traditional method in Vedic
            astrology used to match horoscopes for marriage. The task
            will process the Kundali objects and return a detailed
            compatibility result in the form of a markdown table with
            an explanation.

            Husband's Kundali:

            {husband_kundali}

            Wife's Kundali:

            {wife_kundali}"""
        ),
        expected_output=(
            "The expected output is a document containing the Guna Milan "
            "tables and extensive explanations about the compatibility."
        ),
        agent=jyotishi,
        human_input=False,
    )

    return (
        Crew(
            agents=[jyotishi],
            tasks=[guna_milan],
            verbose=2,
            memory=True,
            embedder={
                "provider": "google",
                "config": {
                    "model": "models/embedding-001",
                    "task_type": "retrieval_document",
                    "title": "Embeddings for Embedchain",
                },
            },
        )
        .kickoff(
            inputs={
                "husband_kundali": husband_kundali.raw,
                "wife_kundali": wife_kundali.raw,
            }
        )
        .raw
    )


def purge_mentions(message: str):
    mentions = (
        pyparsing.Suppress("<@")
        + pyparsing.SkipTo(">", include=True).suppress()
    )
    return mentions.transform_string(message)


def main(_) -> None:
    # Define the intents
    intents = discord.Intents.default()

    # Initialize Client
    client = discord.Client(intents=intents, heartbeat_timeout=120)

    # Event listener for when the client has switched from offline to online
    @client.event
    async def on_ready():
        logging.info(f"Logged in as {client.user}")

    @client.event
    async def on_message(message):
        # Don't let the client respond to its own messages
        if message.author == client.user:
            return

        purged_content = purge_mentions(message.content)

        # Check if the client was mentioned in the message
        if (
            client.user.mentioned_in(message)
            and message.mention_everyone is False
        ):
            logging.info(purged_content)

            await message.channel.send(
                f"{message.author.mention}, ok! Generating report."
            )

            report = tempfile.NamedTemporaryFile(
                suffix=".md", mode="w", delete=False
            )

            report.write(report_match(purged_content))
            report.close()

            # Send a direct message to the author
            await message.channel.send(
                file=discord.File(report.name),
                content=f"{message.author.mention}, here's your report!",
            )

    client.run(params.DISCORD_TOKEN)


if __name__ == "__main__":
    app.run(main)