Skip to content

Commit

Permalink
fix: Make lint and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jorge-jrzz committed Nov 29, 2024
1 parent 3ea34f3 commit 62b997e
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 68 deletions.
108 changes: 83 additions & 25 deletions docs/docs/integrations/tools/google_calendar.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -10,58 +10,74 @@
"source": [
"# Google Calendar Toolkit\n",
"\n",
"## Overview\n",
"\n",
"> [Google Calendar](https://workspace.google.com/intl/en-419/products/calendar/) is a product of Google that allows users to organize their schedules and events. It is a cloud-based calendar that allows users to create, edit, and delete events. It also allows users to share their calendars with others.\n",
"\n",
"This notebook will help you getting started with the Google Calendar Toolkit. This toolkit interacts with the Google Calendar API to perform various operations on the calendar. It allows you to create, search, update, and delete events on your calendar. It also allows you to list events on your calendar.\n",
"\n",
"To use this toolkit, you will need to set up your credentials explained in the [Google Calendar API docs](https://developers.google.com/calendar/api/quickstart/python#authorize_credentials_for_a_desktop_application). Once you've downloaded the `credentials.json` file, you can start using the Google Calendar API.\n",
"\n",
"## Setup\n",
"\n",
"To use this toolkit, you will need to set up your credentials explained in the [Google Calendar API docs](https://developers.google.com/calendar/api/quickstart/python#authorize_credentials_for_a_desktop_application). Once you've downloaded the `credentials.json` file, you can start using the Google Calendar API."
"This toolkit requires the Google Python libraries, also, throughout the notebook, the following dependencies are used"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install --upgrade --quiet google-api-python-client google-auth-httplib2 google-auth-oauthlib\n",
"%pip install --upgrade --quiet langchain\n",
"%pip install --upgrade --quiet langchain-community\n",
"%pip install --upgrade --quiet langchain-openai\n",
"%pip install --upgrade --quiet langgraph"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Installation\n",
"## Instantiation\n",
"\n",
"This toolkit requires the Google Python libraries:"
"By default the toolkit reads the local `credentials.json` file. You can also manually provide a `Credentials` object."
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%pip install --upgrade --quiet google-api-python-client google-auth-httplib2 google-auth-oauthlib\n",
"%pip install -qU langchain-community"
"from langchain_community.agent_toolkits import GoogleCalendarToolkit\n",
"\n",
"toolkit = GoogleCalendarToolkit()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Usage\n",
"### Customizing Authentication\n",
"\n",
"By default the toolkit reads the local `credentials.json` file. You can also manually provide a `Credentials` object.\n",
"\n",
"### Build the resource rervice and tollkit"
"Behind the scenes, a `googleapi` resource is created using the following methods. you can manually build a `googleapi` resource for more auth control."
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.agent_toolkits import GoogleCalendarToolkit\n",
"from langchain_community.tools.google_calendar.utils import (\n",
" build_resource_service,\n",
" get_google_calendar_credentials, \n",
" get_google_calendar_credentials,\n",
")\n",
"\n",
"# Can review scopes here: https://developers.google.com/calendar/api/auth \n",
"# Can review scopes here: https://developers.google.com/calendar/api/auth\n",
"credentials = get_google_calendar_credentials(\n",
" token_file=\"token.json\",\n",
" scopes=[\"https://www.googleapis.com/auth/calendar\"],\n",
Expand All @@ -75,7 +91,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"### Tools\n",
"## Invocation\n",
"\n",
"View available tools:"
]
Expand All @@ -88,12 +104,12 @@
{
"data": {
"text/plain": [
"[CalendarCreateEvent(api_resource=<googleapiclient.discovery.Resource object at 0x109ef48f0>),\n",
" CalendarSearchEvents(api_resource=<googleapiclient.discovery.Resource object at 0x109ef48f0>),\n",
" CalendarUpdateEvent(api_resource=<googleapiclient.discovery.Resource object at 0x109ef48f0>),\n",
" GetCalendarsInfo(api_resource=<googleapiclient.discovery.Resource object at 0x109ef48f0>),\n",
" CalendarMoveEvent(api_resource=<googleapiclient.discovery.Resource object at 0x109ef48f0>),\n",
" CalendarDeleteEvent(api_resource=<googleapiclient.discovery.Resource object at 0x109ef48f0>)]"
"[CalendarCreateEvent(api_resource=<googleapiclient.discovery.Resource object at 0x120f77350>),\n",
" CalendarSearchEvents(api_resource=<googleapiclient.discovery.Resource object at 0x120f77350>),\n",
" CalendarUpdateEvent(api_resource=<googleapiclient.discovery.Resource object at 0x120f77350>),\n",
" GetCalendarsInfo(api_resource=<googleapiclient.discovery.Resource object at 0x120f77350>),\n",
" CalendarMoveEvent(api_resource=<googleapiclient.discovery.Resource object at 0x120f77350>),\n",
" CalendarDeleteEvent(api_resource=<googleapiclient.discovery.Resource object at 0x120f77350>)]"
]
},
"execution_count": 2,
Expand All @@ -110,16 +126,49 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"### Use within an agent\n",
"## Chaining"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ContentString: \n",
"ToolCalls: [{'name': 'create_calendar_event', 'args': {'summary': 'Meeting with John', 'start_datetime': '2024-11-29 10:00:00', 'end_datetime': '2024-11-29 11:00:00'}, 'id': 'call_IJUCAmUhLPXwbCQGNZ4wlM1S', 'type': 'tool_call'}]\n"
]
}
],
"source": [
"from langchain_core.messages import HumanMessage\n",
"from langchain_openai import ChatOpenAI\n",
"\n",
"Below we show how to incorporate the toolkit into an Agent.\n",
"llm = ChatOpenAI(model=\"gpt-4o-mini\", temperature=0)\n",
"llm_with_tools = llm.bind_tools(tools)\n",
"response = llm_with_tools.invoke(\n",
" [HumanMessage(\"Create a event tomorrow at 10am for meeting with John.\")]\n",
")\n",
"\n",
"We will need a LLM or chat model:"
"print(f\"ContentString: {response.content}\")\n",
"print(f\"ToolCalls: {response.tool_calls}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use within an agent\n",
"\n",
"Below we show how to incorporate the toolkit into an Agent with `langgraph`"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -130,7 +179,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
Expand Down Expand Up @@ -182,6 +231,15 @@
"for event in events:\n",
" event[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## API reference\n",
"\n",
"Refer to the [Google Calendar API overview  |  Google for Developers](https://developers.google.com/calendar/api/guides/overview) for more details."
]
}
],
"metadata": {
Expand Down
10 changes: 5 additions & 5 deletions libs/community/langchain_community/agent_toolkits/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
from langchain_community.agent_toolkits.gmail.toolkit import (
GmailToolkit,
)
from langchain_community.agent_toolkits.google_calendar.toolkit import (
GoogleCalendarToolkit,
)
from langchain_community.agent_toolkits.jira.toolkit import (
JiraToolkit,
)
Expand Down Expand Up @@ -96,9 +99,6 @@
from langchain_community.agent_toolkits.zapier.toolkit import (
ZapierToolkit,
)
from langchain_community.agent_toolkits.google_calendar.toolkit import (
GoogleCalendarToolkit,
)

__all__ = [
"AINetworkToolkit",
Expand All @@ -109,6 +109,7 @@
"ConneryToolkit",
"FileManagementToolkit",
"GmailToolkit",
"GoogleCalendarToolkit",
"JiraToolkit",
"JsonToolkit",
"MultionToolkit",
Expand All @@ -130,7 +131,6 @@
"create_pbi_chat_agent",
"create_spark_sql_agent",
"create_sql_agent",
"GoogleCalendarToolkit",
]


Expand All @@ -143,6 +143,7 @@
"ConneryToolkit": "langchain_community.agent_toolkits.connery",
"FileManagementToolkit": "langchain_community.agent_toolkits.file_management.toolkit", # noqa: E501
"GmailToolkit": "langchain_community.agent_toolkits.gmail.toolkit",
"GoogleCalendarToolkit": "langchain_community.agent_toolkits.google_calendar.toolkit", # noqa: E501
"JiraToolkit": "langchain_community.agent_toolkits.jira.toolkit",
"JsonToolkit": "langchain_community.agent_toolkits.json.toolkit",
"MultionToolkit": "langchain_community.agent_toolkits.multion.toolkit",
Expand All @@ -164,7 +165,6 @@
"create_pbi_chat_agent": "langchain_community.agent_toolkits.powerbi.chat_base",
"create_spark_sql_agent": "langchain_community.agent_toolkits.spark_sql.base",
"create_sql_agent": "langchain_community.agent_toolkits.sql.base",
"GoogleCalendarToolkit": "langchain_community.agent_toolkits.google_calendar.toolkit",
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
from pydantic import ConfigDict, Field

from langchain_community.tools.google_calendar.create_event import CalendarCreateEvent
from langchain_community.tools.google_calendar.search_events import CalendarSearchEvents
from langchain_community.tools.google_calendar.delete_event import CalendarDeleteEvent
from langchain_community.tools.google_calendar.get_calendars_info import GetCalendarsInfo
from langchain_community.tools.google_calendar.get_calendars_info import (
GetCalendarsInfo,
)
from langchain_community.tools.google_calendar.move_event import CalendarMoveEvent
from langchain_community.tools.google_calendar.search_events import CalendarSearchEvents
from langchain_community.tools.google_calendar.update_event import CalendarUpdateEvent
from langchain_community.tools.google_calendar.utils import build_resource_service

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
"""Google Calendar tools."""

from langchain_community.tools.google_calendar.create_event import CalendarCreateEvent
from langchain_community.tools.google_calendar.search_events import CalendarSearchEvents
from langchain_community.tools.google_calendar.delete_event import CalendarDeleteEvent
from langchain_community.tools.google_calendar.get_calendars_info import GetCalendarsInfo
from langchain_community.tools.google_calendar.get_calendars_info import (
GetCalendarsInfo,
)
from langchain_community.tools.google_calendar.move_event import CalendarMoveEvent
from langchain_community.tools.google_calendar.search_events import CalendarSearchEvents
from langchain_community.tools.google_calendar.update_event import CalendarUpdateEvent
from langchain_community.tools.google_calendar.utils import get_google_calendar_credentials
from langchain_community.tools.google_calendar.utils import (
get_google_calendar_credentials,
)

__all__ = [
"CalendarCreateEvent",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""Create an event in Google Calendar.""" # NUEVO

import re
from uuid import uuid4
from datetime import datetime
from typing import Any, Dict, List, Optional, Type, Union
from uuid import uuid4

from langchain_core.callbacks import CallbackManagerForToolRun
from pydantic import BaseModel, Field
Expand Down Expand Up @@ -250,6 +250,6 @@ def _run(
)
.execute()
)
return f"Event created: {event.get("htmlLink")}"
return f"Event created: {event.get('htmlLink')}"
except Exception as error:
raise Exception(f"An error occurred: {error}") from error
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Search an event in Google Calendar."""

from datetime import datetime
from zoneinfo import ZoneInfo # Python 3.9+
from typing import Any, Dict, List, Optional, Type
from zoneinfo import ZoneInfo # Python 3.9+

from langchain_core.callbacks import CallbackManagerForToolRun
from pydantic import BaseModel, Field, field_validator
from pydantic import BaseModel, Field

from langchain_community.tools.google_calendar.base import GoogleCalendarBaseTool

Expand Down Expand Up @@ -48,34 +48,6 @@ class SearchEventsSchema(BaseModel):
),
)

