from crewai import Agent, Task, Crew, Process, LLMfrom crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource# Create a knowledge sourcecontent = "Users name is John. He is 30 years old and lives in San Francisco."string_source = StringKnowledgeSource(content=content)# Create an LLM with a temperature of 0 to ensure deterministic outputsllm = LLM(model="gpt-4o-mini", temperature=0)# Create an agent with the knowledge storeagent = Agent( role="About User", goal="You know everything about the user.", backstory="You are a master at understanding people and their preferences.", verbose=True, allow_delegation=False, llm=llm,)task = Task( description="Answer the following questions about the user: {question}", expected_output="An answer to the question.", agent=agent,)crew = Crew( agents=[agent], tasks=[task], verbose=True, process=Process.sequential, knowledge_sources=[string_source], # Enable knowledge by adding the sources here)result = crew.kickoff(inputs={"question": "What city does John live in and how old is he?"})
from crewai import LLM, Agent, Crew, Process, Taskfrom crewai.knowledge.source.crew_docling_source import CrewDoclingSource# Create a knowledge source from web contentcontent_source = CrewDoclingSource( file_paths=[ "https://lilianweng.github.io/posts/2024-11-28-reward-hacking", "https://lilianweng.github.io/posts/2024-07-07-hallucination", ],)# Create an LLM with a temperature of 0 to ensure deterministic outputsllm = LLM(model="gpt-4o-mini", temperature=0)# Create an agent with the knowledge storeagent = Agent( role="About papers", goal="You know everything about the papers.", backstory="You are a master at understanding papers and their content.", verbose=True, allow_delegation=False, llm=llm,)task = Task( description="Answer the following questions about the papers: {question}", expected_output="An answer to the question.", agent=agent,)crew = Crew( agents=[agent], tasks=[task], verbose=True, process=Process.sequential, knowledge_sources=[content_source],)result = crew.kickoff( inputs={"question": "What is the reward hacking paper about? Be sure to provide sources."})
from crewai import Agent, Task, Crewfrom crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource# Agent-specific knowledgeagent_knowledge = StringKnowledgeSource( content="Agent-specific information that only this agent needs")agent = Agent( role="Specialist", goal="Use specialized knowledge", backstory="Expert with specific knowledge", knowledge_sources=[agent_knowledge], embedder={ # Agent can have its own embedder "provider": "openai", "config": {"model": "text-embedding-3-small"} })task = Task( description="Answer using your specialized knowledge", agent=agent, expected_output="Answer based on agent knowledge")# No crew knowledge neededcrew = Crew(agents=[agent], tasks=[task])result = crew.kickoff() # Works perfectly
# Different knowledge for different agentssales_knowledge = StringKnowledgeSource(content="Sales procedures and pricing")tech_knowledge = StringKnowledgeSource(content="Technical documentation")support_knowledge = StringKnowledgeSource(content="Support procedures")sales_agent = Agent( role="Sales Representative", knowledge_sources=[sales_knowledge], embedder={"provider": "openai", "config": {"model": "text-embedding-3-small"}})tech_agent = Agent( role="Technical Expert", knowledge_sources=[tech_knowledge], embedder={"provider": "ollama", "config": {"model": "mxbai-embed-large"}})support_agent = Agent( role="Support Specialist", knowledge_sources=[support_knowledge] # Will use crew embedder as fallback)crew = Crew( agents=[sales_agent, tech_agent, support_agent], tasks=[...], embedder={ # Fallback embedder for agents without their own "provider": "google", "config": {"model": "text-embedding-004"} })# Each agent gets only their specific knowledge# Each can use different embedding providers
벡터 데이터베이스에서 도구를 사용한 검색과 달리, 사전에 지식이 탑재된 에이전트는 검색 퍼소나나 태스크가 필요하지 않습니다.
에이전트나 crew가 동작하는 데 필요한 관련 지식 소스만 추가하면 됩니다.지식 소스는 에이전트 또는 crew 레벨에 추가할 수 있습니다.
crew 레벨 지식 소스는 crew 내 모든 에이전트가 사용하게 됩니다.
에이전트 레벨 지식 소스는 해당 지식이 사전 탑재된 특정 에이전트만 사용하게 됩니다.
import osfrom crewai import Crew# Set custom storage location for all CrewAI dataos.environ["CREWAI_STORAGE_DIR"] = "./my_project_storage"# All knowledge will now be stored in ./my_project_storage/knowledge/crew = Crew( agents=[...], tasks=[...], knowledge_sources=[...])
import osfrom pathlib import Path# Store knowledge in project directoryproject_root = Path(__file__).parentknowledge_dir = project_root / "knowledge_storage"os.environ["CREWAI_STORAGE_DIR"] = str(knowledge_dir)# Now all knowledge will be stored in your project directory
from crewai import Agent, Crew, LLMfrom crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource# When using Claude as your LLM...agent = Agent( role="Researcher", goal="Research topics", backstory="Expert researcher", llm=LLM(provider="anthropic", model="claude-3-sonnet") # Using Claude)# CrewAI will still use OpenAI embeddings by default for knowledge# This ensures consistency but may not match your LLM provider preferenceknowledge_source = StringKnowledgeSource(content="Research data...")crew = Crew( agents=[agent], tasks=[...], knowledge_sources=[knowledge_source] # Default: Uses OpenAI embeddings even with Claude LLM)
agent = Agent( role="Researcher", goal="Research topics", backstory="Expert researcher", knowledge_sources=[knowledge_source], embedder={ "provider": "azure", "config": { "api_key": "your-azure-api-key", "model": "text-embedding-ada-002", # change to the model you are using and is deployed in Azure "api_base": "https://your-azure-endpoint.openai.azure.com/", "api_version": "2024-02-01" } })
# Original task prompttask_prompt = "Answer the following questions about the user's favorite movies: What movie did John watch last week? Format your answer in JSON."# Behind the scenes, this might be rewritten as:rewritten_query = "What movies did John watch last week?"
재작성된 쿼리는 핵심 정보 요구에 더 집중하며, 출력 형식에 대한 불필요한 지시사항을 제거합니다.
이 메커니즘은 완전히 자동으로 동작하며 사용자가 별도의 설정을 할 필요가 없습니다. agent의 LLM을 사용하여 쿼리 재작성을 수행하므로, 더 강력한 LLM을 사용할 경우 재작성된 쿼리의 품질이 향상될 수 있습니다.
CrewAI를 사용하면 BaseKnowledgeSource 클래스를 확장하여 모든 유형의 데이터에 대한 맞춤형 지식 소스를 만들 수 있습니다. 이제 우주 뉴스 기사를 가져오고 처리하는 실용적인 예제를 만들어보겠습니다.최근 우주 탐사 동향은 다음과 같습니다. 최신 우주 뉴스 기사들을 기반으로 정리하였습니다:
SpaceX가 2023년 11월 17일 오전에 예정된, 두 번째 Starship/Super Heavy 통합 발사를 위한 최종 규제 승인을 받았습니다. 이는 SpaceX의 우주 탐사 및 우주 식민화에 대한 야심찬 계획에서 중요한 단계입니다. 출처: SpaceNews
SpaceX는 미국 연방통신위원회(FCC)에 1세대 차세대 Starlink Gen2 위성의 첫 발사를 시작할 계획임을 알렸습니다. 이는 전 세계에 고속 인터넷을 제공하는 Starlink 위성 인터넷 서비스의 주요 업그레이드입니다. 출처: Teslarati
AI 스타트업 Synthetaic이 시리즈 B 펀딩에서 1,500만 달러를 유치했습니다. 이 회사는 인공 지능을 사용하여 우주 및 공중 센서에서 데이터를 분석하며, 이는 우주 탐사와 위성 기술에 큰 응용 가능성이 있습니다. 출처: SpaceNews
미 우주군(Space Force)은 미국 인도-태평양 사령부(Indo-Pacific Command) 내에 부대를 공식적으로 창설하여 인도-태평양 지역에 항구적인 존재감을 확보하였습니다. 이는 우주 안보 및 지정학에 중대한 영향을 미칠 수 있습니다. 출처: SpaceNews
우주 추적 및 데이터 분석 기업 Slingshot Aerospace는 저지구 궤도(LEO) 커버리지를 확대하기 위해 지상 광학 망원경 네트워크를 확장하고 있습니다. 이는 저지구 궤도의 위성 및 우주 잔해 추적과 분석 능력을 향상시킬 수 있습니다. 출처: SpaceNews
중국 국가자연과학기금위원회는 연구자들이 초대형 우주선 조립을 연구하기 위한 5개년 프로젝트를 발표했습니다. 이는 우주선 기술과 우주 탐사 역량의 비약적인 발전을 가져올 수 있습니다. 출처: SpaceNews
스탠포드 대학교의 AEroSpace Autonomy Research 센터(CAESAR)는 우주선 자율성에 초점을 맞추고 있습니다. 센터는 2024년 5월 22일에 업계, 학계, 정부 간 협력을 촉진하기 위한 시작 행사를 개최하였습니다. 이는 자율 우주선 기술의 발전에 중대한 기여를 할 수 있습니다. 출처: SpaceNews
Copy
Ask AI
</CodeGroup>## 디버깅 및 문제 해결### 지식 문제 디버깅#### 에이전트 지식 초기화 확인```pythonfrom crewai import Agent, Crew, Taskfrom crewai.knowledge.source.string_knowledge_source import StringKnowledgeSourceknowledge_source = StringKnowledgeSource(content="Test knowledge")agent = Agent( role="Test Agent", goal="Test knowledge", backstory="Testing", knowledge_sources=[knowledge_source])crew = Crew(agents=[agent], tasks=[Task(...)])# Before kickoff - knowledge not initializedprint(f"Before kickoff - Agent knowledge: {getattr(agent, 'knowledge', None)}")crew.kickoff()# After kickoff - knowledge initializedprint(f"After kickoff - Agent knowledge: {agent.knowledge}")print(f"Agent knowledge collection: {agent.knowledge.storage.collection_name}")print(f"Number of sources: {len(agent.knowledge.sources)}")
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource# Create a test knowledge sourcetest_source = StringKnowledgeSource( content="Test knowledge content for debugging", chunk_size=100, # Small chunks for testing chunk_overlap=20)# Check chunking behaviorprint(f"Original content length: {len(test_source.content)}")print(f"Chunk size: {test_source.chunk_size}")print(f"Chunk overlap: {test_source.chunk_overlap}")# Process and inspect chunkstest_source.add()print(f"Number of chunks created: {len(test_source.chunks)}")for i, chunk in enumerate(test_source.chunks[:3]): # Show first 3 chunks print(f"Chunk {i+1}: {chunk[:50]}...")
# Ensure files are in the correct locationfrom crewai.utilities.constants import KNOWLEDGE_DIRECTORYimport osknowledge_dir = KNOWLEDGE_DIRECTORY # Usually "knowledge"file_path = os.path.join(knowledge_dir, "your_file.pdf")if not os.path.exists(file_path): print(f"File not found: {file_path}") print(f"Current working directory: {os.getcwd()}") print(f"Expected knowledge directory: {os.path.abspath(knowledge_dir)}")
“Embedding dimension mismatch” 오류:
Copy
Ask AI
# This happens when switching embedding providers# Reset knowledge storage to clear old embeddingscrew.reset_memories(command_type='knowledge')# Or use consistent embedding providerscrew = Crew( agents=[...], tasks=[...], knowledge_sources=[...], embedder={"provider": "openai", "config": {"model": "text-embedding-3-small"}})