agentengine-sdk-python 0.8.8__py3-none-any.whl → 0.8.9__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.
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/METADATA +12 -15
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/RECORD +181 -173
- ksadk/_build_provenance.json +1 -1
- ksadk/agui/agent.py +1 -1
- ksadk/builders/framework_requirements.py +1 -1
- ksadk/cli/cmd_run.py +4 -0
- ksadk/cli/cmd_web.py +4 -0
- ksadk/cli/runtime_logging.py +30 -0
- ksadk/context_engine/capabilities.py +13 -9
- ksadk/conversations/context.py +5 -0
- ksadk/conversations/message_projection.py +28 -19
- ksadk/conversations/runtime_compaction.py +6 -2
- ksadk/conversations/runtime_input.py +4 -0
- ksadk/conversations/runtime_invocation.py +5 -1
- ksadk/conversations/runtime_metadata.py +6 -7
- ksadk/conversations/runtime_payloads.py +5 -1
- ksadk/conversations/runtime_persistence.py +23 -0
- ksadk/conversations/runtime_preparation.py +128 -5
- ksadk/events/adapters/langgraph.py +53 -1
- ksadk/kernel/control.py +16 -22
- ksadk/kernel/history_projection.py +191 -58
- ksadk/kernel/ingress.py +16 -2
- ksadk/kernel/postgres_event_log.py +10 -2
- ksadk/kernel/postgres_store.py +81 -2
- ksadk/kernel/run_references.py +38 -0
- ksadk/kernel/worker_controls.py +11 -1
- ksadk/mcp_runtime/oauth/kernel.py +5 -0
- ksadk/mcp_runtime/oauth/local/broker.py +18 -8
- ksadk/mcp_runtime/oauth/local/protocol.py +3 -11
- ksadk/mcp_runtime/oauth/local/transport.py +9 -2
- ksadk/resource_runtime/contracts.py +39 -1
- ksadk/resource_runtime/managed_projection.py +8 -6
- ksadk/resource_runtime/worker.py +8 -1
- ksadk/runners/_adk_canonical_stream.py +16 -15
- ksadk/runners/_langgraph_answer_contract.py +1 -7
- ksadk/runners/_langgraph_canonical_stream.py +13 -6
- ksadk/runners/_langgraph_context.py +265 -0
- ksadk/runners/_langgraph_model_budget.py +397 -0
- ksadk/runners/_langgraph_runner_streams.py +7 -6
- ksadk/runners/adk_runner.py +13 -21
- ksadk/runners/langgraph_runner.py +130 -8
- ksadk/runners/usage_accumulator.py +40 -0
- ksadk/runtime/conversation_execution.py +26 -4
- ksadk/server/factory.py +3 -1
- ksadk/server/routes/control.py +24 -8
- ksadk/server/routes/history_items.py +157 -0
- ksadk/server/routes/kernel_ingress.py +51 -12
- ksadk/server/routes/local_kernel_control.py +16 -0
- ksadk/server/routes/models.py +26 -0
- ksadk/server/routes/openai_compat.py +10 -3
- ksadk/server/routes/projection.py +4 -0
- ksadk/server/routes/run.py +4 -2
- ksadk/server/routes/sessions.py +20 -1
- ksadk/server/static/assets/{ArtifactsPanel-Cdr5C_vM.js → ArtifactsPanel-iZ_6CAQ2.js} +1 -1
- ksadk/server/static/assets/{CodeBlock-BWRafud9.js → CodeBlock-D6uglm5n.js} +1 -1
- ksadk/server/static/assets/{MathMessageMarkdown-CFKeJIvy.js → MathMessageMarkdown-D6ojdxCG.js} +1 -1
- ksadk/server/static/assets/{MermaidBlock-BneAGUOd.js → MermaidBlock-Csk2ivT7.js} +6 -6
- ksadk/server/static/assets/{NativeTerminalPanel-BHI85zDO.js → NativeTerminalPanel-CCJA1XSH.js} +1 -1
- ksadk/server/static/assets/{OfficialA2uiRenderer-BOmT36lJ.js → OfficialA2uiRenderer-C06jus9N.js} +1 -1
- ksadk/server/static/assets/{abnfDiagram-VCTEODGH-DQvlOsBI.js → abnfDiagram-VCTEODGH-BhrF5tmL.js} +1 -1
- ksadk/server/static/assets/{arc-CGx0e4pN.js → arc-Btsh3kfy.js} +1 -1
- ksadk/server/static/assets/architecture-7GRP2DOG-BSXho3cq.js +1 -0
- ksadk/server/static/assets/{architectureDiagram-5GKGNRK7-WyybcNKX.js → architectureDiagram-5GKGNRK7-Cl8MfAmp.js} +1 -1
- ksadk/server/static/assets/{blockDiagram-NRAW4CY4-C9Cx_GVs.js → blockDiagram-NRAW4CY4-CeHSr8E_.js} +1 -1
- ksadk/server/static/assets/{c4Diagram-UCG6FXSJ-Bh7X3bGr.js → c4Diagram-UCG6FXSJ-BSD7RUKo.js} +1 -1
- ksadk/server/static/assets/channel-BpyDVKis.js +1 -0
- ksadk/server/static/assets/chunk-2Q5K7J3B-HLcpmPI2.js +1 -0
- ksadk/server/static/assets/{chunk-5VM5RSS4-cP9XupZj.js → chunk-5VM5RSS4-wz0pkBjp.js} +1 -1
- ksadk/server/static/assets/{chunk-F27PBJKO-Bm77fvR9.js → chunk-F27PBJKO-shjQ7cPM.js} +1 -1
- ksadk/server/static/assets/{chunk-G27WJ6UU-DDKNPesQ.js → chunk-G27WJ6UU-DL_MfUsu.js} +1 -1
- ksadk/server/static/assets/{chunk-JWPE2WC7-BqiUDB7s.js → chunk-JWPE2WC7-moUdwYpb.js} +1 -1
- ksadk/server/static/assets/{chunk-LCL6LL3I-C528mMZy.js → chunk-LCL6LL3I-B3QcDsZM.js} +1 -1
- ksadk/server/static/assets/{chunk-POPQ4Y6H-CzZ9g_Uf.js → chunk-POPQ4Y6H-BLBKb48A.js} +1 -1
- ksadk/server/static/assets/{chunk-RHFEMEQ7-CXj4tUZ-.js → chunk-RHFEMEQ7-CXR6ZzOx.js} +1 -1
- ksadk/server/static/assets/{chunk-SVP7TREG-BHyd85pS.js → chunk-SVP7TREG-DoR8BxkO.js} +1 -1
- ksadk/server/static/assets/{chunk-XXDRQBXY-Qe29PHGe.js → chunk-XXDRQBXY-8HJaIq0q.js} +1 -1
- ksadk/server/static/assets/classDiagram-DTDB5LWJ-DlNiRtSN.js +1 -0
- ksadk/server/static/assets/classDiagram-v2-JRS7N3AN-DlNiRtSN.js +1 -0
- ksadk/server/static/assets/{cose-bilkent-JH36ORCC-maRKgeec.js → cose-bilkent-JH36ORCC-DnSSHHqS.js} +1 -1
- ksadk/server/static/assets/cynefin-OW5HDTMX-DxNym3qg.js +1 -0
- ksadk/server/static/assets/{cynefinDiagram-5FMLGOSQ-CoD0bEvn.js → cynefinDiagram-5FMLGOSQ-4eCi_Rw5.js} +1 -1
- ksadk/server/static/assets/{dagre-3AP2YEHR-BkpgQqyW.js → dagre-3AP2YEHR-DpPk9jsh.js} +1 -1
- ksadk/server/static/assets/{dagre-BUaTFrYa.js → dagre-G789Mawt.js} +1 -1
- ksadk/server/static/assets/{diagram-S7CK7UJ4-25HdTbjE.js → diagram-S7CK7UJ4-7x2FScRJ.js} +1 -1
- ksadk/server/static/assets/{diagram-UQ7AKVKN-KO-WqOIg.js → diagram-UQ7AKVKN-DGvliWDD.js} +1 -1
- ksadk/server/static/assets/{diagram-VSXAHHWV-B360BkDQ.js → diagram-VSXAHHWV-C0i4uEyS.js} +1 -1
- ksadk/server/static/assets/{diagram-VX7I27RA-COr1Oqsg.js → diagram-VX7I27RA-C7SmgIl5.js} +1 -1
- ksadk/server/static/assets/{diagram-Z3DM3KII-CgaKrIwB.js → diagram-Z3DM3KII-Xca7TB4U.js} +1 -1
- ksadk/server/static/assets/{dist-By-MVndb.js → dist-B3rsrE8r.js} +1 -1
- ksadk/server/static/assets/{dist-Bsuusoi0.js → dist-BM6KIyhr.js} +1 -1
- ksadk/server/static/assets/{dist-DzdXSBJb.js → dist-BMZKBrmN.js} +1 -1
- ksadk/server/static/assets/{dist-DmWw0IXB.js → dist-BUGNcOx8.js} +1 -1
- ksadk/server/static/assets/{dist-DXOlCAay.js → dist-BbIN_x76.js} +1 -1
- ksadk/server/static/assets/{dist--HftQyp9.js → dist-CGB89Aru.js} +1 -1
- ksadk/server/static/assets/{dist-DKG0OYnk.js → dist-CGIWL8mC.js} +1 -1
- ksadk/server/static/assets/{dist-DgJ57sRe.js → dist-CHeuPGXZ.js} +1 -1
- ksadk/server/static/assets/{dist-_0Xgu_07.js → dist-CMJq3QL-.js} +1 -1
- ksadk/server/static/assets/{dist-CwnkOyDn.js → dist-CiUeIDKz.js} +1 -1
- ksadk/server/static/assets/{dist-BoRn8a_t.js → dist-CmaZEf5M.js} +1 -1
- ksadk/server/static/assets/{dist-BQ116UdZ.js → dist-Cq4qlsg3.js} +1 -1
- ksadk/server/static/assets/{dist-CBo9AHUv.js → dist-DDVDyH7h.js} +1 -1
- ksadk/server/static/assets/{dist-DSw5Ju6-.js → dist-DDi9q5bO.js} +1 -1
- ksadk/server/static/assets/{dist-CxIl4t92.js → dist-DJ8mj6p4.js} +1 -1
- ksadk/server/static/assets/{dist-Brbrdmff.js → dist-DRGym1nc.js} +1 -1
- ksadk/server/static/assets/{dist-BEbS8Bag.js → dist-DcrTYAeW.js} +1 -1
- ksadk/server/static/assets/{dist-C9BTMVwS.js → dist-DpuxDDLa.js} +1 -1
- ksadk/server/static/assets/{dist-B3Jp5r1e.js → dist-EFGQ7G_k.js} +1 -1
- ksadk/server/static/assets/{dist-HHvdjADB.js → dist-IyCF0NNA.js} +1 -1
- ksadk/server/static/assets/{dist-Bxcu8Ca0.js → dist-Ny95vkRV.js} +1 -1
- ksadk/server/static/assets/{dist-CR61WJFC.js → dist-s5cohO5C.js} +1 -1
- ksadk/server/static/assets/{ebnfDiagram-PWID7BFC-DogDP2db.js → ebnfDiagram-PWID7BFC-DNwVczAJ.js} +1 -1
- ksadk/server/static/assets/{erDiagram-SSCWMZ5O-CeBDnUjR.js → erDiagram-SSCWMZ5O-OxFlhx6v.js} +1 -1
- ksadk/server/static/assets/eventmodeling-NTZA5JFV-C-gXDupK.js +1 -0
- ksadk/server/static/assets/flowDiagram-A5DVABFB-CkpCYD4e.js +1 -0
- ksadk/server/static/assets/{ganttDiagram-EL5Y4UJY-oIQL3MCp.js → ganttDiagram-EL5Y4UJY-D4krNgUz.js} +1 -1
- ksadk/server/static/assets/gitGraph-4MIJSDKK-0RSkEgC5.js +1 -0
- ksadk/server/static/assets/{gitGraphDiagram-WWUBYQGX-B7qz0cmZ.js → gitGraphDiagram-WWUBYQGX-BUSVPN1s.js} +1 -1
- ksadk/server/static/assets/index-B9UP7He9.css +2 -0
- ksadk/server/static/assets/index-COn4kn-G.js +1135 -0
- ksadk/server/static/assets/info-A6RAGUB7-C6KX7WO4.js +1 -0
- ksadk/server/static/assets/{infoDiagram-RXCK75RN-yQRC41Ya.js → infoDiagram-RXCK75RN-b6w3u3-O.js} +1 -1
- ksadk/server/static/assets/{ishikawaDiagram-5VMMS53U-BCu4HiwL.js → ishikawaDiagram-5VMMS53U-CsC7gzRt.js} +1 -1
- ksadk/server/static/assets/{journeyDiagram-EYS64GPL-JaqmO73K.js → journeyDiagram-EYS64GPL-BATLNoy1.js} +1 -1
- ksadk/server/static/assets/{kanban-definition-3QL26DDD-DQo4X8NO.js → kanban-definition-3QL26DDD-C49zL_s0.js} +1 -1
- ksadk/server/static/assets/{katex-t_DWylQw.js → katex-CDVgGGy2.js} +1 -1
- ksadk/server/static/assets/{linear-DWdnI35B.js → linear-DkyDumSy.js} +1 -1
- ksadk/server/static/assets/{mermaid-parser.core-BHrT2Pfe.js → mermaid-parser.core-BDX-LqSy.js} +2 -2
- ksadk/server/static/assets/{mindmap-definition-FBJOCRG2-PBVAhZYV.js → mindmap-definition-FBJOCRG2-DRPnzL2n.js} +1 -1
- ksadk/server/static/assets/packet-AYTQ26CC-CMMupxPW.js +1 -0
- ksadk/server/static/assets/{pegDiagram-XKGWAZYB-CU_cLfow.js → pegDiagram-XKGWAZYB-Zm-xrNrr.js} +1 -1
- ksadk/server/static/assets/pie-WAS4IAKB-Bfo0pa9v.js +1 -0
- ksadk/server/static/assets/{pieDiagram-E7YTZNPT-B1h0-_pW.js → pieDiagram-E7YTZNPT-a8C1Jxo4.js} +1 -1
- ksadk/server/static/assets/{quadrantDiagram-AXDQQJYC-DEMoGo5a.js → quadrantDiagram-AXDQQJYC-ihH8znBv.js} +1 -1
- ksadk/server/static/assets/radar-RG4KPBEZ-PRBiHoJx.js +1 -0
- ksadk/server/static/assets/railroad-74A4TZTK-BCJ-XMRJ.js +1 -0
- ksadk/server/static/assets/railroad-abnf-HS5TGJTU-Bbttj0Jz.js +1 -0
- ksadk/server/static/assets/railroad-ebnf-LZEXJU2U-Bo18264J.js +1 -0
- ksadk/server/static/assets/railroad-peg-WCYAUIDC-xZDJTFLD.js +1 -0
- ksadk/server/static/assets/{railroadDiagram-O6MQD6OU-BTAob2wg.js → railroadDiagram-O6MQD6OU-DD9lFfXo.js} +1 -1
- ksadk/server/static/assets/{requirementDiagram-EFPCY7ZU-Dl0Q2SuO.js → requirementDiagram-EFPCY7ZU-CGn93Iyb.js} +1 -1
- ksadk/server/static/assets/{sankeyDiagram-P5KCCOFB-DeaTWkur.js → sankeyDiagram-P5KCCOFB-BuyjrHuW.js} +1 -1
- ksadk/server/static/assets/{sequenceDiagram-WJ2MYXX4-gFQYrsOd.js → sequenceDiagram-WJ2MYXX4-D-Iw-30A.js} +1 -1
- ksadk/server/static/assets/{sizeCapture-X5ZJPWSS-pGQzddMB.js → sizeCapture-X5ZJPWSS-B0EHLwrD.js} +1 -1
- ksadk/server/static/assets/{stateDiagram-HBIQ2CUA-DmpYOZt1.js → stateDiagram-HBIQ2CUA-k9Zyg69R.js} +1 -1
- ksadk/server/static/assets/stateDiagram-v2-4QOOHH4V-tUEVnq9-.js +1 -0
- ksadk/server/static/assets/{swimlanes-XN3QIQJK-BfuSAsrr.js → swimlanes-XN3QIQJK-D2BewKmp.js} +1 -1
- ksadk/server/static/assets/swimlanesDiagram-VK2B7HYN-CGBmsrCQ.js +8 -0
- ksadk/server/static/assets/{timeline-definition-24CTP7MA-CgJwrrxf.js → timeline-definition-24CTP7MA-czSzsYbz.js} +1 -1
- ksadk/server/static/assets/treeView-Q6P3EWNA-CrEvfC8M.js +1 -0
- ksadk/server/static/assets/treemap-WGGIJYW6-D1TmShtn.js +1 -0
- ksadk/server/static/assets/{vennDiagram-4TSXK5OY-CBSAgXDd.js → vennDiagram-4TSXK5OY-BJF_qZLF.js} +1 -1
- ksadk/server/static/assets/wardley-WFR3VGLG-0gZiSyL0.js +1 -0
- ksadk/server/static/assets/{wardleyDiagram-VM6X3IG4-013TZ2JZ.js → wardleyDiagram-VM6X3IG4-BfwUuJpr.js} +1 -1
- ksadk/server/static/assets/{xychartDiagram-S5SC5T6Z-u6Frp8xp.js → xychartDiagram-S5SC5T6Z-Ci6Nsp4p.js} +1 -1
- ksadk/server/static/index.html +2 -2
- ksadk/server/static/ui-source.json +6 -6
- ksadk/sessions/_postgres_history_backfill.py +80 -0
- ksadk/sessions/_postgres_schema.py +117 -0
- ksadk/sessions/_postgres_tables.py +6 -0
- ksadk/sessions/base.py +24 -0
- ksadk/sessions/history_tool_refs.py +244 -0
- ksadk/sessions/in_memory.py +42 -0
- ksadk/sessions/local_service.py +78 -0
- ksadk/sessions/model_history.py +20 -0
- ksadk/sessions/postgres_service.py +215 -19
- ksadk/sessions/resilient.py +24 -0
- ksadk/studio/static/assets/{ChannelsPage-Do_mRmVu.js → ChannelsPage-Ot9iV_QP.js} +1 -1
- ksadk/studio/static/assets/{CodeBlock-DMIf4h33-CsO7rJKv.js → CodeBlock-DMIf4h33-Cfs6se0v.js} +1 -1
- ksadk/studio/static/assets/{MathMessageMarkdown-BesSeCYl-CiB60plG.js → MathMessageMarkdown-BesSeCYl-BIBDiQAl.js} +1 -1
- ksadk/studio/static/assets/{MessageMarkdown-CwMTvgFj-BzEmQkHH.js → MessageMarkdown-CwMTvgFj-CWM4n-9K.js} +2 -2
- ksadk/studio/static/assets/{OfficialA2uiRenderer-DI49Kpxu-BBxfdj3P.js → OfficialA2uiRenderer-DI49Kpxu-BZSumE9D.js} +1 -1
- ksadk/studio/static/assets/{TeamsPage-qNVYpcox.js → TeamsPage-CVOpMIMf.js} +2 -2
- ksadk/studio/static/assets/index-CW1D-Kqg.css +2 -0
- ksadk/studio/static/assets/index-DMexeQ1-.js +1155 -0
- ksadk/studio/static/index.html +3 -3
- ksadk/studio/static/ui-source.json +6 -6
- ksadk/version.py +1 -1
- ksadk/server/static/assets/architecture-7GRP2DOG-CFWjFkDL.js +0 -1
- ksadk/server/static/assets/channel-D6Dp_l74.js +0 -1
- ksadk/server/static/assets/chunk-2Q5K7J3B-CwmjhFYK.js +0 -1
- ksadk/server/static/assets/classDiagram-DTDB5LWJ-DsbvkCAV.js +0 -1
- ksadk/server/static/assets/classDiagram-v2-JRS7N3AN-DsbvkCAV.js +0 -1
- ksadk/server/static/assets/cynefin-OW5HDTMX-CBZRVuc4.js +0 -1
- ksadk/server/static/assets/eventmodeling-NTZA5JFV-vXZWMkpn.js +0 -1
- ksadk/server/static/assets/flowDiagram-A5DVABFB-5LRgzKLv.js +0 -1
- ksadk/server/static/assets/gitGraph-4MIJSDKK-BUWSkncI.js +0 -1
- ksadk/server/static/assets/index-4g1ndaxW.js +0 -1132
- ksadk/server/static/assets/index-DEVfafsU.css +0 -2
- ksadk/server/static/assets/info-A6RAGUB7-CzJ_YrOs.js +0 -1
- ksadk/server/static/assets/packet-AYTQ26CC-CXoos6fx.js +0 -1
- ksadk/server/static/assets/pie-WAS4IAKB-CjF9NoIt.js +0 -1
- ksadk/server/static/assets/radar-RG4KPBEZ-BQGWs9nw.js +0 -1
- ksadk/server/static/assets/railroad-74A4TZTK-B6znvLUK.js +0 -1
- ksadk/server/static/assets/railroad-abnf-HS5TGJTU-Bzquz0As.js +0 -1
- ksadk/server/static/assets/railroad-ebnf-LZEXJU2U-1IikGkb5.js +0 -1
- ksadk/server/static/assets/railroad-peg-WCYAUIDC-BKKgHzdc.js +0 -1
- ksadk/server/static/assets/stateDiagram-v2-4QOOHH4V-Dolxgkw3.js +0 -1
- ksadk/server/static/assets/swimlanesDiagram-VK2B7HYN-BuI1erYj.js +0 -8
- ksadk/server/static/assets/treeView-Q6P3EWNA-DtMdDH8N.js +0 -1
- ksadk/server/static/assets/treemap-WGGIJYW6-VoU8QtLZ.js +0 -1
- ksadk/server/static/assets/wardley-WFR3VGLG-YWSRB0Zm.js +0 -1
- ksadk/studio/static/assets/index-Cp9Unfkn.css +0 -2
- ksadk/studio/static/assets/index-HepnaEeR.js +0 -1152
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/WHEEL +0 -0
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/entry_points.txt +0 -0
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/licenses/LICENSE +0 -0
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""New-turn message assembly for native LangGraph message graphs.
|
|
2
|
+
|
|
3
|
+
The graph schema and model nodes remain unchanged. Only a new root input may
|
|
4
|
+
replace messages; Command/resume paths never call this module.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import operator
|
|
10
|
+
from typing import Any, get_origin
|
|
11
|
+
|
|
12
|
+
TURN_KEY = "ksadk_invocation_id"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def standard_messages(graph: Any) -> bool:
|
|
16
|
+
from langgraph.channels.last_value import LastValue
|
|
17
|
+
from langgraph.graph.message import add_messages
|
|
18
|
+
|
|
19
|
+
channel = getattr(graph, "channels", {}).get("messages")
|
|
20
|
+
return getattr(channel, "operator", None) in (add_messages, operator.add) or (
|
|
21
|
+
type(channel) is LastValue and (channel.typ is list or get_origin(channel.typ) is list)
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def framework_summary(graph: Any) -> bool:
|
|
26
|
+
# DeepAgents keeps a cutoff into its raw messages. Replacing that list would
|
|
27
|
+
# invalidate the cutoff. LangChain's explicit middleware also owns its summary.
|
|
28
|
+
return "_summarization_event" in getattr(graph, "channels", {}) or any(
|
|
29
|
+
str(name).startswith("SummarizationMiddleware.") for name in getattr(graph, "nodes", {})
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def checkpoint_messages(graph: Any, config: dict) -> list:
|
|
34
|
+
from langchain_core.messages import convert_to_messages
|
|
35
|
+
|
|
36
|
+
from ksadk.runtime.langgraph_checkpoint_view import _FRESH_READ, fresh_checkpoint_view
|
|
37
|
+
|
|
38
|
+
saver = getattr(graph, "checkpointer", None)
|
|
39
|
+
if not saver or getattr(saver, "_ksadk_resume_only", False):
|
|
40
|
+
return []
|
|
41
|
+
# A preparatory read must not consume the graph execution's fresh-turn read.
|
|
42
|
+
# Use the existing orphan-tool repair on a copy, never update an old checkpoint.
|
|
43
|
+
token = _FRESH_READ.set({"used": False})
|
|
44
|
+
try:
|
|
45
|
+
if not standard_messages(graph):
|
|
46
|
+
# DeepAgents can use a DeltaChannel; its persisted value is a
|
|
47
|
+
# sentinel, so let LangGraph reconstruct it through the public API.
|
|
48
|
+
snapshot = await graph.aget_state(config)
|
|
49
|
+
return convert_to_messages(snapshot.values.get("messages", []))
|
|
50
|
+
saved = await saver.aget_tuple(config)
|
|
51
|
+
saved = fresh_checkpoint_view(config, saved)
|
|
52
|
+
return (
|
|
53
|
+
convert_to_messages(saved.checkpoint.get("channel_values", {}).get("messages", []))
|
|
54
|
+
if saved
|
|
55
|
+
else []
|
|
56
|
+
)
|
|
57
|
+
finally:
|
|
58
|
+
_FRESH_READ.reset(token)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def text_history(history: list) -> list:
|
|
62
|
+
from langchain_core.messages import AIMessage, HumanMessage
|
|
63
|
+
|
|
64
|
+
messages = []
|
|
65
|
+
for row in history:
|
|
66
|
+
content = row.get("content", "")
|
|
67
|
+
if isinstance(content, str) and content.startswith(
|
|
68
|
+
("[tool_call]", "[tool_result]", "[approval_request]", "[approval_response]")
|
|
69
|
+
):
|
|
70
|
+
continue
|
|
71
|
+
if row.get("role") == "user":
|
|
72
|
+
messages.append(HumanMessage(content=content))
|
|
73
|
+
elif row.get("role") in ("model", "assistant"):
|
|
74
|
+
messages.append(AIMessage(content=content))
|
|
75
|
+
return messages
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def current_hook_messages(messages: list, histories: list[list], user_input: Any) -> list:
|
|
79
|
+
"""Remove only a known history prefix from an existing prepare-state hook.
|
|
80
|
+
|
|
81
|
+
The hook still receives its original history for business field mapping.
|
|
82
|
+
Content equality is used for this prefix only, never to deduplicate real turns.
|
|
83
|
+
"""
|
|
84
|
+
from langchain_core.messages import SystemMessage, convert_to_messages
|
|
85
|
+
|
|
86
|
+
messages = convert_to_messages(messages)
|
|
87
|
+
start = 0
|
|
88
|
+
while start < len(messages) and isinstance(messages[start], SystemMessage):
|
|
89
|
+
start += 1
|
|
90
|
+
for history in histories:
|
|
91
|
+
prefix = text_history(history)
|
|
92
|
+
if not prefix:
|
|
93
|
+
continue
|
|
94
|
+
signatures = [(m.type, m.content) for m in prefix]
|
|
95
|
+
candidate = messages[start : start + len(prefix)]
|
|
96
|
+
if [(m.type, m.content) for m in candidate] != signatures:
|
|
97
|
+
continue
|
|
98
|
+
end = start + len(prefix)
|
|
99
|
+
# Legacy SDK history includes the current user event. Some hooks use
|
|
100
|
+
# that list directly instead of appending the current input once more.
|
|
101
|
+
if (
|
|
102
|
+
end == len(messages)
|
|
103
|
+
and candidate[-1].type == "human"
|
|
104
|
+
and candidate[-1].content == user_input
|
|
105
|
+
):
|
|
106
|
+
end -= 1
|
|
107
|
+
return [*messages[:start], *messages[end:]]
|
|
108
|
+
return messages
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def effective_history(context: dict, saved: list) -> list:
|
|
112
|
+
"""Keep native tool/content blocks for retained turns when a saver has them."""
|
|
113
|
+
from langchain_core.messages import SystemMessage
|
|
114
|
+
|
|
115
|
+
previous = []
|
|
116
|
+
groups: dict[str, list] = {}
|
|
117
|
+
turn = ""
|
|
118
|
+
for message in saved:
|
|
119
|
+
if isinstance(message, SystemMessage) and message.response_metadata.get(TURN_KEY):
|
|
120
|
+
continue # Request policy/ambient context is rebuilt for the new turn.
|
|
121
|
+
marker = message.response_metadata.get(TURN_KEY)
|
|
122
|
+
if marker:
|
|
123
|
+
turn = marker
|
|
124
|
+
if turn == context.get("invocation_id"):
|
|
125
|
+
break # A retry must not append its current input again.
|
|
126
|
+
previous.append(message)
|
|
127
|
+
if turn:
|
|
128
|
+
groups.setdefault(turn, []).append(message)
|
|
129
|
+
rows = context.get("history") or []
|
|
130
|
+
turns = context.get("turns") or []
|
|
131
|
+
last_native_turn = next(reversed(groups), None)
|
|
132
|
+
last_session_turn = turns[-1]["invocation_id"] if turns else None
|
|
133
|
+
native_text = [
|
|
134
|
+
(m.type, m.content)
|
|
135
|
+
for m in previous
|
|
136
|
+
if m.type in {"human", "ai"} and m.content and not getattr(m, "tool_calls", None)
|
|
137
|
+
]
|
|
138
|
+
session_text = [(m.type, m.content) for m in text_history(rows)]
|
|
139
|
+
if (
|
|
140
|
+
context.get("uncompacted")
|
|
141
|
+
and previous
|
|
142
|
+
and (
|
|
143
|
+
not rows
|
|
144
|
+
or native_text == session_text
|
|
145
|
+
or (last_native_turn is not None and last_native_turn == last_session_turn)
|
|
146
|
+
)
|
|
147
|
+
):
|
|
148
|
+
# Preserve checkpoint-only history as well, e.g. after a local session
|
|
149
|
+
# store restart. No raw prefix has been replaced by an SDK summary yet.
|
|
150
|
+
return previous
|
|
151
|
+
|
|
152
|
+
# Application-owned system messages may live in checkpoint state; they are
|
|
153
|
+
# not part of the SDK transcript summary and must remain available.
|
|
154
|
+
result = [m for m in previous if isinstance(m, SystemMessage)]
|
|
155
|
+
cursor = 0
|
|
156
|
+
for retained in turns:
|
|
157
|
+
expected = retained["history"]
|
|
158
|
+
native = groups.get(retained["invocation_id"])
|
|
159
|
+
if not native or not expected:
|
|
160
|
+
continue
|
|
161
|
+
for index in range(cursor, len(rows) - len(expected) + 1):
|
|
162
|
+
if rows[index : index + len(expected)] == expected:
|
|
163
|
+
result.extend(text_history(rows[cursor:index]))
|
|
164
|
+
result.extend(m for m in native if not isinstance(m, SystemMessage))
|
|
165
|
+
cursor = index + len(expected)
|
|
166
|
+
break
|
|
167
|
+
result.extend(text_history(rows[cursor:]))
|
|
168
|
+
return result
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def merge_hook_current(
|
|
172
|
+
sdk_messages: list, hook_messages: Any, user_input: Any, histories: list[list]
|
|
173
|
+
) -> list:
|
|
174
|
+
"""Keep hook policy and its final user input; SDK supplies prior history."""
|
|
175
|
+
from copy import deepcopy
|
|
176
|
+
|
|
177
|
+
from langchain_core.messages import HumanMessage, SystemMessage, convert_to_messages
|
|
178
|
+
from langgraph.types import Overwrite
|
|
179
|
+
|
|
180
|
+
result = deepcopy(sdk_messages)
|
|
181
|
+
if isinstance(hook_messages, Overwrite):
|
|
182
|
+
hook_messages = hook_messages.value
|
|
183
|
+
if not isinstance(hook_messages, (list, tuple)):
|
|
184
|
+
return result
|
|
185
|
+
try:
|
|
186
|
+
supplied = convert_to_messages(hook_messages)
|
|
187
|
+
except (TypeError, ValueError, NotImplementedError):
|
|
188
|
+
return result
|
|
189
|
+
|
|
190
|
+
def text(content):
|
|
191
|
+
if isinstance(content, str):
|
|
192
|
+
return content
|
|
193
|
+
if isinstance(content, list):
|
|
194
|
+
return "\n".join(
|
|
195
|
+
part["text"]
|
|
196
|
+
for part in content
|
|
197
|
+
if isinstance(part, dict)
|
|
198
|
+
and part.get("type") in {"text", "input_text"}
|
|
199
|
+
and isinstance(part.get("text"), str)
|
|
200
|
+
)
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
def has_input_block(content, expected):
|
|
204
|
+
return isinstance(content, list) and any(
|
|
205
|
+
isinstance(part, dict)
|
|
206
|
+
and part.get("type") in {"text", "input_text"}
|
|
207
|
+
and part.get("text") in expected
|
|
208
|
+
for part in content
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
policies = [m for m in result if isinstance(m, SystemMessage)]
|
|
212
|
+
for message in supplied:
|
|
213
|
+
if isinstance(message, SystemMessage) and not any(
|
|
214
|
+
m.content == message.content for m in policies
|
|
215
|
+
):
|
|
216
|
+
policies.append(deepcopy(message))
|
|
217
|
+
current = [m for m in result if not isinstance(m, SystemMessage)]
|
|
218
|
+
# Legacy hooks may translate the current question or return image-only
|
|
219
|
+
# content. Their final user message is the current-input contract; requiring
|
|
220
|
+
# equality with the original request would silently discard that behavior.
|
|
221
|
+
# A completed historical turn (ending in AI/tool output) is never current.
|
|
222
|
+
if current and isinstance(current[-1], HumanMessage):
|
|
223
|
+
original = current[-1]
|
|
224
|
+
expected = {
|
|
225
|
+
value
|
|
226
|
+
for value in (text(original.content), user_input)
|
|
227
|
+
if isinstance(value, str) and value
|
|
228
|
+
}
|
|
229
|
+
tail = [m for m in supplied if not isinstance(m, SystemMessage)][-1:]
|
|
230
|
+
match = tail[0] if tail and isinstance(tail[0], HumanMessage) else None
|
|
231
|
+
if match is not None:
|
|
232
|
+
anchored = (
|
|
233
|
+
(original.id is not None and match.id == original.id)
|
|
234
|
+
or text(match.content) in expected
|
|
235
|
+
or has_input_block(match.content, expected)
|
|
236
|
+
)
|
|
237
|
+
# Only an exact known history-only replay can be discarded here.
|
|
238
|
+
# A transformed current input may legitimately equal an older turn.
|
|
239
|
+
body = [(m.type, m.content) for m in supplied if not isinstance(m, SystemMessage)]
|
|
240
|
+
if not anchored and any(
|
|
241
|
+
body == [(m.type, m.content) for m in text_history(history)]
|
|
242
|
+
for history in histories
|
|
243
|
+
if history
|
|
244
|
+
):
|
|
245
|
+
match = None
|
|
246
|
+
if match is not None:
|
|
247
|
+
replacement = deepcopy(match)
|
|
248
|
+
# Retain SDK-provided attachments even when an old text-only hook
|
|
249
|
+
# knows nothing about the current multimodal request.
|
|
250
|
+
if isinstance(original.content, list):
|
|
251
|
+
blocks = (
|
|
252
|
+
replacement.content
|
|
253
|
+
if isinstance(replacement.content, list)
|
|
254
|
+
else [{"type": "text", "text": replacement.content}]
|
|
255
|
+
)
|
|
256
|
+
for block in original.content:
|
|
257
|
+
if (
|
|
258
|
+
isinstance(block, dict)
|
|
259
|
+
and block.get("type") not in {"text", "input_text"}
|
|
260
|
+
and block not in blocks
|
|
261
|
+
):
|
|
262
|
+
blocks.append(deepcopy(block))
|
|
263
|
+
replacement = replacement.model_copy(update={"content": blocks})
|
|
264
|
+
current[-1] = replacement
|
|
265
|
+
return [*policies, *current]
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""Request-local model projection; never modify graph messages or checkpoints.
|
|
2
|
+
|
|
3
|
+
The public BaseChatModel boundaries cover custom StateGraph nodes as well as
|
|
4
|
+
create_agent, including sync nodes executed by LangGraph's executor. Outside a
|
|
5
|
+
SDK graph invocation these wrappers are exact pass-throughs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import inspect
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
15
|
+
from contextvars import ContextVar
|
|
16
|
+
from functools import wraps
|
|
17
|
+
|
|
18
|
+
from langchain_core.callbacks import BaseCallbackHandler
|
|
19
|
+
from langchain_core.language_models.chat_models import BaseChatModel
|
|
20
|
+
from langchain_core.messages import AIMessage, ToolMessage
|
|
21
|
+
|
|
22
|
+
from ksadk.conversations.context import summarize_event_groups
|
|
23
|
+
from ksadk.conversations.model_context import (
|
|
24
|
+
estimate_text_tokens,
|
|
25
|
+
get_effective_context_window_tokens,
|
|
26
|
+
normalize_model_metadata,
|
|
27
|
+
)
|
|
28
|
+
from ksadk.conversations.semantic_summary import summarize_compaction
|
|
29
|
+
from ksadk.sessions.base import SessionEvent
|
|
30
|
+
|
|
31
|
+
_SCOPE = ContextVar("ksadk_langgraph_model_budget", default=None)
|
|
32
|
+
_INSTALLED = False
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _tokens(messages):
|
|
37
|
+
return sum(
|
|
38
|
+
8 + estimate_text_tokens(json.dumps(m.model_dump(), ensure_ascii=False, default=str))
|
|
39
|
+
for m in messages
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _complete_tool_groups(messages):
|
|
44
|
+
"""Only collapse whole, completed exchanges; pending calls remain verbatim."""
|
|
45
|
+
groups = []
|
|
46
|
+
i = 0
|
|
47
|
+
while i < len(messages):
|
|
48
|
+
message = messages[i]
|
|
49
|
+
calls = getattr(message, "tool_calls", None)
|
|
50
|
+
if isinstance(message, AIMessage) and calls:
|
|
51
|
+
pending = {c["id"] for c in calls}
|
|
52
|
+
expected = set(pending)
|
|
53
|
+
received = []
|
|
54
|
+
j = i + 1
|
|
55
|
+
while j < len(messages) and isinstance(messages[j], ToolMessage):
|
|
56
|
+
received.append(messages[j].tool_call_id)
|
|
57
|
+
pending.discard(messages[j].tool_call_id)
|
|
58
|
+
j += 1
|
|
59
|
+
if (
|
|
60
|
+
not pending
|
|
61
|
+
and set(received) == expected
|
|
62
|
+
and len(received) == len(expected) == len(calls)
|
|
63
|
+
):
|
|
64
|
+
groups.append((i, j))
|
|
65
|
+
i = j
|
|
66
|
+
else:
|
|
67
|
+
i += 1
|
|
68
|
+
return groups
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
async def _project(messages, kwargs, *, force=False):
|
|
72
|
+
scope = _SCOPE.get()
|
|
73
|
+
if scope is None:
|
|
74
|
+
return messages
|
|
75
|
+
metadata, model = scope
|
|
76
|
+
# Leave room for tool schemas and provider framing, in addition to the
|
|
77
|
+
# output reserve already accounted for by the shared context policy.
|
|
78
|
+
schema_tokens = estimate_text_tokens(
|
|
79
|
+
json.dumps(kwargs.get("tools", []), ensure_ascii=False, default=str)
|
|
80
|
+
)
|
|
81
|
+
budget = max(1, int(get_effective_context_window_tokens(metadata) * 0.8) - schema_tokens)
|
|
82
|
+
if force:
|
|
83
|
+
budget = min(budget, max(1, _tokens(messages) // 2))
|
|
84
|
+
if _tokens(messages) <= budget:
|
|
85
|
+
return messages
|
|
86
|
+
groups = _complete_tool_groups(messages)
|
|
87
|
+
if not groups:
|
|
88
|
+
return messages # Never silently cut a user's input or system policy.
|
|
89
|
+
removed = set()
|
|
90
|
+
spans = []
|
|
91
|
+
for start, end in groups:
|
|
92
|
+
removed.update(range(start, end))
|
|
93
|
+
# Keep summaries on their side of every retained message. Only directly
|
|
94
|
+
# adjacent exchanges can share a summary at the first exchange's position.
|
|
95
|
+
if spans and spans[-1][1] == start:
|
|
96
|
+
spans[-1][1] = end
|
|
97
|
+
else:
|
|
98
|
+
spans.append([start, end])
|
|
99
|
+
remaining = [m for index, m in enumerate(messages) if index not in removed]
|
|
100
|
+
# Prefer keeping the latest result verbatim; reserve bounded summary space.
|
|
101
|
+
if _tokens(remaining) <= budget - min(1024, budget // 4):
|
|
102
|
+
break
|
|
103
|
+
|
|
104
|
+
receipt_texts = [
|
|
105
|
+
"Completed tool receipts (already executed): "
|
|
106
|
+
+ json.dumps(
|
|
107
|
+
[{"id": m.tool_call_id, "name": m.name, "status": m.status}
|
|
108
|
+
for m in messages[start:end] if isinstance(m, ToolMessage)],
|
|
109
|
+
ensure_ascii=False,
|
|
110
|
+
)
|
|
111
|
+
+ "\n"
|
|
112
|
+
for start, end in spans
|
|
113
|
+
]
|
|
114
|
+
available = (budget - _tokens(remaining) - _tokens([
|
|
115
|
+
AIMessage(content=text) for text in receipt_texts
|
|
116
|
+
]) - 32 * len(spans)) // len(spans)
|
|
117
|
+
if available <= 0:
|
|
118
|
+
return messages
|
|
119
|
+
|
|
120
|
+
summaries = {}
|
|
121
|
+
strategies = set()
|
|
122
|
+
for span_index, ((start, end), receipt_text) in enumerate(zip(spans, receipt_texts)):
|
|
123
|
+
events = [
|
|
124
|
+
[
|
|
125
|
+
SessionEvent(
|
|
126
|
+
event_type="assistant_message",
|
|
127
|
+
content={
|
|
128
|
+
"text": f"Completed tool exchange: {getattr(m, 'tool_call_id', '')} "
|
|
129
|
+
+ json.dumps(m.model_dump(), ensure_ascii=False, default=str)
|
|
130
|
+
},
|
|
131
|
+
)
|
|
132
|
+
for m in messages[group_start:group_end]
|
|
133
|
+
]
|
|
134
|
+
for group_start, group_end in groups
|
|
135
|
+
if start <= group_start < end
|
|
136
|
+
]
|
|
137
|
+
if span_index == 0:
|
|
138
|
+
result = await summarize_compaction(
|
|
139
|
+
groups_to_compact=events,
|
|
140
|
+
previous_summary="",
|
|
141
|
+
pinned_state={},
|
|
142
|
+
model_metadata=metadata,
|
|
143
|
+
model=model,
|
|
144
|
+
)
|
|
145
|
+
strategies.add(result.summary_strategy)
|
|
146
|
+
text = result.summary_text
|
|
147
|
+
else:
|
|
148
|
+
# Bound model latency to one summary RPC per projection even when
|
|
149
|
+
# many retained user messages split the compacted exchanges.
|
|
150
|
+
strategies.add("extractive")
|
|
151
|
+
text = summarize_event_groups(events)
|
|
152
|
+
if estimate_text_tokens(text) > available:
|
|
153
|
+
marker = (
|
|
154
|
+
"\n[Summary shortened to fit model context; "
|
|
155
|
+
"original tool results remain in execution history.]"
|
|
156
|
+
)
|
|
157
|
+
if estimate_text_tokens(marker) > available:
|
|
158
|
+
text = ""
|
|
159
|
+
else:
|
|
160
|
+
lo, hi = 0, len(text)
|
|
161
|
+
while lo < hi:
|
|
162
|
+
mid = (lo + hi + 1) // 2
|
|
163
|
+
if estimate_text_tokens(text[:mid] + marker) <= available:
|
|
164
|
+
lo = mid
|
|
165
|
+
else:
|
|
166
|
+
hi = mid - 1
|
|
167
|
+
text = text[:lo] + marker
|
|
168
|
+
summaries[start] = AIMessage(content=receipt_text + text)
|
|
169
|
+
projected = [
|
|
170
|
+
summaries.get(index, message)
|
|
171
|
+
for index, message in enumerate(messages)
|
|
172
|
+
if index in summaries or index not in removed
|
|
173
|
+
]
|
|
174
|
+
# A bad/oversized summary must not replace a smaller original request.
|
|
175
|
+
if _tokens(projected) <= budget and _tokens(projected) < _tokens(messages):
|
|
176
|
+
logger.info(
|
|
177
|
+
"LangGraph model context compacted: %s -> %s estimated tokens (%s); "
|
|
178
|
+
"graph state unchanged",
|
|
179
|
+
_tokens(messages),
|
|
180
|
+
_tokens(projected),
|
|
181
|
+
", ".join(sorted(strategies)),
|
|
182
|
+
)
|
|
183
|
+
return projected
|
|
184
|
+
return messages
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _sync_project(messages, kwargs, *, force=False):
|
|
188
|
+
if _SCOPE.get() is None:
|
|
189
|
+
return messages
|
|
190
|
+
try:
|
|
191
|
+
asyncio.get_running_loop()
|
|
192
|
+
except RuntimeError:
|
|
193
|
+
return asyncio.run(_project(messages, kwargs, force=force))
|
|
194
|
+
# A synchronous user node may itself run on an event loop. Do not nest
|
|
195
|
+
# asyncio.run or share loop-bound clients; the summarizer creates its client.
|
|
196
|
+
from contextvars import copy_context
|
|
197
|
+
|
|
198
|
+
with ThreadPoolExecutor(max_workers=1) as pool:
|
|
199
|
+
return pool.submit(
|
|
200
|
+
copy_context().run, lambda: asyncio.run(_project(messages, kwargs, force=force))
|
|
201
|
+
).result()
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _track_output(args, kwargs):
|
|
205
|
+
"""Observe implicit streaming without changing the caller's callback manager."""
|
|
206
|
+
emitted = [False]
|
|
207
|
+
if _SCOPE.get() is None:
|
|
208
|
+
return args, kwargs, emitted
|
|
209
|
+
|
|
210
|
+
class OutputObserver(BaseCallbackHandler):
|
|
211
|
+
run_inline = True
|
|
212
|
+
|
|
213
|
+
def on_llm_new_token(self, token, **kwargs):
|
|
214
|
+
emitted[0] = True
|
|
215
|
+
|
|
216
|
+
observer = OutputObserver()
|
|
217
|
+
callbacks = args[1] if len(args) > 1 else kwargs.get("callbacks")
|
|
218
|
+
if callbacks is None or isinstance(callbacks, list):
|
|
219
|
+
callbacks = [*(callbacks or []), observer]
|
|
220
|
+
else:
|
|
221
|
+
callbacks = callbacks.copy()
|
|
222
|
+
callbacks.add_handler(observer, inherit=True)
|
|
223
|
+
if len(args) > 1:
|
|
224
|
+
args = (args[0], callbacks, *args[2:])
|
|
225
|
+
else:
|
|
226
|
+
kwargs = {**kwargs, "callbacks": callbacks}
|
|
227
|
+
return args, kwargs, emitted
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def install_model_budget():
|
|
231
|
+
global _INSTALLED
|
|
232
|
+
if _INSTALLED:
|
|
233
|
+
return
|
|
234
|
+
original_generate = BaseChatModel.generate
|
|
235
|
+
original_agenerate = BaseChatModel.agenerate
|
|
236
|
+
original_stream = BaseChatModel.stream
|
|
237
|
+
original_astream = BaseChatModel.astream
|
|
238
|
+
|
|
239
|
+
def retry(exc, attempt, emitted=False, had_tools=False):
|
|
240
|
+
from ksadk.conversations.runtime_input import _is_prompt_too_long_error
|
|
241
|
+
|
|
242
|
+
if _SCOPE.get() is None or not _is_prompt_too_long_error(exc):
|
|
243
|
+
return False
|
|
244
|
+
if getattr(exc, "ksadk_model_boundary_failure", False):
|
|
245
|
+
return False
|
|
246
|
+
if attempt or emitted:
|
|
247
|
+
# The outer conversation retry must never replay completed tools.
|
|
248
|
+
if emitted or had_tools:
|
|
249
|
+
exc.ksadk_model_boundary_failure = True
|
|
250
|
+
return False
|
|
251
|
+
return True
|
|
252
|
+
|
|
253
|
+
@wraps(original_generate)
|
|
254
|
+
def generate(self, messages, *args, **kwargs):
|
|
255
|
+
args, kwargs, emitted = _track_output(args, kwargs)
|
|
256
|
+
for attempt in range(2):
|
|
257
|
+
rows = [_sync_project(row, kwargs, force=bool(attempt)) for row in messages]
|
|
258
|
+
try:
|
|
259
|
+
return original_generate(self, rows, *args, **kwargs)
|
|
260
|
+
except Exception as exc:
|
|
261
|
+
if not retry(
|
|
262
|
+
exc,
|
|
263
|
+
attempt,
|
|
264
|
+
emitted=emitted[0],
|
|
265
|
+
had_tools=any(isinstance(m, ToolMessage) for row in messages for m in row),
|
|
266
|
+
):
|
|
267
|
+
raise
|
|
268
|
+
|
|
269
|
+
@wraps(original_agenerate)
|
|
270
|
+
async def agenerate(self, messages, *args, **kwargs):
|
|
271
|
+
args, kwargs, emitted = _track_output(args, kwargs)
|
|
272
|
+
for attempt in range(2):
|
|
273
|
+
rows = [await _project(row, kwargs, force=bool(attempt)) for row in messages]
|
|
274
|
+
try:
|
|
275
|
+
return await original_agenerate(self, rows, *args, **kwargs)
|
|
276
|
+
except Exception as exc:
|
|
277
|
+
if not retry(
|
|
278
|
+
exc,
|
|
279
|
+
attempt,
|
|
280
|
+
emitted=emitted[0],
|
|
281
|
+
had_tools=any(isinstance(m, ToolMessage) for row in messages for m in row),
|
|
282
|
+
):
|
|
283
|
+
raise
|
|
284
|
+
|
|
285
|
+
@wraps(original_stream)
|
|
286
|
+
def stream(self, input, *args, **kwargs):
|
|
287
|
+
emitted = False
|
|
288
|
+
for attempt in range(2):
|
|
289
|
+
projected = input
|
|
290
|
+
if _SCOPE.get() is not None:
|
|
291
|
+
projected = _sync_project(
|
|
292
|
+
self._convert_input(input).to_messages(), kwargs, force=bool(attempt)
|
|
293
|
+
)
|
|
294
|
+
try:
|
|
295
|
+
for item in original_stream(self, projected, *args, **kwargs):
|
|
296
|
+
emitted = True
|
|
297
|
+
yield item
|
|
298
|
+
return
|
|
299
|
+
except Exception as exc:
|
|
300
|
+
if not retry(
|
|
301
|
+
exc,
|
|
302
|
+
attempt,
|
|
303
|
+
emitted,
|
|
304
|
+
had_tools=bool(
|
|
305
|
+
_SCOPE.get() is not None
|
|
306
|
+
and any(
|
|
307
|
+
isinstance(m, ToolMessage)
|
|
308
|
+
for m in self._convert_input(input).to_messages()
|
|
309
|
+
)
|
|
310
|
+
),
|
|
311
|
+
):
|
|
312
|
+
raise
|
|
313
|
+
|
|
314
|
+
@wraps(original_astream)
|
|
315
|
+
async def astream(self, input, *args, **kwargs):
|
|
316
|
+
emitted = False
|
|
317
|
+
for attempt in range(2):
|
|
318
|
+
projected = input
|
|
319
|
+
if _SCOPE.get() is not None:
|
|
320
|
+
projected = await _project(
|
|
321
|
+
self._convert_input(input).to_messages(), kwargs, force=bool(attempt)
|
|
322
|
+
)
|
|
323
|
+
try:
|
|
324
|
+
async for item in original_astream(self, projected, *args, **kwargs):
|
|
325
|
+
emitted = True
|
|
326
|
+
yield item
|
|
327
|
+
return
|
|
328
|
+
except Exception as exc:
|
|
329
|
+
if not retry(
|
|
330
|
+
exc,
|
|
331
|
+
attempt,
|
|
332
|
+
emitted,
|
|
333
|
+
had_tools=bool(
|
|
334
|
+
_SCOPE.get() is not None
|
|
335
|
+
and any(
|
|
336
|
+
isinstance(m, ToolMessage)
|
|
337
|
+
for m in self._convert_input(input).to_messages()
|
|
338
|
+
)
|
|
339
|
+
),
|
|
340
|
+
):
|
|
341
|
+
raise
|
|
342
|
+
|
|
343
|
+
BaseChatModel.generate = generate
|
|
344
|
+
BaseChatModel.agenerate = agenerate
|
|
345
|
+
BaseChatModel.stream = stream
|
|
346
|
+
BaseChatModel.astream = astream
|
|
347
|
+
_INSTALLED = True
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def model_budget_scope(method):
|
|
351
|
+
"""Bind only during graph execution; nesting keeps the outer request policy."""
|
|
352
|
+
|
|
353
|
+
def enter(payload):
|
|
354
|
+
install_model_budget()
|
|
355
|
+
if _SCOPE.get() is not None:
|
|
356
|
+
return None
|
|
357
|
+
return _SCOPE.set(
|
|
358
|
+
(normalize_model_metadata(payload.get("model_metadata")), payload.get("model"))
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
if inspect.isasyncgenfunction(method):
|
|
362
|
+
|
|
363
|
+
@wraps(method)
|
|
364
|
+
async def stream(self, input_data, *args, **kwargs):
|
|
365
|
+
iterator = method(self, input_data, *args, **kwargs)
|
|
366
|
+
try:
|
|
367
|
+
while True:
|
|
368
|
+
token = enter(input_data)
|
|
369
|
+
try:
|
|
370
|
+
item = await anext(iterator)
|
|
371
|
+
except StopAsyncIteration:
|
|
372
|
+
return
|
|
373
|
+
finally:
|
|
374
|
+
if token is not None:
|
|
375
|
+
_SCOPE.reset(token)
|
|
376
|
+
# The consumer runs outside our model projection scope.
|
|
377
|
+
yield item
|
|
378
|
+
finally:
|
|
379
|
+
token = enter(input_data)
|
|
380
|
+
try:
|
|
381
|
+
await iterator.aclose()
|
|
382
|
+
finally:
|
|
383
|
+
if token is not None:
|
|
384
|
+
_SCOPE.reset(token)
|
|
385
|
+
|
|
386
|
+
return stream
|
|
387
|
+
|
|
388
|
+
@wraps(method)
|
|
389
|
+
async def invoke(self, input_data, *args, **kwargs):
|
|
390
|
+
token = enter(input_data)
|
|
391
|
+
try:
|
|
392
|
+
return await method(self, input_data, *args, **kwargs)
|
|
393
|
+
finally:
|
|
394
|
+
if token is not None:
|
|
395
|
+
_SCOPE.reset(token)
|
|
396
|
+
|
|
397
|
+
return invoke
|