Skip to content

Commit aadbf3a

Browse files
committed
added websearch for python
1 parent da9c094 commit aadbf3a

10 files changed

Lines changed: 619 additions & 46 deletions

File tree

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ If you are unsure on which path you should choose, ask the instructor for guidan
4747
- [Exercise 03 - Build your first agent tool](./exercises/Python/03-add-your-first-tool.md)
4848
- [Exercise 04 - Building a multi-agent system](./exercises/Python/04-building-multi-agent-system.md)
4949
- [Exercise 05 - Add the Grounding service](./exercises/Python/05-add-the-grounding-service.md)
50-
- [Exercise 06 - Use your AI Agents to solve the crime](./exercises/Python/06-solve-the-crime.md)
50+
- [Exercise 06 - Discover Connected Crimes with Web Search](./exercises/Python/06-discover-connected-crimes.md)
51+
- [Exercise 07 - Use your AI Agents to solve the crime](./exercises/Python/07-solve-the-crime.md)
5152

5253
The instructor will start you on the first exercise. Proceed to the next exercise once the instructor tells you to.
5354

exercises/Python/05-add-the-grounding-service.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,8 @@ In the following exercises, you will:
460460
2. ✅ Add custom tools to your agents so they can access external data
461461
3. ✅ Create a complete crew with multiple agents working together
462462
4. ✅ Integrate the Grounding Service for better reasoning and fact-checking (this exercise)
463-
5. 📌 [Solve the museum art theft mystery](06-solve-the-crime.md) using your fully-featured agent team
463+
5. 📌 [Add web search capabilities](06-discover-connected-crimes.md) to gather external intelligence
464+
6. 📌 [Solve the museum art theft mystery](07-solve-the-crime.md) using your fully-featured agent team
464465

465466
---
466467

exercises/Python/06-discover-connected-crimes.md

Lines changed: 445 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 55 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
# Use your AI Agents to solve the crime
22

3-
The only thing missing now is your **Lead Detective Agent**. This agent will then use the information retrieved from the other two agents to solve the crime and determine the value of the stolen items.
3+
The only thing missing now is your **Lead Detective Agent**. This agent will synthesize information from all three specialized agents to solve the crime and determine the value of the stolen items.
4+
5+
You now have complete intelligence gathering capabilities:
6+
- 📊 **Financial predictions** from the Appraiser (RPT-1)
7+
- 📄 **Internal evidence** from the Evidence Analyst (Grounding Service)
8+
- 🌐 **External intelligence** from the Intelligence Researcher (Web Search)
9+
10+
The Lead Detective will combine all three sources for a comprehensive conclusion.
411

512
## Build Your Lead Detective Agent
613

