Repository navigation
Expand file tree
/
Copy pathapi.py
More file actions
760 lines (668 loc) · 28.1 KB
/
Copy pathapi.py
File metadata and controls
760 lines (668 loc) · 28.1 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
"""
Elegant top-level API for OpenContracts LLM framework.
This module provides a simple interface for creating document or corpus agents.
"""
import logging
from typing import Any, Callable, Literal, Optional, TypeVar, Union, cast
from django.conf import settings
from opencontractserver.conversations.models import ChatMessage, Conversation
from opencontractserver.corpuses.models import Corpus
from opencontractserver.documents.models import Document
from opencontractserver.llms.agents.agent_factory import UnifiedAgentFactory
from opencontractserver.llms.agents.core_agents import CoreAgent
from opencontractserver.llms.tools.tool_factory import CoreTool, create_document_tools
from opencontractserver.llms.types import AgentFramework
from opencontractserver.llms.vector_stores.vector_store_factory import (
UnifiedVectorStoreFactory,
)
from opencontractserver.utils.embeddings import generate_embeddings_from_text
from opencontractserver.utils.tools import as_core_tool
logger = logging.getLogger(__name__)
# Type aliases for cleaner API
FrameworkType = Union[AgentFramework, Literal["pydantic_ai"]]
DocumentType = Union[str, int, Document]
CorpusType = Union[str, int, Corpus]
ToolType = Union[str, CoreTool, Callable[..., Any]]
# Type variable for structured responses
T = TypeVar("T")
class AgentAPI:
"""Simple API for creating document and corpus agents."""
@staticmethod
async def for_document(
document: DocumentType,
corpus: Optional[CorpusType] = None,
*,
framework: Optional[FrameworkType] = None,
user_id: Optional[int] = None,
model: Optional[str] = None,
agent_preferred_llm: Optional[str] = None,
system_prompt: Optional[str] = None,
conversation: Optional[Conversation] = None,
conversation_id: Optional[int] = None,
messages: Optional[list[ChatMessage]] = None,
temperature: float = 0.7,
max_tokens: Optional[int] = None,
streaming: bool = True,
tools: Optional[list[ToolType]] = None,
embedder: Optional[str] = None,
verbose: bool = False,
persist: Optional[bool] = None,
**kwargs,
) -> CoreAgent:
"""
Create a document agent with minimal configuration.
Args:
document: Document ID, instance, or path
framework: "pydantic_ai"
user_id: User ID for message attribution (None = anonymous/ephemeral session)
model: LLM model name (e.g., "gpt-4", "claude-3-sonnet"). Per-call
override — wins over every persisted default.
agent_preferred_llm: Per-agent override
(``AgentConfiguration.preferred_llm``). Wins over the corpus
default but loses to a per-call ``model=``.
system_prompt: Custom system prompt (auto-generated if None)
conversation: Existing conversation object to continue
conversation_id: Existing conversation ID to load
messages: Pre-loaded chat messages
temperature: Temperature for response generation (0.0-2.0)
max_tokens: Maximum tokens in response
streaming: Enable streaming responses
tools: List of tool names, CoreTool instances, or functions
embedder: Custom embedder path
verbose: Enable verbose logging
persist: Optional persistence flag
**kwargs: Additional framework-specific options
Returns:
CoreAgent: Ready-to-use agent implementing the CoreAgent protocol
Examples:
# Anonymous conversation (ephemeral, not stored)
agent = await agents.for_document(123)
response = await agent.chat("What is this about?")
# conversation_id will be None - nothing persisted
# Persistent conversation with user tracking
agent = await agents.for_document(
document=my_doc,
user_id=456, # Required for persistence
conversation_id=789, # Continue existing conversation
framework="pydantic_ai"
)
# Continue persistent conversation later
conversation_id = agent.get_conversation_id() # Real ID if user_id provided
new_agent = await agents.for_document(123, user_id=456, conversation_id=conversation_id)
# With custom configuration
agent = await agents.for_document(
document=my_doc,
framework="pydantic_ai",
model="gpt-4",
temperature=0.3,
system_prompt="You are a legal expert...",
tools=["summarize", "extract_entities"],
user_id=456 # Include for persistence
)
"""
# Resolve default framework if caller did not specify one
resolved_framework = _resolve_framework(framework)
# Convert tool names to CoreTool instances
# ``_resolve_tools`` returns ``list[CoreTool]``; the factory parameter
# is the wider ``list[Union[CoreTool, Callable, str]]`` so it can also
# accept un-resolved tool spec lists from other callers. ``list`` is
# invariant in the type system, so we cast through the wider alias.
resolved_tools: Optional[list[Union[CoreTool, Callable[..., Any], str]]] = (
cast(
"list[Union[CoreTool, Callable[..., Any], str]]",
_resolve_tools(tools),
)
if tools
else None
)
# If caller explicitly disabled persistence we propagate the flags via **kwargs
persistence_overrides: dict[str, Any] = {}
if persist is False:
persistence_overrides = {
"store_user_messages": False,
"store_llm_messages": False,
}
return await UnifiedAgentFactory.create_document_agent(
document,
corpus,
framework=resolved_framework,
user_id=user_id,
conversation=conversation,
conversation_id=conversation_id,
loaded_messages=messages,
model=model,
agent_preferred_llm=agent_preferred_llm,
system_prompt=system_prompt,
temperature=temperature,
max_tokens=max_tokens,
streaming=streaming,
embedder_path=embedder,
tools=resolved_tools,
verbose=verbose,
**persistence_overrides,
**kwargs,
)
@staticmethod
async def for_corpus(
corpus: Union[str, int, Corpus],
*,
framework: Optional[FrameworkType] = None,
user_id: Optional[int] = None,
model: Optional[str] = None,
agent_preferred_llm: Optional[str] = None,
system_prompt: Optional[str] = None,
conversation: Optional[Conversation] = None,
conversation_id: Optional[int] = None,
messages: Optional[list[ChatMessage]] = None,
temperature: float = 0.7,
max_tokens: Optional[int] = None,
streaming: bool = True,
tools: Optional[list[ToolType]] = None,
embedder: Optional[str] = None,
verbose: bool = False,
persist: Optional[bool] = None,
**kwargs,
) -> CoreAgent:
"""
Create a corpus agent with minimal configuration.
Args:
corpus_id: Corpus ID
framework: "pydantic_ai"
user_id: User ID for message attribution (None = anonymous/ephemeral session)
model: LLM model name (e.g., "gpt-4", "claude-3-sonnet"). Per-call
override — wins over every persisted default.
agent_preferred_llm: Per-agent override
(``AgentConfiguration.preferred_llm``). Wins over the corpus
default but loses to a per-call ``model=``.
system_prompt: Custom system prompt (auto-generated if None)
conversation: Existing conversation object to continue
conversation_id: Existing conversation ID to load
messages: Pre-loaded chat messages
temperature: Temperature for response generation (0.0-2.0)
max_tokens: Maximum tokens in response
streaming: Enable streaming responses
tools: List of tool names, CoreTool instances, or functions
embedder: Custom embedder path (uses corpus default if None)
verbose: Enable verbose logging
persist: Optional persistence flag
**kwargs: Additional framework-specific options
Returns:
CoreAgent: Ready-to-use agent implementing the CoreAgent protocol
Examples:
# Anonymous conversation (ephemeral, not stored)
agent = await agents.for_corpus(456)
response = await agent.chat("What are the key themes?")
# conversation_id will be None - nothing persisted
# Persistent conversation with user tracking
agent = await agents.for_corpus(
corpus=456,
user_id=123, # Required for persistence
conversation_id=789 # Continue existing conversation
)
# Continue persistent conversation later
conversation_id = agent.get_conversation_id() # Real ID if user_id provided
new_agent = await agents.for_corpus(456, user_id=123, conversation_id=conversation_id)
# With streaming and custom model
agent = await agents.for_corpus(
corpus_id=456,
framework="pydantic_ai",
model="claude-3-sonnet",
temperature=0.5,
streaming=True,
user_id=123 # Include for persistence
)
async for chunk in agent.stream("Summarize findings"):
print(chunk.content, end="")
"""
# Resolve default framework if caller did not specify one
resolved_framework = _resolve_framework(
framework, setting_name="LLMS_CORPUS_AGENT_FRAMEWORK"
)
# Convert tool names to CoreTool instances
# ``_resolve_tools`` returns ``list[CoreTool]``; the factory parameter
# is the wider ``list[Union[CoreTool, Callable, str]]`` so it can also
# accept un-resolved tool spec lists from other callers. ``list`` is
# invariant in the type system, so we cast through the wider alias.
resolved_tools: Optional[list[Union[CoreTool, Callable[..., Any], str]]] = (
cast(
"list[Union[CoreTool, Callable[..., Any], str]]",
_resolve_tools(tools),
)
if tools
else None
)
# If caller explicitly disabled persistence we propagate the flags via **kwargs
persistence_overrides: dict[str, Any] = {}
if persist is False:
persistence_overrides = {
"store_user_messages": False,
"store_llm_messages": False,
}
return await UnifiedAgentFactory.create_corpus_agent(
corpus,
framework=resolved_framework,
user_id=user_id,
conversation=conversation,
conversation_id=conversation_id,
loaded_messages=messages,
model=model,
agent_preferred_llm=agent_preferred_llm,
system_prompt=system_prompt,
temperature=temperature,
max_tokens=max_tokens,
streaming=streaming,
embedder_path=embedder,
tools=resolved_tools,
verbose=verbose,
**persistence_overrides,
**kwargs,
)
@staticmethod
async def get_structured_response_from_document(
document: DocumentType,
corpus: Optional[CorpusType],
prompt: str,
target_type: type[T],
*,
framework: Optional[FrameworkType] = None,
user_id: Optional[int] = None,
model: Optional[str] = None,
temperature: float = 0.7,
max_tokens: Optional[int] = None,
tools: Optional[list[ToolType]] = None,
embedder: Optional[str] = None,
**kwargs,
) -> Optional[T]:
"""
Extract structured data from a document in a one-shot, ephemeral manner.
This method creates a temporary agent, performs the extraction, and returns
the result without storing any conversation history.
Args:
document: Document ID, instance, or path
corpus: Corpus ID, instance, or path (optional - None for documents not in a corpus)
prompt: Natural language prompt for data extraction
target_type: Python type for the desired output (e.g., int, str, list[str], MyPydanticModel)
framework: "pydantic_ai" (defaults to pydantic_ai for structured extraction)
user_id: User ID (not used for persistence in this method)
model: LLM model name (e.g., "gpt-4", "claude-3-sonnet")
temperature: Temperature for response generation (0.0-2.0)
max_tokens: Maximum tokens in response
tools: List of tools to use during extraction
embedder: Custom embedder path
**kwargs: Additional framework-specific options
Returns:
Instance of target_type if successful, None if extraction failed
Examples:
# Extract a simple type
page_count = await agents.get_structured_response_from_document(
document=123,
corpus=456,
prompt="How many pages are in this document?",
target_type=int
)
# Extract a list
parties = await agents.get_structured_response_from_document(
document=doc,
corpus=corpus,
prompt="List all parties mentioned in this contract",
target_type=list[str]
)
# Extract structured data using Pydantic
from pydantic import BaseModel
class ContractTerms(BaseModel):
start_date: str
end_date: str
total_value: float
parties: list[str]
terms = await agents.get_structured_response_from_document(
document=doc,
corpus=corpus,
prompt="Extract the key contract terms",
target_type=ContractTerms,
model="gpt-4",
temperature=0.3
)
"""
# Default to pydantic_ai for structured extraction
if framework is None:
framework = AgentFramework.PYDANTIC_AI
# Create ephemeral agent with persistence disabled
agent = await AgentAPI.for_document(
document=document,
corpus=corpus,
framework=framework,
user_id=user_id,
model=model,
temperature=temperature,
max_tokens=max_tokens,
streaming=False, # No streaming for structured responses
tools=tools,
embedder=embedder,
persist=False, # Ensure no persistence
**kwargs,
)
# Use the structured_response method
return await agent.structured_response(
prompt=prompt,
target_type=target_type,
model=model,
temperature=temperature,
max_tokens=max_tokens,
**kwargs,
)
@staticmethod
async def get_structured_response_and_sources_from_document(
document: DocumentType,
corpus: Optional[CorpusType],
prompt: str,
target_type: type[T],
*,
framework: Optional[FrameworkType] = None,
user_id: Optional[int] = None,
model: Optional[str] = None,
temperature: float = 0.7,
max_tokens: Optional[int] = None,
tools: Optional[list[ToolType]] = None,
embedder: Optional[str] = None,
**kwargs,
) -> tuple[Optional[T], list[int]]:
"""Like :meth:`get_structured_response_from_document`, plus citations.
Returns a tuple of ``(result, annotation_ids)`` where
``annotation_ids`` is the deduplicated list of real Annotation PKs
that the agent's retrieval tools (similarity_search, …) returned
during this run. Callers use the IDs to populate M2M source links
on the owning object (``Datacell.sources`` for extraction,
``ChatMessage.source_annotations`` for chat).
Synthetic / negative IDs produced by ad-hoc match tools are filtered
out inside the retrieval tools themselves.
"""
if framework is None:
framework = AgentFramework.PYDANTIC_AI
# Config-time kwargs (vector store / agent construction) belong on
# ``for_document``; ``structured_response`` only accepts run-time
# kwargs (filtered through its own allowlist), so don't double-pass.
config_only_keys = {"similarity_top_k"}
run_kwargs = {k: v for k, v in kwargs.items() if k not in config_only_keys}
agent = await AgentAPI.for_document(
document=document,
corpus=corpus,
framework=framework,
user_id=user_id,
model=model,
temperature=temperature,
max_tokens=max_tokens,
streaming=False,
tools=tools,
embedder=embedder,
persist=False,
**kwargs,
)
result = await agent.structured_response(
prompt=prompt,
target_type=target_type,
model=model,
temperature=temperature,
max_tokens=max_tokens,
**run_kwargs,
)
# The tool implementations appended to this list during the run.
# Dedupe while preserving order of first occurrence so the most
# relevant (earliest retrieved) citations come first.
agent_deps = getattr(agent, "agent_deps", None)
raw_ids = getattr(agent_deps, "retrieved_annotation_ids", []) or []
seen: set[int] = set()
annotation_ids: list[int] = []
for aid in raw_ids:
if isinstance(aid, int) and aid > 0 and aid not in seen:
seen.add(aid)
annotation_ids.append(aid)
return result, annotation_ids
@staticmethod
async def get_structured_response_from_corpus(
corpus: CorpusType,
prompt: str,
target_type: type[T],
*,
framework: Optional[FrameworkType] = None,
user_id: Optional[int] = None,
model: Optional[str] = None,
temperature: float = 0.7,
max_tokens: Optional[int] = None,
tools: Optional[list[ToolType]] = None,
embedder: Optional[str] = None,
**kwargs,
) -> Optional[T]:
"""
Extract structured data from a corpus in a one-shot, ephemeral manner.
This method creates a temporary agent, performs the extraction, and returns
the result without storing any conversation history.
Args:
corpus: Corpus ID, instance, or path
prompt: Natural language prompt for data extraction
target_type: Python type for the desired output (e.g., int, str, list[str], MyPydanticModel)
framework: "pydantic_ai" (defaults to pydantic_ai for structured extraction)
user_id: User ID (not used for persistence in this method)
model: LLM model name (e.g., "gpt-4", "claude-3-sonnet")
temperature: Temperature for response generation (0.0-2.0)
max_tokens: Maximum tokens in response
tools: List of tools to use during extraction
embedder: Custom embedder path
**kwargs: Additional framework-specific options
Returns:
Instance of target_type if successful, None if extraction failed
Examples:
# Extract a count across documents
doc_count = await agents.get_structured_response_from_corpus(
corpus=456,
prompt="How many documents contain confidentiality clauses?",
target_type=int
)
# Extract a summary structure
from pydantic import BaseModel
class CorpusSummary(BaseModel):
main_themes: list[str]
document_count: int
key_entities: list[str]
date_range: dict[str, str]
summary = await agents.get_structured_response_from_corpus(
corpus=corpus,
prompt="Provide a comprehensive summary of this corpus",
target_type=CorpusSummary,
model="gpt-4",
temperature=0.5
)
"""
# Default to pydantic_ai for structured extraction
if framework is None:
framework = AgentFramework.PYDANTIC_AI
# Create ephemeral agent with persistence disabled
agent = await AgentAPI.for_corpus(
corpus=corpus,
framework=framework,
user_id=user_id,
model=model,
temperature=temperature,
max_tokens=max_tokens,
streaming=False, # No streaming for structured responses
tools=tools,
embedder=embedder,
persist=False, # Ensure no persistence
**kwargs,
)
# Use the structured_response method
return await agent.structured_response(
prompt=prompt,
target_type=target_type,
model=model,
temperature=temperature,
max_tokens=max_tokens,
**kwargs, # Pass through any additional kwargs like extra_context
)
class EmbeddingAPI:
"""Simple API for generating embeddings."""
@staticmethod
def generate(
text: str,
*,
corpus_id: Optional[int] = None,
mimetype: Optional[str] = None,
embedder: Optional[str] = None,
) -> tuple[Optional[str], Optional[list[float]]]:
"""
Generate embeddings for text using the OpenContracts pipeline.
Args:
text: Text to embed
corpus_id: Optional corpus ID for context-specific embedding
mimetype: Currently a no-op, kept for call-site compatibility.
Per-MIME embedder resolution was removed (issue #2114): mixing
embedder classes/dimensions per MIME type would fragment the
single global, cross-corpus vector index. Use ``embedder`` for
an explicit override.
embedder: Optional custom embedder path
Returns:
Tuple of (embedder_path, embedding_vector)
Examples:
# Simple embedding
embedder_path, vector = embeddings.generate("Hello world")
# With corpus context
embedder_path, vector = embeddings.generate(
"Legal document text",
corpus_id=123,
)
"""
return generate_embeddings_from_text(
text=text, corpus_id=corpus_id, mimetype=mimetype, embedder_path=embedder
)
class ToolAPI:
"""Simple API for working with tools."""
@staticmethod
def document_tools() -> list[CoreTool]:
"""Get standard document-related tools."""
return create_document_tools()
@staticmethod
def from_function(
func: Callable[..., Any],
*,
name: Optional[str] = None,
description: Optional[str] = None,
parameter_descriptions: Optional[dict[str, str]] = None,
) -> CoreTool:
"""
Create a CoreTool from a Python function.
Args:
func: Python function to wrap
name: Optional custom name
description: Optional custom description
parameter_descriptions: Optional parameter descriptions
Returns:
CoreTool instance
Examples:
def my_tool(query: str) -> str:
'''Search for information.'''
return f"Results for: {query}"
tool = tools.from_function(my_tool)
"""
return CoreTool.from_function(
func=func,
name=name,
description=description,
parameter_descriptions=parameter_descriptions,
)
class VectorStoreAPI:
"""Simple API for working with vector stores."""
@staticmethod
def create(
*,
framework: Optional[FrameworkType] = None,
user_id: Optional[Union[str, int]] = None,
corpus_id: Optional[Union[str, int]] = None,
document_id: Optional[Union[str, int]] = None,
embedder_path: Optional[str] = None,
must_have_text: Optional[str] = None,
embed_dim: int = 384,
**kwargs,
) -> Any:
"""
Create a vector store using the specified framework.
Args:
framework: "pydantic_ai"
user_id: Filter by user ID
corpus_id: Filter by corpus ID
document_id: Filter by document ID
embedder_path: Path to embedder model to use
must_have_text: Filter by text content
embed_dim: Embedding dimension to use (384, 768, 1024, 1536, 3072, or 4096)
**kwargs: Additional framework-specific arguments
Returns:
Framework-specific vector store instance
Examples:
# Pydantic AI vector store
store = vector_stores.create("pydantic_ai", corpus_id=123)
# Pydantic AI vector store
store = vector_stores.create("pydantic_ai", document_id=456)
"""
# Resolve default framework if caller did not specify one. Vector
# stores have their own dedicated setting — the document-agent
# default would have been a leaky abstraction that surprised
# operators who wanted to tune the two independently. When the
# setting is absent ``_resolve_framework`` falls through to
# ``AgentFramework.PYDANTIC_AI``, the same default the agent paths
# use, so existing deployments continue to work without a settings
# change.
resolved_framework = _resolve_framework(
framework, setting_name="LLMS_VECTOR_STORE_FRAMEWORK"
)
return UnifiedVectorStoreFactory.create_vector_store(
framework=resolved_framework,
user_id=user_id,
corpus_id=corpus_id,
document_id=document_id,
embedder_path=embedder_path,
must_have_text=must_have_text,
embed_dim=embed_dim,
**kwargs,
)
def _resolve_tools(tools: list[ToolType]) -> list[CoreTool]:
"""Convert tool specifications to CoreTool instances.
String names are resolved via :class:`ToolFunctionRegistry`, which is
the single source of truth for tool name -> function mapping.
"""
from opencontractserver.llms.tools.tool_registry import ToolFunctionRegistry
registry = ToolFunctionRegistry.get()
resolved: list[CoreTool] = []
for tool in tools:
if isinstance(tool, str):
core_tool = registry.to_core_tool(tool)
if core_tool is not None:
resolved.append(core_tool)
else:
logger.warning("Unknown tool: %s", tool)
elif isinstance(tool, CoreTool) or callable(tool):
resolved.append(as_core_tool(tool))
else:
logger.warning("Invalid tool specification: %s", tool)
return resolved
def _resolve_framework(
framework: Optional[FrameworkType],
*,
setting_name: str = "LLMS_DOCUMENT_AGENT_FRAMEWORK",
) -> AgentFramework:
"""Coerce a caller-supplied framework spec into a concrete ``AgentFramework``.
Accepts ``None`` (falls back to the named Django setting / pydantic-ai
default), the literal framework name, or an ``AgentFramework`` member.
"""
resolved: Any = framework
if resolved is None:
resolved = getattr(settings, setting_name, AgentFramework.PYDANTIC_AI)
if isinstance(resolved, str):
resolved = AgentFramework(resolved)
if not isinstance(resolved, AgentFramework):
raise TypeError(
f"Could not resolve framework {framework!r} to an AgentFramework"
)
return resolved
# Create singleton instances for the agent API
agents = AgentAPI()
embeddings = EmbeddingAPI()
tools = ToolAPI()
vector_stores = VectorStoreAPI()