@field_validator("order_by")
@classmethod
def validate_order_by(cls, v: str) -> str:
"""Validate the order_by field."""
if v not in ["startTime", "updated"]:
raise ValueError("order_by must be 'startTime' or 'updated'")
return v

@field_validator("max_results")
@classmethod
def validate_max_results(cls, v: int) -> int:
"""Validate the max_results field."""
if v <= 0:
raise ValueError("max_results must be a positive integer")
return v

@field_validator("max_datetime")
@classmethod
def validate_datetimes(cls, v: Any, values: Any) -> Any:
"""Validate the max_datetime field."""
min_dt_str = values.get("min_datetime")
if min_dt_str:
min_dt = datetime.strptime(min_dt_str, "%Y-%m-%d %H:%M:%S")
max_dt = datetime.strptime(v, "%Y-%m-%d %H:%M:%S")
if max_dt < min_dt:
raise ValueError("max_datetime must be after min_datetime")
return v


class CalendarSearchEvents(GoogleCalendarBaseTool):
"""Tool that retrieves events from Google Calendar."""
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""Update an event in Google Calendar."""

import re
from uuid import uuid4
from datetime import datetime
from typing import Any, Dict, List, Optional, Type, Union
from uuid import uuid4

from langchain_core.callbacks import CallbackManagerForToolRun
from pydantic import BaseModel, Field
Expand Down

0 comments on commit 62b997e

Please sign in to comment.