polyrob 0.5.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.
- agents/README.md +453 -0
- agents/__init__.py +164 -0
- agents/base_agent.py +743 -0
- agents/personality/character.py +119 -0
- agents/personality/character_manager.py +309 -0
- agents/personality/characters/rob.character.json +56 -0
- agents/personality/characters/trump.character.json +63 -0
- agents/personality/persona_render.py +78 -0
- agents/personality/persona_resolver.py +115 -0
- agents/prompt/__init__.py +58 -0
- agents/prompt/base_prompt.py +92 -0
- agents/prompt/system.py +417 -0
- agents/task/README_PATH_MANAGEMENT.md +141 -0
- agents/task/__init__.py +162 -0
- agents/task/agent/__init__.py +70 -0
- agents/task/agent/agent_state.py +408 -0
- agents/task/agent/async_delegation.py +274 -0
- agents/task/agent/autonomy_state.py +275 -0
- agents/task/agent/conversation.py +75 -0
- agents/task/agent/core/__init__.py +6 -0
- agents/task/agent/core/aux_metering.py +61 -0
- agents/task/agent/core/background_review.py +157 -0
- agents/task/agent/core/construction.py +1179 -0
- agents/task/agent/core/conversational_exit.py +49 -0
- agents/task/agent/core/correspondent_gate.py +227 -0
- agents/task/agent/core/curator.py +246 -0
- agents/task/agent/core/episodic_digest.py +103 -0
- agents/task/agent/core/error_recovery.py +480 -0
- agents/task/agent/core/history_io.py +257 -0
- agents/task/agent/core/llm_provisioning.py +287 -0
- agents/task/agent/core/llm_runner.py +547 -0
- agents/task/agent/core/logging_io.py +276 -0
- agents/task/agent/core/loop_detection.py +262 -0
- agents/task/agent/core/memory_prefetch.py +325 -0
- agents/task/agent/core/memory_writer.py +667 -0
- agents/task/agent/core/model_introspection.py +82 -0
- agents/task/agent/core/model_swap.py +177 -0
- agents/task/agent/core/next_action_internal.py +1331 -0
- agents/task/agent/core/output_validation.py +303 -0
- agents/task/agent/core/project_context.py +272 -0
- agents/task/agent/core/resources.py +93 -0
- agents/task/agent/core/result_processing.py +389 -0
- agents/task/agent/core/run_loop.py +661 -0
- agents/task/agent/core/safety_lifecycle.py +228 -0
- agents/task/agent/core/secret_guard.py +293 -0
- agents/task/agent/core/self_wake.py +280 -0
- agents/task/agent/core/session_metadata.py +104 -0
- agents/task/agent/core/step.py +781 -0
- agents/task/agent/core/step_execution.py +398 -0
- agents/task/agent/core/step_telemetry.py +222 -0
- agents/task/agent/core/test_aux_metering.py +50 -0
- agents/task/agent/core/test_billing_failover.py +68 -0
- agents/task/agent/core/test_fatal_error_classifier.py +38 -0
- agents/task/agent/core/test_judge_validation.py +275 -0
- agents/task/agent/core/test_model_swap.py +190 -0
- agents/task/agent/core/test_reflection_offload.py +54 -0
- agents/task/agent/core/turn_input.py +8 -0
- agents/task/agent/core/untrusted_wrap.py +103 -0
- agents/task/agent/core/user_ingress.py +228 -0
- agents/task/agent/hitl_manager.py +396 -0
- agents/task/agent/log_sanitize.py +36 -0
- agents/task/agent/message_manager/config.py +97 -0
- agents/task/agent/message_manager/service.py +758 -0
- agents/task/agent/message_manager/tests.py +305 -0
- agents/task/agent/message_manager/tool_call_builder.py +539 -0
- agents/task/agent/message_manager/tool_message_repair.py +364 -0
- agents/task/agent/message_manager/views.py +143 -0
- agents/task/agent/messages/__init__.py +8 -0
- agents/task/agent/messages/builders.py +309 -0
- agents/task/agent/messages/compactor.py +611 -0
- agents/task/agent/messages/context_references.py +271 -0
- agents/task/agent/messages/filters.py +333 -0
- agents/task/agent/messages/guidance.py +328 -0
- agents/task/agent/messages/persistence.py +448 -0
- agents/task/agent/messages/retrieval.py +506 -0
- agents/task/agent/messages/sqlite_persistence.py +85 -0
- agents/task/agent/messages/test_compaction_upgrade.py +349 -0
- agents/task/agent/messages/test_persistence_subdir_fix.py +28 -0
- agents/task/agent/messages/test_sqlite_persistence.py +54 -0
- agents/task/agent/messages/token_counter.py +532 -0
- agents/task/agent/orchestrator.py +776 -0
- agents/task/agent/profile_manager.py +105 -0
- agents/task/agent/profile_registry.py +173 -0
- agents/task/agent/prompts.py +1090 -0
- agents/task/agent/scenario_registry.py +226 -0
- agents/task/agent/service.py +509 -0
- agents/task/agent/session.py +984 -0
- agents/task/agent/skill_discovery.py +110 -0
- agents/task/agent/skill_frontmatter.py +94 -0
- agents/task/agent/skill_manager.py +1201 -0
- agents/task/agent/skill_store.py +627 -0
- agents/task/agent/skill_validation.py +56 -0
- agents/task/agent/skill_writer.py +492 -0
- agents/task/agent/sub_agent_manager.py +1137 -0
- agents/task/agent/test_session_disk_recovery.py +34 -0
- agents/task/agent/tests.py +513 -0
- agents/task/agent/tool_call_tracker.py +511 -0
- agents/task/agent/views.py +469 -0
- agents/task/config.py +432 -0
- agents/task/constants.py +1384 -0
- agents/task/flag_defaults.py +63 -0
- agents/task/goals/__init__.py +1 -0
- agents/task/goals/autonomy_marker.py +28 -0
- agents/task/goals/board.py +690 -0
- agents/task/goals/completion_judge.py +247 -0
- agents/task/goals/context.py +62 -0
- agents/task/goals/dispatcher.py +848 -0
- agents/task/goals/escalation.py +102 -0
- agents/task/goals/planner.py +114 -0
- agents/task/logging_config.py +155 -0
- agents/task/path.py +991 -0
- agents/task/robust_parse_config.py +400 -0
- agents/task/runtime/__init__.py +0 -0
- agents/task/runtime/run_as_session.py +130 -0
- agents/task/runtime_safety.py +308 -0
- agents/task/session/__init__.py +5 -0
- agents/task/session/browser_pool.py +130 -0
- agents/task/session/cleanup.py +612 -0
- agents/task/session/execution.py +397 -0
- agents/task/session/feed.py +200 -0
- agents/task/session/hitl_ingress.py +201 -0
- agents/task/session/hooks.py +83 -0
- agents/task/session/multi_agent.py +243 -0
- agents/task/session/workspace.py +91 -0
- agents/task/session_registry.py +91 -0
- agents/task/session_route.py +35 -0
- agents/task/sqlite_session_registry.py +261 -0
- agents/task/surface_config.py +185 -0
- agents/task/telemetry/__init__.py +58 -0
- agents/task/telemetry/event_log.py +180 -0
- agents/task/telemetry/formatters.py +642 -0
- agents/task/telemetry/manager.py +571 -0
- agents/task/telemetry/memory_events.py +66 -0
- agents/task/telemetry/self_events.py +53 -0
- agents/task/telemetry/sequence.py +160 -0
- agents/task/telemetry/service.py +1265 -0
- agents/task/telemetry/views.py +882 -0
- agents/task/templates.py +98 -0
- agents/task/test_aux_chain.py +151 -0
- agents/task/test_aux_router.py +41 -0
- agents/task/tests/test_parse_robustness.py +170 -0
- agents/task/tool_defaults.py +110 -0
- agents/task/utils.py +762 -0
- agents/task/utils_json.py +768 -0
- agents/task/utils_webview.py +86 -0
- agents/task/workspace_context.py +229 -0
- agents/task_agent_lite.py +2398 -0
- api/README.md +683 -0
- api/TASK_API_DOCS.md +151 -0
- api/__init__.py +0 -0
- api/a2a/__init__.py +37 -0
- api/a2a/agent_card.py +337 -0
- api/a2a/client.py +657 -0
- api/a2a/endpoints.py +375 -0
- api/a2a/models.py +268 -0
- api/a2a/streaming.py +419 -0
- api/a2a/task_handler.py +929 -0
- api/admin_endpoints.py +1584 -0
- api/app.py +923 -0
- api/auth_constants.py +28 -0
- api/auth_endpoints.py +402 -0
- api/auth_state.py +36 -0
- api/chat_via_task.py +42 -0
- api/conversation_manager.py +231 -0
- api/dependencies.py +186 -0
- api/eip8004_endpoints.py +452 -0
- api/hyperliquid_models.py +174 -0
- api/hyperliquid_routes.py +450 -0
- api/interfaces.py +207 -0
- api/jwt_middleware.py +83 -0
- api/kb/__init__.py +1 -0
- api/kb/endpoints.py +314 -0
- api/mcp_models.py +279 -0
- api/mcp_routes.py +438 -0
- api/middleware.py +526 -0
- api/models.py +176 -0
- api/openai_compat/__init__.py +0 -0
- api/openai_compat/model_map.py +25 -0
- api/openai_compat/models.py +59 -0
- api/openai_compat/router.py +140 -0
- api/payment_endpoints.py +444 -0
- api/payment_verification.py +138 -0
- api/polymarket_models.py +155 -0
- api/polymarket_routes.py +501 -0
- api/pricing_endpoints.py +89 -0
- api/session_routing.py +54 -0
- api/skill_endpoints.py +453 -0
- api/task_http_api.py +1856 -0
- api/webhooks.py +52 -0
- api/x402_endpoints.py +280 -0
- avatar/README.md +44 -0
- avatar/__init__.py +1 -0
- avatar/config/rob.json +7 -0
- avatar/mindprint.js +395 -0
- avatar/renders/rob.meta.json +20 -0
- avatar/renders/rob.png +0 -0
- avatar/studio.html +373 -0
- avatar/webview/avatar-live.js +44 -0
- cli/README.md +89 -0
- cli/__init__.py +0 -0
- cli/cli_surface.py +67 -0
- cli/commands/__init__.py +0 -0
- cli/commands/_bootstrap.py +49 -0
- cli/commands/_errors.py +53 -0
- cli/commands/chat.py +973 -0
- cli/commands/config.py +100 -0
- cli/commands/dashboard.py +103 -0
- cli/commands/doctor.py +222 -0
- cli/commands/email.py +174 -0
- cli/commands/gateway.py +346 -0
- cli/commands/goals.py +509 -0
- cli/commands/init.py +276 -0
- cli/commands/journey.py +30 -0
- cli/commands/kb.py +280 -0
- cli/commands/model.py +107 -0
- cli/commands/owner.py +431 -0
- cli/commands/pfp.py +232 -0
- cli/commands/run.py +414 -0
- cli/commands/serve.py +41 -0
- cli/commands/session.py +684 -0
- cli/commands/skill_install.py +786 -0
- cli/commands/skills.py +128 -0
- cli/commands/subagents.py +100 -0
- cli/commands/surface.py +81 -0
- cli/commands/telegram.py +185 -0
- cli/commands/todos.py +209 -0
- cli/commands/tools.py +102 -0
- cli/commands/update.py +316 -0
- cli/commands/whatsapp.py +175 -0
- cli/config_store.py +276 -0
- cli/gitignore.py +43 -0
- cli/inventory.py +46 -0
- cli/keys.py +101 -0
- cli/persona.py +17 -0
- cli/polyrob.py +137 -0
- cli/ui/__init__.py +64 -0
- cli/ui/activity.py +141 -0
- cli/ui/app.py +538 -0
- cli/ui/banner.py +233 -0
- cli/ui/blocks.py +534 -0
- cli/ui/bootstrap_notice.py +47 -0
- cli/ui/commands/__init__.py +41 -0
- cli/ui/commands/h_cron.py +64 -0
- cli/ui/commands/h_journey.py +164 -0
- cli/ui/commands/h_kb.py +121 -0
- cli/ui/commands/h_learn.py +100 -0
- cli/ui/commands/h_mcp.py +215 -0
- cli/ui/commands/h_self.py +113 -0
- cli/ui/commands/h_skills.py +314 -0
- cli/ui/commands/handlers.py +1672 -0
- cli/ui/commands/registry.py +426 -0
- cli/ui/dialog.py +425 -0
- cli/ui/event_registry.py +110 -0
- cli/ui/event_specs.py +45 -0
- cli/ui/events.py +433 -0
- cli/ui/identity.py +15 -0
- cli/ui/lifecycle.py +159 -0
- cli/ui/live_hooks.py +43 -0
- cli/ui/model_selector.py +532 -0
- cli/ui/persistent_loop.py +181 -0
- cli/ui/pick.py +113 -0
- cli/ui/plain_renderer.py +351 -0
- cli/ui/renderer.py +384 -0
- cli/ui/rich_renderer.py +533 -0
- cli/ui/secrets.py +115 -0
- cli/ui/state.py +376 -0
- cli/ui/statusbar.py +231 -0
- cli/ui/streaming.py +254 -0
- cli/ui/terminal_render.py +105 -0
- cli/ui/theme.py +132 -0
- cli/update/__init__.py +6 -0
- cli/update/context.py +121 -0
- cli/update/detect.py +176 -0
- cli/update/engine.py +95 -0
- cli/update/migrate_guarded.py +55 -0
- cli/update/process_guard.py +215 -0
- cli/update/runners.py +78 -0
- cli/update/snapshot.py +270 -0
- cli/update/versions.py +205 -0
- core/README.md +377 -0
- core/__init__.py +174 -0
- core/assets.py +87 -0
- core/async_bridge.py +76 -0
- core/autonomy_runtime.py +259 -0
- core/base_component.py +302 -0
- core/bootstrap.py +681 -0
- core/bot.py +310 -0
- core/config.py +833 -0
- core/constants.py +126 -0
- core/container.py +462 -0
- core/db_manifest.py +101 -0
- core/embedding.py +57 -0
- core/env.py +39 -0
- core/exceptions.py +287 -0
- core/flags.py +144 -0
- core/flags_catalog.py +345 -0
- core/home_migration.py +62 -0
- core/identity.py +118 -0
- core/initialization.py +1004 -0
- core/instance.py +537 -0
- core/interactive_gate.py +96 -0
- core/logging.py +436 -0
- core/owner_doc_writer.py +176 -0
- core/pairing.py +193 -0
- core/path_safety.py +20 -0
- core/paths.py +27 -0
- core/payment_config.py +21 -0
- core/permissions.py +322 -0
- core/runtime_config.py +96 -0
- core/runtime_paths.py +135 -0
- core/seams.py +35 -0
- core/secret_scan.py +25 -0
- core/secret_scrub.py +71 -0
- core/secrets.py +35 -0
- core/security_logging_filter.py +148 -0
- core/self_context_writer.py +333 -0
- core/self_evolution.py +294 -0
- core/session_context.py +47 -0
- core/sqlite_util.py +59 -0
- core/surfaces/__init__.py +16 -0
- core/surfaces/access.py +118 -0
- core/surfaces/binding.py +88 -0
- core/surfaces/bootstrap.py +78 -0
- core/surfaces/circuit.py +168 -0
- core/surfaces/continuity.py +77 -0
- core/surfaces/correspondents.py +228 -0
- core/surfaces/dispatcher.py +216 -0
- core/surfaces/envelopes.py +75 -0
- core/surfaces/gc.py +30 -0
- core/surfaces/idempotency.py +57 -0
- core/surfaces/inbound_webhook.py +124 -0
- core/surfaces/media.py +32 -0
- core/surfaces/message_router.py +91 -0
- core/surfaces/outbound_allowlist.py +80 -0
- core/surfaces/outbound_dispatcher.py +110 -0
- core/surfaces/outbound_mirror.py +37 -0
- core/surfaces/outbound_queue.py +107 -0
- core/surfaces/outbound_target.py +12 -0
- core/surfaces/owner_admin.py +29 -0
- core/surfaces/proactive.py +78 -0
- core/surfaces/progress.py +108 -0
- core/surfaces/rate_bucket.py +21 -0
- core/surfaces/registry.py +51 -0
- core/surfaces/rendering.py +53 -0
- core/surfaces/send_policy.py +14 -0
- core/surfaces/serialize.py +24 -0
- core/surfaces/session_chat_registry.py +112 -0
- core/surfaces/session_policy.py +60 -0
- core/surfaces/surface.py +288 -0
- core/surfaces/transcription.py +88 -0
- core/surfaces/voice_echo.py +26 -0
- core/surfaces/voice_guard.py +23 -0
- core/tickers.py +174 -0
- core/tool_catalog.py +192 -0
- core/version.py +75 -0
- core/wallet/__init__.py +5 -0
- core/wallet/agent_wallet.py +59 -0
- core/wallet/audit_sink.py +61 -0
- core/wallet/config.py +70 -0
- core/wallet/factory.py +87 -0
- core/wallet/policy.py +104 -0
- core/wallet/signer.py +51 -0
- cron/README.md +65 -0
- cron/__init__.py +0 -0
- cron/delivery.py +277 -0
- cron/digest.py +124 -0
- cron/jobs.py +207 -0
- cron/runner.py +297 -0
- cron/schedule.py +194 -0
- cron/scheduler.py +201 -0
- cron/service.py +57 -0
- cron/wake_gate.py +223 -0
- data/__init__.py +1 -0
- data/prompts/autov2_prompts.json +87 -0
- data/prompts/skills/browser-automation/SKILL.md +43 -0
- data/prompts/skills/coding-workflow/SKILL.md +36 -0
- data/prompts/skills/crypto-trading-safety/SKILL.md +53 -0
- data/prompts/skills/document-writing/SKILL.md +33 -0
- data/prompts/skills/email-comms/SKILL.md +33 -0
- data/prompts/skills/file-data-ops/SKILL.md +35 -0
- data/prompts/skills/hyperliquid-account-review/SKILL.md +48 -0
- data/prompts/skills/hyperliquid-market-data/SKILL.md +52 -0
- data/prompts/skills/hyperliquid-trading/SKILL.md +59 -0
- data/prompts/skills/lead-research/SKILL.md +86 -0
- data/prompts/skills/market-research-brief/SKILL.md +104 -0
- data/prompts/skills/person-analyzer/SKILL.md +124 -0
- data/prompts/skills/polymarket-market-research/SKILL.md +54 -0
- data/prompts/skills/polymarket-portfolio-review/SKILL.md +50 -0
- data/prompts/skills/polymarket-trading/SKILL.md +55 -0
- data/prompts/skills/presentation-creator/SKILL.md +36 -0
- data/prompts/skills/project-analyzer/SKILL.md +169 -0
- data/prompts/skills/rules.json +268 -0
- data/prompts/skills/secret-handling/SKILL.md +20 -0
- data/prompts/skills/skill-authoring/SKILL.md +31 -0
- data/prompts/skills/skill-security-review/SKILL.md +27 -0
- data/prompts/skills/social-discovery/SKILL.md +57 -0
- data/prompts/skills/task-planning/SKILL.md +33 -0
- data/prompts/skills/web-research/SKILL.md +39 -0
- data/prompts/skills/web-scraping/SKILL.md +73 -0
- data/prompts/skills/x-engagement/SKILL.md +69 -0
- data/prompts/system_prompts.json +4 -0
- data/subscription_channels.json +5 -0
- modules/README.md +503 -0
- modules/__init__.py +124 -0
- modules/auth/__init__.py +13 -0
- modules/auth/api_key_manager.py +157 -0
- modules/auth/identity_mapper.py +380 -0
- modules/auth/siwe_auth.py +273 -0
- modules/auth/tier_manager.py +173 -0
- modules/base_module.py +190 -0
- modules/credits/__init__.py +29 -0
- modules/credits/balance_manager.py +237 -0
- modules/credits/cost_utils.py +129 -0
- modules/credits/pricing.py +139 -0
- modules/credits/unified_ledger.py +148 -0
- modules/credits/usage_meter.py +310 -0
- modules/credits/usage_tracker.py +674 -0
- modules/database/__init__.py +33 -0
- modules/database/audit_log.py +322 -0
- modules/database/auth_tables.py +276 -0
- modules/database/connection.py +644 -0
- modules/database/connection_pool.py +305 -0
- modules/database/conversation_contexts.py +446 -0
- modules/database/database_manager.py +237 -0
- modules/database/hyperliquid.py +375 -0
- modules/database/polymarket.py +574 -0
- modules/database/user_mcp_servers.py +728 -0
- modules/database/user_profiles.py +562 -0
- modules/database/utils.py +107 -0
- modules/database/x402_tables.py +92 -0
- modules/eip8004/README.md +1069 -0
- modules/eip8004/__init__.py +65 -0
- modules/eip8004/contracts.py +498 -0
- modules/eip8004/models.py +271 -0
- modules/eip8004/registration.py +148 -0
- modules/eip8004/reputation.py +367 -0
- modules/eip8004/validation.py +277 -0
- modules/llm/__init__.py +97 -0
- modules/llm/adapters.py +963 -0
- modules/llm/anthropic_client.py +831 -0
- modules/llm/available_models.py +106 -0
- modules/llm/brain_scrubber.py +137 -0
- modules/llm/cache_hints.py +162 -0
- modules/llm/deepseek_client.py +562 -0
- modules/llm/gemini_client.py +1367 -0
- modules/llm/llm_client.py +1139 -0
- modules/llm/llm_client_registry.py +188 -0
- modules/llm/llm_factory.py +237 -0
- modules/llm/llm_manager.py +1036 -0
- modules/llm/messages.py +374 -0
- modules/llm/model_registry.py +1935 -0
- modules/llm/nvidia_client.py +125 -0
- modules/llm/openai_client.py +800 -0
- modules/llm/openrouter_client.py +969 -0
- modules/llm/profiles.py +178 -0
- modules/llm/test_anthropic_cache_capture.py +35 -0
- modules/llm/test_cached_pricing_derivation.py +24 -0
- modules/llm/think_scrubber.py +444 -0
- modules/llm/token_counter.py +268 -0
- modules/memory/__init__.py +35 -0
- modules/memory/backend_factory.py +83 -0
- modules/memory/cache_manager.py +186 -0
- modules/memory/episodic.py +108 -0
- modules/memory/local_vector_memory_provider.py +552 -0
- modules/memory/memory_manager.py +225 -0
- modules/memory/models.py +312 -0
- modules/memory/provider.py +210 -0
- modules/memory/registry.py +205 -0
- modules/memory/sqlite_memory_provider.py +767 -0
- modules/memory/task/__init__.py +52 -0
- modules/memory/task/compaction_manager.py +157 -0
- modules/memory/task/context_retriever.py +809 -0
- modules/memory/task/hierarchical_memory.py +1002 -0
- modules/memory/task/lexical_retriever.py +71 -0
- modules/memory/task/null_context_manager.py +213 -0
- modules/memory/task/phase_manager.py +625 -0
- modules/memory/task/reflection_service.py +157 -0
- modules/memory/task/semantic_retriever.py +218 -0
- modules/memory/task/task_context_manager.py +1165 -0
- modules/memory/task/test_forgetting_engages.py +24 -0
- modules/memory/task/test_reflection_llm.py +39 -0
- modules/memory/task/test_threat_scan.py +53 -0
- modules/memory/task/threat_scan.py +90 -0
- modules/memory/test_sqlite_memory_provider.py +106 -0
- modules/memory/user_profile_manager.py +527 -0
- modules/payments/__init__.py +11 -0
- modules/payments/deposit_monitor.py +478 -0
- modules/payments/price_oracle.py +70 -0
- modules/payments/treasury_sweeper.py +401 -0
- modules/payments/wallet_generator.py +145 -0
- modules/pfp/__init__.py +1 -0
- modules/pfp/config.py +92 -0
- modules/pfp/mesh.py +565 -0
- modules/pfp/push.py +69 -0
- modules/pfp/renderer.py +85 -0
- modules/pfp/store.py +82 -0
- modules/skills/__init__.py +1 -0
- modules/skills/skill_usage.py +248 -0
- modules/transcription/__init__.py +24 -0
- modules/transcription/base.py +20 -0
- modules/transcription/faster_whisper_transcriber.py +55 -0
- modules/x402/README.md +249 -0
- modules/x402/__init__.py +22 -0
- modules/x402/invoicing.py +416 -0
- modules/x402/middleware.py +364 -0
- modules/x402/settlement_watcher.py +145 -0
- modules/x402/x402_integration.py +344 -0
- polyrob-0.5.0.dist-info/METADATA +482 -0
- polyrob-0.5.0.dist-info/RECORD +745 -0
- polyrob-0.5.0.dist-info/WHEEL +5 -0
- polyrob-0.5.0.dist-info/entry_points.txt +2 -0
- polyrob-0.5.0.dist-info/licenses/LICENSE +21 -0
- polyrob-0.5.0.dist-info/top_level.txt +12 -0
- surfaces/README.md +70 -0
- surfaces/__init__.py +0 -0
- surfaces/email/__init__.py +0 -0
- surfaces/email/dedup.py +44 -0
- surfaces/email/harness.py +187 -0
- surfaces/email/inbound.py +159 -0
- surfaces/email/seed.py +60 -0
- surfaces/email/surface.py +105 -0
- surfaces/telegram/__init__.py +0 -0
- surfaces/telegram/dedup.py +83 -0
- surfaces/telegram/harness.py +886 -0
- surfaces/telegram/inbound.py +145 -0
- surfaces/telegram/interactive_tools.py +49 -0
- surfaces/telegram/markdown.py +347 -0
- surfaces/telegram/rate_limit.py +167 -0
- surfaces/telegram/surface.py +187 -0
- surfaces/telegram/voice.py +52 -0
- surfaces/whatsapp/__init__.py +0 -0
- surfaces/whatsapp/client.py +51 -0
- surfaces/whatsapp/harness.py +62 -0
- surfaces/whatsapp/inbound.py +132 -0
- surfaces/whatsapp/surface.py +64 -0
- surfaces/whatsapp/window.py +34 -0
- tools/README.md +578 -0
- tools/__init__.py +424 -0
- tools/alchemy/__init__.py +5 -0
- tools/alchemy/alchemy_tool.py +389 -0
- tools/anysite/__init__.py +17 -0
- tools/anysite/client.py +88 -0
- tools/anysite/tool.py +89 -0
- tools/base_tool.py +468 -0
- tools/browser/__init__.py +22 -0
- tools/browser/actions.py +118 -0
- tools/browser/browser.py +1457 -0
- tools/browser/browser_manager.py +690 -0
- tools/browser/context.py +1748 -0
- tools/browser/playwright_utils.py +137 -0
- tools/browser/views.py +56 -0
- tools/code_exec/SANDBOX_SECURITY.md +144 -0
- tools/code_exec/__init__.py +178 -0
- tools/code_exec/backend.py +73 -0
- tools/code_exec/backends/__init__.py +1 -0
- tools/code_exec/backends/docker.py +779 -0
- tools/code_exec/backends/local_subprocess.py +154 -0
- tools/code_exec/env_policy.py +45 -0
- tools/code_exec/result.py +42 -0
- tools/code_exec/sandbox_guard.py +59 -0
- tools/code_exec/tool.py +227 -0
- tools/coding/__init__.py +50 -0
- tools/coding/edit.py +107 -0
- tools/coding/search.py +113 -0
- tools/coding/tool.py +353 -0
- tools/collabland/__init__.py +5 -0
- tools/collabland/collabland_tool.py +471 -0
- tools/controller/__init__.py +0 -0
- tools/controller/_helpers.py +165 -0
- tools/controller/action_registration.py +1765 -0
- tools/controller/approval.py +244 -0
- tools/controller/approval_interactive.py +90 -0
- tools/controller/delegation.py +195 -0
- tools/controller/execution.py +797 -0
- tools/controller/execution_context.py +141 -0
- tools/controller/hooks.py +135 -0
- tools/controller/introspection.py +344 -0
- tools/controller/mcp_registrar.py +190 -0
- tools/controller/message_send.py +31 -0
- tools/controller/registry/__init__.py +4 -0
- tools/controller/registry/schema_generators.py +395 -0
- tools/controller/registry/schema_sanitizer.py +406 -0
- tools/controller/registry/service.py +1266 -0
- tools/controller/registry/views.py +151 -0
- tools/controller/service.py +409 -0
- tools/controller/tool_management.py +334 -0
- tools/controller/types.py +28 -0
- tools/controller/views.py +450 -0
- tools/cronjob_tools.py +166 -0
- tools/crypto_trade_gate.py +59 -0
- tools/descriptors.py +452 -0
- tools/dom/__init__.py +0 -0
- tools/dom/history_tree_processor/service.py +244 -0
- tools/dom/history_tree_processor/view.py +99 -0
- tools/dom/service.py +471 -0
- tools/dom/views.py +346 -0
- tools/email_tool.py +403 -0
- tools/exceptions.py +169 -0
- tools/filesystem.py +1038 -0
- tools/filesystem_docproc.py +331 -0
- tools/filesystem_pdf.py +755 -0
- tools/git/__init__.py +42 -0
- tools/git/tool.py +258 -0
- tools/github/__init__.py +33 -0
- tools/github/client.py +94 -0
- tools/github/tool.py +237 -0
- tools/goal_tools.py +309 -0
- tools/hyperliquid/__init__.py +56 -0
- tools/hyperliquid/models.py +233 -0
- tools/hyperliquid/service.py +1680 -0
- tools/knowledge_ingest.py +950 -0
- tools/mcp/README.md +535 -0
- tools/mcp/__init__.py +52 -0
- tools/mcp/catalog.py +115 -0
- tools/mcp/config.py +337 -0
- tools/mcp/mcp_tool.py +1415 -0
- tools/mcp/param_coercion.py +289 -0
- tools/mcp/protocol.py +1520 -0
- tools/mcp/rate_limit.py +50 -0
- tools/mcp/security.py +424 -0
- tools/mcp/self_install.py +111 -0
- tools/mcp/server_manager.py +829 -0
- tools/mcp/subscriptions.py +72 -0
- tools/mcp/user_mcp_service.py +899 -0
- tools/mcp/validation_tracker.py +89 -0
- tools/mcp/views.py +346 -0
- tools/oauth/__init__.py +17 -0
- tools/oauth/manager.py +75 -0
- tools/oauth/provider.py +69 -0
- tools/oauth/providers/__init__.py +1 -0
- tools/oauth/providers/generic_oauth2.py +96 -0
- tools/perplexity_tool.py +280 -0
- tools/polymarket/__init__.py +41 -0
- tools/polymarket/clob_adapter.py +76 -0
- tools/polymarket/models.py +182 -0
- tools/polymarket/service.py +2082 -0
- tools/self_env/__init__.py +61 -0
- tools/self_env/tool.py +274 -0
- tools/shell/__init__.py +80 -0
- tools/shell/backend_pool.py +118 -0
- tools/shell/discipline.py +62 -0
- tools/shell/executor.py +157 -0
- tools/shell/loopback_allow.py +87 -0
- tools/shell/process_registry.py +113 -0
- tools/shell/process_tool.py +131 -0
- tools/shell/state.py +129 -0
- tools/shell/tool.py +151 -0
- tools/task_tool.py +637 -0
- tools/twitter_tool.py +2086 -0
- tools/user_directory.py +179 -0
- tools/web_fetch/__init__.py +3 -0
- tools/web_fetch/fetcher.py +144 -0
- tools/web_fetch/render.py +44 -0
- tools/web_fetch/tool.py +60 -0
- tools/x402/__init__.py +60 -0
- tools/x402/client.py +47 -0
- tools/x402/invoice_tool.py +143 -0
- tools/x402/real_client.py +250 -0
- tools/x402/service.py +131 -0
- utils/README.md +498 -0
- utils/__init__.py +46 -0
- utils/auth_utils.py +114 -0
- utils/bounded_collections.py +162 -0
- utils/circuit_breaker.py +389 -0
- utils/gif_utils.py +435 -0
- utils/markdown_utils.py +291 -0
- utils/message_utils.py +147 -0
- utils/metrics.py +36 -0
- utils/path_validator.py +227 -0
- utils/rate_limit_manager.py +399 -0
- utils/result_size.py +296 -0
- utils/time_utils.py +206 -0
- utils/user_utils.py +188 -0
- webview/README.md +111 -0
- webview/RENAME_AND_ALIGN_HANDOFF.md +200 -0
- webview/__init__.py +8 -0
- webview/activity.py +636 -0
- webview/owner_auth.py +108 -0
- webview/pages.py +448 -0
- webview/repair_sessions.py +399 -0
- webview/server.py +4323 -0
- webview/server_launcher.py +112 -0
- webview/static/css/activity.css +89 -0
- webview/static/css/chat.css +1772 -0
- webview/static/css/components.css +1190 -0
- webview/static/css/config-panel.css +651 -0
- webview/static/css/pages/admin.css +766 -0
- webview/static/css/pages/profile.css +231 -0
- webview/static/css/pages/settings.css +297 -0
- webview/static/css/pages/signin.css +316 -0
- webview/static/css/style.css +4250 -0
- webview/static/css/variables.css +147 -0
- webview/static/css/workspace-fullwidth-fix.css +109 -0
- webview/static/img/favicon.ico +0 -0
- webview/static/js/activity.js +394 -0
- webview/static/js/admin/activity.js +186 -0
- webview/static/js/admin/dashboard.js +163 -0
- webview/static/js/admin/user_detail.js +400 -0
- webview/static/js/admin/users.js +174 -0
- webview/static/js/admin/utils.js +214 -0
- webview/static/js/chat.js +3178 -0
- webview/static/js/config-panel.js +522 -0
- webview/static/js/constants.js +20 -0
- webview/static/js/error-handler.js +226 -0
- webview/static/js/ethers.min.js +1 -0
- webview/static/js/event-filter.js +137 -0
- webview/static/js/event-store.js +351 -0
- webview/static/js/file-attachments.js +374 -0
- webview/static/js/file-loader.js +163 -0
- webview/static/js/index.js +103 -0
- webview/static/js/performance-utils.js +196 -0
- webview/static/js/profile.js +396 -0
- webview/static/js/screenshot.js +386 -0
- webview/static/js/session.js +1527 -0
- webview/static/js/settings.js +1288 -0
- webview/static/js/sidebar-data.js +766 -0
- webview/static/js/sidebar-toggle.js +296 -0
- webview/static/js/socket.io.min.js +7 -0
- webview/static/js/stats.js +355 -0
- webview/static/js/ui-utils.js +420 -0
- webview/static/js/workspace.js +966 -0
- webview/stats_service.py +613 -0
- webview/templates/__init__.py +1 -0
- webview/templates/__pycache__/__init__.cpython-311.pyc +0 -0
- webview/templates/activity.html +36 -0
- webview/templates/admin/activity.html +122 -0
- webview/templates/admin/dashboard.html +112 -0
- webview/templates/admin/user_detail.html +228 -0
- webview/templates/admin/users.html +105 -0
- webview/templates/autonomy.html +60 -0
- webview/templates/error.html +133 -0
- webview/templates/finance.html +90 -0
- webview/templates/identity.html +73 -0
- webview/templates/index.html +42 -0
- webview/templates/layout.html +125 -0
- webview/templates/memory.html +59 -0
- webview/templates/owner_login.html +15 -0
- webview/templates/profile.html +121 -0
- webview/templates/session.html +312 -0
- webview/templates/settings.html +534 -0
- webview/templates/sidebar.html +112 -0
- webview/templates/signin.html +213 -0
- webview/templates/status.html +14 -0
- webview/templates/system.html +45 -0
- webview/webgate.py +196 -0
|
@@ -0,0 +1,831 @@
|
|
|
1
|
+
"""Anthropic Claude API Client."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import asyncio
|
|
6
|
+
import time
|
|
7
|
+
from typing import List, Dict, Any, Optional, Union, Tuple
|
|
8
|
+
|
|
9
|
+
import anthropic
|
|
10
|
+
from anthropic.types import ContentBlock, MessageParam, Message
|
|
11
|
+
|
|
12
|
+
from modules.llm.llm_client import LLMClient
|
|
13
|
+
from modules.llm.token_counter import count_messages_tokens
|
|
14
|
+
from core.exceptions import LLMError, LLMConfigError, LLMRateLimitError, LLMAuthenticationError, LLMContextLengthError, LLMInvalidRequestError, LLMConnectionError, ServiceError
|
|
15
|
+
from core.config import BotConfig
|
|
16
|
+
import os
|
|
17
|
+
|
|
18
|
+
# Import default model from registry
|
|
19
|
+
from modules.llm.llm_client_registry import get_default_model
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _clamp_thinking(model_cap, budget, current_max_tokens):
|
|
23
|
+
"""H4: return (budget, max_tokens) valid for Anthropic extended thinking.
|
|
24
|
+
|
|
25
|
+
Anthropic requires ``max_tokens > thinking.budget_tokens`` AND
|
|
26
|
+
``max_tokens <= the model's real completion cap``. Registry entries set
|
|
27
|
+
budget == cap, so the old ``max_tokens = budget + 4096`` overran the cap and 400'd.
|
|
28
|
+
Shrink the budget to leave >=4096 output room under the cap; if the cap is too
|
|
29
|
+
small to fit any thinking, return (None, ...) so the caller disables thinking.
|
|
30
|
+
"""
|
|
31
|
+
if not budget or budget <= 0:
|
|
32
|
+
return None, current_max_tokens
|
|
33
|
+
if model_cap and model_cap > 0:
|
|
34
|
+
max_budget = model_cap - 4096
|
|
35
|
+
if max_budget < 1024:
|
|
36
|
+
# Cap too small to fit thinking + output room — disable thinking.
|
|
37
|
+
return None, min(current_max_tokens, model_cap)
|
|
38
|
+
if budget > max_budget:
|
|
39
|
+
budget = max_budget
|
|
40
|
+
max_tokens = current_max_tokens
|
|
41
|
+
if max_tokens <= budget:
|
|
42
|
+
max_tokens = budget + 4096
|
|
43
|
+
max_tokens = min(max_tokens, model_cap)
|
|
44
|
+
return budget, max_tokens
|
|
45
|
+
# No cap known — preserve legacy behaviour (bump above budget).
|
|
46
|
+
max_tokens = current_max_tokens
|
|
47
|
+
if max_tokens <= budget:
|
|
48
|
+
max_tokens = budget + 4096
|
|
49
|
+
return budget, max_tokens
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _build_cached_system_param(system):
|
|
53
|
+
"""Build Anthropic ``system`` as content blocks with a prompt-cache breakpoint.
|
|
54
|
+
|
|
55
|
+
Flow-efficiency D4-a: the system prompt (and the tool definitions that precede
|
|
56
|
+
it in the request) are stable across steps within a session, so marking the
|
|
57
|
+
LAST system block with ``cache_control: ephemeral`` lets Anthropic serve the
|
|
58
|
+
whole tools+system prefix from cache (~10x cheaper on repeated input).
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
system: the system prompt as a ``str`` or a list of content-block dicts.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
A list of content-block dicts (last one carrying ``cache_control`` when
|
|
65
|
+
caching is enabled), or ``None`` if ``system`` is falsy.
|
|
66
|
+
|
|
67
|
+
Caching is on by default; set ``ANTHROPIC_PROMPT_CACHE=0`` to disable.
|
|
68
|
+
Does not mutate the input list.
|
|
69
|
+
"""
|
|
70
|
+
if not system:
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
if isinstance(system, list):
|
|
74
|
+
blocks = [dict(b) for b in system] # shallow copy so we never mutate caller's list
|
|
75
|
+
else:
|
|
76
|
+
blocks = [{"type": "text", "text": system}]
|
|
77
|
+
|
|
78
|
+
from modules.llm.cache_hints import prompt_cache_enabled
|
|
79
|
+
if prompt_cache_enabled() and blocks:
|
|
80
|
+
blocks[-1] = {**blocks[-1], "cache_control": {"type": "ephemeral"}}
|
|
81
|
+
return blocks
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _apply_conversation_cache(messages, n: int = 3):
|
|
85
|
+
"""Mark the last ``n`` conversation messages with ``cache_control: ephemeral``.
|
|
86
|
+
|
|
87
|
+
Flow-efficiency B1 (Reference ``system_and_3`` parity, see
|
|
88
|
+
docs/REFERENCE_VS_ROB_CONTEXT_SYSTEM_2026-06.md §9): Anthropic allows up to **4**
|
|
89
|
+
cache breakpoints per request. ``_build_cached_system_param`` already spends 1 on
|
|
90
|
+
the system block; this spends the remaining 3 on the tail of the *conversation*,
|
|
91
|
+
so the growing message prefix is served from cache instead of re-paying full input
|
|
92
|
+
cost every turn.
|
|
93
|
+
|
|
94
|
+
Does not mutate the caller's list. No-op (returns input unchanged) when
|
|
95
|
+
``ANTHROPIC_PROMPT_CACHE`` is disabled or ``messages`` is empty.
|
|
96
|
+
"""
|
|
97
|
+
from modules.llm.cache_hints import prompt_cache_enabled
|
|
98
|
+
if not prompt_cache_enabled() or not messages:
|
|
99
|
+
return messages
|
|
100
|
+
|
|
101
|
+
out = [dict(m) for m in messages]
|
|
102
|
+
for m in out[-n:]:
|
|
103
|
+
content = m.get("content")
|
|
104
|
+
if isinstance(content, str):
|
|
105
|
+
m["content"] = [{"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}]
|
|
106
|
+
elif isinstance(content, list) and content:
|
|
107
|
+
# copy the last block so we don't mutate the shared dict, then mark it
|
|
108
|
+
content = [dict(b) if isinstance(b, dict) else b for b in content]
|
|
109
|
+
if isinstance(content[-1], dict):
|
|
110
|
+
content[-1] = {**content[-1], "cache_control": {"type": "ephemeral"}}
|
|
111
|
+
m["content"] = content
|
|
112
|
+
return out
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class AnthropicClient(LLMClient):
|
|
116
|
+
"""Anthropic Claude API client.
|
|
117
|
+
|
|
118
|
+
All model configuration comes from model_registry (single source of truth).
|
|
119
|
+
Deprecated fallback dicts removed Dec 13, 2025.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
# UP-07: the dead EXTENDED_THINKING_MODELS dict was removed — its budgets now live in
|
|
123
|
+
# model_registry (thinking_budget_tokens) and drive a real `thinking` block below.
|
|
124
|
+
|
|
125
|
+
def __init__(self, config: BotConfig, name: str = "anthropic_client"):
|
|
126
|
+
"""Initialize the client."""
|
|
127
|
+
super().__init__(config=config, name=name)
|
|
128
|
+
self._client = None
|
|
129
|
+
|
|
130
|
+
# Model and API configuration
|
|
131
|
+
self.model_type = config.get_llm_config()['anthropic'].get('model', get_default_model('anthropic'))
|
|
132
|
+
self.api_key = config.get_llm_config()['anthropic']['api_key']
|
|
133
|
+
self.last_response = None # Store the last response for token usage reporting
|
|
134
|
+
|
|
135
|
+
# Get defaults from model_registry (single source of truth)
|
|
136
|
+
from modules.llm.model_registry import get_model_config
|
|
137
|
+
model_config = get_model_config(self.model_type)
|
|
138
|
+
|
|
139
|
+
if model_config:
|
|
140
|
+
self.max_tokens = model_config.max_completion_tokens or 8192
|
|
141
|
+
else:
|
|
142
|
+
self.max_tokens = 8192 # Conservative fallback
|
|
143
|
+
|
|
144
|
+
# Resolve vision support via base helper (falls back to True if not in registry)
|
|
145
|
+
self.supports_vision = self._resolve_supports_vision()
|
|
146
|
+
|
|
147
|
+
self.temperature = 0.7 # Default temperature
|
|
148
|
+
|
|
149
|
+
self.logger.debug(
|
|
150
|
+
f"Anthropic client initialized: model={self.model_type}, "
|
|
151
|
+
f"supports_vision={self.supports_vision}"
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
def _validate_llm_config(self) -> None:
|
|
155
|
+
"""Validate LLM config."""
|
|
156
|
+
if not self.api_key:
|
|
157
|
+
raise ServiceError("Anthropic API key not provided")
|
|
158
|
+
|
|
159
|
+
def _profile_base_url(self) -> Optional[str]:
|
|
160
|
+
"""Read base_url from the Anthropic ProviderProfile (None => SDK default).
|
|
161
|
+
|
|
162
|
+
Delegates to the base ``_resolve_profile_base_url`` helper so that a
|
|
163
|
+
self-hosted gateway / proxy is configured in one place (profiles.py).
|
|
164
|
+
"""
|
|
165
|
+
return self._resolve_profile_base_url("anthropic")
|
|
166
|
+
|
|
167
|
+
async def _setup_client(self) -> None:
|
|
168
|
+
"""Set up the Anthropic client."""
|
|
169
|
+
try:
|
|
170
|
+
kwargs = {"api_key": self.api_key}
|
|
171
|
+
base_url = self._profile_base_url()
|
|
172
|
+
if base_url:
|
|
173
|
+
kwargs["base_url"] = base_url
|
|
174
|
+
self._client = anthropic.AsyncAnthropic(**kwargs)
|
|
175
|
+
self.logger.debug("Anthropic client setup completed")
|
|
176
|
+
except Exception as e:
|
|
177
|
+
raise ServiceError(f"Failed to set up Anthropic client: {e}")
|
|
178
|
+
|
|
179
|
+
async def _initialize(self) -> None:
|
|
180
|
+
"""Initialize the client."""
|
|
181
|
+
if self._initialized:
|
|
182
|
+
return
|
|
183
|
+
try:
|
|
184
|
+
# Validate configuration
|
|
185
|
+
self._validate_llm_config()
|
|
186
|
+
|
|
187
|
+
# Initialize client with API key
|
|
188
|
+
await self._setup_client()
|
|
189
|
+
|
|
190
|
+
# Validate connection (skipped for fast startup; clients validate
|
|
191
|
+
# lazily on first real call — matches the base client and gemini)
|
|
192
|
+
if not self._skip_validate:
|
|
193
|
+
await self._validate_connection()
|
|
194
|
+
|
|
195
|
+
self._initialized = True
|
|
196
|
+
|
|
197
|
+
except Exception as e:
|
|
198
|
+
self.logger.error(f"Failed to initialize Anthropic client: {e}")
|
|
199
|
+
raise ServiceError(f"Failed to initialize Anthropic client: {e}")
|
|
200
|
+
|
|
201
|
+
async def _generate_with_tools(
|
|
202
|
+
self,
|
|
203
|
+
messages: List[Dict[str, str]],
|
|
204
|
+
tools: List[Dict[str, Any]],
|
|
205
|
+
system: Optional[str] = None,
|
|
206
|
+
temperature: Optional[float] = None,
|
|
207
|
+
max_tokens: Optional[int] = None,
|
|
208
|
+
**kwargs
|
|
209
|
+
) -> Tuple[str, List[Dict[str, Any]]]:
|
|
210
|
+
"""Generate response with native tool/function calling support.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
Tuple of (content, tool_calls) where tool_calls is a list of tool call dicts
|
|
214
|
+
"""
|
|
215
|
+
start_time = time.time()
|
|
216
|
+
success = False
|
|
217
|
+
error_message = None
|
|
218
|
+
|
|
219
|
+
try:
|
|
220
|
+
# Ensure client is initialized
|
|
221
|
+
if not self._initialized:
|
|
222
|
+
await self._initialize()
|
|
223
|
+
|
|
224
|
+
# Convert messages to Anthropic format
|
|
225
|
+
anthropic_messages = []
|
|
226
|
+
for msg in messages:
|
|
227
|
+
role = msg.get('role', '')
|
|
228
|
+
content = msg.get('content', '')
|
|
229
|
+
|
|
230
|
+
# Skip system messages as they're handled separately, BUT recover
|
|
231
|
+
# the system prompt from the message list when no explicit `system`
|
|
232
|
+
# kwarg was supplied — the agent builds the real system prompt in the
|
|
233
|
+
# message list, not via the kwarg. Without this the entire system
|
|
234
|
+
# prompt (persona/brain-state format/security/tool guidance) is
|
|
235
|
+
# silently dropped on the Anthropic native tool path.
|
|
236
|
+
if role == 'system':
|
|
237
|
+
if system is None and isinstance(content, str) and content:
|
|
238
|
+
system = content
|
|
239
|
+
continue
|
|
240
|
+
|
|
241
|
+
# Map roles
|
|
242
|
+
if role == 'user':
|
|
243
|
+
anthropic_role = 'user'
|
|
244
|
+
elif role in ['assistant', 'ai']:
|
|
245
|
+
anthropic_role = 'assistant'
|
|
246
|
+
elif role == 'tool':
|
|
247
|
+
# Handle tool result messages
|
|
248
|
+
anthropic_role = 'user'
|
|
249
|
+
# Anthropic expects tool results in a specific format
|
|
250
|
+
tool_call_id = msg.get('tool_call_id', '')
|
|
251
|
+
content = [{
|
|
252
|
+
"type": "tool_result",
|
|
253
|
+
"tool_use_id": tool_call_id,
|
|
254
|
+
"content": content
|
|
255
|
+
}]
|
|
256
|
+
else:
|
|
257
|
+
self.logger.warning(f"Unknown role {role}, treating as user")
|
|
258
|
+
anthropic_role = 'user'
|
|
259
|
+
|
|
260
|
+
# Handle tool calls in assistant messages
|
|
261
|
+
if role == 'assistant' and 'tool_calls' in msg:
|
|
262
|
+
# Convert tool calls to Anthropic format
|
|
263
|
+
content_blocks = []
|
|
264
|
+
if content:
|
|
265
|
+
content_blocks.append({
|
|
266
|
+
"type": "text",
|
|
267
|
+
"text": content
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
for tool_call in msg['tool_calls']:
|
|
271
|
+
content_blocks.append({
|
|
272
|
+
"type": "tool_use",
|
|
273
|
+
"id": tool_call.get('id', ''),
|
|
274
|
+
"name": tool_call.get('function', {}).get('name', ''),
|
|
275
|
+
"input": json.loads(tool_call.get('function', {}).get('arguments', '{}'))
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
anthropic_messages.append({
|
|
279
|
+
"role": anthropic_role,
|
|
280
|
+
"content": content_blocks
|
|
281
|
+
})
|
|
282
|
+
else:
|
|
283
|
+
# Regular message
|
|
284
|
+
anthropic_messages.append({
|
|
285
|
+
"role": anthropic_role,
|
|
286
|
+
"content": content
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
# Use provided parameters or defaults
|
|
290
|
+
temp = temperature if temperature is not None else self.temperature
|
|
291
|
+
|
|
292
|
+
# Estimate input tokens (messages + system, Anthropic sends them separately)
|
|
293
|
+
estimated_input_tokens = count_messages_tokens(messages, self.model_type)
|
|
294
|
+
if system:
|
|
295
|
+
estimated_input_tokens += count_messages_tokens([{"role": "system", "content": system}], self.model_type)
|
|
296
|
+
|
|
297
|
+
# Clamp max_tokens to model limits (single canonical logic on base)
|
|
298
|
+
max_tokens_value = self._adjust_max_tokens(
|
|
299
|
+
messages=messages,
|
|
300
|
+
max_tokens=max_tokens,
|
|
301
|
+
estimated_input_tokens=estimated_input_tokens,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
# Log request
|
|
305
|
+
self.logger.info(f"Anthropic API request with tools: model={self.model_type}, tools={len(tools)}, max_tokens={max_tokens_value}")
|
|
306
|
+
|
|
307
|
+
# Filter kwargs - CRITICAL: Exclude 'system' to prevent override
|
|
308
|
+
supported_params = {
|
|
309
|
+
'model', 'messages', 'temperature', 'max_tokens',
|
|
310
|
+
'tools', 'tool_choice', 'metadata', 'top_p', 'top_k', 'stop_sequences'
|
|
311
|
+
}
|
|
312
|
+
filtered_kwargs = {k: v for k, v in kwargs.items() if k in supported_params}
|
|
313
|
+
|
|
314
|
+
# Make API request with tools
|
|
315
|
+
# Convert system to list form + add prompt-cache breakpoint (D4-a).
|
|
316
|
+
system_param = _build_cached_system_param(system)
|
|
317
|
+
|
|
318
|
+
# Build API call params - only include system if not None
|
|
319
|
+
api_params = {
|
|
320
|
+
'model': self.model_type,
|
|
321
|
+
'messages': anthropic_messages,
|
|
322
|
+
'temperature': temp,
|
|
323
|
+
'max_tokens': max_tokens_value,
|
|
324
|
+
'tools': tools,
|
|
325
|
+
'tool_choice': kwargs.get('tool_choice', {'type': 'auto'}),
|
|
326
|
+
**filtered_kwargs
|
|
327
|
+
}
|
|
328
|
+
if system_param is not None:
|
|
329
|
+
api_params['system'] = system_param
|
|
330
|
+
# B1: cache the conversation prefix (system + last 3 msgs = 4 breakpoints).
|
|
331
|
+
api_params['messages'] = _apply_conversation_cache(api_params['messages'])
|
|
332
|
+
|
|
333
|
+
# UP-07: extended-thinking block from the registry budget (gated, default OFF).
|
|
334
|
+
# Anthropic requires max_tokens > budget_tokens and temperature == 1 when
|
|
335
|
+
# thinking is enabled. Per-call override via kwargs['thinking'] wins.
|
|
336
|
+
from modules.llm.model_registry import (
|
|
337
|
+
thinking_config_enabled, get_thinking_config, get_model_config,
|
|
338
|
+
)
|
|
339
|
+
# P1-9: extended thinking + tool calls requires replaying the assistant's
|
|
340
|
+
# thinking block(s) (with their signature) ahead of tool_use on the NEXT
|
|
341
|
+
# request; this client discards thinking blocks (see response processing
|
|
342
|
+
# below) and never replays them, so the follow-up tool_result request 400s
|
|
343
|
+
# at step 2 of a tool loop. Until block-replay lands, REFUSE to enable
|
|
344
|
+
# thinking when tools are present (the agent's primary path is a tool loop).
|
|
345
|
+
# A forced non-auto tool_choice is likewise invalid with thinking — moot
|
|
346
|
+
# here since we never combine them. One-time WARN so it's visible.
|
|
347
|
+
if 'thinking' not in api_params and thinking_config_enabled():
|
|
348
|
+
if tools:
|
|
349
|
+
if not getattr(self, '_thinking_tools_warned', False):
|
|
350
|
+
self.logger.warning(
|
|
351
|
+
"extended thinking is disabled for tool-calling requests in "
|
|
352
|
+
"this build (thinking blocks are not yet replayed, which would "
|
|
353
|
+
"400 the follow-up tool_result request). Set THINKING_CONFIG_"
|
|
354
|
+
"ENABLED=off to silence, or use thinking only on no-tool calls."
|
|
355
|
+
)
|
|
356
|
+
self._thinking_tools_warned = True
|
|
357
|
+
else:
|
|
358
|
+
tcfg = get_thinking_config(self.model_type)
|
|
359
|
+
budget = tcfg.get('budget_tokens')
|
|
360
|
+
if budget:
|
|
361
|
+
# H4: clamp so max_tokens > budget AND max_tokens <= the model cap
|
|
362
|
+
# (registry entries set budget == cap, which overran the cap -> 400).
|
|
363
|
+
_cfg = get_model_config(self.model_type)
|
|
364
|
+
model_cap = getattr(_cfg, 'max_completion_tokens', None) if _cfg else None
|
|
365
|
+
budget, max_tokens_value = _clamp_thinking(model_cap, budget, max_tokens_value)
|
|
366
|
+
if budget:
|
|
367
|
+
api_params['thinking'] = {'type': 'enabled', 'budget_tokens': budget}
|
|
368
|
+
api_params['temperature'] = 1 # required by the API when thinking is on
|
|
369
|
+
api_params['max_tokens'] = max_tokens_value
|
|
370
|
+
|
|
371
|
+
# FIXED: Use streaming for high max_tokens to avoid Anthropic SDK error
|
|
372
|
+
# "Streaming is required for operations that may take longer than 10 minutes"
|
|
373
|
+
# This happens when max_tokens is high (e.g., 65536). A thinking budget raises
|
|
374
|
+
# max_tokens above 8192, so this path is always taken when thinking is on.
|
|
375
|
+
use_streaming = max_tokens_value > 8192
|
|
376
|
+
|
|
377
|
+
response_text = ""
|
|
378
|
+
tool_calls = []
|
|
379
|
+
|
|
380
|
+
if use_streaming:
|
|
381
|
+
self.logger.debug(f"Using streaming for tool call (max_tokens={max_tokens_value})")
|
|
382
|
+
# Use streaming to avoid timeout error
|
|
383
|
+
async with self._client.messages.stream(**api_params) as stream:
|
|
384
|
+
self.last_response = await stream.get_final_message()
|
|
385
|
+
else:
|
|
386
|
+
self.last_response = await self._client.messages.create(**api_params)
|
|
387
|
+
|
|
388
|
+
success = True
|
|
389
|
+
|
|
390
|
+
# Process response - extract both content and tool calls
|
|
391
|
+
if hasattr(self.last_response, 'content') and self.last_response.content:
|
|
392
|
+
for block in self.last_response.content:
|
|
393
|
+
if hasattr(block, 'type'):
|
|
394
|
+
if block.type == 'text' and hasattr(block, 'text'):
|
|
395
|
+
response_text += block.text + " "
|
|
396
|
+
elif block.type == 'tool_use':
|
|
397
|
+
# Convert Anthropic tool use to standard format
|
|
398
|
+
tool_calls.append({
|
|
399
|
+
'id': block.id,
|
|
400
|
+
'type': 'function',
|
|
401
|
+
'function': {
|
|
402
|
+
'name': block.name,
|
|
403
|
+
'arguments': json.dumps(block.input) if isinstance(block.input, dict) else str(block.input)
|
|
404
|
+
}
|
|
405
|
+
})
|
|
406
|
+
|
|
407
|
+
# Capture telemetry
|
|
408
|
+
self._extract_usage_and_capture_telemetry(start_time, success, None, kwargs.get('metadata'))
|
|
409
|
+
|
|
410
|
+
# Extract usage data
|
|
411
|
+
usage_data = self._extract_usage_data()
|
|
412
|
+
|
|
413
|
+
return response_text.strip(), tool_calls, usage_data
|
|
414
|
+
|
|
415
|
+
except Exception as e:
|
|
416
|
+
success = False
|
|
417
|
+
error_message = str(e)
|
|
418
|
+
self.logger.error(f"Anthropic tool calling error: {e}")
|
|
419
|
+
|
|
420
|
+
# Capture telemetry
|
|
421
|
+
self._extract_usage_and_capture_telemetry(start_time, success, error_message, kwargs.get('metadata'))
|
|
422
|
+
|
|
423
|
+
# Fall back to non-tool generation
|
|
424
|
+
self.logger.warning(f"Falling back to non-tool generation due to error: {e}")
|
|
425
|
+
response = await self._generate(messages, system, temperature, max_tokens, **kwargs)
|
|
426
|
+
# Canonical 3-tuple: usage is unavailable on this error path; use a zero/null dict
|
|
427
|
+
# consistent with _extract_usage_data()'s no-response shape.
|
|
428
|
+
fallback_usage: Dict[str, Optional[int]] = {
|
|
429
|
+
'prompt_tokens': None,
|
|
430
|
+
'completion_tokens': None,
|
|
431
|
+
'total_tokens': None,
|
|
432
|
+
}
|
|
433
|
+
return response, [], fallback_usage
|
|
434
|
+
|
|
435
|
+
# ✅ REFERENCE IMPLEMENTATION FOR ALL PROVIDERS
|
|
436
|
+
# This method demonstrates the correct pattern:
|
|
437
|
+
# 1. Extract system/temperature/max_tokens from kwargs
|
|
438
|
+
# 2. Pass them explicitly to _generate_with_tools
|
|
439
|
+
# 3. _generate_with_tools uses them in API call
|
|
440
|
+
# OpenAI and Gemini should match this pattern.
|
|
441
|
+
async def generate_agent_response(
|
|
442
|
+
self,
|
|
443
|
+
messages: List[Dict[str, Any]],
|
|
444
|
+
tools: List[Dict[str, Any]],
|
|
445
|
+
**kwargs
|
|
446
|
+
) -> Tuple[str, List[Dict[str, Any]], Dict[str, Optional[int]]]:
|
|
447
|
+
"""Generate response with tool-calling support for agents.
|
|
448
|
+
|
|
449
|
+
This method bridges the adapter contract to enable native tool-calling
|
|
450
|
+
for Anthropic. It delegates to _generate_with_tools which handles the
|
|
451
|
+
wire-format conversion and API interaction.
|
|
452
|
+
|
|
453
|
+
Args:
|
|
454
|
+
messages: List of message dictionaries
|
|
455
|
+
tools: List of tool schemas in provider format
|
|
456
|
+
**kwargs: Additional generation parameters (including system, temperature, etc.)
|
|
457
|
+
|
|
458
|
+
Returns:
|
|
459
|
+
3-tuple (content, tool_calls, usage_data). tool_calls may be empty list when
|
|
460
|
+
the model produced no tool calls. usage_data dict contains:
|
|
461
|
+
prompt_tokens, completion_tokens, total_tokens.
|
|
462
|
+
|
|
463
|
+
Raises:
|
|
464
|
+
LLMError: If generation fails
|
|
465
|
+
"""
|
|
466
|
+
try:
|
|
467
|
+
self.logger.info(f"[generate_agent_response] Called with {len(messages)} messages and {len(tools) if tools else 0} tools")
|
|
468
|
+
|
|
469
|
+
# Extract system message if present in kwargs
|
|
470
|
+
system = kwargs.pop('system', None)
|
|
471
|
+
temperature = kwargs.pop('temperature', None)
|
|
472
|
+
max_tokens = kwargs.pop('max_tokens', None)
|
|
473
|
+
|
|
474
|
+
# Call the existing _generate_with_tools method
|
|
475
|
+
result = await self._generate_with_tools(
|
|
476
|
+
messages=messages,
|
|
477
|
+
tools=tools,
|
|
478
|
+
system=system,
|
|
479
|
+
temperature=temperature,
|
|
480
|
+
max_tokens=max_tokens,
|
|
481
|
+
**kwargs
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
# _generate_with_tools ALWAYS returns a 3-tuple (content, tool_calls, usage).
|
|
485
|
+
# Unpack directly; a non-3-tuple here is a programming error.
|
|
486
|
+
content, tool_calls, usage = result
|
|
487
|
+
self.logger.info(f"[generate_agent_response] Returning 3-tuple with {len(tool_calls)} tool calls + usage")
|
|
488
|
+
|
|
489
|
+
return result
|
|
490
|
+
|
|
491
|
+
except LLMError:
|
|
492
|
+
# Re-raise LLM errors as-is
|
|
493
|
+
raise
|
|
494
|
+
except Exception as e:
|
|
495
|
+
# Wrap other exceptions using core.exceptions pattern
|
|
496
|
+
self.logger.error(f"generate_agent_response failed: {str(e)}", exc_info=True)
|
|
497
|
+
raise LLMError(f"Failed to generate agent response: {str(e)}")
|
|
498
|
+
|
|
499
|
+
async def _generate(
|
|
500
|
+
self,
|
|
501
|
+
messages: List[Dict[str, str]],
|
|
502
|
+
system: Optional[str] = None,
|
|
503
|
+
temperature: Optional[float] = None,
|
|
504
|
+
max_tokens: Optional[int] = None,
|
|
505
|
+
**kwargs
|
|
506
|
+
) -> str:
|
|
507
|
+
"""Generate a response from Claude API."""
|
|
508
|
+
start_time = time.time()
|
|
509
|
+
success = False
|
|
510
|
+
error_message = None
|
|
511
|
+
|
|
512
|
+
try:
|
|
513
|
+
# Ensure client is initialized
|
|
514
|
+
if not self._initialized:
|
|
515
|
+
await self._initialize()
|
|
516
|
+
|
|
517
|
+
# Convert messages to Anthropic format, skipping system
|
|
518
|
+
anthropic_messages = []
|
|
519
|
+
for msg in messages:
|
|
520
|
+
role = msg.get('role', '')
|
|
521
|
+
content = msg.get('content', '')
|
|
522
|
+
|
|
523
|
+
# Skip system messages as they're handled separately in Claude API,
|
|
524
|
+
# BUT recover the in-list system prompt when no explicit `system`
|
|
525
|
+
# kwarg was supplied (see _generate_with_tools for rationale).
|
|
526
|
+
if role == 'system':
|
|
527
|
+
if system is None and isinstance(content, str) and content:
|
|
528
|
+
system = content
|
|
529
|
+
continue
|
|
530
|
+
|
|
531
|
+
# Map roles
|
|
532
|
+
if role == 'user':
|
|
533
|
+
anthropic_role = 'user'
|
|
534
|
+
elif role in ['assistant', 'ai']:
|
|
535
|
+
anthropic_role = 'assistant'
|
|
536
|
+
else:
|
|
537
|
+
self.logger.warning(f"Unknown role {role}, treating as user")
|
|
538
|
+
anthropic_role = 'user'
|
|
539
|
+
|
|
540
|
+
anthropic_messages.append({
|
|
541
|
+
"role": anthropic_role,
|
|
542
|
+
"content": content
|
|
543
|
+
})
|
|
544
|
+
|
|
545
|
+
# Use provided parameters or default to instance attributes
|
|
546
|
+
temp = temperature if temperature is not None else self.temperature
|
|
547
|
+
|
|
548
|
+
# Estimate input tokens (messages + system, Anthropic sends them separately)
|
|
549
|
+
estimated_input_tokens = count_messages_tokens(messages, self.model_type)
|
|
550
|
+
if system:
|
|
551
|
+
# Add system message token estimate
|
|
552
|
+
estimated_input_tokens += count_messages_tokens([{"role": "system", "content": system}], self.model_type)
|
|
553
|
+
|
|
554
|
+
# Clamp max_tokens to model limits (single canonical logic on base)
|
|
555
|
+
max_tokens_value = self._adjust_max_tokens(
|
|
556
|
+
messages=messages,
|
|
557
|
+
max_tokens=max_tokens,
|
|
558
|
+
estimated_input_tokens=estimated_input_tokens,
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
# Log request details with proper values being used
|
|
562
|
+
self.logger.info(f"Anthropic API request: model={self.model_type}, temperature={temp}, max_tokens={max_tokens_value}, est_input_tokens={estimated_input_tokens}")
|
|
563
|
+
|
|
564
|
+
# Filter kwargs to only include supported parameters
|
|
565
|
+
# CRITICAL: Exclude 'system' from kwargs to prevent override of system_param
|
|
566
|
+
supported_params = {
|
|
567
|
+
'model', 'messages', 'temperature', 'max_tokens',
|
|
568
|
+
'metadata', 'top_p', 'top_k', 'stop_sequences', 'stream'
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
filtered_kwargs = {k: v for k, v in kwargs.items() if k in supported_params}
|
|
572
|
+
|
|
573
|
+
# Make API request
|
|
574
|
+
# Convert system to list form + add prompt-cache breakpoint (D4-a).
|
|
575
|
+
system_param = _build_cached_system_param(system)
|
|
576
|
+
|
|
577
|
+
# Build API call params - only include system if not None
|
|
578
|
+
api_params = {
|
|
579
|
+
'model': self.model_type,
|
|
580
|
+
'messages': anthropic_messages,
|
|
581
|
+
'temperature': temp,
|
|
582
|
+
'max_tokens': max_tokens_value,
|
|
583
|
+
**filtered_kwargs
|
|
584
|
+
}
|
|
585
|
+
if system_param is not None:
|
|
586
|
+
api_params['system'] = system_param
|
|
587
|
+
# B1: cache the conversation prefix (system + last 3 msgs = 4 breakpoints).
|
|
588
|
+
api_params['messages'] = _apply_conversation_cache(api_params['messages'])
|
|
589
|
+
|
|
590
|
+
# FIXED: Use streaming for high max_tokens to avoid Anthropic SDK error
|
|
591
|
+
# "Streaming is required for operations that may take longer than 10 minutes"
|
|
592
|
+
use_streaming = max_tokens_value > 8192
|
|
593
|
+
|
|
594
|
+
if use_streaming:
|
|
595
|
+
self.logger.debug(f"Using streaming for _generate (max_tokens={max_tokens_value})")
|
|
596
|
+
async with self._client.messages.stream(**api_params) as stream:
|
|
597
|
+
self.last_response = await stream.get_final_message()
|
|
598
|
+
else:
|
|
599
|
+
self.last_response = await self._client.messages.create(**api_params)
|
|
600
|
+
|
|
601
|
+
# Mark as successful
|
|
602
|
+
success = True
|
|
603
|
+
|
|
604
|
+
# Process response
|
|
605
|
+
response_text = ""
|
|
606
|
+
if hasattr(self.last_response, 'content') and self.last_response.content:
|
|
607
|
+
text_blocks = [
|
|
608
|
+
block.text for block in self.last_response.content
|
|
609
|
+
if hasattr(block, 'text') and block.text
|
|
610
|
+
]
|
|
611
|
+
response_text = " ".join(text_blocks)
|
|
612
|
+
|
|
613
|
+
# Capture telemetry with actual timing and usage data
|
|
614
|
+
self._extract_usage_and_capture_telemetry(start_time, success, None, kwargs.get('metadata'))
|
|
615
|
+
|
|
616
|
+
return response_text
|
|
617
|
+
|
|
618
|
+
except anthropic.APIError as e:
|
|
619
|
+
success = False
|
|
620
|
+
error_message = str(e)
|
|
621
|
+
self.logger.error(f"Anthropic API error: {e}")
|
|
622
|
+
|
|
623
|
+
# Capture telemetry for failed requests too
|
|
624
|
+
self._extract_usage_and_capture_telemetry(start_time, success, error_message, kwargs.get('metadata'))
|
|
625
|
+
|
|
626
|
+
raise ServiceError(f"Anthropic API error: {e}")
|
|
627
|
+
except Exception as e:
|
|
628
|
+
success = False
|
|
629
|
+
error_message = str(e)
|
|
630
|
+
self.logger.error(f"Error generating response from Anthropic: {e}")
|
|
631
|
+
|
|
632
|
+
# Capture telemetry for failed requests too
|
|
633
|
+
self._extract_usage_and_capture_telemetry(start_time, success, error_message, kwargs.get('metadata'))
|
|
634
|
+
|
|
635
|
+
raise ServiceError(f"Error generating response from Anthropic: {e}")
|
|
636
|
+
|
|
637
|
+
async def generate_response(
|
|
638
|
+
self,
|
|
639
|
+
prompt: Optional[Union[str, Dict[str, Any]]] = None,
|
|
640
|
+
messages: Optional[List[Dict[str, str]]] = None,
|
|
641
|
+
system: Optional[str] = None,
|
|
642
|
+
temperature: Optional[float] = None,
|
|
643
|
+
max_tokens: Optional[int] = None,
|
|
644
|
+
metadata: Optional[Dict[str, Any]] = None,
|
|
645
|
+
**kwargs
|
|
646
|
+
) -> str:
|
|
647
|
+
"""Generate a response from the LLM."""
|
|
648
|
+
try:
|
|
649
|
+
# Handle prompt formats
|
|
650
|
+
if messages is not None:
|
|
651
|
+
# Use messages directly if provided
|
|
652
|
+
formatted_messages = messages
|
|
653
|
+
elif isinstance(prompt, list) and all(isinstance(m, dict) for m in prompt):
|
|
654
|
+
# Prompt is already a list of messages
|
|
655
|
+
formatted_messages = prompt
|
|
656
|
+
elif isinstance(prompt, dict) and 'messages' in prompt:
|
|
657
|
+
# Extract messages and system from prompt dict
|
|
658
|
+
formatted_messages = prompt['messages']
|
|
659
|
+
if 'system' in prompt and not system:
|
|
660
|
+
system = prompt['system']
|
|
661
|
+
elif isinstance(prompt, str):
|
|
662
|
+
# Convert string prompt to message format
|
|
663
|
+
formatted_messages = [{"role": "user", "content": prompt}]
|
|
664
|
+
else:
|
|
665
|
+
# Default to empty message
|
|
666
|
+
formatted_messages = [{"role": "user", "content": "Hello"}]
|
|
667
|
+
|
|
668
|
+
# Anthropic doesn't support all metadata types
|
|
669
|
+
# Filter to what we can use
|
|
670
|
+
filtered_kwargs = kwargs.copy()
|
|
671
|
+
|
|
672
|
+
# Ensure metadata is passed through to _generate for telemetry
|
|
673
|
+
if metadata:
|
|
674
|
+
filtered_kwargs['metadata'] = metadata
|
|
675
|
+
|
|
676
|
+
# Extract Anthropic-supported metadata
|
|
677
|
+
anthropic_metadata = {}
|
|
678
|
+
for key, value in metadata.items():
|
|
679
|
+
# Anthropic supports user_id in metadata
|
|
680
|
+
if key == 'user_id' and isinstance(value, str):
|
|
681
|
+
anthropic_metadata[key] = value
|
|
682
|
+
|
|
683
|
+
# Only include if we have valid metadata for Anthropic
|
|
684
|
+
if anthropic_metadata:
|
|
685
|
+
filtered_kwargs.update(anthropic_metadata)
|
|
686
|
+
|
|
687
|
+
# Generate response
|
|
688
|
+
response = await self._generate(
|
|
689
|
+
messages=formatted_messages,
|
|
690
|
+
system=system,
|
|
691
|
+
temperature=temperature,
|
|
692
|
+
max_tokens=max_tokens,
|
|
693
|
+
**filtered_kwargs
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
return response
|
|
697
|
+
|
|
698
|
+
except Exception as e:
|
|
699
|
+
self.logger.error(f"Failed to generate response: {e}")
|
|
700
|
+
raise ServiceError(f"Failed to generate response: {e}")
|
|
701
|
+
|
|
702
|
+
async def _validate_connection(self) -> None:
|
|
703
|
+
"""Validate connection to Anthropic."""
|
|
704
|
+
try:
|
|
705
|
+
# Simple test completion
|
|
706
|
+
response = await self._client.messages.create(
|
|
707
|
+
model=self.model_type,
|
|
708
|
+
max_tokens=10,
|
|
709
|
+
messages=[{"role": "user", "content": "Test connection"}]
|
|
710
|
+
)
|
|
711
|
+
if not response:
|
|
712
|
+
raise LLMConnectionError("No response from Anthropic API")
|
|
713
|
+
self.logger.debug("Anthropic API connection validated successfully")
|
|
714
|
+
except Exception as e:
|
|
715
|
+
self.logger.error(f"Failed to validate Anthropic connection: {e}")
|
|
716
|
+
raise ServiceError(f"Failed to validate Anthropic connection: {e}")
|
|
717
|
+
|
|
718
|
+
async def _cleanup_client(self) -> None:
|
|
719
|
+
"""Clean up Anthropic client."""
|
|
720
|
+
try:
|
|
721
|
+
if hasattr(self, '_client'):
|
|
722
|
+
# Just set it to None for garbage collection
|
|
723
|
+
self._client = None
|
|
724
|
+
self.logger.debug("Anthropic client resources released")
|
|
725
|
+
except Exception as e:
|
|
726
|
+
self.logger.error(f"Error cleaning up Anthropic client: {e}")
|
|
727
|
+
|
|
728
|
+
async def cleanup(self) -> None:
|
|
729
|
+
"""Clean up resources."""
|
|
730
|
+
await self._cleanup_client()
|
|
731
|
+
self._client = None
|
|
732
|
+
self._initialized = False
|
|
733
|
+
self.logger.info("Anthropic client cleaned up")
|
|
734
|
+
|
|
735
|
+
def _format_messages(self, prompt: Union[str, List[Dict[str, Any]], Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
736
|
+
"""Format messages for Anthropic API."""
|
|
737
|
+
try:
|
|
738
|
+
if isinstance(prompt, str):
|
|
739
|
+
return [{
|
|
740
|
+
"role": "user",
|
|
741
|
+
"content": prompt
|
|
742
|
+
}]
|
|
743
|
+
elif isinstance(prompt, list):
|
|
744
|
+
return [
|
|
745
|
+
{
|
|
746
|
+
"role": msg.get("role", "user"),
|
|
747
|
+
"content": msg.get("content", "")
|
|
748
|
+
}
|
|
749
|
+
for msg in prompt
|
|
750
|
+
if msg.get("content") and msg.get("role") != "system" # Skip system and empty messages
|
|
751
|
+
]
|
|
752
|
+
elif isinstance(prompt, dict):
|
|
753
|
+
messages = []
|
|
754
|
+
|
|
755
|
+
# Handle messages list
|
|
756
|
+
if "messages" in prompt:
|
|
757
|
+
return [
|
|
758
|
+
{
|
|
759
|
+
"role": msg.get("role", "user"),
|
|
760
|
+
"content": msg.get("content", "")
|
|
761
|
+
}
|
|
762
|
+
for msg in prompt["messages"]
|
|
763
|
+
if msg.get("content") and msg.get("role") != "system" # Skip system and empty messages
|
|
764
|
+
]
|
|
765
|
+
|
|
766
|
+
return messages
|
|
767
|
+
|
|
768
|
+
return []
|
|
769
|
+
|
|
770
|
+
except Exception as e:
|
|
771
|
+
self.logger.error(f"Error formatting messages: {e}")
|
|
772
|
+
raise LLMError(f"Failed to format messages: {e}")
|
|
773
|
+
|
|
774
|
+
async def _make_validation_request(self) -> Any:
|
|
775
|
+
"""Make minimal test request to Anthropic."""
|
|
776
|
+
return await self._client.messages.create(
|
|
777
|
+
model=self.model_type,
|
|
778
|
+
messages=[{"role": "user", "content": "test"}],
|
|
779
|
+
max_tokens=1
|
|
780
|
+
)
|
|
781
|
+
|
|
782
|
+
def _check_validation_response(self, response: Any) -> None:
|
|
783
|
+
"""Validate Anthropic response."""
|
|
784
|
+
if not response or not response.content:
|
|
785
|
+
raise ValueError("Invalid response from Anthropic")
|
|
786
|
+
|
|
787
|
+
def _extract_usage_data(self) -> Dict[str, Optional[int]]:
|
|
788
|
+
"""Extract usage data from last_response.
|
|
789
|
+
|
|
790
|
+
Returns dict with prompt_tokens, completion_tokens, total_tokens.
|
|
791
|
+
Returns None values if usage data not available.
|
|
792
|
+
|
|
793
|
+
Note: Anthropic uses input_tokens/output_tokens, we map to standard names.
|
|
794
|
+
"""
|
|
795
|
+
if not self.last_response:
|
|
796
|
+
self.logger.warning("No last_response available for usage extraction")
|
|
797
|
+
return {'prompt_tokens': None, 'completion_tokens': None, 'total_tokens': None}
|
|
798
|
+
|
|
799
|
+
if not hasattr(self.last_response, 'usage') or not self.last_response.usage:
|
|
800
|
+
self.logger.warning(f"No usage data in response for model {self.model_type}")
|
|
801
|
+
return {'prompt_tokens': None, 'completion_tokens': None, 'total_tokens': None}
|
|
802
|
+
|
|
803
|
+
usage = self.last_response.usage
|
|
804
|
+
# Anthropic uses input_tokens/output_tokens instead of prompt/completion
|
|
805
|
+
input_tokens = getattr(usage, 'input_tokens', None)
|
|
806
|
+
output_tokens = getattr(usage, 'output_tokens', None)
|
|
807
|
+
|
|
808
|
+
# Anthropic reports cache reads/writes SEPARATELY and EXCLUDES them from
|
|
809
|
+
# input_tokens (total input = input_tokens + cache_read + cache_creation).
|
|
810
|
+
# Fold them back so the meter sees full input, expose cache READS as
|
|
811
|
+
# cached_tokens (billed at 0.1x) and cache CREATION as cache_creation_tokens
|
|
812
|
+
# (G3: billed at 1.25x via ModelPricing.cache_write_price downstream).
|
|
813
|
+
cache_read = getattr(usage, 'cache_read_input_tokens', 0) or 0
|
|
814
|
+
cache_creation = getattr(usage, 'cache_creation_input_tokens', 0) or 0
|
|
815
|
+
total_input = None if input_tokens is None else input_tokens + cache_read + cache_creation
|
|
816
|
+
|
|
817
|
+
# Calculate total
|
|
818
|
+
total_tokens = None
|
|
819
|
+
if total_input is not None and output_tokens is not None:
|
|
820
|
+
total_tokens = total_input + output_tokens
|
|
821
|
+
|
|
822
|
+
usage_data = {
|
|
823
|
+
'prompt_tokens': total_input,
|
|
824
|
+
'completion_tokens': output_tokens,
|
|
825
|
+
'total_tokens': total_tokens,
|
|
826
|
+
'cached_tokens': cache_read,
|
|
827
|
+
'cache_creation_tokens': cache_creation
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
self.logger.debug(f"Extracted usage: {usage_data}")
|
|
831
|
+
return usage_data
|