@@ -30,8 +37,13 @@ lead_detective_agent:
3037
```yaml
3138
solve_crime:
3239
description: >
33-
Find the thief among the suspects by activating the evidence analyst agent and instructing them to look for information on each of the three suspects
34-
using the grounding tool. They should find information on alibis and motives and return a report for you to analyze.
40+
Find the thief among the suspects by reviewing:
41+
1. The insurance appraisal values from the appraiser agent
42+
2. The internal evidence analysis from the evidence analyst agent
43+
3. The web intelligence report from the intelligence researcher agent
44+
45+
Synthesize all three sources to identify the culprit with high confidence.
46+
Consider both internal evidence and external patterns/connections found online.
3547
expected_output: >
3648
The name of the thief and the total value of the stolen goods for the insurance.
3749
agent: lead_detective_agent
@@ -43,7 +55,7 @@ Now you'll add the Lead Detective Agent and its task to your investigator crew.
4355

4456
👉 Open [`/project/Python/starter-project/investigator_crew.py`](/project/Python/starter-project/investigator_crew.py)
4557

46-
👉 **Inside the `InvestigatorCrew` class**, add the new agent and task methods **after** the existing `analyze_evidence_task` method and **before** the `@crew` method:
58+
👉 **Inside the `InvestigatorCrew` class**, add the new agent and task methods **after** the existing `research_criminal_network` method and **before** the `@crew` method:
4759

4860
```python
4961
@agent
@@ -57,25 +69,27 @@ Now you'll add the Lead Detective Agent and its task to your investigator crew.
5769
def solve_crime(self) -> Task:
5870
return Task(
5971
config=self.tasks_config['solve_crime'],
60-
context=[self.appraise_loss_task(), self.analyze_evidence_task()] # 👈 Lead detective uses results from other tasks
72+
context=[self.appraise_loss_task(), self.analyze_evidence_task(), self.research_criminal_network()] # Lead detective uses all three sources
6173
)
6274
```
6375

64-
> 💡 **Where to place this code**: Add these methods inside the `InvestigatorCrew` class, after your `analyze_evidence_task()` method. The final order should be:
76+
> 💡 **Where to place this code**: Add these methods inside the `InvestigatorCrew` class, after your `research_criminal_network()` method. The final order should be:
6577
>
6678
> 1. `appraiser_agent()` method
6779
> 2. `appraise_loss_task()` method
6880
> 3. `evidence_analyst_agent()` method
6981
> 4. `analyze_evidence_task()` method
70-
> 5. **👈 Add `lead_detective_agent()` here**
71-
> 6. **👈 Add `solve_crime()` here**
72-
> 7. `crew()` method (keep at the end)
82+
> 5. `intelligence_researcher_agent()` method (from Exercise 06)
83+
> 6. `research_criminal_network()` method (from Exercise 06)
84+
> 7. **👈 Add `lead_detective_agent()` here**
85+
> 8. **👈 Add `solve_crime()` here**
86+
> 9. `crew()` method (keep at the end)
7387

7488
> 💡 **Understanding the `context` parameter:**
7589
>
76-
> - `context=[self.appraise_loss_task(), self.analyze_evidence_task()]` tells CrewAI that the `solve_crime` task depends on the other two tasks
77-
> - The Lead Detective will receive the output from both the Loss Appraiser and Evidence Analyst
78-
> - This enables the detective to combine financial predictions with evidence analysis to solve the crime
90+
> - `context=[self.appraise_loss_task(), self.analyze_evidence_task(), self.research_criminal_network()]` tells CrewAI that the `solve_crime` task depends on all three prior tasks
91+
> - The Lead Detective receives output from the Appraiser, Evidence Analyst, AND Intelligence Researcher
92+
> - This enables comprehensive analysis using financial data, internal evidence, and web intelligence
7993

8094
### Step 4: Verify Crew Configuration
8195

@@ -87,9 +101,9 @@ Your crew configuration should already be set from Exercise 04, but let's verify
87101
@crew
88102
def crew(self) -> Crew:
89103
return Crew(
90-
agents=self.agents, # Automatically collected by @agent decorator (all 3 agents)
91-
tasks=self.tasks, # Automatically collected by @task decorator (all 3 tasks)
92-
process=Process.sequential, # Tasks run in order: appraise → analyze → solve
104+
agents=self.agents, # Automatically collected by @agent decorator (all 4 agents)
105+
tasks=self.tasks, # Automatically collected by @task decorator (all 4 tasks)
106+
process=Process.sequential, # Tasks run in order: appraise → analyze → research → solve
93107
verbose=True # Print detailed execution logs
94108
)
95109
```
@@ -98,9 +112,9 @@ Your crew configuration should already be set from Exercise 04, but let's verify
98112

99113
### Step 5: Verify main.py (No Changes Needed)
100114

101-
Your `main.py` from Exercise 04 should already be correct. It doesn't need any changes for Exercise 06!
115+
Your `main.py` from Exercise 04 should already be correct. It doesn't need any changes for Exercise 07!
102116

103-
> 💡 **What's happening:** The same `main.py` that ran 2 agents in Exercise 04 will now automatically run all 3 agents (including your new Lead Detective). CrewAI collects all `@agent` and `@task` decorated methods automatically.
117+
> 💡 **What's happening:** The same `main.py` that ran 2 agents in Exercise 04 will now automatically run all 4 agents (Appraiser, Evidence Analyst, Intelligence Researcher, and Lead Detective). CrewAI collects all `@agent` and `@task` decorated methods automatically.
104118

