ovid-core 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ovid_core/__init__.py +83 -0
- ovid_core/adapters/__init__.py +0 -0
- ovid_core/adapters/pydantic_ai/__init__.py +19 -0
- ovid_core/adapters/pydantic_ai/_agent_errors.py +53 -0
- ovid_core/adapters/pydantic_ai/_agent_runtime.py +205 -0
- ovid_core/adapters/pydantic_ai/_agent_stream.py +234 -0
- ovid_core/adapters/pydantic_ai/_codex_http.py +107 -0
- ovid_core/adapters/pydantic_ai/_deferred_tools.py +140 -0
- ovid_core/adapters/pydantic_ai/_events.py +79 -0
- ovid_core/adapters/pydantic_ai/_extension_validation.py +39 -0
- ovid_core/adapters/pydantic_ai/_instruction_sources.py +28 -0
- ovid_core/adapters/pydantic_ai/_interrupted_replay.py +92 -0
- ovid_core/adapters/pydantic_ai/_journal.py +162 -0
- ovid_core/adapters/pydantic_ai/_provider_errors.py +60 -0
- ovid_core/adapters/pydantic_ai/_provider_retry.py +45 -0
- ovid_core/adapters/pydantic_ai/_request_parts.py +160 -0
- ovid_core/adapters/pydantic_ai/_response_parts.py +171 -0
- ovid_core/adapters/pydantic_ai/_run_input.py +130 -0
- ovid_core/adapters/pydantic_ai/_steering.py +94 -0
- ovid_core/adapters/pydantic_ai/_stream_events.py +231 -0
- ovid_core/adapters/pydantic_ai/_tool_collisions.py +78 -0
- ovid_core/adapters/pydantic_ai/_tool_context.py +62 -0
- ovid_core/adapters/pydantic_ai/_tool_execution.py +126 -0
- ovid_core/adapters/pydantic_ai/_tool_hooks.py +208 -0
- ovid_core/adapters/pydantic_ai/_usage_tracking.py +103 -0
- ovid_core/adapters/pydantic_ai/_user_content.py +104 -0
- ovid_core/adapters/pydantic_ai/ag_ui.py +178 -0
- ovid_core/adapters/pydantic_ai/agents.py +112 -0
- ovid_core/adapters/pydantic_ai/budget.py +16 -0
- ovid_core/adapters/pydantic_ai/capabilities.py +54 -0
- ovid_core/adapters/pydantic_ai/codex.py +226 -0
- ovid_core/adapters/pydantic_ai/compaction.py +151 -0
- ovid_core/adapters/pydantic_ai/effects.py +28 -0
- ovid_core/adapters/pydantic_ai/extensions.py +67 -0
- ovid_core/adapters/pydantic_ai/history.py +30 -0
- ovid_core/adapters/pydantic_ai/integrations.py +217 -0
- ovid_core/adapters/pydantic_ai/messages.py +161 -0
- ovid_core/adapters/pydantic_ai/models.py +176 -0
- ovid_core/adapters/pydantic_ai/results.py +167 -0
- ovid_core/adapters/pydantic_ai/routing.py +82 -0
- ovid_core/adapters/pydantic_ai/skills.py +43 -0
- ovid_core/adapters/pydantic_ai/tools.py +204 -0
- ovid_core/adapters/pydantic_ai/usage.py +56 -0
- ovid_core/adapters/pydantic_ai/web.py +50 -0
- ovid_core/adapters/pydantic_ai/web_read.py +95 -0
- ovid_core/adapters/starlette/__init__.py +1 -0
- ovid_core/adapters/starlette/ag_ui.py +108 -0
- ovid_core/adapters/starlette/app.py +216 -0
- ovid_core/adapters/starlette/http.py +137 -0
- ovid_core/agent_build.py +173 -0
- ovid_core/agent_definition.py +49 -0
- ovid_core/agent_runtime.py +215 -0
- ovid_core/agents.py +190 -0
- ovid_core/authentication/__init__.py +42 -0
- ovid_core/authentication/api_key.py +48 -0
- ovid_core/authentication/bindings.py +25 -0
- ovid_core/authentication/codex.py +161 -0
- ovid_core/authentication/contracts.py +57 -0
- ovid_core/authentication/models.py +92 -0
- ovid_core/authentication/providers.py +110 -0
- ovid_core/authentication/registry.py +108 -0
- ovid_core/capabilities/__init__.py +25 -0
- ovid_core/capabilities/base.py +89 -0
- ovid_core/capabilities/budget.py +36 -0
- ovid_core/capabilities/deferred.py +29 -0
- ovid_core/capabilities/history.py +16 -0
- ovid_core/capabilities/integrations.py +158 -0
- ovid_core/capabilities/specs.py +75 -0
- ovid_core/codex/__init__.py +12 -0
- ovid_core/codex/_browser.py +191 -0
- ovid_core/codex/_device.py +92 -0
- ovid_core/codex/_login.py +43 -0
- ovid_core/codex/_oauth.py +41 -0
- ovid_core/codex/auth.py +236 -0
- ovid_core/codex/catalog.py +47 -0
- ovid_core/codex/keyring.py +109 -0
- ovid_core/codex/models.py +59 -0
- ovid_core/codex/tokens.py +173 -0
- ovid_core/compaction/__init__.py +3 -0
- ovid_core/compaction/capability.py +46 -0
- ovid_core/compaction/models.py +12 -0
- ovid_core/config/__init__.py +10 -0
- ovid_core/config/migration.py +38 -0
- ovid_core/config/models.py +56 -0
- ovid_core/conversation_state.py +71 -0
- ovid_core/credentials/__init__.py +9 -0
- ovid_core/credentials/models.py +43 -0
- ovid_core/credentials/resolvers.py +32 -0
- ovid_core/errors.py +235 -0
- ovid_core/hooks/__init__.py +7 -0
- ovid_core/hooks/base.py +29 -0
- ovid_core/hooks/models.py +36 -0
- ovid_core/identifiers.py +9 -0
- ovid_core/journal.py +131 -0
- ovid_core/mcp/__init__.py +8 -0
- ovid_core/mcp/capability.py +63 -0
- ovid_core/mcp/models.py +57 -0
- ovid_core/messages/__init__.py +27 -0
- ovid_core/messages/content.py +53 -0
- ovid_core/messages/models.py +232 -0
- ovid_core/models.py +22 -0
- ovid_core/observability.py +10 -0
- ovid_core/persistence.py +149 -0
- ovid_core/plugins/__init__.py +20 -0
- ovid_core/plugins/activation.py +181 -0
- ovid_core/plugins/capability.py +46 -0
- ovid_core/plugins/discovery.py +86 -0
- ovid_core/plugins/host.py +124 -0
- ovid_core/plugins/models.py +45 -0
- ovid_core/plugins/registrar.py +223 -0
- ovid_core/policy.py +48 -0
- ovid_core/py.typed +0 -0
- ovid_core/read/__init__.py +20 -0
- ovid_core/read/capability.py +28 -0
- ovid_core/read/errors.py +14 -0
- ovid_core/read/handlers.py +98 -0
- ovid_core/read/models.py +121 -0
- ovid_core/read/registry.py +68 -0
- ovid_core/read/router.py +233 -0
- ovid_core/read/tool.py +102 -0
- ovid_core/read/window.py +53 -0
- ovid_core/recovery.py +107 -0
- ovid_core/relay/__init__.py +30 -0
- ovid_core/relay/_locking.py +22 -0
- ovid_core/relay/_state.py +40 -0
- ovid_core/relay/capability.py +30 -0
- ovid_core/relay/connection.py +73 -0
- ovid_core/relay/contracts.py +45 -0
- ovid_core/relay/errors.py +21 -0
- ovid_core/relay/memory.py +250 -0
- ovid_core/relay/models.py +42 -0
- ovid_core/relay/tools.py +163 -0
- ovid_core/routing/__init__.py +16 -0
- ovid_core/routing/factory.py +10 -0
- ovid_core/routing/models.py +85 -0
- ovid_core/routing/options.py +68 -0
- ovid_core/routing/router.py +93 -0
- ovid_core/runtime/__init__.py +20 -0
- ovid_core/runtime/context.py +16 -0
- ovid_core/runtime/events.py +138 -0
- ovid_core/runtime/identifiers.py +2 -0
- ovid_core/runtime/results.py +145 -0
- ovid_core/server/__init__.py +44 -0
- ovid_core/server/active_runs.py +222 -0
- ovid_core/server/ag_ui.py +22 -0
- ovid_core/server/app.py +53 -0
- ovid_core/server/contracts.py +136 -0
- ovid_core/server/conversations.py +218 -0
- ovid_core/server/errors.py +162 -0
- ovid_core/server/lifespan.py +28 -0
- ovid_core/server/models.py +100 -0
- ovid_core/server/registry.py +44 -0
- ovid_core/server/runtime.py +241 -0
- ovid_core/server/sessions.py +45 -0
- ovid_core/server/stdio.py +110 -0
- ovid_core/server/stdio_connection.py +245 -0
- ovid_core/server/stdio_models.py +102 -0
- ovid_core/services.py +169 -0
- ovid_core/sessions/__init__.py +7 -0
- ovid_core/sessions/hooks.py +56 -0
- ovid_core/sessions/runner.py +91 -0
- ovid_core/skills.py +126 -0
- ovid_core/todo/__init__.py +24 -0
- ovid_core/todo/_reducer_state.py +112 -0
- ovid_core/todo/capability.py +117 -0
- ovid_core/todo/errors.py +29 -0
- ovid_core/todo/models.py +208 -0
- ovid_core/todo/reducer.py +158 -0
- ovid_core/todo/service.py +49 -0
- ovid_core/todo/store.py +94 -0
- ovid_core/tools/__init__.py +20 -0
- ovid_core/tools/base.py +141 -0
- ovid_core/tools/deferred.py +96 -0
- ovid_core/tools/models.py +44 -0
- ovid_core/usage/__init__.py +5 -0
- ovid_core/usage/models.py +122 -0
- ovid_core/usage/tracking.py +92 -0
- ovid_core-0.1.0.dist-info/METADATA +304 -0
- ovid_core-0.1.0.dist-info/RECORD +181 -0
- ovid_core-0.1.0.dist-info/WHEEL +4 -0
- ovid_core-0.1.0.dist-info/licenses/LICENSE +21 -0
ovid_core/__init__.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
from ovid_core.adapters.pydantic_ai.agents import DefaultAgentCompiler as DefaultAgentCompiler
|
|
2
|
+
from ovid_core.adapters.pydantic_ai.models import DefaultModelFactory as DefaultModelFactory
|
|
3
|
+
from ovid_core.adapters.pydantic_ai.models import available_model_options as available_model_options
|
|
4
|
+
from ovid_core.agent_build import AgentBuildContext as AgentBuildContext
|
|
5
|
+
from ovid_core.agent_build import AgentConstructionDiagnostics as AgentConstructionDiagnostics
|
|
6
|
+
from ovid_core.agent_build import AgentExtensionProvenance as AgentExtensionProvenance
|
|
7
|
+
from ovid_core.agent_build import AgentServiceDiagnostic as AgentServiceDiagnostic
|
|
8
|
+
from ovid_core.agents import AgentCompiler as AgentCompiler
|
|
9
|
+
from ovid_core.agents import AgentDefinition as AgentDefinition
|
|
10
|
+
from ovid_core.agents import AgentFactory as AgentFactory
|
|
11
|
+
from ovid_core.agents import AgentModelSelector as AgentModelSelector
|
|
12
|
+
from ovid_core.agents import AgentRuntime as AgentRuntime
|
|
13
|
+
from ovid_core.agents import AgentStream as AgentStream
|
|
14
|
+
from ovid_core.agents import OvidAgent as OvidAgent
|
|
15
|
+
from ovid_core.agents import PreparedAgentDefinition as PreparedAgentDefinition
|
|
16
|
+
from ovid_core.capabilities.base import AgentCapabilityDescriptor as AgentCapabilityDescriptor
|
|
17
|
+
from ovid_core.credentials.resolvers import ProviderAPIKeyResolver as ProviderAPIKeyResolver
|
|
18
|
+
from ovid_core.errors import AgentConstructionError as AgentConstructionError
|
|
19
|
+
from ovid_core.errors import AgentRunError as AgentRunError
|
|
20
|
+
from ovid_core.errors import AgentRunInputError as AgentRunInputError
|
|
21
|
+
from ovid_core.errors import AgentTimeoutError as AgentTimeoutError
|
|
22
|
+
from ovid_core.errors import AuthenticationError as AuthenticationError
|
|
23
|
+
from ovid_core.errors import CodexAuthError as CodexAuthError
|
|
24
|
+
from ovid_core.errors import ConfigurationError as ConfigurationError
|
|
25
|
+
from ovid_core.errors import ContextWindowError as ContextWindowError
|
|
26
|
+
from ovid_core.errors import CredentialError as CredentialError
|
|
27
|
+
from ovid_core.errors import DeferredToolAnswerError as DeferredToolAnswerError
|
|
28
|
+
from ovid_core.errors import ExtensionCollisionError as ExtensionCollisionError
|
|
29
|
+
from ovid_core.errors import ModelResolutionError as ModelResolutionError
|
|
30
|
+
from ovid_core.errors import NothingToResumeError as NothingToResumeError
|
|
31
|
+
from ovid_core.errors import OvidCoreError as OvidCoreError
|
|
32
|
+
from ovid_core.errors import PersistenceConflictError as PersistenceConflictError
|
|
33
|
+
from ovid_core.errors import PersistenceError as PersistenceError
|
|
34
|
+
from ovid_core.errors import PluginError as PluginError
|
|
35
|
+
from ovid_core.errors import ProviderError as ProviderError
|
|
36
|
+
from ovid_core.errors import ResumeLimitError as ResumeLimitError
|
|
37
|
+
from ovid_core.errors import ServerConstructionError as ServerConstructionError
|
|
38
|
+
from ovid_core.errors import SessionHookError as SessionHookError
|
|
39
|
+
from ovid_core.errors import ToolApprovalRequired as ToolApprovalRequired
|
|
40
|
+
from ovid_core.errors import ToolDeferred as ToolDeferred
|
|
41
|
+
from ovid_core.errors import ToolError as ToolError
|
|
42
|
+
from ovid_core.errors import ToolExecutionError as ToolExecutionError
|
|
43
|
+
from ovid_core.errors import ToolRetryError as ToolRetryError
|
|
44
|
+
from ovid_core.errors import ToolTimeoutError as ToolTimeoutError
|
|
45
|
+
from ovid_core.errors import ToolValidationError as ToolValidationError
|
|
46
|
+
from ovid_core.errors import TransportError as TransportError
|
|
47
|
+
from ovid_core.errors import UsageLimitError as UsageLimitError
|
|
48
|
+
from ovid_core.models import BaseModel as BaseModel
|
|
49
|
+
from ovid_core.models import BaseRootModel as BaseRootModel
|
|
50
|
+
from ovid_core.observability import ObservabilityConfig as ObservabilityConfig
|
|
51
|
+
from ovid_core.persistence import ConversationHistoryStore as ConversationHistoryStore
|
|
52
|
+
from ovid_core.persistence import ConversationJournalStore as ConversationJournalStore
|
|
53
|
+
from ovid_core.persistence import ConversationStore as ConversationStore
|
|
54
|
+
from ovid_core.persistence import DeferredToolRequestStore as DeferredToolRequestStore
|
|
55
|
+
from ovid_core.persistence import InMemoryConversationStore as InMemoryConversationStore
|
|
56
|
+
from ovid_core.persistence import MessageCodec as MessageCodec
|
|
57
|
+
from ovid_core.plugins import AgentServiceConfiguratorFactory as AgentServiceConfiguratorFactory
|
|
58
|
+
from ovid_core.plugins import AgentServiceProviderFactory as AgentServiceProviderFactory
|
|
59
|
+
from ovid_core.plugins import CapabilityFactory as CapabilityFactory
|
|
60
|
+
from ovid_core.plugins import PluginActivationContext as PluginActivationContext
|
|
61
|
+
from ovid_core.plugins import PluginRegistrar as PluginRegistrar
|
|
62
|
+
from ovid_core.plugins import PluginServiceFactories as PluginServiceFactories
|
|
63
|
+
from ovid_core.policy import AgentRetryPolicy as AgentRetryPolicy
|
|
64
|
+
from ovid_core.policy import AgentRunPolicy as AgentRunPolicy
|
|
65
|
+
from ovid_core.policy import AgentUsageLimits as AgentUsageLimits
|
|
66
|
+
from ovid_core.policy import ProviderFailureKind as ProviderFailureKind
|
|
67
|
+
from ovid_core.policy import ProviderRetryPolicy as ProviderRetryPolicy
|
|
68
|
+
from ovid_core.routing.options import ModelProviderOption as ModelProviderOption
|
|
69
|
+
from ovid_core.routing.options import ModelSelectionOptions as ModelSelectionOptions
|
|
70
|
+
from ovid_core.routing.options import SelectionOption as SelectionOption
|
|
71
|
+
from ovid_core.services import AgentServiceBinding as AgentServiceBinding
|
|
72
|
+
from ovid_core.services import AgentServiceCollisionError as AgentServiceCollisionError
|
|
73
|
+
from ovid_core.services import AgentServiceCompatibilityError as AgentServiceCompatibilityError
|
|
74
|
+
from ovid_core.services import AgentServiceError as AgentServiceError
|
|
75
|
+
from ovid_core.services import AgentServiceKey as AgentServiceKey
|
|
76
|
+
from ovid_core.services import AgentServiceMissingError as AgentServiceMissingError
|
|
77
|
+
from ovid_core.services import AgentServiceRef as AgentServiceRef
|
|
78
|
+
from ovid_core.services import AgentServiceRequirement as AgentServiceRequirement
|
|
79
|
+
from ovid_core.services import AgentServices as AgentServices
|
|
80
|
+
from ovid_core.skills import SkillLibraryConfig as SkillLibraryConfig
|
|
81
|
+
from ovid_core.skills import SkillsCapability as SkillsCapability
|
|
82
|
+
from ovid_core.tools.models import AgentToolDescriptor as AgentToolDescriptor
|
|
83
|
+
from ovid_core.tools.models import AgentToolsetDescriptor as AgentToolsetDescriptor
|
|
File without changes
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from ovid_core.adapters.pydantic_ai.agents import DefaultAgentCompiler as DefaultAgentCompiler
|
|
2
|
+
from ovid_core.adapters.pydantic_ai.capabilities import pydantic_ai_capability as pydantic_ai_capability
|
|
3
|
+
from ovid_core.adapters.pydantic_ai.codex import CodexSubscriptionModelFactory as CodexSubscriptionModelFactory
|
|
4
|
+
from ovid_core.adapters.pydantic_ai.effects import resolve_effect as resolve_effect
|
|
5
|
+
from ovid_core.adapters.pydantic_ai.integrations import adapt_integration_capability as adapt_integration_capability
|
|
6
|
+
from ovid_core.adapters.pydantic_ai.integrations import inspect_mcp_server as inspect_mcp_server
|
|
7
|
+
from ovid_core.adapters.pydantic_ai.messages import message_from_pydantic as message_from_pydantic
|
|
8
|
+
from ovid_core.adapters.pydantic_ai.messages import message_to_pydantic as message_to_pydantic
|
|
9
|
+
from ovid_core.adapters.pydantic_ai.models import DefaultModelFactory as DefaultModelFactory
|
|
10
|
+
from ovid_core.adapters.pydantic_ai.models import available_api_key_model_options as available_api_key_model_options
|
|
11
|
+
from ovid_core.adapters.pydantic_ai.models import available_api_key_models as available_api_key_models
|
|
12
|
+
from ovid_core.adapters.pydantic_ai.models import available_model_options as available_model_options
|
|
13
|
+
from ovid_core.adapters.pydantic_ai.models import known_models as known_models
|
|
14
|
+
from ovid_core.adapters.pydantic_ai.results import result_from_pydantic as result_from_pydantic
|
|
15
|
+
from ovid_core.adapters.pydantic_ai.tools import PydanticAICapabilityAdapter as PydanticAICapabilityAdapter
|
|
16
|
+
from ovid_core.adapters.pydantic_ai.tools import PydanticAIToolsetAdapter as PydanticAIToolsetAdapter
|
|
17
|
+
from ovid_core.adapters.pydantic_ai.usage import aggregate_usage_from_pydantic as aggregate_usage_from_pydantic
|
|
18
|
+
from ovid_core.adapters.pydantic_ai.usage import request_usage_from_pydantic as request_usage_from_pydantic
|
|
19
|
+
from ovid_core.adapters.pydantic_ai.usage import usage_from_pydantic as usage_from_pydantic
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from pydantic import ValidationError
|
|
2
|
+
from pydantic_ai.exceptions import ModelAPIError, ModelHTTPError, UsageLimitExceeded
|
|
3
|
+
|
|
4
|
+
from ovid_core.adapters.pydantic_ai._provider_errors import is_context_window_error, provider_failure_kind
|
|
5
|
+
from ovid_core.errors import (
|
|
6
|
+
AgentRunError,
|
|
7
|
+
AgentTimeoutError,
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
ContextWindowError,
|
|
10
|
+
CredentialError,
|
|
11
|
+
OvidCoreError,
|
|
12
|
+
ProviderError,
|
|
13
|
+
UsageLimitError,
|
|
14
|
+
)
|
|
15
|
+
from ovid_core.policy import ProviderFailureKind
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def normalize_run_error(error: Exception) -> OvidCoreError:
|
|
19
|
+
input_limit_exceeded = isinstance(error, UsageLimitExceeded) and 'per_request_input_tokens_limit' in str(error)
|
|
20
|
+
if input_limit_exceeded or is_context_window_error(error):
|
|
21
|
+
return ContextWindowError('Model context window is full. Compact the conversation or start a new one')
|
|
22
|
+
if isinstance(error, AuthenticationError):
|
|
23
|
+
return AuthenticationError('Provider authentication failed')
|
|
24
|
+
if isinstance(error, CredentialError):
|
|
25
|
+
return CredentialError('Provider credentials are unavailable')
|
|
26
|
+
if isinstance(error, OvidCoreError):
|
|
27
|
+
return error
|
|
28
|
+
if provider_failure_kind(error) is ProviderFailureKind.AUTHENTICATION:
|
|
29
|
+
return AuthenticationError('Provider authentication failed')
|
|
30
|
+
if isinstance(error, TimeoutError):
|
|
31
|
+
return AgentTimeoutError('Agent run timed out')
|
|
32
|
+
if isinstance(error, UsageLimitExceeded):
|
|
33
|
+
return UsageLimitError('Agent usage limit exceeded')
|
|
34
|
+
if isinstance(error, ValidationError):
|
|
35
|
+
return AgentRunError('Pydantic AI returned invalid agent data')
|
|
36
|
+
if not isinstance(error, ModelAPIError):
|
|
37
|
+
return AgentRunError('Agent run failed')
|
|
38
|
+
|
|
39
|
+
kind = provider_failure_kind(error)
|
|
40
|
+
status_code = error.status_code if isinstance(error, ModelHTTPError) else None
|
|
41
|
+
message = f'Provider request failed ({kind})'
|
|
42
|
+
if status_code is not None:
|
|
43
|
+
message = f'Provider request failed ({kind}, status {status_code})'
|
|
44
|
+
if error.retry_after is not None:
|
|
45
|
+
message = f'{message}. The provider asked for a wait of {error.retry_after:g} seconds before a retry'
|
|
46
|
+
|
|
47
|
+
return ProviderError(
|
|
48
|
+
message,
|
|
49
|
+
failure_kind=kind,
|
|
50
|
+
status_code=status_code,
|
|
51
|
+
provider_code=error.provider_error_code,
|
|
52
|
+
retry_after_seconds=error.retry_after,
|
|
53
|
+
)
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
from collections.abc import AsyncGenerator, Generator, Sequence
|
|
4
|
+
from contextlib import AbstractAsyncContextManager, asynccontextmanager, contextmanager
|
|
5
|
+
from typing import Never
|
|
6
|
+
|
|
7
|
+
from pydantic_ai import Agent, capture_run_messages
|
|
8
|
+
from pydantic_ai.tools import DeferredToolRequests as PydanticDeferredToolRequests
|
|
9
|
+
|
|
10
|
+
from ovid_core.adapters.pydantic_ai._agent_errors import normalize_run_error
|
|
11
|
+
from ovid_core.adapters.pydantic_ai._agent_stream import PydanticAIStream
|
|
12
|
+
from ovid_core.adapters.pydantic_ai._run_input import RunInput, RunRequest
|
|
13
|
+
from ovid_core.adapters.pydantic_ai._usage_tracking import usage_limits
|
|
14
|
+
from ovid_core.adapters.pydantic_ai.compaction import ManualCompaction
|
|
15
|
+
from ovid_core.adapters.pydantic_ai.results import result_from_pydantic
|
|
16
|
+
from ovid_core.agent_runtime import AgentRuntime, AgentStream, PendingContent
|
|
17
|
+
from ovid_core.compaction.models import CompactionResult
|
|
18
|
+
from ovid_core.errors import CompactionUnavailableError, CredentialError
|
|
19
|
+
from ovid_core.messages.content import UserContent
|
|
20
|
+
from ovid_core.messages.models import AgentMessage, AppEntryPart
|
|
21
|
+
from ovid_core.persistence import RunJournal
|
|
22
|
+
from ovid_core.policy import AgentRunPolicy
|
|
23
|
+
from ovid_core.runtime.identifiers import ConversationId, RunId
|
|
24
|
+
from ovid_core.runtime.results import DeferredRunResult, RunResult
|
|
25
|
+
from ovid_core.tools.deferred import DeferredToolResume, InterruptedRunResume
|
|
26
|
+
from ovid_core.usage.tracking import UsageTracker
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PydanticAIAgentRuntime[Deps, Output](AgentRuntime[Deps, Output]):
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
*,
|
|
33
|
+
agent: Agent[Deps, Output],
|
|
34
|
+
policy: AgentRunPolicy,
|
|
35
|
+
stream_thinking: bool,
|
|
36
|
+
compaction: ManualCompaction | None,
|
|
37
|
+
) -> None:
|
|
38
|
+
self._agent = agent
|
|
39
|
+
self._policy = policy
|
|
40
|
+
self._stream_thinking = stream_thinking
|
|
41
|
+
self._compaction = compaction
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def upstream_agent(self) -> Agent[Deps, Output]:
|
|
45
|
+
return self._agent
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def policy(self) -> AgentRunPolicy:
|
|
49
|
+
return self._policy
|
|
50
|
+
|
|
51
|
+
async def run(
|
|
52
|
+
self,
|
|
53
|
+
prompt: str | Sequence[UserContent] | None,
|
|
54
|
+
*,
|
|
55
|
+
resume: DeferredToolResume | InterruptedRunResume | None,
|
|
56
|
+
deps: Deps,
|
|
57
|
+
messages: tuple[AgentMessage, ...],
|
|
58
|
+
run_id: RunId | None,
|
|
59
|
+
conversation_id: ConversationId | None,
|
|
60
|
+
usage_tracker: UsageTracker | None,
|
|
61
|
+
entries: tuple[AppEntryPart, ...],
|
|
62
|
+
) -> RunResult[Output] | DeferredRunResult:
|
|
63
|
+
request = RunRequest(
|
|
64
|
+
prompt=prompt,
|
|
65
|
+
resume=resume,
|
|
66
|
+
messages=messages,
|
|
67
|
+
run_id=run_id,
|
|
68
|
+
conversation_id=conversation_id,
|
|
69
|
+
usage_tracker=usage_tracker,
|
|
70
|
+
entries=entries,
|
|
71
|
+
)
|
|
72
|
+
run = RunInput[Deps].create(request, journal=None)
|
|
73
|
+
with _logged_run(run.run_id, run.conversation_id):
|
|
74
|
+
try:
|
|
75
|
+
async with asyncio.timeout(self._policy.timeout_seconds):
|
|
76
|
+
result = await self._agent.run(
|
|
77
|
+
run.prompt,
|
|
78
|
+
output_type=[self._agent.output_type, PydanticDeferredToolRequests],
|
|
79
|
+
deps=deps,
|
|
80
|
+
message_history=run.history,
|
|
81
|
+
deferred_tool_results=run.results,
|
|
82
|
+
run_id=str(run.run_id),
|
|
83
|
+
conversation_id=str(run.conversation_id),
|
|
84
|
+
usage_limits=usage_limits(self._policy),
|
|
85
|
+
capabilities=run.capabilities,
|
|
86
|
+
)
|
|
87
|
+
normalized = result_from_pydantic(result, approvals=run.approvals.approvals, transcript=run.transcript)
|
|
88
|
+
await run.recorder.record(normalized.usage)
|
|
89
|
+
except Exception as error:
|
|
90
|
+
_raise_normalized(error)
|
|
91
|
+
|
|
92
|
+
return normalized
|
|
93
|
+
|
|
94
|
+
async def compact(self, messages: tuple[AgentMessage, ...], *, instructions: str | None) -> CompactionResult:
|
|
95
|
+
if self._compaction is None:
|
|
96
|
+
raise CompactionUnavailableError('this agent has no compaction capability')
|
|
97
|
+
try:
|
|
98
|
+
return await self._compaction(messages, instructions=instructions)
|
|
99
|
+
except Exception as error:
|
|
100
|
+
_raise_normalized(error)
|
|
101
|
+
|
|
102
|
+
def stream(
|
|
103
|
+
self,
|
|
104
|
+
prompt: str | Sequence[UserContent] | None,
|
|
105
|
+
*,
|
|
106
|
+
resume: DeferredToolResume | InterruptedRunResume | None,
|
|
107
|
+
deps: Deps,
|
|
108
|
+
messages: tuple[AgentMessage, ...],
|
|
109
|
+
run_id: RunId | None,
|
|
110
|
+
conversation_id: ConversationId | None,
|
|
111
|
+
usage_tracker: UsageTracker | None,
|
|
112
|
+
journal: RunJournal | None,
|
|
113
|
+
entries: tuple[AppEntryPart, ...],
|
|
114
|
+
pending: PendingContent | None,
|
|
115
|
+
) -> AbstractAsyncContextManager[AgentStream[Output]]:
|
|
116
|
+
request = RunRequest(
|
|
117
|
+
prompt=prompt,
|
|
118
|
+
resume=resume,
|
|
119
|
+
messages=messages,
|
|
120
|
+
run_id=run_id,
|
|
121
|
+
conversation_id=conversation_id,
|
|
122
|
+
usage_tracker=usage_tracker,
|
|
123
|
+
entries=entries,
|
|
124
|
+
pending=pending,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
return self._stream(request, deps=deps, journal=journal)
|
|
128
|
+
|
|
129
|
+
@asynccontextmanager
|
|
130
|
+
async def _stream(
|
|
131
|
+
self,
|
|
132
|
+
request: RunRequest,
|
|
133
|
+
*,
|
|
134
|
+
deps: Deps,
|
|
135
|
+
journal: RunJournal | None,
|
|
136
|
+
) -> AsyncGenerator[AgentStream[Output]]:
|
|
137
|
+
run = RunInput[Deps].create(request, journal)
|
|
138
|
+
stream: PydanticAIStream[Output] | None = None
|
|
139
|
+
with capture_run_messages() as captured, _logged_run(run.run_id, run.conversation_id):
|
|
140
|
+
try:
|
|
141
|
+
async with (
|
|
142
|
+
asyncio.timeout(self._policy.timeout_seconds),
|
|
143
|
+
self._agent.run_stream_events(
|
|
144
|
+
run.prompt,
|
|
145
|
+
output_type=[self._agent.output_type, PydanticDeferredToolRequests],
|
|
146
|
+
deps=deps,
|
|
147
|
+
message_history=run.history,
|
|
148
|
+
deferred_tool_results=run.results,
|
|
149
|
+
run_id=str(run.run_id),
|
|
150
|
+
conversation_id=str(run.conversation_id),
|
|
151
|
+
usage_limits=usage_limits(self._policy),
|
|
152
|
+
capabilities=run.capabilities,
|
|
153
|
+
) as events,
|
|
154
|
+
):
|
|
155
|
+
stream = PydanticAIStream(
|
|
156
|
+
events=events,
|
|
157
|
+
run_id=run.run_id,
|
|
158
|
+
conversation_id=run.conversation_id,
|
|
159
|
+
approvals=run.approvals.approvals,
|
|
160
|
+
transcript=run.transcript,
|
|
161
|
+
steering=run.steering,
|
|
162
|
+
stream_thinking=self._stream_thinking,
|
|
163
|
+
)
|
|
164
|
+
yield stream
|
|
165
|
+
except (Exception, asyncio.CancelledError) as error:
|
|
166
|
+
normalized = error if isinstance(error, asyncio.CancelledError) else normalize_run_error(error)
|
|
167
|
+
if stream is not None:
|
|
168
|
+
stream.record_failure(captured, normalized, run.recorder.usage)
|
|
169
|
+
_raise_as(error, normalized)
|
|
170
|
+
|
|
171
|
+
if stream is None or not stream.complete:
|
|
172
|
+
return
|
|
173
|
+
|
|
174
|
+
await run.recorder.record(stream.result.usage)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@contextmanager
|
|
178
|
+
def _logged_run(run_id: RunId, conversation_id: ConversationId) -> Generator[None]:
|
|
179
|
+
logger = logging.getLogger('ovid_core')
|
|
180
|
+
logger.info('Agent run started: run_id=%s conversation_id=%s', run_id, conversation_id)
|
|
181
|
+
try:
|
|
182
|
+
yield
|
|
183
|
+
except BaseException as error:
|
|
184
|
+
logger.warning(
|
|
185
|
+
'Agent run failed: run_id=%s conversation_id=%s error_type=%s',
|
|
186
|
+
run_id,
|
|
187
|
+
conversation_id,
|
|
188
|
+
type(error).__name__,
|
|
189
|
+
)
|
|
190
|
+
raise
|
|
191
|
+
|
|
192
|
+
logger.info('Agent run ended: run_id=%s conversation_id=%s', run_id, conversation_id)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _raise_normalized(error: Exception) -> Never:
|
|
196
|
+
_raise_as(error, normalize_run_error(error))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _raise_as(error: BaseException, normalized: BaseException) -> Never:
|
|
200
|
+
if normalized is error:
|
|
201
|
+
raise error
|
|
202
|
+
if isinstance(normalized, CredentialError):
|
|
203
|
+
raise normalized from None
|
|
204
|
+
|
|
205
|
+
raise normalized from error
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from collections import deque
|
|
3
|
+
from collections.abc import AsyncIterator, Mapping, Sequence
|
|
4
|
+
from typing import Any, cast
|
|
5
|
+
|
|
6
|
+
from pydantic_ai.messages import (
|
|
7
|
+
AgentStreamEvent,
|
|
8
|
+
FunctionToolCallEvent,
|
|
9
|
+
FunctionToolResultEvent,
|
|
10
|
+
ModelMessage,
|
|
11
|
+
PartStartEvent,
|
|
12
|
+
)
|
|
13
|
+
from pydantic_ai.run import AgentRunResult, AgentRunResultEvent
|
|
14
|
+
|
|
15
|
+
from ovid_core.adapters.pydantic_ai._agent_errors import normalize_run_error
|
|
16
|
+
from ovid_core.adapters.pydantic_ai._request_parts import tool_content_from_pydantic, tool_metadata_from_pydantic
|
|
17
|
+
from ovid_core.adapters.pydantic_ai._steering import SteeringCapability
|
|
18
|
+
from ovid_core.adapters.pydantic_ai._stream_events import StreamEventTranslator
|
|
19
|
+
from ovid_core.adapters.pydantic_ai.results import RunTranscript, partial_from_pydantic, result_from_pydantic
|
|
20
|
+
from ovid_core.agent_runtime import AgentStream
|
|
21
|
+
from ovid_core.errors import AgentRunError, OvidCoreError
|
|
22
|
+
from ovid_core.messages.content import UserContent
|
|
23
|
+
from ovid_core.runtime.events import (
|
|
24
|
+
AgentEvent,
|
|
25
|
+
ModelRequestStartedEvent,
|
|
26
|
+
RunCompletedEvent,
|
|
27
|
+
RunDeferredEvent,
|
|
28
|
+
RunFailedEvent,
|
|
29
|
+
RunStartedEvent,
|
|
30
|
+
ToolCallEvent,
|
|
31
|
+
ToolDeferredEvent,
|
|
32
|
+
ToolResultEvent,
|
|
33
|
+
UsageUpdateEvent,
|
|
34
|
+
)
|
|
35
|
+
from ovid_core.runtime.identifiers import ConversationId, RunId
|
|
36
|
+
from ovid_core.runtime.results import DeferredRunResult, PartialRunResult, RunResult
|
|
37
|
+
from ovid_core.tools.models import ToolApproval
|
|
38
|
+
from ovid_core.usage.models import Usage
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PydanticAIStream[Output](AgentStream[Output]):
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
*,
|
|
45
|
+
events: AsyncIterator[AgentStreamEvent | AgentRunResultEvent[Any]],
|
|
46
|
+
run_id: RunId,
|
|
47
|
+
conversation_id: ConversationId,
|
|
48
|
+
approvals: Mapping[str, ToolApproval],
|
|
49
|
+
transcript: RunTranscript,
|
|
50
|
+
steering: SteeringCapability[Any],
|
|
51
|
+
stream_thinking: bool,
|
|
52
|
+
) -> None:
|
|
53
|
+
self._events = events
|
|
54
|
+
self._run_id = run_id
|
|
55
|
+
self._conversation_id = conversation_id
|
|
56
|
+
self._approvals = approvals
|
|
57
|
+
self._transcript = transcript
|
|
58
|
+
self._steering = steering
|
|
59
|
+
self._pending: deque[AgentEvent] = deque(
|
|
60
|
+
(RunStartedEvent(run_id=run_id, conversation_id=conversation_id, sequence=0),)
|
|
61
|
+
)
|
|
62
|
+
self._result: RunResult[Output] | DeferredRunResult | None = None
|
|
63
|
+
self._error: OvidCoreError | None = None
|
|
64
|
+
self._partial: PartialRunResult | None = None
|
|
65
|
+
self._expect_request = True
|
|
66
|
+
self._request_index = 0
|
|
67
|
+
self._translator = StreamEventTranslator(
|
|
68
|
+
run_id=run_id, conversation_id=conversation_id, stream_thinking=stream_thinking
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def result(self) -> RunResult[Output] | DeferredRunResult:
|
|
73
|
+
if self._result is None:
|
|
74
|
+
raise AgentRunError('Agent stream has not completed')
|
|
75
|
+
|
|
76
|
+
return self._result
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def complete(self) -> bool:
|
|
80
|
+
return self._result is not None
|
|
81
|
+
|
|
82
|
+
def partial(self) -> PartialRunResult | None:
|
|
83
|
+
return self._partial
|
|
84
|
+
|
|
85
|
+
def steer(self, content: str | Sequence[UserContent]) -> str:
|
|
86
|
+
return self._steering.enqueue(content, 'asap')
|
|
87
|
+
|
|
88
|
+
def follow_up(self, content: str | Sequence[UserContent]) -> str:
|
|
89
|
+
return self._steering.enqueue(content, 'when_idle')
|
|
90
|
+
|
|
91
|
+
def record_failure(self, captured: Sequence[ModelMessage], error: BaseException, usage: Usage) -> None:
|
|
92
|
+
self._partial = partial_from_pydantic(
|
|
93
|
+
captured,
|
|
94
|
+
error=error,
|
|
95
|
+
run_id=self._run_id,
|
|
96
|
+
conversation_id=self._conversation_id,
|
|
97
|
+
usage=usage,
|
|
98
|
+
transcript=self._transcript,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def __aiter__(self) -> PydanticAIStream[Output]:
|
|
102
|
+
return self
|
|
103
|
+
|
|
104
|
+
async def __anext__(self) -> AgentEvent:
|
|
105
|
+
if self._pending:
|
|
106
|
+
return self._pending.popleft()
|
|
107
|
+
if self._error is not None:
|
|
108
|
+
raise self._error
|
|
109
|
+
|
|
110
|
+
while True:
|
|
111
|
+
try:
|
|
112
|
+
upstream = await anext(self._events)
|
|
113
|
+
except StopAsyncIteration:
|
|
114
|
+
raise
|
|
115
|
+
except asyncio.CancelledError:
|
|
116
|
+
raise
|
|
117
|
+
except Exception as error:
|
|
118
|
+
self._error = normalize_run_error(error)
|
|
119
|
+
return RunFailedEvent(
|
|
120
|
+
run_id=self._run_id,
|
|
121
|
+
conversation_id=self._conversation_id,
|
|
122
|
+
sequence=self._translator.next_sequence(),
|
|
123
|
+
error_type=type(self._error).__name__,
|
|
124
|
+
message=str(self._error),
|
|
125
|
+
code=self._error.code,
|
|
126
|
+
retryable=self._error.code.retryable,
|
|
127
|
+
details=self._error.details,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
self._pending.extend(self._translate(upstream))
|
|
131
|
+
if self._pending:
|
|
132
|
+
return self._pending.popleft()
|
|
133
|
+
|
|
134
|
+
def _translate(self, event: AgentStreamEvent | AgentRunResultEvent[Any]) -> tuple[AgentEvent, ...]:
|
|
135
|
+
if isinstance(event, PartStartEvent):
|
|
136
|
+
return self._part_start_events(event)
|
|
137
|
+
if isinstance(event, FunctionToolCallEvent) and event.part.tool_name and event.part.tool_call_id:
|
|
138
|
+
return (
|
|
139
|
+
ToolCallEvent(
|
|
140
|
+
run_id=self._run_id,
|
|
141
|
+
conversation_id=self._conversation_id,
|
|
142
|
+
sequence=self._translator.next_sequence(),
|
|
143
|
+
tool_name=event.part.tool_name,
|
|
144
|
+
arguments=event.part.args,
|
|
145
|
+
tool_call_id=event.part.tool_call_id,
|
|
146
|
+
),
|
|
147
|
+
)
|
|
148
|
+
if isinstance(event, FunctionToolResultEvent):
|
|
149
|
+
return self._tool_result_events(event)
|
|
150
|
+
if isinstance(event, AgentRunResultEvent):
|
|
151
|
+
return self._result_events(cast(AgentRunResult[Output], event.result))
|
|
152
|
+
|
|
153
|
+
return self._translator.translate(event)
|
|
154
|
+
|
|
155
|
+
def _part_start_events(self, event: PartStartEvent) -> tuple[AgentEvent, ...]:
|
|
156
|
+
events: list[AgentEvent] = []
|
|
157
|
+
if self._expect_request:
|
|
158
|
+
events.append(
|
|
159
|
+
ModelRequestStartedEvent(
|
|
160
|
+
run_id=self._run_id,
|
|
161
|
+
conversation_id=self._conversation_id,
|
|
162
|
+
sequence=self._translator.next_sequence(),
|
|
163
|
+
request_index=self._request_index,
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
self._request_index += 1
|
|
167
|
+
self._expect_request = False
|
|
168
|
+
events.extend(self._translator.part_start(event.part))
|
|
169
|
+
|
|
170
|
+
return tuple(events)
|
|
171
|
+
|
|
172
|
+
def _tool_result_events(self, event: FunctionToolResultEvent) -> tuple[AgentEvent, ...]:
|
|
173
|
+
self._expect_request = True
|
|
174
|
+
if not (event.part.tool_name and event.part.tool_call_id):
|
|
175
|
+
return ()
|
|
176
|
+
|
|
177
|
+
return (
|
|
178
|
+
ToolResultEvent(
|
|
179
|
+
run_id=self._run_id,
|
|
180
|
+
conversation_id=self._conversation_id,
|
|
181
|
+
sequence=self._translator.next_sequence(),
|
|
182
|
+
tool_name=event.part.tool_name,
|
|
183
|
+
content=tool_content_from_pydantic(event.part)[0],
|
|
184
|
+
tool_call_id=event.part.tool_call_id,
|
|
185
|
+
outcome=event.part.outcome,
|
|
186
|
+
metadata=tool_metadata_from_pydantic(event.part),
|
|
187
|
+
),
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
def _result_events(self, value: AgentRunResult[Output]) -> tuple[AgentEvent, ...]:
|
|
191
|
+
result = result_from_pydantic(value, approvals=self._approvals, transcript=self._transcript)
|
|
192
|
+
self._result = result
|
|
193
|
+
request_usage = next(
|
|
194
|
+
(
|
|
195
|
+
message.request_usage
|
|
196
|
+
for message in reversed(result.history or result.messages)
|
|
197
|
+
if message.role == 'response'
|
|
198
|
+
),
|
|
199
|
+
None,
|
|
200
|
+
)
|
|
201
|
+
deferred = self._deferred_events(result) if isinstance(result, DeferredRunResult) else ()
|
|
202
|
+
usage_update = UsageUpdateEvent(
|
|
203
|
+
run_id=self._run_id,
|
|
204
|
+
conversation_id=self._conversation_id,
|
|
205
|
+
sequence=self._translator.next_sequence(),
|
|
206
|
+
usage=result.usage,
|
|
207
|
+
request_usage=request_usage,
|
|
208
|
+
is_final=True,
|
|
209
|
+
)
|
|
210
|
+
terminal_type = RunDeferredEvent if isinstance(result, DeferredRunResult) else RunCompletedEvent
|
|
211
|
+
terminal = terminal_type(
|
|
212
|
+
run_id=self._run_id,
|
|
213
|
+
conversation_id=self._conversation_id,
|
|
214
|
+
sequence=self._translator.next_sequence(),
|
|
215
|
+
usage=result.usage,
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
return (*deferred, usage_update, terminal)
|
|
219
|
+
|
|
220
|
+
def _deferred_events(self, result: DeferredRunResult) -> tuple[ToolDeferredEvent, ...]:
|
|
221
|
+
return tuple(
|
|
222
|
+
ToolDeferredEvent(
|
|
223
|
+
run_id=self._run_id,
|
|
224
|
+
conversation_id=self._conversation_id,
|
|
225
|
+
sequence=self._translator.next_sequence(),
|
|
226
|
+
tool_call_id=request.tool_call_id,
|
|
227
|
+
tool_name=request.tool_name,
|
|
228
|
+
arguments=request.arguments,
|
|
229
|
+
deferral_kind=request.kind,
|
|
230
|
+
reason=request.approval.reason if request.approval is not None else None,
|
|
231
|
+
metadata=request.metadata,
|
|
232
|
+
)
|
|
233
|
+
for request in result.requests.calls
|
|
234
|
+
)
|