Skip to content

Commit

Permalink
Merge pull request #1271 from phidatahq/storage-cookbooks-phi-1703
Browse files Browse the repository at this point in the history
storage-cookbooks-phi-1703
  • Loading branch information
ashpreetbedi authored Oct 22, 2024
2 parents 85df834 + 48e43e6 commit 4dddd76
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 60 deletions.
1 change: 1 addition & 0 deletions cookbook/examples/dynamodb_as_storage/agent.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import typer
from typing import Optional, List

from phi.agent import Agent
from phi.storage.agent.dynamodb import DynamoDbAgentStorage

Expand Down
Empty file added cookbook/storage/__init__.py
Empty file.
14 changes: 14 additions & 0 deletions cookbook/storage/dynamodb_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Run `pip install duckduckgo-search boto3 openai` to install dependencies."""

from phi.agent import Agent
from phi.tools.duckduckgo import DuckDuckGo
from phi.storage.agent.dynamodb import DynamoDbAgentStorage

agent = Agent(
storage=DynamoDbAgentStorage(table_name="agent_sessions", region_name="us-east-1"),
tools=[DuckDuckGo()],
add_history_to_messages=True,
debug_mode=True,
)
agent.print_response("How many people live in Canada?")
agent.print_response("What is their national anthem called?")
15 changes: 15 additions & 0 deletions cookbook/storage/postgres_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Run `pip install duckduckgo-search sqlalchemy openai` to install dependencies."""

from phi.agent import Agent
from phi.tools.duckduckgo import DuckDuckGo
from phi.storage.agent.postgres import PgAgentStorage

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"

agent = Agent(
storage=PgAgentStorage(table_name="agent_sessions", db_url=db_url),
tools=[DuckDuckGo()],
add_history_to_messages=True,
)
agent.print_response("How many people live in Canada?")
agent.print_response("What is their national anthem called?")
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,25 @@
from phi.tools.duckduckgo import DuckDuckGo
from phi.storage.agent.singlestore import S2AgentStorage

# -*- SingleStore Configuration -*-
# Configure SingleStore DB connection
USERNAME = getenv("SINGLESTORE_USERNAME")
PASSWORD = getenv("SINGLESTORE_PASSWORD")
HOST = getenv("SINGLESTORE_HOST")
PORT = getenv("SINGLESTORE_PORT")
DATABASE = getenv("SINGLESTORE_DATABASE")
SSL_CERT = getenv("SINGLESTORE_SSL_CERT", None)

# -*- SingleStore DB URL
# SingleStore DB URL
db_url = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}?charset=utf8mb4"
if SSL_CERT:
db_url += f"&ssl_ca={SSL_CERT}&ssl_verify_cert=true"

# -*- SingleStore DB Engine
# Create a DB engine
db_engine = create_engine(db_url)

# Create an agent with SingleStore storage
agent = Agent(
storage=S2AgentStorage(table_name="agent_runs", db_engine=db_engine, schema=DATABASE),
storage=S2AgentStorage(table_name="agent_sessions", db_engine=db_engine, schema=DATABASE),
tools=[DuckDuckGo()],
add_history_to_messages=True,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from phi.storage.agent.sqlite import SqlAgentStorage

agent = Agent(
storage=SqlAgentStorage(table_name="agent_runs", db_file="tmp/data.db"),
storage=SqlAgentStorage(table_name="agent_sessions", db_file="tmp/data.db"),
tools=[DuckDuckGo()],
add_history_to_messages=True,
)
Expand Down
9 changes: 9 additions & 0 deletions cookbook/tools/github_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,12 @@
show_tool_calls=True,
)
agent.print_response("List open pull requests", markdown=True)

# # Example usage: Get pull request details
# agent.print_response("Get details of #1239", markdown=True)
# # Example usage: Get pull request changes
# agent.print_response("Show changes for #1239", markdown=True)
# # Example usage: List open issues
# agent.print_response("What is the latest opened issue?", markdown=True)
# # Example usage: Create an issue
# agent.print_response("Explain the comments for the most recent issue", markdown=True)
58 changes: 21 additions & 37 deletions cookbook/tools/twitter_tools.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
from phi.agent import Agent
from phi.tools.twitter import TwitterToolkit

# Replace the values with your actual twitter access token
consumer_key = ""
consumer_secret = ""


bearer_token = ""
access_token = ""
access_token_secret = ""
from phi.tools.twitter import TwitterTools

# Export the following environment variables or provide them as arguments to the TwitterTools constructor
# - TWITTER_CONSUMER_KEY
# - TWITTER_CONSUMER_SECRET
# - TWITTER_ACCESS_TOKEN
# - TWITTER_ACCESS_TOKEN_SECRET
# - TWITTER_BEARER_TOKEN

