Skip to content

Commit

Permalink
v2.0.36
Browse files Browse the repository at this point in the history
  • Loading branch information
ashpreetbedi committed Nov 10, 2023
1 parent cd5a344 commit b01a803
Show file tree
Hide file tree
Showing 35 changed files with 938 additions and 95 deletions.
1 change: 1 addition & 0 deletions phi/agent/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from phi.agent.agent import Agent
27 changes: 27 additions & 0 deletions phi/agent/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from collections import OrderedDict
from typing import Callable, Dict

from phi.tool.function import Function
from phi.utils.log import logger


class Agent:
def __init__(self, name: str = "base_agent"):
self.name: str = name
self.functions: Dict[str, Function] = OrderedDict()

def register(self, function: Callable):
try:
f = Function.from_callable(function)
self.functions[f.name] = f
logger.debug(f"Function: {f.name} registered with {self.name}")
# logger.debug(f"Json Schema: {f.to_dict()}")
except Exception as e:
logger.warning(f"Failed to create Function for: {function.__name__}")
raise e

def __repr__(self):
return f"<{self.__class__.__name__} name={self.name} functions={list(self.functions.keys())}>"

def __str__(self):
return self.__repr__()
6 changes: 3 additions & 3 deletions phi/tool/arxiv.py → phi/agent/arxiv.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

from phi.document import Document
from phi.knowledge.arxiv import ArxivKnowledgeBase
from phi.tool.registry import ToolRegistry
from phi.agent import Agent
from phi.utils.log import logger


class ArxivTool(ToolRegistry):
class ArxivAgent(Agent):
def __init__(self, knowledge_base: Optional[ArxivKnowledgeBase] = None):
super().__init__(name="arxiv_tools")
super().__init__(name="arxiv_agent")
self.knowledge_base: Optional[ArxivKnowledgeBase] = knowledge_base

if self.knowledge_base is not None and isinstance(self.knowledge_base, ArxivKnowledgeBase):
Expand Down
12 changes: 6 additions & 6 deletions phi/tool/duckdb.py → phi/agent/duckdb.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Optional, Tuple

from phi.tool.registry import ToolRegistry
from phi.agent import Agent
from phi.utils.log import logger

try:
Expand All @@ -9,14 +9,14 @@
raise ImportError("`duckdb` not installed. Please install it using `pip install duckdb`.")


class DuckDbTool(ToolRegistry):
class DuckDbAgent(Agent):
def __init__(
self,
db_path: str = ":memory:",
s3_region: str = "us-east-1",
duckdb_connection: Optional[duckdb.DuckDBPyConnection] = None,
):
super().__init__(name="duckdb_tools")
super().__init__(name="duckdb_agent")

self.db_path: str = db_path
self.s3_region: str = s3_region
Expand Down Expand Up @@ -329,9 +329,9 @@ def full_text_search(self, table_name: str, unique_key: str, search_text: str) -
"""
logger.debug(f"Running full_text_search for {search_text} in {table_name}")
search_text_statement = f"""SELECT fts_main_corpus.match_bm25({unique_key}, '{search_text}') AS score,*
FROM {table_name}
WHERE score IS NOT NULL
ORDER BY score;"""
FROM {table_name}
WHERE score IS NOT NULL
ORDER BY score;"""

logger.debug(f"Running {search_text_statement}")
result = self.run_query(search_text_statement)
Expand Down
6 changes: 3 additions & 3 deletions phi/tool/email.py → phi/agent/email.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
from typing import Optional

from phi.tool.registry import ToolRegistry
from phi.agent import Agent
from phi.utils.log import logger


class EmailTool(ToolRegistry):
class EmailAgent(Agent):
def __init__(
self,
receiver_email: Optional[str] = None,
sender_name: Optional[str] = None,
sender_email: Optional[str] = None,
sender_passkey: Optional[str] = None,
):
super().__init__(name="email_tools")
super().__init__(name="email_agent")
self.receiver_email: Optional[str] = receiver_email
self.sender_name: Optional[str] = sender_name
self.sender_email: Optional[str] = sender_email
Expand Down
18 changes: 18 additions & 0 deletions phi/agent/google.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from phi.agent import Agent
from phi.utils.log import logger


class GoogleAgent(Agent):
def __init__(self):
super().__init__(name="google_agent")
self.register(self.get_result_from_google)

def get_result_from_google(self, query: str) -> str:
"""Gets the result for a query from Google.
Use this function to find an answer when not available in the knowledge base.
:param query: The query to search for.
:return: The result from Google.
"""
logger.info(f"Searching google for: {query}")
return "Sorry, this capability is not available yet."
6 changes: 3 additions & 3 deletions phi/tool/phi.py → phi/agent/phi.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import uuid
from typing import Optional

from phi.tool.registry import ToolRegistry
from phi.agent import Agent
from phi.utils.log import logger


class PhiTool(ToolRegistry):
class PhiAgent(Agent):
def __init__(self):
super().__init__(name="phi_tools")
super().__init__(name="phi_agent")
self.register(self.create_new_app)
self.register(self.start_user_workspace)
self.register(self.validate_phi_is_ready)
Expand Down
19 changes: 19 additions & 0 deletions phi/agent/pubmed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from phi.agent import Agent
from phi.utils.log import logger


class PubMedAgent(Agent):
def __init__(self):
super().__init__(name="pubmed_agent")
self.register(self.get_articles_from_pubmed)

