Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/crewai/agent.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import os
from inspect import signature
from typing import Any, List, Optional, Union

from pydantic import Field, InstanceOf, PrivateAttr, model_validator

from crewai.agents import CacheHandler
from crewai.utilities import Converter, Prompts
from crewai.tools.agent_tools import AgentTools
from crewai.agents.crew_agent_executor import CrewAgentExecutor
from crewai.agents.agent_builder.base_agent import BaseAgent
from crewai.agents.crew_agent_executor import CrewAgentExecutor
from crewai.llm import LLM
from crewai.memory.contextual.contextual_memory import ContextualMemory
from crewai.tools.agent_tools import AgentTools
from crewai.utilities import Converter, Prompts
from crewai.utilities.constants import TRAINED_AGENTS_DATA_FILE, TRAINING_DATA_FILE
from crewai.utilities.training_handler import CrewTrainingHandler
from crewai.utilities.token_counter_callback import TokenCalcHandler
from crewai.llm import LLM
from crewai.utilities.training_handler import CrewTrainingHandler


def mock_agent_ops_provider():
Expand Down Expand Up @@ -292,9 +293,9 @@ def create_agent_executor(self, tools=None, task=None) -> None:
step_callback=self.step_callback,
function_calling_llm=self.function_calling_llm,
respect_context_window=self.respect_context_window,
request_within_rpm_limit=self._rpm_controller.check_or_wait
if self._rpm_controller
else None,
request_within_rpm_limit=(
self._rpm_controller.check_or_wait if self._rpm_controller else None
),
callbacks=[TokenCalcHandler(self._token_process)],
)

Expand Down
33 changes: 22 additions & 11 deletions src/crewai/memory/storage/rag_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,6 @@
import shutil
from typing import Any, Dict, List, Optional

from embedchain import App
from embedchain.llm.base import BaseLlm
from embedchain.models.data_type import DataType
from embedchain.vectordb.chroma import InvalidDimensionException

from crewai.memory.storage.interface import Storage
from crewai.utilities.paths import db_storage_path

Expand All @@ -29,10 +24,6 @@ def suppress_logging(
logger.setLevel(original_level)


class FakeLLM(BaseLlm):
pass


class RAGStorage(Storage):
"""
Extends Storage to handle embeddings for memory entries, improving
Expand Down Expand Up @@ -74,9 +65,19 @@ def __init__(self, type, allow_reset=True, embedder_config=None, crew=None):
if embedder_config:
config["embedder"] = embedder_config
self.type = type
self.app = App.from_config(config=config)
self.config = config
self.allow_reset = allow_reset

def _initialize_app(self):
from embedchain import App
from embedchain.llm.base import BaseLlm

class FakeLLM(BaseLlm):
pass

self.app = App.from_config(config=self.config)
self.app.llm = FakeLLM()
if allow_reset:
if self.allow_reset:
self.app.reset()

def _sanitize_role(self, role: str) -> str:
Expand All @@ -86,6 +87,8 @@ def _sanitize_role(self, role: str) -> str:
return role.replace("\n", "").replace(" ", "_").replace("/", "_")

def save(self, value: Any, metadata: Dict[str, Any]) -> None:
if not hasattr(self, "app"):
self._initialize_app()
self._generate_embedding(value, metadata)

def search( # type: ignore # BUG?: Signature of "search" incompatible with supertype "Storage"
Expand All @@ -95,6 +98,10 @@ def search( # type: ignore # BUG?: Signature of "search" incompatible with supe
filter: Optional[dict] = None,
score_threshold: float = 0.35,
) -> List[Any]:
if not hasattr(self, "app"):
self._initialize_app()
from embedchain.vectordb.chroma import InvalidDimensionException

with suppress_logging():
try:
results = (
Expand All @@ -108,6 +115,10 @@ def search( # type: ignore # BUG?: Signature of "search" incompatible with supe
return [r for r in results if r["metadata"]["score"] >= score_threshold]

def _generate_embedding(self, text: str, metadata: Dict[str, Any]) -> Any:
if not hasattr(self, "app"):
self._initialize_app()
from embedchain.models.data_type import DataType

self.app.add(text, data_type=DataType.TEXT, metadata=metadata)

def reset(self) -> None:
Expand Down
4 changes: 1 addition & 3 deletions src/crewai/telemetry/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ def suppress_warnings():


from opentelemetry import trace # noqa: E402
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
OTLPSpanExporter, # noqa: E402
)
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter # noqa: E402
from opentelemetry.sdk.resources import SERVICE_NAME, Resource # noqa: E402
from opentelemetry.sdk.trace import TracerProvider # noqa: E402
from opentelemetry.sdk.trace.export import BatchSpanProcessor # noqa: E402
Expand Down
3 changes: 2 additions & 1 deletion src/crewai/tools/agent_tools.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from langchain.tools import StructuredTool
from crewai.agents.agent_builder.utilities.base_agent_tool import BaseAgentTools


class AgentTools(BaseAgentTools):
"""Default tools around agent delegation"""

def tools(self):
from langchain.tools import StructuredTool

coworkers = ", ".join([f"{agent.role}" for agent in self.agents])
tools = [
StructuredTool.from_function(
Expand Down
3 changes: 2 additions & 1 deletion src/crewai/tools/cache_tools.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from langchain.tools import StructuredTool
from pydantic import BaseModel, Field

from crewai.agents.cache import CacheHandler
Expand All @@ -14,6 +13,8 @@ class CacheTools(BaseModel):
)

def tool(self):
from langchain.tools import StructuredTool

return StructuredTool.from_function(
func=self.hit_cache,
name=self.name,
Expand Down
7 changes: 4 additions & 3 deletions src/crewai/utilities/internal_instructor.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
from typing import Any, Optional, Type

import instructor
from litellm import completion


class InternalInstructor:
"""Class that wraps an agent llm with instructor."""
Expand All @@ -28,6 +25,10 @@ def set_instructor(self):
if self.agent and not self.llm:
self.llm = self.agent.function_calling_llm or self.agent.llm

# Lazy import
import instructor
from litellm import completion

self._client = instructor.from_litellm(
completion,
mode=instructor.Mode.TOOLS,
Expand Down
1 change: 1 addition & 0 deletions src/crewai/utilities/token_counter_callback.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from litellm.integrations.custom_logger import CustomLogger

from crewai.agents.agent_builder.utilities.base_token_process import TokenProcess


Expand Down