mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-08 07:38:29 +00:00
Compare commits
5 Commits
devin/1746
...
devin/1746
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c63010daaa | ||
|
|
d0191df996 | ||
|
|
e27bcfb381 | ||
|
|
082cbd2c1c | ||
|
|
3361fab293 |
@@ -6,12 +6,11 @@ import shutil
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import numpy as np
|
||||
from chromadb.api import ClientAPI
|
||||
|
||||
from crewai.memory.storage.base_rag_storage import BaseRAGStorage
|
||||
from crewai.utilities import EmbeddingConfigurator
|
||||
from crewai.utilities.constants import MAX_FILE_NAME_LENGTH, MEMORY_CHUNK_SIZE, MEMORY_CHUNK_OVERLAP
|
||||
from crewai.utilities.constants import MAX_FILE_NAME_LENGTH
|
||||
from crewai.utilities.paths import db_storage_path
|
||||
|
||||
|
||||
@@ -139,57 +138,15 @@ class RAGStorage(BaseRAGStorage):
|
||||
logging.error(f"Error during {self.type} search: {str(e)}")
|
||||
return []
|
||||
|
||||
def _chunk_text(self, text: str) -> List[str]:
|
||||
"""
|
||||
Split text into chunks to avoid token limits.
|
||||
|
||||
Args:
|
||||
text: Input text to chunk.
|
||||
|
||||
Returns:
|
||||
List[str]: A list of chunked text segments, adhering to defined size and overlap.
|
||||
Empty list if input text is empty.
|
||||
"""
|
||||
if not text:
|
||||
return []
|
||||
|
||||
if len(text) <= MEMORY_CHUNK_SIZE:
|
||||
return [text]
|
||||
|
||||
chunks = []
|
||||
start_indices = range(0, len(text), MEMORY_CHUNK_SIZE - MEMORY_CHUNK_OVERLAP)
|
||||
for i in start_indices:
|
||||
chunk = text[i:i + MEMORY_CHUNK_SIZE]
|
||||
if chunk: # Only add non-empty chunks
|
||||
chunks.append(chunk)
|
||||
|
||||
return chunks
|
||||
|
||||
def _generate_embedding(self, text: str, metadata: Optional[Dict[str, Any]] = None) -> Optional[None]:
|
||||
"""
|
||||
Generate embeddings for text and add to collection.
|
||||
|
||||
Args:
|
||||
text: Input text to generate embeddings for.
|
||||
metadata: Optional metadata to associate with the embeddings.
|
||||
|
||||
Returns:
|
||||
None if successful, None if text is empty.
|
||||
"""
|
||||
def _generate_embedding(self, text: str, metadata: Dict[str, Any]) -> None: # type: ignore
|
||||
if not hasattr(self, "app") or not hasattr(self, "collection"):
|
||||
self._initialize_app()
|
||||
|
||||
chunks = self._chunk_text(text)
|
||||
|
||||
if not chunks:
|
||||
return None
|
||||
|
||||
for chunk in chunks:
|
||||
self.collection.add(
|
||||
documents=[chunk],
|
||||
metadatas=[metadata or {}],
|
||||
ids=[str(uuid.uuid4())],
|
||||
)
|
||||
self.collection.add(
|
||||
documents=[text],
|
||||
metadatas=[metadata or {}],
|
||||
ids=[str(uuid.uuid4())],
|
||||
)
|
||||
|
||||
def reset(self) -> None:
|
||||
try:
|
||||
|
||||
11
src/crewai/patches/__init__.py
Normal file
11
src/crewai/patches/__init__.py
Normal file
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
Patches module for CrewAI.
|
||||
|
||||
This module contains patches for external dependencies to fix known issues.
|
||||
|
||||
Version: 1.0.0
|
||||
"""
|
||||
|
||||
from crewai.patches.litellm_patch import apply_patches, patch_litellm_ollama_pt
|
||||
|
||||
__all__ = ["apply_patches", "patch_litellm_ollama_pt"]
|
||||
186
src/crewai/patches/litellm_patch.py
Normal file
186
src/crewai/patches/litellm_patch.py
Normal file
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
Patch for litellm to fix IndexError in ollama_pt function.
|
||||
|
||||
This patch addresses issue #2744 in the crewAI repository, where an IndexError occurs
|
||||
in litellm's Ollama prompt template function when CrewAI Agent with Tools uses Ollama/Qwen models.
|
||||
|
||||
Version: 1.0.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
||||
|
||||
# Set up logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Patch version
|
||||
PATCH_VERSION = "1.0.0"
|
||||
|
||||
|
||||
class PatchApplicationError(Exception):
|
||||
"""Exception raised when a patch fails to apply."""
|
||||
pass
|
||||
|
||||
|
||||
def apply_patches() -> bool:
|
||||
"""
|
||||
Apply all patches to fix known issues with dependencies.
|
||||
|
||||
Returns:
|
||||
bool: True if all patches were applied successfully, False otherwise.
|
||||
"""
|
||||
success = patch_litellm_ollama_pt()
|
||||
logger.info(f"LiteLLM ollama_pt patch applied: {success}")
|
||||
return success
|
||||
|
||||
|
||||
def patch_litellm_ollama_pt() -> bool:
|
||||
"""
|
||||
Patch the ollama_pt function in litellm to fix IndexError.
|
||||
|
||||
The issue occurs when accessing messages[msg_i].get("tool_calls") without checking
|
||||
if msg_i is within bounds of the messages list. This happens after tool execution
|
||||
during the next LLM call.
|
||||
|
||||
Returns:
|
||||
bool: True if the patch was applied successfully, False otherwise.
|
||||
|
||||
Raises:
|
||||
PatchApplicationError: If there's an error during patch application.
|
||||
"""
|
||||
try:
|
||||
# Import the module containing the function to patch
|
||||
import litellm.litellm_core_utils.prompt_templates.factory as factory
|
||||
|
||||
# Define a patched version of the function
|
||||
def patched_ollama_pt(model: str, messages: List[Dict]) -> Dict[str, Any]:
|
||||
"""
|
||||
Patched version of ollama_pt that adds bounds checking.
|
||||
|
||||
This fixes the IndexError that occurs when the assistant message is the last
|
||||
message in the list and msg_i goes out of bounds.
|
||||
|
||||
Args:
|
||||
model: The model name.
|
||||
messages: The list of messages to process.
|
||||
|
||||
Returns:
|
||||
Dict containing the prompt and images.
|
||||
"""
|
||||
user_message_types = {"user", "tool", "function"}
|
||||
msg_i = 0
|
||||
images: List[str] = []
|
||||
prompt = ""
|
||||
|
||||
# Handle empty messages list
|
||||
if not messages:
|
||||
return {"prompt": prompt, "images": images}
|
||||
|
||||
while msg_i < len(messages):
|
||||
init_msg_i = msg_i
|
||||
user_content_str = ""
|
||||
## MERGE CONSECUTIVE USER CONTENT ##
|
||||
while msg_i < len(messages) and messages[msg_i]["role"] in user_message_types:
|
||||
msg_content = messages[msg_i].get("content")
|
||||
if msg_content:
|
||||
if isinstance(msg_content, list):
|
||||
for m in msg_content:
|
||||
if m.get("type", "") == "image_url":
|
||||
if isinstance(m["image_url"], str):
|
||||
images.append(m["image_url"])
|
||||
elif isinstance(m["image_url"], dict):
|
||||
images.append(m["image_url"]["url"])
|
||||
elif m.get("type", "") == "text":
|
||||
user_content_str += m["text"]
|
||||
else:
|
||||
# Tool message content will always be a string
|
||||
user_content_str += msg_content
|
||||
|
||||
msg_i += 1
|
||||
|
||||
if user_content_str:
|
||||
prompt += f"### User:\n{user_content_str}\n\n"
|
||||
|
||||
system_content_str, msg_i = factory._handle_ollama_system_message(
|
||||
messages, prompt, msg_i
|
||||
)
|
||||
if system_content_str:
|
||||
prompt += f"### System:\n{system_content_str}\n\n"
|
||||
|
||||
assistant_content_str = ""
|
||||
## MERGE CONSECUTIVE ASSISTANT CONTENT ##
|
||||
while msg_i < len(messages) and messages[msg_i]["role"] == "assistant":
|
||||
assistant_content_str += factory.convert_content_list_to_str(messages[msg_i])
|
||||
msg_i += 1
|
||||
|
||||
# Add bounds check before accessing messages[msg_i]
|
||||
# This is the key fix for the IndexError
|
||||
if msg_i < len(messages):
|
||||
tool_calls = messages[msg_i].get("tool_calls")
|
||||
ollama_tool_calls = []
|
||||
if tool_calls:
|
||||
for call in tool_calls:
|
||||
call_id = call["id"]
|
||||
function_name = call["function"]["name"]
|
||||
arguments = json.loads(call["function"]["arguments"])
|
||||
|
||||
ollama_tool_calls.append(
|
||||
{
|
||||
"id": call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": function_name,
|
||||
"arguments": arguments,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if ollama_tool_calls:
|
||||
assistant_content_str += (
|
||||
f"Tool Calls: {json.dumps(ollama_tool_calls, indent=2)}"
|
||||
)
|
||||
|
||||
msg_i += 1
|
||||
|
||||
if assistant_content_str:
|
||||
prompt += f"### Assistant:\n{assistant_content_str}\n\n"
|
||||
|
||||
if msg_i == init_msg_i: # prevent infinite loops
|
||||
raise factory.litellm.BadRequestError(
|
||||
message=factory.BAD_MESSAGE_ERROR_STR + f"passed in {messages[msg_i]}",
|
||||
model=model,
|
||||
llm_provider="ollama",
|
||||
)
|
||||
|
||||
response_dict = {
|
||||
"prompt": prompt,
|
||||
"images": images,
|
||||
}
|
||||
|
||||
return response_dict
|
||||
|
||||
# Replace the original function with our patched version
|
||||
factory.ollama_pt = patched_ollama_pt
|
||||
|
||||
logger.info(f"Successfully applied litellm ollama_pt patch version {PATCH_VERSION}")
|
||||
return True
|
||||
except Exception as e:
|
||||
error_msg = f"Failed to apply litellm ollama_pt patch: {e}"
|
||||
logger.error(error_msg)
|
||||
return False
|
||||
|
||||
|
||||
# For backwards compatibility
|
||||
def patch_litellm() -> bool:
|
||||
"""
|
||||
Legacy function for backwards compatibility.
|
||||
|
||||
Returns:
|
||||
bool: True if the patch was applied successfully, False otherwise.
|
||||
"""
|
||||
try:
|
||||
return patch_litellm_ollama_pt()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to apply legacy litellm patch: {e}")
|
||||
return False
|
||||
@@ -4,5 +4,3 @@ DEFAULT_SCORE_THRESHOLD = 0.35
|
||||
KNOWLEDGE_DIRECTORY = "knowledge"
|
||||
MAX_LLM_RETRY = 3
|
||||
MAX_FILE_NAME_LENGTH = 255
|
||||
MEMORY_CHUNK_SIZE = 4000
|
||||
MEMORY_CHUNK_OVERLAP = 200
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
import pytest
|
||||
import numpy as np
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from crewai.memory.short_term.short_term_memory import ShortTermMemory
|
||||
from crewai.agent import Agent
|
||||
from crewai.crew import Crew
|
||||
from crewai.task import Task
|
||||
from crewai.utilities.constants import MEMORY_CHUNK_SIZE
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def short_term_memory():
|
||||
"""Fixture to create a ShortTermMemory instance"""
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Search relevant data and provide results",
|
||||
backstory="You are a researcher at a leading tech think tank.",
|
||||
tools=[],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Perform a search on specific topics.",
|
||||
expected_output="A list of relevant URLs based on the search query.",
|
||||
agent=agent,
|
||||
)
|
||||
return ShortTermMemory(crew=Crew(agents=[agent], tasks=[task]))
|
||||
|
||||
|
||||
def test_memory_with_large_input(short_term_memory):
|
||||
"""Test that memory can handle large inputs without token limit errors"""
|
||||
large_input = "test value " * (MEMORY_CHUNK_SIZE + 1000)
|
||||
|
||||
with patch.object(
|
||||
short_term_memory.storage, '_chunk_text',
|
||||
return_value=["chunk1", "chunk2"]
|
||||
) as mock_chunk_text:
|
||||
with patch.object(
|
||||
short_term_memory.storage.collection, 'add'
|
||||
) as mock_add:
|
||||
short_term_memory.save(value=large_input, agent="test_agent")
|
||||
|
||||
assert mock_chunk_text.called
|
||||
|
||||
with patch.object(
|
||||
short_term_memory.storage, 'search',
|
||||
return_value=[{"context": large_input, "metadata": {"agent": "test_agent"}, "score": 0.95}]
|
||||
):
|
||||
result = short_term_memory.search(large_input[:100], score_threshold=0.01)
|
||||
assert result[0]["context"] == large_input
|
||||
assert result[0]["metadata"]["agent"] == "test_agent"
|
||||
|
||||
|
||||
def test_memory_with_empty_input(short_term_memory):
|
||||
"""Test that memory correctly handles empty input strings"""
|
||||
empty_input = ""
|
||||
|
||||
with patch.object(
|
||||
short_term_memory.storage, '_chunk_text',
|
||||
return_value=[]
|
||||
) as mock_chunk_text:
|
||||
with patch.object(
|
||||
short_term_memory.storage.collection, 'add'
|
||||
) as mock_add:
|
||||
short_term_memory.save(value=empty_input, agent="test_agent")
|
||||
|
||||
mock_chunk_text.assert_called_with(empty_input)
|
||||
mock_add.assert_not_called()
|
||||
|
||||
|
||||
def test_memory_with_exact_chunk_size_input(short_term_memory):
|
||||
"""Test that memory correctly handles inputs that match chunk size exactly"""
|
||||
exact_size_input = "x" * MEMORY_CHUNK_SIZE
|
||||
|
||||
with patch.object(
|
||||
short_term_memory.storage, '_chunk_text',
|
||||
return_value=[exact_size_input]
|
||||
) as mock_chunk_text:
|
||||
with patch.object(
|
||||
short_term_memory.storage.collection, 'add'
|
||||
) as mock_add:
|
||||
short_term_memory.save(value=exact_size_input, agent="test_agent")
|
||||
|
||||
mock_chunk_text.assert_called_with(exact_size_input)
|
||||
assert mock_add.call_count == 1
|
||||
71
tests/patches/test_litellm_patch.py
Normal file
71
tests/patches/test_litellm_patch.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
Test for the litellm patch that fixes the IndexError in ollama_pt function.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import litellm
|
||||
import pytest
|
||||
from litellm.litellm_core_utils.prompt_templates.factory import ollama_pt
|
||||
|
||||
from crewai.patches.litellm_patch import patch_litellm_ollama_pt
|
||||
|
||||
|
||||
class TestLitellmPatch(unittest.TestCase):
|
||||
def test_ollama_pt_patch_fixes_index_error(self):
|
||||
"""Test that the patch fixes the IndexError in ollama_pt."""
|
||||
# Create a message list where the assistant message is the last one
|
||||
messages = [
|
||||
{"role": "user", "content": "Hello"},
|
||||
{"role": "assistant", "content": "Hi there"},
|
||||
]
|
||||
|
||||
# Store the original function to restore it after the test
|
||||
original_ollama_pt = litellm.litellm_core_utils.prompt_templates.factory.ollama_pt
|
||||
|
||||
try:
|
||||
# Apply the patch
|
||||
success = patch_litellm_ollama_pt()
|
||||
self.assertTrue(success, "Patch application failed")
|
||||
|
||||
# Use the function from the module directly to ensure we're using the patched version
|
||||
result = litellm.litellm_core_utils.prompt_templates.factory.ollama_pt("qwen3:4b", messages)
|
||||
|
||||
# Verify the result is as expected
|
||||
self.assertIn("prompt", result)
|
||||
self.assertIn("images", result)
|
||||
self.assertIn("### User:\nHello", result["prompt"])
|
||||
self.assertIn("### Assistant:\nHi there", result["prompt"])
|
||||
finally:
|
||||
# Restore the original function to avoid affecting other tests
|
||||
litellm.litellm_core_utils.prompt_templates.factory.ollama_pt = original_ollama_pt
|
||||
|
||||
def test_ollama_pt_patch_with_empty_messages(self):
|
||||
"""Test that the patch handles empty message lists."""
|
||||
messages = []
|
||||
|
||||
# Store the original function to restore it after the test
|
||||
original_ollama_pt = litellm.litellm_core_utils.prompt_templates.factory.ollama_pt
|
||||
|
||||
try:
|
||||
# Apply the patch
|
||||
success = patch_litellm_ollama_pt()
|
||||
self.assertTrue(success, "Patch application failed")
|
||||
|
||||
# Use the function from the module directly to ensure we're using the patched version
|
||||
result = litellm.litellm_core_utils.prompt_templates.factory.ollama_pt("qwen3:4b", messages)
|
||||
|
||||
# Verify the result is as expected
|
||||
self.assertIn("prompt", result)
|
||||
self.assertIn("images", result)
|
||||
self.assertEqual("", result["prompt"])
|
||||
self.assertEqual([], result["images"])
|
||||
finally:
|
||||
# Restore the original function to avoid affecting other tests
|
||||
litellm.litellm_core_utils.prompt_templates.factory.ollama_pt = original_ollama_pt
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user