# Initialize the Twitter toolkit
twitter_toolkit = TwitterToolkit(bearer_token, consumer_key, consumer_secret, access_token, access_token_secret)
twitter_tools = TwitterTools()

# Create an agent with the twitter toolkit
agent = Agent(
Expand All @@ -23,37 +20,24 @@
"Provide informative responses about the user's timeline and tweets",
"Respect Twitter's usage policies and rate limits",
],
tools=[twitter_toolkit],
debug_mode=True,
tools=[twitter_tools],
show_tool_calls=True,
)


# # Example usage: Retrieve information about a specific user.
agent.print_response("Can you retrieve information about this user https://x.com/phidatahq ", markdown=True)


# # Example usage: Reply To a Tweet

agent.print_response(
"Can you reply to this post as a general message as to how great this project is:https://x.com/phidatahq/status/1836101177500479547",
markdown=True,
)


# agent.print_response(
# "Can you reply to this post as a general message as to how great this project is:https://x.com/phidatahq/status/1836101177500479547",
# markdown=True,
# )
# # Example usage: Get your details
agent.print_response("Can you return my twitter profile?", markdown=True)

# agent.print_response("Can you return my twitter profile?", markdown=True)
# # Example usage: Send a direct message

agent.print_response(
"Can a send direct message to the user: https://x.com/phidatahq assking you want learn more about them and a link to their community?",
markdown=True,
)


# agent.print_response(
# "Can a send direct message to the user: https://x.com/phidatahq assking you want learn more about them and a link to their community?",
# markdown=True,
# )
# # Example usage: Create a new tweet
agent.print_response("Create & post a tweet about the importance of AI ethics", markdown=True)

# Example usage: Get home timeline
agent.print_response("Get my timeline", markdown=True)
# agent.print_response("Create & post a tweet about the importance of AI ethics", markdown=True)
# # Example usage: Get home timeline
# agent.print_response("Get my timeline", markdown=True)
12 changes: 8 additions & 4 deletions phi/storage/agent/dynamodb.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import time
from typing import Optional, List, Dict, Any
from decimal import Decimal
import time
from botocore.exceptions import ClientError
import boto3
from boto3.dynamodb.conditions import Key

from phi.agent.session import AgentSession
from phi.storage.agent.base import AgentStorage
from phi.utils.log import logger

try:
import boto3
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError
except ImportError:
raise ImportError("`boto3` not installed. Please install using `pip install boto3`.")


class DynamoDbAgentStorage(AgentStorage):
def __init__(
Expand Down
43 changes: 29 additions & 14 deletions phi/tools/twitter.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,49 @@
import os
import json
from typing import Optional

from phi.tools import Toolkit
from phi.utils.log import logger
import json

try:
import tweepy
except ImportError:
raise ImportError("`tweepy` not installed. Please install using `pip install tweepy`.")


class TwitterToolkit(Toolkit):
class TwitterTools(Toolkit):
def __init__(
self, bearer_token: str, consumer_key: str, consumer_secret: str, access_token: str, access_token_secret: str
self,
bearer_token: Optional[str] = None,
consumer_key: Optional[str] = None,
consumer_secret: Optional[str] = None,
access_token: Optional[str] = None,
access_token_secret: Optional[str] = None,
):
"""
Initialize the TwitterToolkit.
Initialize the TwitterTools.
Args:
bearer_token (str): The bearer token for authentication.
consumer_key (str): The consumer key for authentication.
consumer_secret (str): The consumer secret for authentication.
access_token (str): The access token for authentication.
access_token_secret (str): The access token secret for authentication.
bearer_token Optional[str]: The bearer token for Twitter API.
consumer_key Optional[str]: The consumer key for Twitter API.
consumer_secret Optional[str]: The consumer secret for Twitter API.
access_token Optional[str]: The access token for Twitter API.
access_token_secret Optional[str]: The access token secret for Twitter API.
"""
super().__init__(name="twitter")

self.bearer_token = bearer_token or os.getenv("TWITTER_BEARER_TOKEN")
self.consumer_key = consumer_key or os.getenv("TWITTER_CONSUMER_KEY")
self.consumer_secret = consumer_secret or os.getenv("TWITTER_CONSUMER_SECRET")
self.access_token = access_token or os.getenv("TWITTER_ACCESS_TOKEN")
self.access_token_secret = access_token_secret or os.getenv("TWITTER_ACCESS_TOKEN_SECRET")

self.client = tweepy.Client(
bearer_token=bearer_token,
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret,
bearer_token=self.bearer_token,
consumer_key=self.consumer_key,
consumer_secret=self.consumer_secret,
access_token=self.access_token,
access_token_secret=self.access_token_secret,
)
self.auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
self.api = tweepy.API(self.auth)
Expand Down

0 comments on commit 4dddd76

Please sign in to comment.