105119
👉 (Optional) Double-check your [`/project/Python/starter-project/main.py`](/project/Python/starter-project/main.py) has both required inputs:
106120

@@ -153,11 +167,12 @@ python main.py
153167
python main.py
154168
```
155169

156-
> ⏱️ **This may take 2-5 minutes** as your agents:
170+
> ⏱️ **This may take 3-6 minutes** as your agents:
157171
>
158-
> 1. Search evidence documents for each suspect
159-
> 2. Predict values of stolen items using RPT-1
160-
> 3. Analyze findings and identify the culprit
172+
> 1. Search evidence documents for each suspect (Evidence Analyst)
173+
> 2. Predict values of stolen items using RPT-1 (Appraiser)
174+
> 3. Search the web for criminal patterns (Intelligence Researcher)
175+
> 4. Synthesize all findings and identify the culprit (Lead Detective)
161176

162177
👉 Review the final output—who does your Lead Detective identify as the thief?
163178

@@ -236,11 +251,12 @@ python main.py
236251

237252
You created a complete multi-agent system where:
238253

239-
1. **The Lead Detective Agent** orchestrates the investigation by delegating tasks
240-
2. **The Evidence Analyst Agent** retrieves and analyzes evidence from documents
241-
3. **The Loss Appraiser Agent** predicts financial values of stolen items
242-
4. **Agent Communication** flows through task delegation and result aggregation
243-
5. **Reasoning Integration** combines evidence, alibis, motives, and values to solve the crime
254+
1. **The Lead Detective Agent** orchestrates the investigation by synthesizing multiple sources
255+
2. **The Evidence Analyst Agent** retrieves and analyzes evidence from internal documents
256+
3. **The Intelligence Researcher Agent** gathers external intelligence via web search
257+
4. **The Loss Appraiser Agent** predicts financial values of stolen items
258+
5. **Agent Communication** flows through task delegation and result aggregation
259+
6. **Multi-Source Reasoning** combines internal evidence, web intelligence, and financial data to solve the crime
244260

245261
### The Investigation Flow
246262

@@ -252,10 +268,14 @@ flowchart TD
252268
A --> E[Loss Appraisal]
253269
E --> F[RPT-1 Predictions]
254270
F --> G[Value Determination]
255-
D --> H[Crime Resolution]
256-
G --> H
257-
H --> I[Suspect Identification]
258-
I --> J[Final Report]
271+
A --> H[Web Intelligence]
272+
H --> I[Sonar-Pro Search]
273+
I --> J[Pattern Analysis]
274+
D --> K[Crime Resolution]
275+
G --> K
276+
J --> K
277+
K --> L[Suspect Identification]
278+
L --> M[Final Report]
259279
```
260280

261281
### Why This Matters
@@ -290,14 +310,16 @@ In the following exercises, you will:
290310
2. ✅ Add custom tools to your agents so they can access external data
291311
3. ✅ Create a complete crew with multiple agents working together
292312
4. ✅ Integrate the Grounding Service for better reasoning and fact-checking
293-
5. ✅ Solve the museum art theft mystery using your fully-featured agent team (this exercise)
313+
5. ✅ Add web search for external intelligence gathering
314+
6. ✅ Solve the museum art theft mystery using your fully-featured agent team (this exercise)
294315

295316
Congratulations on completing the CodeJam! You've successfully built a sophisticated multi-agent AI system that can:
296317

297-
- Analyze evidence from documents
318+
- Analyze evidence from internal documents
319+
- Search the web for external intelligence
298320
- Predict financial values using the SAP-RPT-1 model
299321
- Coordinate between multiple specialized agents
300-
- Solve complex real-world problems through collaborative reasoning
322+
- Solve complex real-world problems through collaborative reasoning with multi-source intelligence
301323

