Skip to content

Commit

Permalink
Fix static typing errors (#187)
Browse files Browse the repository at this point in the history
Co-authored-by: João Moura <joaomdmoura@gmail.com>
  • Loading branch information
gvieira and joaomdmoura committed Jan 29, 2024
1 parent cd77981 commit 29c31a2
Show file tree
Hide file tree
Showing 18 changed files with 135 additions and 87 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/black.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
name: Lint

on: [push, pull_request]
on: [pull_request]

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: psf/black@stable
- uses: psf/black@stable
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: Run Tests

on: [push, pull_request]
on: [pull_request]

permissions:
contents: write
Expand Down
30 changes: 30 additions & 0 deletions .github/workflows/type-checker.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

name: Run Type Checks

on: [pull_request]

permissions:
contents: write

jobs:
type-checker:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.10'

- name: Install Requirements
run: |
sudo apt-get update &&
pip install poetry &&
poetry lock &&
poetry install
- name: Run type checks
run: poetry run pyright
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,11 @@ pre-commit install
poetry run pytest
```

### Running static type checks
```bash
poetry run pyright
```

### Packaging
```bash
poetry build
Expand All @@ -224,5 +229,3 @@ If you are interested on having access to it and hiring weekly hours with our te

## License
CrewAI is released under the MIT License


55 changes: 29 additions & 26 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ Repository = "https://github.com/joaomdmoura/crewai"
[tool.poetry.dependencies]
python = ">=3.9,<4.0"
pydantic = "^2.4.2"
langchain = "^0.1.0"
langchain = "0.1.0"
openai = "^1.7.1"
langchain-openai = "^0.0.2"
pyright = "1.1.333"
black = {git = "https://github.com/psf/black.git", rev = "stable"}

[tool.poetry.group.dev.dependencies]
isort = "^5.13.2"
black = "^23.12.1"
black = "^24.1"
autoflake = "^2.2.1"
pre-commit = "^3.6.0"
mkdocs-material = "^9.5.3"
Expand All @@ -33,6 +35,7 @@ mkdocs-material = "^9.5.3"
profile = "black"
known_first_party = ["crewai"]


[tool.poetry.group.test.dependencies]
pytest = "^7.4"
pytest-vcr = "^1.0.2"
Expand Down
29 changes: 16 additions & 13 deletions src/crewai/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
from typing import Any, List, Optional

from langchain.agents.format_scratchpad import format_log_to_str
from langchain.agents.agent import RunnableAgent
from langchain.memory import ConversationSummaryMemory
from langchain.tools.render import render_text_description
from langchain_core.runnables.config import RunnableConfig
from langchain_openai import ChatOpenAI
from langchain_core.language_models import BaseLanguageModel
from pydantic import (
UUID4,
BaseModel,
Expand Down Expand Up @@ -47,7 +49,7 @@ class Agent(BaseModel):
tools: Tools at agents disposal
"""

__hash__ = object.__hash__
__hash__ = object.__hash__ # type: ignore
_logger: Logger = PrivateAttr()
_rpm_controller: RPMController = PrivateAttr(default=None)
_request_within_rpm_limit: Any = PrivateAttr(default=None)
Expand Down Expand Up @@ -80,21 +82,19 @@ class Agent(BaseModel):
max_iter: Optional[int] = Field(
default=15, description="Maximum iterations for an agent to execute a task"
)
agent_executor: Optional[InstanceOf[CrewAgentExecutor]] = Field(
agent_executor: InstanceOf[CrewAgentExecutor] = Field(
default=None, description="An instance of the CrewAgentExecutor class."
)
tools_handler: Optional[InstanceOf[ToolsHandler]] = Field(
tools_handler: InstanceOf[ToolsHandler] = Field(
default=None, description="An instance of the ToolsHandler class."
)
cache_handler: Optional[InstanceOf[CacheHandler]] = Field(
cache_handler: InstanceOf[CacheHandler] = Field(
default=CacheHandler(), description="An instance of the CacheHandler class."
)
i18n: Optional[I18N] = Field(
default=I18N(), description="Internationalization settings."
)
llm: Optional[Any] = Field(
i18n: I18N = Field(default=I18N(), description="Internationalization settings.")
llm: Any = Field(
default_factory=lambda: ChatOpenAI(
model_name="gpt-4",
model="gpt-4",
),
description="Language model that will run the agent.",
)
Expand Down Expand Up @@ -140,6 +140,7 @@ def execute_task(
Returns:
Output of the agent
"""

if context:
task = self.i18n.slice("task_with_context").format(
task=task, context=context
Expand Down Expand Up @@ -203,9 +204,9 @@ def __create_agent_executor(self) -> None:
}

if self._rpm_controller:
executor_args[
"request_within_rpm_limit"
] = self._rpm_controller.check_or_wait
executor_args["request_within_rpm_limit"] = (
self._rpm_controller.check_or_wait
)

if self.memory:
summary_memory = ConversationSummaryMemory(
Expand Down Expand Up @@ -234,7 +235,9 @@ def __create_agent_executor(self) -> None:
i18n=self.i18n,
)
)
self.agent_executor = CrewAgentExecutor(agent=inner_agent, **executor_args)
self.agent_executor = CrewAgentExecutor(
agent=RunnableAgent(runnable=inner_agent), **executor_args
)

@staticmethod
def __tools_names(tools) -> str:
Expand Down
4 changes: 1 addition & 3 deletions src/crewai/agents/cache/cache_handler.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from typing import Optional

from pydantic import PrivateAttr


class CacheHandler:
"""Callback handler for tool usage."""

_cache: PrivateAttr = {}
_cache: dict = {}

def __init__(self):
self._cache = {}
Expand Down
6 changes: 5 additions & 1 deletion src/crewai/agents/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,12 @@ def _iter_next_step(
if self._should_force_answer():
if isinstance(output, AgentAction):
output = output
else:
elif isinstance(output, CacheHit):
output = output.action
else:
raise ValueError(
f"Unexpected output type from agent: {type(output)}"
)
yield self._force_answer(output)
return

Expand Down
1 change: 0 additions & 1 deletion src/crewai/agents/output_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ class Config:
i18n: I18N

def parse(self, text: str) -> Union[AgentAction, AgentFinish, CacheHit]:
FINAL_ANSWER_ACTION in text
regex = (
r"Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
)
Expand Down
4 changes: 2 additions & 2 deletions src/crewai/agents/tools_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ class ToolsHandler(BaseCallbackHandler):
"""Callback handler for tool usage."""

last_used_tool: Dict[str, Any] = {}
cache: CacheHandler = None
cache: CacheHandler

def __init__(self, cache: CacheHandler = None, **kwargs: Any):
def __init__(self, cache: CacheHandler, **kwargs: Any):
"""Initialize the callback handler."""
self.cache = cache
super().__init__(**kwargs)
Expand Down
Loading

0 comments on commit 29c31a2

Please sign in to comment.