-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathmain.py
More file actions
3167 lines (2639 loc) · 112 KB
/
Copy pathmain.py
File metadata and controls
3167 lines (2639 loc) · 112 KB
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Deep Research Engine - Adaptive Intelligence System
A meta-level research system that performs comprehensive multi-stream intelligence gathering.
It dynamically classifies queries, executes parallel research streams, and iteratively
refines hypotheses to produce well-sourced analytical packages for any domain.
"""
import asyncio
import datetime
import hashlib
import os
import time
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import aiohttp
from agentfield import Agent, AIConfig
from pydantic import BaseModel, Field
from temporal_context import get_temporal_context
from doc_generation_pipeline import (
DocumentResponse as DocGenDocumentResponse,
FinalDocument as DocGenFinalDocument,
generate_document_from_package_core,
)
# ==============================================================================
# GLOBAL CONFIGURATION
# ==============================================================================
# The maximum number of concurrent AI calls to make at once.
# Adjust this based on your model provider's rate limits.
AI_CALL_CONCURRENCY_LIMIT = 20
MAX_ARTICLES_PER_TASK = 10
NUM_SEARCH_TERMS_PER_TASK = 3
# A hard safety limit on the number of task execution loops.
MAX_BLUEPRINT_EXECUTION_LOOPS = int(os.getenv("MAX_BLUEPRINT_EXECUTION_LOOPS", "3"))
ADJUDICATION_BATCH_SIZE = 50
# Batch size for entity deduplication - larger values may overwhelm smaller models
ENTITY_BATCH_SIZE = 10
# --- AI Configuration & Agent Setup ---
# Build litellm_params - supports local Ollama deployments
litellm_params = {"drop_params": True}
# If OLLAMA_BASE_URL is set, configure for local Ollama deployment
ollama_base_url = os.getenv("OLLAMA_BASE_URL")
if ollama_base_url:
litellm_params["api_base"] = ollama_base_url
print(f"🦙 Using local Ollama at: {ollama_base_url}")
ai_config = AIConfig(
model=os.getenv("DEFAULT_MODEL", "openrouter/deepseek/deepseek-chat-v3.1"),
temperature=float(os.getenv("TEMPERATURE", "0.6")),
max_tokens=8192,
litellm_params=litellm_params,
)
app = Agent(
node_id="meta_deep_research",
agentfield_server=os.getenv('AGENTFIELD_SERVER', 'http://localhost:8080'),
version="3.0.0",
dev_mode=True,
callback_url=os.getenv("AGENT_CALLBACK_URL", None),
api_key=os.getenv("AGENTFIELD_API_KEY", None),
ai_config=ai_config,
)
# ==============================================================================
# CORE UTILITIES & HELPERS
# ==============================================================================
async def search_web_for_content(query: str) -> List[Dict]:
"""
Performs a web search using the available search provider.
Automatically detects and uses the first available provider from:
Jina, Tavily, Firecrawl, or Serper (in priority order).
Set SEARCH_PROVIDER env var to force a specific provider.
"""
from skills.search import search, list_provider_status
try:
# Log provider status on first call for debugging
status = list_provider_status()
available = [name for name, is_available in status.items() if is_available]
if available:
print(f"🔍 DEBUG: Available search providers: {available}")
else:
print("⚠️ WARNING: No search providers available! Configure at least one API key.")
return []
response = await search(query)
print(f"🔍 DEBUG: Search completed via {response.provider} - {len(response.results)} results for: {query[:50]}...")
# Convert SearchResult objects to dicts matching expected format
return [
{
"url": result.url,
"title": result.title,
"content": result.content,
"description": result.description,
}
for result in response.results
]
except RuntimeError as e:
print(f"⚠️ WARNING: No search providers available: {e}")
return []
except Exception as e:
print(f"❌ ERROR: Search failed for query '{query}': {e}")
return []
async def ai_with_dynamic_params(
*args, model: Optional[str] = None, api_key: Optional[str] = None, **kwargs
) -> Any:
"""A wrapper for app.ai calls to allow dynamic model and API key overrides."""
dynamic_params = {}
if model:
dynamic_params["model"] = model
if api_key:
dynamic_params["api_key"] = api_key
merged_kwargs = {**kwargs, **dynamic_params}
return await app.ai(*args, **merged_kwargs)
def create_content_hash(content: str) -> str:
"""Creates a unique MD5 hash for a string of content to identify duplicates."""
return hashlib.md5(content.encode()).hexdigest()
async def run_in_batches(tasks: List, batch_size: int):
"""Executes a list of asyncio tasks in batches to manage rate limits."""
results = []
for i in range(0, len(tasks), batch_size):
batch = tasks[i : i + batch_size]
batch_results = await asyncio.gather(*batch, return_exceptions=True)
results.extend(batch_results)
return [r for r in results if not isinstance(r, Exception)]
def translate_control_knob_to_description(level: int) -> str:
"""Translates a 1-5 integer into a qualitative descriptor for AI prompts."""
return {
1: "Minimal: Stay strictly on topic. Surface level.",
2: "Constrained: Explore only immediate, directly connected concepts.",
3: "Balanced: Investigate the main topic and its most important related areas.",
4: "Expansive: Actively seek out adjacent topics and secondary connections.",
5: "Maximum: Explore all potentially relevant tangents, contexts, and implications.",
}.get(level, "Balanced")
# ==============================================================================
# DATA SCHEMAS
# ==============================================================================
# --- Query Classification & Intelligence Schemas ---
class QueryClassification(BaseModel):
"""Classifies the user's query into a research category."""
query_type: str = Field(
description="The category of the research query (e.g., 'Market_Intelligence', 'Entity_Analysis', 'Competitive_Analysis', 'Technology_Assessment', 'Strategic_Assessment')."
)
core_subject: str = Field(
description="The primary company, technology, or market being investigated."
)
key_question: str = Field(
description="A refined, single-sentence question that captures the user's core intent."
)
class EntityPair(BaseModel):
"""Represents a potential duplicate entity pair."""
entity1_name: str
entity2_name: str
similarity_reason: str
class EntityPairList(BaseModel):
"""List of potential duplicate entity pairs."""
pairs: List[EntityPair]
class MergedEntity(BaseModel):
"""Result of merging two entities."""
name: str
type: str
summary: str
class ResearchHypothesis(BaseModel):
"""A structured research hypothesis based on synthesized intelligence."""
core_thesis: str = Field(
description="The central argument or hypothesis being investigated."
)
supporting_strengths: List[str] = Field(
description="The top 3-4 factors that support the thesis."
)
counter_risks: List[str] = Field(
description="The most significant risks or weaknesses that challenge the thesis."
)
key_unknowns: List[str] = Field(
description="Critical unanswered questions that require deeper investigation."
)
# --- Core Data Schemas ---
class Article(BaseModel):
"""Represents a single source article found during research."""
id: int
title: str
url: str
content: str
content_hash: str
class ArticleEvidence(BaseModel):
"""Contains structured data extracted from a single source article."""
article_id: int
relevance_summary: str
facts: List[str]
quotes: List[str]
class Entity(BaseModel):
"""Represents a person, organization, concept, or other key noun."""
name: str
type: str = Field(
description="The entity category (e.g., 'Organization', 'Person', 'Technology', 'Market_Trend', 'Concept', 'Metric')."
)
summary: str
class Relationship(BaseModel):
"""Describes a connection between two entities."""
source_entity: str
target_entity: str
description: str
relationship_type: str = Field(
description="The connection type (e.g., 'Competes_With', 'Partners_With', 'Founded_By', 'Influences', 'Depends_On')."
)
class InquiryProbe(BaseModel):
"""A suggested question for future investigation."""
question: str
rationale: str
suggested_method: str
class UniversalResearchPackage(BaseModel):
"""The final, comprehensive output. Schema is compatible with the original."""
query: str
core_thesis: str
key_discoveries: List[str]
confidence_assessment: str
entities: List[Entity]
relationships: List[Relationship]
observed_causal_chains: List[str]
hypothesized_implications: List[str]
next_inquiry_probes: List[InquiryProbe]
source_articles: List[Article]
article_evidence: List[ArticleEvidence]
class ResearchResponse(BaseModel):
"""Base response format for all research APIs."""
mode: str
version: str
research_package: dict
metadata: dict
# Type aliases for API-specific responses (same structure, different semantic meaning)
ModeAwareResearchResponse = ResearchResponse # For prepare/continue APIs
ResearchBriefingResponse = ResearchResponse # For briefing API
DocumentResponse = ResearchResponse # For document generation API
class StreamOutput(BaseModel):
"""Holds all outputs from a single intelligence stream."""
stream_type: str
synthesized_intel: Dict[str, Any]
source_articles: List[Article]
article_evidence: List[ArticleEvidence]
class AdaptiveInquiryProbes(BaseModel):
"""Container for adaptive inquiry probes."""
probes: List[InquiryProbe]
# === NEW INTERNAL SCHEMAS (unchanged external APIs) ===
class ResearchQualityScore(BaseModel):
"""Simple quality assessment of current research state."""
confidence_score: float = Field(description="Research confidence from 0.0 to 1.0")
evidence_adequacy: str = Field(
description="'sufficient', 'moderate', or 'insufficient'"
)
critical_gaps_present: bool = Field(
description="True if major knowledge gaps remain"
)
class ResearchGap(BaseModel):
"""Individual knowledge gap that needs investigation."""
gap_description: str = Field(description="What specific knowledge is missing")
gap_priority: str = Field(description="'high', 'medium', or 'low'")
gap_type: str = Field(
description="'entity', 'relationship', 'evidence', or 'context'"
)
class GapFillingQuery(BaseModel):
"""Targeted query to fill specific research gaps."""
search_query: str = Field(description="Specific search query to address gaps")
expected_insights: str = Field(description="What this query should reveal")
query_priority: str = Field(description="'high', 'medium', or 'low'")
class LoopDecision(BaseModel):
"""Decision on whether to continue research iterations."""
should_continue: bool = Field(description="True if another research loop is needed")
termination_reason: str = Field(description="Why stopping or continuing")
focus_areas: str = Field(description="What to focus on in next iteration")
# ==============================================================================
# META-REASONER AGENTS
# ==============================================================================
# --- Parallelized Processing Utilities ---
@app.reasoner()
async def merge_entity_pair(
entity1: Entity,
entity2: Entity,
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> MergedEntity:
"""Merges two specific entities into one."""
prompt = f"""
<entity1>
Name: {entity1.name}
Type: {entity1.type}
Summary: {entity1.summary}
</entity1>
<entity2>
Name: {entity2.name}
Type: {entity2.type}
Summary: {entity2.summary}
</entity2>
<instructions>
Merge these two entities into a single, comprehensive entity.
- Choose the most complete/accurate name
- Use the most appropriate type
- Create a summary that combines the best information from both
</instructions>
"""
return await ai_with_dynamic_params(
system="You are an Entity Merger. Combine two entities into one comprehensive entity without losing information.",
user=prompt,
schema=MergedEntity,
model=model,
api_key=api_key,
)
@app.reasoner()
async def detect_entity_duplicates_batch(
entities_batch: List[Entity],
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> EntityPairList:
"""Detects potential duplicate entities in a batch."""
entities_text = "\n".join(
[f"- {e.name} ({e.type}): {e.summary}" for e in entities_batch]
)
prompt = f"""
<entities>
{entities_text}
</entities>
<instructions>
Analyze the entities above and identify pairs that likely represent the same real-world entity.
Look for:
- Same names with slight variations
- Same organizations/people described differently
- Concepts that are essentially the same thing
Only include pairs where you're confident they represent the same entity.
Provide a brief reason for each potential duplicate pair.
</instructions>
"""
return await ai_with_dynamic_params(
system="You are an Entity Deduplication Specialist. Identify potential duplicate entities with high confidence.",
user=prompt,
schema=EntityPairList,
model=model,
api_key=api_key,
)
async def process_entity_consolidation_parallel(
all_entities: List[Entity],
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> List[Entity]:
"""Consolidates entities using parallel processing."""
if len(all_entities) <= 1:
return all_entities
# Create batches for parallel processing
if len(all_entities) <= 50:
entity_batches = [all_entities]
else:
entity_batches = batch_list(all_entities, ENTITY_BATCH_SIZE)
# Step 1: Detect duplicates in all batches in parallel
# Show sample entities being processed
sample_entities = [e.name for e in all_entities[:3]]
entities_preview = ", ".join(sample_entities)
if len(all_entities) > 3:
entities_preview += "…"
app.note(f"Verifying if {entities_preview} are the same organizations…")
batch_tasks = [
detect_entity_duplicates_batch(batch, model=model, api_key=api_key)
for batch in entity_batches
]
batch_results = await run_in_batches(batch_tasks, AI_CALL_CONCURRENCY_LIMIT)
# Step 2: Collect all duplicate pairs
all_duplicate_pairs = []
for result in batch_results:
if result and hasattr(result, "pairs"):
all_duplicate_pairs.extend(result.pairs)
# Step 3: Create entity lookup and prepare merge tasks
entities_dict = {entity.name: entity for entity in all_entities}
merge_tasks = []
pairs_to_process = []
for pair in all_duplicate_pairs:
if pair.entity1_name in entities_dict and pair.entity2_name in entities_dict:
entity1 = entities_dict[pair.entity1_name]
entity2 = entities_dict[pair.entity2_name]
merge_tasks.append(
merge_entity_pair(entity1, entity2, model=model, api_key=api_key)
)
pairs_to_process.append(pair)
# Step 4: Execute all merges in parallel
if merge_tasks:
# Show specific entities being merged
merge_examples = []
for pair in pairs_to_process[:2]: # Show first 2 examples
merge_examples.append(f"{pair.entity1_name} and {pair.entity2_name}")
if len(pairs_to_process) == 1:
app.note(
f"Found {merge_examples[0]} refer to the same entity — consolidating information…"
)
elif len(pairs_to_process) == 2:
app.note(f"Consolidating information for: {' | '.join(merge_examples)}…")
else:
app.note(
f"Consolidating profiles for {merge_examples[0]} and other organizations…"
)
merge_results = await run_in_batches(merge_tasks, AI_CALL_CONCURRENCY_LIMIT)
# Step 5: Apply merge results
for i, merged in enumerate(merge_results):
if merged and i < len(pairs_to_process):
pair = pairs_to_process[i]
merged_entity = Entity(
name=merged.name, type=merged.type, summary=merged.summary
)
# Update entities dict
entities_dict[merged.name] = merged_entity
if pair.entity1_name != merged.name:
entities_dict.pop(pair.entity1_name, None)
if pair.entity2_name != merged.name:
entities_dict.pop(pair.entity2_name, None)
return list(entities_dict.values())
class EvidenceDeduplication(BaseModel):
"""Result of evidence deduplication."""
is_duplicate: bool
reason: str
class RelationshipPair(BaseModel):
"""Represents a potential duplicate relationship pair."""
relationship1_description: str
relationship2_description: str
similarity_reason: str
class RelationshipPairList(BaseModel):
"""List of potential duplicate relationship pairs."""
pairs: List[RelationshipPair]
@app.reasoner()
async def detect_relationship_duplicates_batch(
relationships_batch: List[Relationship],
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> RelationshipPairList:
"""Detects potential duplicate relationships in a batch."""
rels_text = "\n".join(
[
f"- {r.source_entity} {r.description} {r.target_entity} ({r.relationship_type})"
for r in relationships_batch
]
)
prompt = f"""
<relationships>
{rels_text}
</relationships>
<instructions>
Identify pairs of relationships that describe essentially the same connection between entities.
Look for:
- Same relationship expressed differently
- Redundant descriptions of the same connection
- Similar relationships that should be consolidated
Only include pairs where consolidation would reduce redundancy without losing meaning.
</instructions>
"""
return await ai_with_dynamic_params(
system="You are a Relationship Deduplication Specialist. Identify redundant relationships.",
user=prompt,
schema=RelationshipPairList,
model=model,
api_key=api_key,
)
class MergedRelationship(BaseModel):
"""Result of merging two relationships."""
source_entity: str
target_entity: str
description: str
relationship_type: str
@app.reasoner()
async def merge_relationship_pair(
rel1: Relationship,
rel2: Relationship,
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> MergedRelationship:
"""Merges two specific relationships into one."""
prompt = f"""
<relationship1>
Source: {rel1.source_entity}
Target: {rel1.target_entity}
Description: {rel1.description}
Type: {rel1.relationship_type}
</relationship1>
<relationship2>
Source: {rel2.source_entity}
Target: {rel2.target_entity}
Description: {rel2.description}
Type: {rel2.relationship_type}
</relationship2>
<instructions>
Merge these relationships into a single, comprehensive relationship.
- Use the most accurate entity names
- Create a description that captures the complete relationship
- Choose the most appropriate relationship type
</instructions>
"""
return await ai_with_dynamic_params(
system="You are a Relationship Merger. Combine relationships without losing information.",
user=prompt,
schema=MergedRelationship,
model=model,
api_key=api_key,
)
def batch_list(items: List, batch_size: int) -> List[List]:
"""Split a list into batches of specified size."""
return [items[i : i + batch_size] for i in range(0, len(items), batch_size)]
async def process_relationship_consolidation_parallel(
all_relationships: List[Relationship],
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> List[Relationship]:
"""Consolidates relationships using parallel processing."""
if len(all_relationships) <= 1:
return all_relationships
# Create batches for parallel processing
if len(all_relationships) <= 30:
rel_batches = [all_relationships]
else:
rel_batches = batch_list(all_relationships, 15)
# Step 1: Detect duplicates in all batches in parallel
# Get dynamic context from relationships being processed
if all_relationships:
sample_entities = set()
for rel in all_relationships[:3]:
sample_entities.add(rel.source_entity)
sample_entities.add(rel.target_entity)
entities_context = ", ".join(list(sample_entities)[:3])
if len(sample_entities) > 3:
entities_context += "…"
app.note(f"Mapping connections between {entities_context}…")
else:
app.note("Mapping connections between key players…")
batch_tasks = [
detect_relationship_duplicates_batch(batch, model=model, api_key=api_key)
for batch in rel_batches
]
batch_results = await run_in_batches(batch_tasks, AI_CALL_CONCURRENCY_LIMIT)
# Step 2: Collect all duplicate pairs and create lookup
all_duplicate_pairs = []
for result in batch_results:
if result and hasattr(result, "pairs"):
all_duplicate_pairs.extend(result.pairs)
# Step 3: Create relationship lookup and prepare merge tasks
rel_dict = {}
for rel in all_relationships:
key = (rel.source_entity, rel.target_entity, rel.description)
rel_dict[key] = rel
merge_tasks = []
pairs_to_process = []
for pair in all_duplicate_pairs:
# Find relationships by description
rel1 = next(
(
r
for r in all_relationships
if r.description == pair.relationship1_description
),
None,
)
rel2 = next(
(
r
for r in all_relationships
if r.description == pair.relationship2_description
),
None,
)
if rel1 and rel2:
merge_tasks.append(
merge_relationship_pair(rel1, rel2, model=model, api_key=api_key)
)
pairs_to_process.append((rel1, rel2))
# Step 4: Execute all merges in parallel
if merge_tasks:
app.note("Connecting the dots between relationships…")
merge_results = await run_in_batches(merge_tasks, AI_CALL_CONCURRENCY_LIMIT)
# Step 5: Apply merge results
for i, merged in enumerate(merge_results):
if merged and i < len(pairs_to_process):
rel1, rel2 = pairs_to_process[i]
merged_rel = Relationship(
source_entity=merged.source_entity,
target_entity=merged.target_entity,
description=merged.description,
relationship_type=merged.relationship_type,
)
# Update relationships dict
new_key = (
merged.source_entity,
merged.target_entity,
merged.description,
)
rel_dict[new_key] = merged_rel
# Remove originals
old_key1 = (rel1.source_entity, rel1.target_entity, rel1.description)
old_key2 = (rel2.source_entity, rel2.target_entity, rel2.description)
rel_dict.pop(old_key1, None)
rel_dict.pop(old_key2, None)
return list(rel_dict.values())
@app.reasoner()
async def check_evidence_duplication(
evidence1: ArticleEvidence,
evidence2: ArticleEvidence,
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> EvidenceDeduplication:
"""Checks if two pieces of evidence are duplicates."""
prompt = f"""
<evidence1>
Summary: {evidence1.relevance_summary}
Facts: {evidence1.facts[:3]}
Quotes: {evidence1.quotes[:2]}
</evidence1>
<evidence2>
Summary: {evidence2.relevance_summary}
Facts: {evidence2.facts[:3]}
Quotes: {evidence2.quotes[:2]}
</evidence2>
<instructions>
Determine if these represent duplicate/redundant evidence.
Consider them duplicates if they convey essentially the same information.
</instructions>
"""
return await ai_with_dynamic_params(
system="You are an Evidence Analyst. Determine if evidence pieces are duplicates.",
user=prompt,
schema=EvidenceDeduplication,
model=model,
api_key=api_key,
)
async def process_evidence_deduplication_parallel(
all_evidence: List[ArticleEvidence],
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> List[ArticleEvidence]:
"""Advanced evidence deduplication using parallel AI analysis."""
if len(all_evidence) <= 1:
return all_evidence
# Step 1: Basic hash-based deduplication
unique_evidence = []
seen_hashes = set()
for evidence in all_evidence:
evidence_content = f"{evidence.relevance_summary}{''.join(evidence.facts[:3])}"
evidence_hash = create_content_hash(evidence_content)
if evidence_hash not in seen_hashes:
seen_hashes.add(evidence_hash)
unique_evidence.append(evidence)
# Step 2: AI-based similarity checking for remaining evidence
if len(unique_evidence) <= 20: # Only use AI for manageable sizes
similarity_tasks = []
pairs_to_check = []
for i in range(len(unique_evidence)):
for j in range(i + 1, len(unique_evidence)):
similarity_tasks.append(
check_evidence_duplication(
unique_evidence[i],
unique_evidence[j],
model=model,
api_key=api_key,
)
)
pairs_to_check.append((i, j))
if similarity_tasks:
# Show what we're cross-referencing
sample_sources = [
f"source {unique_evidence[i].article_id}"
for i in range(min(3, len(unique_evidence)))
]
sources_context = ", ".join(sample_sources)
if len(unique_evidence) > 3:
sources_context += f" and {len(unique_evidence) - 3} others"
app.note(f"Analyzing insights from {sources_context}…")
similarity_results = await run_in_batches(
similarity_tasks, AI_CALL_CONCURRENCY_LIMIT
)
# Remove duplicates based on AI analysis
indices_to_remove = set()
for k, result in enumerate(similarity_results):
if result and result.is_duplicate and k < len(pairs_to_check):
i, j = pairs_to_check[k]
indices_to_remove.add(j) # Remove the second one
unique_evidence = [
evidence
for i, evidence in enumerate(unique_evidence)
if i not in indices_to_remove
]
return unique_evidence
@app.reasoner()
async def generate_adaptive_hypothesis(
query: str,
query_type: str,
key_discoveries: List[str],
entities: List[Entity],
relationships: List[Relationship],
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> ResearchHypothesis:
"""Generates adaptive hypothesis based on query type and domain."""
# Create rich context from extracted network
entities_xml = "\n".join(
[
f'<entity name="{e.name}" type="{e.type}">{e.summary}</entity>'
for e in entities[:20]
]
)
relationships_xml = "\n".join(
[
f"<relationship>{r.source_entity} {r.description} {r.target_entity} (type: {r.relationship_type})</relationship>"
for r in relationships[:15]
]
)
discoveries_xml = "\n".join(
[f"<discovery>{discovery}</discovery>" for discovery in key_discoveries]
)
# Adaptive system prompts based on query type
domain_frameworks = {
"Market_Intelligence": {
"persona": "You are a Market Strategy Analyst synthesizing market intelligence into strategic insights.",
"thesis_focus": "market opportunity, competitive dynamics, and strategic positioning",
"strengths_focus": "market drivers, competitive advantages, and growth opportunities",
"risks_focus": "market risks, competitive threats, and adoption barriers",
},
"Entity_Analysis": {
"persona": "You are a Strategic Analyst evaluating entities and their systemic importance.",
"thesis_focus": "entity capabilities, strategic position, and systemic impact",
"strengths_focus": "core capabilities, strategic assets, and competitive advantages",
"risks_focus": "operational risks, strategic vulnerabilities, and external threats",
},
"Competitive_Analysis": {
"persona": "You are a Competitive Intelligence Analyst mapping competitive landscapes.",
"thesis_focus": "competitive positioning, differentiation, and market dynamics",
"strengths_focus": "competitive advantages, market position, and strategic assets",
"risks_focus": "competitive threats, market shifts, and strategic vulnerabilities",
},
"Technology_Assessment": {
"persona": "You are a Technology Strategy Analyst evaluating technological capabilities and trends.",
"thesis_focus": "technological capabilities, innovation potential, and adoption dynamics",
"strengths_focus": "technical advantages, innovation capacity, and adoption drivers",
"risks_focus": "technical limitations, obsolescence risks, and adoption barriers",
},
}
framework = domain_frameworks.get(query_type, domain_frameworks["Entity_Analysis"])
prompt = f"""
<mission>
{framework["persona"]} Your task is to synthesize comprehensive research findings into a testable strategic hypothesis.
</mission>
<research_context>
<original_query>{query}</original_query>
<query_classification>{query_type}</query_classification>
</research_context>
<comprehensive_research_findings>
<key_discoveries>
{discoveries_xml}
</key_discoveries>
<extracted_entities>
{entities_xml}
</extracted_entities>
<discovered_relationships>
{relationships_xml}
</discovered_relationships>
</comprehensive_research_findings>
<hypothesis_synthesis_framework>
**Core Thesis Development:**
Focus on {framework["thesis_focus"]}. Synthesize the research findings into a single, testable central argument that addresses the original query. The thesis should:
- Integrate insights from entities, relationships, and discoveries
- Be specific and actionable rather than generic
- Make a clear claim that can be supported or refuted by evidence
**Supporting Strengths Analysis:**
Identify factors related to {framework["strengths_focus"]} that support the core thesis:
- Draw from entity capabilities and relationship advantages
- Reference specific discoveries that strengthen the position
- Focus on sustainable competitive advantages or strategic assets
**Counter Risks Assessment:**
Identify factors related to {framework["risks_focus"]} that could challenge the thesis:
- Consider entity vulnerabilities and relationship weaknesses
- Include external threats and market risks from discoveries
- Focus on factors that could invalidate the core argument
**Knowledge Gaps Identification:**
What critical questions remain unanswered that would strengthen or weaken the thesis:
- Missing information about key entities or relationships
- Uncertain causation or correlation in discovered patterns
- External factors not yet investigated that could impact conclusions
</hypothesis_synthesis_framework>
<instructions>
Synthesize the comprehensive research findings into a structured hypothesis:
1. **Core Thesis**: A single, clear statement that synthesizes the main finding/conclusion
2. **Supporting Strengths**: 3-5 key factors that support the thesis based on the research
3. **Counter Risks**: 3-5 significant risks or weaknesses that could challenge the thesis
4. **Key Unknowns**: 3-5 critical unanswered questions that need investigation
Ensure the hypothesis directly addresses the original query and integrates insights from the entity/relationship network analysis.
</instructions>
"""
return await ai_with_dynamic_params(
system=framework["persona"]
+ " You synthesize comprehensive research into testable strategic hypotheses that integrate network analysis with domain expertise.",
user=prompt,
schema=ResearchHypothesis, # Reuse schema but make it domain-adaptive
model=model,
api_key=api_key,
)
# ==============================================================================
# ORCHESTRATOR & PUBLIC API REASONERS
# ==============================================================================
@app.reasoner()
async def assess_research_completeness(
query: str,
entities: List[Entity],
relationships: List[Relationship],
key_discoveries: List[str],
hypothesis_confidence: str,
model: Optional[str] = None,
api_key: Optional[str] = None,
) -> ResearchQualityScore:
"""Evaluates the completeness and quality of current research state."""
entity_count = len(entities)