-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.py
272 lines (229 loc) · 10.3 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""
Example usage of the Deep Research SDK with different web clients.
"""
import asyncio
import os
import logging
from deep_research import DeepResearch
from deep_research.utils import DoclingClient, DoclingServerClient, FirecrawlClient
from deep_research.utils.cache import CacheConfig
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
async def example_with_docling():
"""Run example with standard Docling client."""
# Get API keys from environment variables
openai_api_key = os.environ.get("OPENAI_API_KEY")
brave_api_key = os.environ.get("BRAVE_SEARCH_API_KEY")
# Define a research topic
topic = "create a terraform code to deploy a kubernetes cluster in aws"
if not openai_api_key:
print("Error: OPENAI_API_KEY environment variable not set")
return
if not brave_api_key:
print(
"Warning: BRAVE_API_KEY environment variable not set. Falling back to DuckDuckGo search."
)
print("\n\n==== USING STANDARD DOCLING CLIENT ====")
# Create a Deep Research instance with DoclingClient
researcher = DeepResearch(
web_client=DoclingClient(
brave_api_key=brave_api_key,
max_concurrent_requests=8,
cache_config=CacheConfig(enabled=True),
page_content_max_chars=8000, # Maximum number of characters to return in the scraped page content
),
llm_api_key=openai_api_key,
research_model="gpt-4o-mini", # You can change this to any supported model
reasoning_model="o3-mini", # You can change this to any supported model
max_depth=2, # Limit depth for this example
time_limit_minutes=1.5, # Limit time for this example
)
# Run the full research
print(f"Starting research with DoclingClient on: {topic}")
# Set max_tokens to avoid context window errors
result = await researcher.research(topic, max_tokens=8000)
# Check the result
if result.success:
print("\n==== RESEARCH SUCCESSFUL ====")
print(f"- Found {len(result.data['findings'])} pieces of information")
print(f"- Used {len(result.data['sources'])} sources")
print(
f"- Completed {result.data['completed_steps']} of {result.data['total_steps']} steps"
)
print("\n==== SEARCH QUERIES USED ====")
if "search_queries" in result.data:
for i, query in enumerate(result.data["search_queries"]):
print(
f"{i + 1}. Query: {query['query']} (Relevance: {query['relevance']:.2f})"
)
if "explanation" in query and query["explanation"]:
print(f" Explanation: {query['explanation']}")
else:
print("No search queries data available.")
print("\n==== SOURCES USED ====")
for i, source in enumerate(result.data["sources"]):
print(f"{i + 1}. {source['title']} (Relevance: {source['relevance']:.2f})")
print(f" URL: {source['url']}")
print("\n==== FINAL ANALYSIS ====")
print(result.data["analysis"])
else:
print("\n==== RESEARCH FAILED ====")
print(f"Error: {result.error}")
print(
f"- Found {len(result.data['findings'])} pieces of information before failure"
)
if "sources" in result.data:
print(f"- Used {len(result.data['sources'])} sources")
print(
f"- Completed {result.data['completed_steps']} of {result.data['total_steps']} steps"
)
async def example_with_docling_server():
"""Run example with DoclingServer client."""
# Get API keys from environment variables
openai_api_key = os.environ.get("OPENAI_API_KEY")
brave_api_key = os.environ.get("BRAVE_SEARCH_API_KEY")
# Define a research topic
topic = "Advances in machine learning for natural language processing"
if not openai_api_key:
print("Error: OPENAI_API_KEY environment variable not set")
return
print("\n\n==== USING DOCLING SERVER CLIENT ====")
# Create a Deep Research instance with DoclingServerClient
async with DoclingServerClient(
server_url="http://localhost:8000", # Update with your Docling server URL
brave_api_key=brave_api_key,
max_concurrent_requests=8,
cache_config=CacheConfig(enabled=True),
page_content_max_chars=8000,
) as docling_server_client:
researcher = DeepResearch(
web_client=docling_server_client,
llm_api_key=openai_api_key,
research_model="gpt-4o-mini",
reasoning_model="o3-mini",
max_depth=2,
time_limit_minutes=1.5,
)
# Run the full research
print(f"Starting research with DoclingServerClient on: {topic}")
result = await researcher.research(topic, max_tokens=8000)
# Check the result
if result.success:
print("\n==== RESEARCH SUCCESSFUL ====")
print(f"- Found {len(result.data['findings'])} pieces of information")
print(f"- Used {len(result.data['sources'])} sources")
print(
f"- Completed {result.data['completed_steps']} of {result.data['total_steps']} steps"
)
print("\n==== SEARCH QUERIES USED ====")
if "search_queries" in result.data:
for i, query in enumerate(result.data["search_queries"]):
print(
f"{i + 1}. Query: {query['query']} (Relevance: {query['relevance']:.2f})"
)
if "explanation" in query and query["explanation"]:
print(f" Explanation: {query['explanation']}")
else:
print("No search queries data available.")
print("\n==== SOURCES USED ====")
for i, source in enumerate(result.data["sources"]):
print(
f"{i + 1}. {source['title']} (Relevance: {source['relevance']:.2f})"
)
print(f" URL: {source['url']}")
print("\n==== FINAL ANALYSIS ====")
print(result.data["analysis"])
else:
print("\n==== RESEARCH FAILED ====")
print(f"Error: {result.error}")
print(
f"- Found {len(result.data['findings'])} pieces of information before failure"
)
if "sources" in result.data:
print(f"- Used {len(result.data['sources'])} sources")
print(
f"- Completed {result.data['completed_steps']} of {result.data['total_steps']} steps"
)
async def example_with_firecrawl():
"""Run example with Firecrawl client."""
# Get API keys from environment variables
openai_api_key = os.environ.get("OPENAI_API_KEY")
firecrawl_api_key = os.environ.get("FIRECRAWL_API_KEY")
# Define a research topic
topic = "Recent developments in renewable energy technology"
if not openai_api_key:
print("Error: OPENAI_API_KEY environment variable not set")
return
if not firecrawl_api_key:
print("Error: FIRECRAWL_API_KEY environment variable not set")
return
print("\n\n==== USING FIRECRAWL CLIENT ====")
# Create a Deep Research instance with FirecrawlClient
async with (
FirecrawlClient(
api_key=firecrawl_api_key,
api_url="https://api.firecrawl.dev", # Update with your Firecrawl API URL if different
max_concurrent_requests=8,
cache_config=CacheConfig(enabled=True),
page_content_max_chars=8000,
) as firecrawl_client
):
researcher = DeepResearch(
web_client=firecrawl_client,
llm_api_key=openai_api_key,
research_model="gpt-4o-mini",
reasoning_model="o3-mini",
max_depth=2,
time_limit_minutes=1.5,
)
# Run the full research
print(f"Starting research with FirecrawlClient on: {topic}")
result = await researcher.research(topic, max_tokens=8000)
# Check the result
if result.success:
print("\n==== RESEARCH SUCCESSFUL ====")
print(f"- Found {len(result.data['findings'])} pieces of information")
print(f"- Used {len(result.data['sources'])} sources")
print(
f"- Completed {result.data['completed_steps']} of {result.data['total_steps']} steps"
)
print("\n==== SEARCH QUERIES USED ====")
if "search_queries" in result.data:
for i, query in enumerate(result.data["search_queries"]):
print(
f"{i + 1}. Query: {query['query']} (Relevance: {query['relevance']:.2f})"
)
if "explanation" in query and query["explanation"]:
print(f" Explanation: {query['explanation']}")
else:
print("No search queries data available.")
print("\n==== SOURCES USED ====")
for i, source in enumerate(result.data["sources"]):
print(
f"{i + 1}. {source['title']} (Relevance: {source['relevance']:.2f})"
)
print(f" URL: {source['url']}")
print("\n==== FINAL ANALYSIS ====")
print(result.data["analysis"])
else:
print("\n==== RESEARCH FAILED ====")
print(f"Error: {result.error}")
print(
f"- Found {len(result.data['findings'])} pieces of information before failure"
)
if "sources" in result.data:
print(f"- Used {len(result.data['sources'])} sources")
print(
f"- Completed {result.data['completed_steps']} of {result.data['total_steps']} steps"
)
async def main():
"""Run all examples."""
# You can comment out the examples you don't want to run
await example_with_docling()
# Note: The following examples require additional setup:
# - DoclingServer example requires a running instance of docling-serve
# - Firecrawl example requires a Firecrawl API key
# Uncomment to run these examples if you have the required setup
# await example_with_docling_server()
# await example_with_firecrawl()
if __name__ == "__main__":
asyncio.run(main())