302324
---
303325

project/JavaScript/solution/src/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ export interface RPT1Payload {
5252
index_column: string
5353
rows: StolenItem[]
5454
parse_data_types?: boolean // Optional: control data type parsing
55+
data_schema?: any // Optional: schema definition for data types
5556
}
5657

5758
/**

project/Python/solution/config/agents.yaml

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,29 @@ evidence_analyst_agent:
1212
role: >
1313
Criminal Evidence Analyst
1414
goal: >
15-
Retrieve and analyze evidence ONLY via the call_grounding_service tool.
16-
Search for each suspect by name: {suspect_names}. Do NOT fabricate any evidence or alibis.
15+
Retrieve and analyze evidence ONLY via the call_grounding_service tool.
16+
Search for each suspect by name: {suspect_names}. Do NOT fabricate any evidence or alibis.
1717
Report only what the tool returns.
1818
backstory: >
1919
You are a methodical evidence analyst who bases conclusions strictly on retrieved documents. You never assume facts.
2020
llm: sap/anthropic--claude-4.5-opus
2121

22+
intelligence_researcher_agent:
23+
role: >
24+
Open-Source Intelligence (OSINT) Researcher
25+
goal: >
26+
Search the web for similar art thefts, criminal patterns, and suspect backgrounds
27+
to determine if this heist is part of a larger criminal network. Use the
28+
call_sonar_pro_search tool to find recent incidents, news reports, and public
29+
criminal records for all three suspects: {suspect_names}.
30+
backstory: >
31+
You are an OSINT specialist who excels at finding patterns across multiple
32+
crime scenes. You search public databases, news archives, and criminal records
33+
to connect seemingly isolated incidents. Your expertise has uncovered several
34+
international art theft rings, and you know how to distinguish professional
35+
criminals from amateurs.
36+
llm: sap/gpt-4o
37+
2238
lead_detective_agent:
2339
role: >
2440
Lead Detective and Case Manager

project/Python/solution/config/tasks.yaml

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,45 @@ appraise_loss_task:
77

88
analyze_evidence_task:
99
description: >
10-
Analyze the evidence of the theft that you can access via the grounding tool.
11-
Provide any insights that can help in the investigation especially regarding alabies.
12-
Check the evidence for all three suspect names 1. Sophie Dubois, 2. Marcus Chen and
10+
Analyze the evidence of the theft that you can access via the grounding tool.
11+
Provide any insights that can help in the investigation especially regarding alabies.
12+
Check the evidence for all three suspect names 1. Sophie Dubois, 2. Marcus Chen and
1313
3. Viktor Petrovand and provide an analysis for each of them.
1414
expected_output: >
1515
A detailed analysis of the evidence for each suspect, including any insights that can help in the investigation.
1616
agent: evidence_analyst_agent
1717

18+
research_criminal_network:
19+
description: >
20+
Search the web for intelligence about the three suspects ({suspect_names}) and
21+
related crimes. Use the call_sonar_pro_search tool to find:
22+
1. Public criminal records or prior convictions for each suspect
23+
2. Similar art theft incidents with the same modus operandi (insider job, no forced entry)
24+
3. Connections to known art theft rings or criminal networks
25+
4. News reports or public information about any of the suspects
26+
5. Recent museum heists in Europe with similar patterns
27+
28+
Cross-reference your web findings with the internal evidence analyzed by the
29+
evidence analyst. Focus on discovering whether this is an isolated incident or
30+
part of a larger criminal operation.
31+
expected_output: >
32+
A comprehensive intelligence report containing:
33+
- Background checks for all three suspects with web sources
34+
- List of similar art thefts found online (dates, locations, MO)
35+
- Evidence of criminal network connections (if any)
36+
- Assessment: isolated incident vs. organized crime ring
37+
- All findings MUST include web sources with URLs and dates
38+
agent: intelligence_researcher_agent
39+
1840
solve_crime:
1941
description: >
20-
Find the thief from, the suspects by activating the evidence investigator agent and instructing him to look for the three suspects
21-
using the grounding tool. He should find information on alibies and motives and return a report for you to analyze. And use the appraise_loss_task from
22-
the appraiser agent to find the value of the stolen goods.
42+
Find the thief among the suspects by reviewing:
43+
1. The insurance appraisal values from the appraiser agent
44+
2. The internal evidence analysis from the evidence analyst agent
45+
3. The web intelligence report from the intelligence researcher agent
46+
47+
Synthesize all three sources to identify the culprit with high confidence.
48+
Consider both internal evidence and external patterns/connections found online.
2349
expected_output: >
2450
The name of the thief and the total value of the stolen goods for the insurance.
2551
agent: lead_detective_agent

project/Python/solution/investigator_crew.py

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,45 @@ def call_grounding_service(user_question: str) -> str:
7070

7171
response_dict = json.dumps(response.model_dump(), indent=2) # Convert to JSON string
7272
return response_dict # Return retrieved document chunks to the agent
73-
73+
74+
75+
@tool("call_sonar_pro_search")
76+
def call_sonar_pro_search(search_query: str) -> str:
77+
"""Search the web using Perplexity's sonar-pro model for real-time information
78+
about crimes, suspects, and criminal patterns. Use this to find similar incidents,
79+
criminal networks, public records, or patterns that are not in internal documents.
80+
81+
Args:
82+
search_query: The search query about crimes, suspects, or criminal patterns
83+
84+
Returns:
85+
Search results with source citations from the web
86+
"""
87+
from litellm import completion
88+
89+
try:
90+
response = completion(
91+
model="sap/sonar-pro", # Perplexity model with web search
92+
messages=[
93+
{
94+
"role": "system",
95+
"content": "You are a web search assistant specializing in criminal intelligence. Search for accurate, recent information and always provide source citations with URLs and dates."
96+
},
97+
{
98+
"role": "user",
99+
"content": search_query
100+
}
101+
],
102+
temperature=0.2, # Lower temperature for factual search
103+
)
104+
105+
result = response.choices[0].message.content
106+
return result
107+
108+
except Exception as e:
109+
return f"Error calling sonar-pro web search: {str(e)}"
110+
111+
74112
@CrewBase
75113
class InvestigatorCrew():
76114
"""InvestigatorCrew crew"""
@@ -105,7 +143,22 @@ def analyze_evidence_task(self) -> Task:
105143
return Task(
106144
config=self.tasks_config['analyze_evidence_task']
107145
)
108-
146+
147+
@agent
148+
def intelligence_researcher_agent(self) -> Agent:
149+
return Agent(
150+
config=self.agents_config['intelligence_researcher_agent'],
151+
verbose=True,
152+
tools=[call_sonar_pro_search] # Web search tool
153+
)
154+
155+
@task
156+
def research_criminal_network(self) -> Task:
157+
return Task(
158+
config=self.tasks_config['research_criminal_network'],
159+
context=[self.analyze_evidence_task()] # Uses internal evidence to inform web searches
160+
)
161+
109162
@agent
110163
def lead_detective_agent(self) -> Agent:
111164
return Agent(
@@ -117,7 +170,7 @@ def lead_detective_agent(self) -> Agent:
117170
def solve_crime(self) -> Task:
118171
return Task(
119172
config=self.tasks_config['solve_crime'],
120-
context=[self.appraise_loss_task(), self.analyze_evidence_task()] # 👈 Lead detective uses results from other tasks
173+
context=[self.appraise_loss_task(), self.analyze_evidence_task(), self.research_criminal_network()] # Lead detective uses all three sources
121174
)
122175

123176
@crew
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
crewai==0.86.0
2+
litellm==1.82.6
3+
python-dotenv==1.0.0
4+
sap-ai-sdk-gen
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
crewai==0.86.0
2+
litellm==1.82.6
3+
python-dotenv==1.0.0
4+
sap-ai-sdk-gen

0 commit comments

Comments
 (0)