def get_articles_from_pubmed(self, query: str, num_articles: int = 2) -> str:
"""Gets the abstract for articles related to a query from PubMed: a database of biomedical literature
Use this function to find information about a medical concept when not available in the knowledge base or Google
:param query: The query to get related articles for.
:param num_articles: The number of articles to return.
:return: JSON string containing the articles
"""
logger.info(f"Searching Pubmed for: {query}")
return "Sorry, this capability is not available yet."
6 changes: 3 additions & 3 deletions phi/tool/shell.py → phi/agent/shell.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from typing import List

from phi.tool.registry import ToolRegistry
from phi.agent import Agent
from phi.utils.log import logger


class ShellTool(ToolRegistry):
class ShellAgent(Agent):
def __init__(self):
super().__init__(name="shell_tools")
super().__init__(name="shell_agent")
self.register(self.run_shell_command)

def run_shell_command(self, args: List[str], tail: int = 100) -> str:
Expand Down
6 changes: 3 additions & 3 deletions phi/tool/website.py → phi/agent/website.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

from phi.document import Document
from phi.knowledge.website import WebsiteKnowledgeBase
from phi.tool.registry import ToolRegistry
from phi.agent import Agent
from phi.utils.log import logger


class WebsiteTool(ToolRegistry):
class WebsiteAgent(Agent):
def __init__(self, knowledge_base: Optional[WebsiteKnowledgeBase] = None):
super().__init__(name="website_tools")
super().__init__(name="website_agent")
self.knowledge_base: Optional[WebsiteKnowledgeBase] = knowledge_base

if self.knowledge_base is not None and isinstance(self.knowledge_base, WebsiteKnowledgeBase):
Expand Down
6 changes: 3 additions & 3 deletions phi/tool/wikipedia.py → phi/agent/wikipedia.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

from phi.document import Document
from phi.knowledge.wikipedia import WikipediaKnowledgeBase
from phi.tool.registry import ToolRegistry
from phi.agent import Agent
from phi.utils.log import logger


class WikipediaTool(ToolRegistry):
class WikipediaAgent(Agent):
def __init__(self, knowledge_base: Optional[WikipediaKnowledgeBase] = None):
super().__init__(name="wikipedia_tools")
super().__init__(name="wikipedia_agent")
self.knowledge_base: Optional[WikipediaKnowledgeBase] = knowledge_base

if self.knowledge_base is not None and isinstance(self.knowledge_base, WikipediaKnowledgeBase):
Expand Down
8 changes: 4 additions & 4 deletions phi/ai/phi_ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
from phi.cli.config import PhiCliConfig
from phi.cli.console import console
from phi.cli.settings import phi_cli_settings
from phi.llm.schemas import Message
from phi.llm.message import Message
from phi.tool.function import Function, FunctionCall
from phi.tool.shell import ShellTool
from phi.tool.phi import PhiTool
from phi.agent.shell import ShellAgent
from phi.agent.phi import PhiAgent
from phi.workspace.config import WorkspaceConfig
from phi.utils.log import logger
from phi.utils.functions import get_function_call
Expand All @@ -42,7 +42,7 @@ def __init__(
_active_workspace = _phi_config.get_active_ws_config()

self.conversation_db: Optional[List[Dict[str, Any]]] = None
self.functions: Dict[str, Function] = {**ShellTool().functions, **PhiTool().functions}
self.functions: Dict[str, Function] = {**ShellAgent().functions, **PhiAgent().functions}

_conversation_id = None
_conversation_history = None
Expand Down
2 changes: 1 addition & 1 deletion phi/api/ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
ConversationCreateResponse,
)
from phi.api.schemas.user import UserSchema
from phi.llm.schemas import Message
from phi.llm.message import Message
from phi.tool.function import Function
from phi.utils.log import logger

Expand Down
8 changes: 4 additions & 4 deletions phi/assistant/assistant.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@

from pydantic import BaseModel, ConfigDict, field_validator, model_validator

from phi.agent import Agent
from phi.assistant.file import File
from phi.assistant.row import AssistantRow
from phi.assistant.storage import AssistantStorage
from phi.assistant.exceptions import AssistantIdNotSet
from phi.tool import Tool
from phi.tool.registry import ToolRegistry
from phi.tool.function import Function
from phi.knowledge.base import KnowledgeBase
from phi.utils.log import logger, set_log_level_to_debug
Expand Down Expand Up @@ -42,7 +42,7 @@ class Assistant(BaseModel):
# -*- Assistant Tools
# A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant.
# Tools can be of types code_interpreter, retrieval, or function.
tools: Optional[List[Union[Tool, Dict, Callable, ToolRegistry]]] = None
tools: Optional[List[Union[Tool, Dict, Callable, Agent]]] = None
# -*- Functions available to the Assistant to call
# Functions provided from the tools. Note: These are not sent to the LLM API.
functions: Optional[Dict[str, Function]] = None
Expand Down Expand Up @@ -101,7 +101,7 @@ def extract_functions_from_tools(self) -> "Assistant":
for tool in self.tools:
if self.functions is None:
self.functions = {}
if isinstance(tool, ToolRegistry):
if isinstance(tool, Agent):
self.functions.update(tool.functions)
logger.debug(f"Tools from {tool.name} added to Assistant.")
elif callable(tool):
Expand Down Expand Up @@ -133,7 +133,7 @@ def get_tools_for_api(self) -> Optional[List[Dict[str, Any]]]:
elif callable(tool):
func = Function.from_callable(tool)
tools_for_api.append({"type": "function", "function": func.to_dict()})
elif isinstance(tool, ToolRegistry):
elif isinstance(tool, Agent):
for _f in tool.functions.values():
tools_for_api.append({"type": "function", "function": _f.to_dict()})
return tools_for_api
Expand Down
Loading

0 comments on commit b01a803

Please sign in to comment.