api-mapper-client 1.0.1__tar.gz → 1.3.0__tar.gz
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.
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/.gitignore +60 -1
- api_mapper_client-1.3.0/PKG-INFO +127 -0
- api_mapper_client-1.3.0/README.md +91 -0
- api_mapper_client-1.3.0/api_mapper_client/__init__.py +37 -0
- api_mapper_client-1.3.0/api_mapper_client/agents.py +167 -0
- api_mapper_client-1.3.0/api_mapper_client/client.py +637 -0
- api_mapper_client-1.3.0/api_mapper_client/contracts.py +179 -0
- api_mapper_client-1.3.0/api_mapper_client/webhooks.py +43 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/pyproject.toml +23 -10
- api_mapper_client-1.0.1/PKG-INFO +0 -82
- api_mapper_client-1.0.1/README.md +0 -50
- api_mapper_client-1.0.1/api_mapper_client/__init__.py +0 -17
- api_mapper_client-1.0.1/api_mapper_client/client.py +0 -220
- api_mapper_client-1.0.1/api_mapper_client/contracts.py +0 -28
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/LICENSE +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_client/auth/__init__.py +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_client/auth/api_key.py +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_client/auth/base.py +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_client/auth/delegated_bearer.py +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_client/auth/oauth2_client_credentials.py +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_langchain/__init__.py +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_langchain/toolkit.py +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_langgraph/__init__.py +0 -0
- {api_mapper_client-1.0.1 → api_mapper_client-1.3.0}/api_mapper_langgraph/nodes.py +0 -0
|
@@ -146,6 +146,17 @@ coverage*.json
|
|
|
146
146
|
coverage*.xml
|
|
147
147
|
coverage*.info
|
|
148
148
|
|
|
149
|
+
# Vitest/v8 writes a coverage *directory*, which the file patterns above do not cover.
|
|
150
|
+
# tools/quality-scan.sh generates it on every run and feeds lcov.info to SonarQube.
|
|
151
|
+
coverage/
|
|
152
|
+
|
|
153
|
+
# SonarScanner working directories, both written into the repository root by tools/quality-scan.sh.
|
|
154
|
+
# .sonarqube holds the generated rulesets and the per-project analysis config between the scanner's
|
|
155
|
+
# begin and end steps; .scannerwork holds the report the end step uploads. Both are rebuilt on every
|
|
156
|
+
# run and neither describes the source.
|
|
157
|
+
.sonarqube/
|
|
158
|
+
.scannerwork/
|
|
159
|
+
|
|
149
160
|
# Visual Studio code coverage results
|
|
150
161
|
*.coverage
|
|
151
162
|
*.coveragexml
|
|
@@ -212,6 +223,10 @@ pnpm-debug.log*
|
|
|
212
223
|
# Generated public site export
|
|
213
224
|
src/PublicSite/CodedProjects.AI.ApiMapper.Public.Web/wwwroot/
|
|
214
225
|
|
|
226
|
+
# License Admin BFF: the SPA build the publish script copies in, and the local Data Protection key ring (plan 0090)
|
|
227
|
+
src/LicenseAdminPortal/CodedProjects.AI.ApiMapper.LicenseAdminPortal.Web/wwwroot/
|
|
228
|
+
src/LicenseAdminPortal/CodedProjects.AI.ApiMapper.LicenseAdminPortal.Web/App_Data/
|
|
229
|
+
|
|
215
230
|
# NuGet Packages
|
|
216
231
|
*.nupkg
|
|
217
232
|
# NuGet Symbol Packages
|
|
@@ -220,6 +235,10 @@ src/PublicSite/CodedProjects.AI.ApiMapper.Public.Web/wwwroot/
|
|
|
220
235
|
**/[Pp]ackages/*
|
|
221
236
|
# except build/, which is used as an MSBuild target.
|
|
222
237
|
!**/[Pp]ackages/build/
|
|
238
|
+
# The TypeScript SDK is an npm workspace whose sources live in packages/. It is not a NuGet
|
|
239
|
+
# restore directory, so the rule above must not swallow it.
|
|
240
|
+
!sdk/typescript/packages/
|
|
241
|
+
!sdk/typescript/packages/**
|
|
223
242
|
# Uncomment if necessary however generally it will be regenerated when needed
|
|
224
243
|
#!**/[Pp]ackages/repositories.config
|
|
225
244
|
# NuGet v3's project.json files produces more ignorable files
|
|
@@ -397,6 +416,46 @@ dist/
|
|
|
397
416
|
# k6 performance test output
|
|
398
417
|
tests/PerformanceTests/reports/*.json
|
|
399
418
|
|
|
419
|
+
# Playwright local run artifacts
|
|
420
|
+
src/Portal/CodedProjects.AI.ApiMapper.Portal.Web/test-results/
|
|
421
|
+
src/Portal/CodedProjects.AI.ApiMapper.Portal.Web/playwright-report/
|
|
422
|
+
|
|
400
423
|
#java maven publish
|
|
401
424
|
sdk/java/*/target/
|
|
402
|
-
sdk/java/target/
|
|
425
|
+
sdk/java/target/
|
|
426
|
+
|
|
427
|
+
# Local AI-assistant model configuration (opencode). Machine-specific, and these files hold provider API
|
|
428
|
+
# keys inline: opencode.json.nvidia_glm51 carried a live NVIDIA key on this branch. Ignored so a key
|
|
429
|
+
# cannot be committed from here again.
|
|
430
|
+
#
|
|
431
|
+
# NOTE: ignoring does not undo the disclosure. The key already in history still needs rotating at the
|
|
432
|
+
# provider, and .gitleaks.toml deliberately does not allowlist it, so the secret scan keeps reporting it
|
|
433
|
+
# until that is done.
|
|
434
|
+
opencode.json
|
|
435
|
+
opencode.json.*
|
|
436
|
+
|
|
437
|
+
# Published release documentation. The build-output rule above ([Rr]eleases/) would otherwise swallow the
|
|
438
|
+
# repository's own /releases directory, so re-include it and the docs it holds while leaving everything
|
|
439
|
+
# else under it ignored.
|
|
440
|
+
!/releases/
|
|
441
|
+
/releases/*
|
|
442
|
+
!/releases/docs/
|
|
443
|
+
|
|
444
|
+
# Plan 0090. The local license folder the repository's compose files mount at /license (LICENSE_DIR). It holds an
|
|
445
|
+
# installation's license file and, in development, the throwaway key ring tools/licensing/create-dev-license.sh
|
|
446
|
+
# generates. A customer license names the customer and a development key ring is trust material for this machine
|
|
447
|
+
# only -- neither belongs in git. Not "license/": on a case-insensitive file system that is the LICENSE file.
|
|
448
|
+
# The trusted public keys the Runtime ships live in src/Runtime/.../Runtime.Host/licensing/public-keys/, not here.
|
|
449
|
+
/license-files/
|
|
450
|
+
|
|
451
|
+
# Plan 0090. The License Admin Portal's local development folder, written by tools/license-admin/setup-dev.sh: the
|
|
452
|
+
# throwaway evaluation signing key (PFX + .cer), the write-once archive, and the .NET dev certificate exported as PEM
|
|
453
|
+
# for the SPA dev server. Private keys for this machine only; never in git (gitleaks scans history).
|
|
454
|
+
/license-admin-dev/
|
|
455
|
+
|
|
456
|
+
#stale sonarqube files
|
|
457
|
+
.sonarqube.stale-*
|
|
458
|
+
|
|
459
|
+
# ZAP replacer configurations carry the scan session's credentials; never commit one, even redacted.
|
|
460
|
+
releases/**/zap-config.prop
|
|
461
|
+
releases/**/zap-runtime-config.prop
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: api-mapper-client
|
|
3
|
+
Version: 1.3.0
|
|
4
|
+
Summary: Client SDK for the CodedProjects AI ApiMapper Runtime
|
|
5
|
+
Project-URL: Homepage, https://apimapper.ai
|
|
6
|
+
Author: Coded Projects
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: ai,apimapper,client,llm,mcp,python,sdk,tools
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Requires-Dist: httpx>=0.28.1
|
|
20
|
+
Provides-Extra: all
|
|
21
|
+
Requires-Dist: langchain-core>=1.3.3; extra == 'all'
|
|
22
|
+
Requires-Dist: langgraph>=1.0.10; extra == 'all'
|
|
23
|
+
Requires-Dist: pydantic>=2.4.0; extra == 'all'
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: respx>=0.21.0; extra == 'dev'
|
|
28
|
+
Provides-Extra: langchain
|
|
29
|
+
Requires-Dist: langchain-core>=1.3.3; extra == 'langchain'
|
|
30
|
+
Requires-Dist: pydantic>=2.4.0; extra == 'langchain'
|
|
31
|
+
Provides-Extra: langgraph
|
|
32
|
+
Requires-Dist: langchain-core>=1.3.3; extra == 'langgraph'
|
|
33
|
+
Requires-Dist: langgraph>=1.0.10; extra == 'langgraph'
|
|
34
|
+
Requires-Dist: pydantic>=2.4.0; extra == 'langgraph'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# api-mapper-client
|
|
38
|
+
|
|
39
|
+
Python SDK for discovering and invoking AI ApiMapper Runtime tools from Python applications and agents.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install api-mapper-client
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Optional integrations:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install "api-mapper-client[langchain]"
|
|
51
|
+
pip install "api-mapper-client[langgraph]"
|
|
52
|
+
pip install "api-mapper-client[all]"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## What it provides
|
|
56
|
+
|
|
57
|
+
- runtime tool discovery,
|
|
58
|
+
- runtime system prompt loading,
|
|
59
|
+
- tool invocation over MCP-compatible HTTP endpoints,
|
|
60
|
+
- API key, delegated bearer token, and OAuth2 client credentials authentication helpers,
|
|
61
|
+
- on-demand hosted-agent executions (start, read, cancel) via `ApiMapperAgentClient`, and a webhook signing helper,
|
|
62
|
+
- optional LangChain and LangGraph integration helpers.
|
|
63
|
+
|
|
64
|
+
## Quick start
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
import uuid
|
|
68
|
+
|
|
69
|
+
from api_mapper_client import ApiMapperClient, ApiMapperClientOptions
|
|
70
|
+
from api_mapper_client.auth.api_key import ApiKeyCredentialProvider
|
|
71
|
+
|
|
72
|
+
client = ApiMapperClient(
|
|
73
|
+
ApiMapperClientOptions(
|
|
74
|
+
base_url="https://runtime.example.com",
|
|
75
|
+
tenant_id=uuid.UUID("11111111-1111-1111-1111-111111111111"),
|
|
76
|
+
client_id="my-ai-client",
|
|
77
|
+
credentials=ApiKeyCredentialProvider("replace-with-your-api-key"),
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
tools = await client.get_tools()
|
|
82
|
+
print([tool.name for tool in tools])
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Streaming (Streamable HTTP / SSE)
|
|
86
|
+
|
|
87
|
+
The Runtime's `/mcp` endpoint may answer a request either with a plain JSON body or, when it
|
|
88
|
+
prefers SSE responses, with an SSE-framed body (`Content-Type: text/event-stream`). The client
|
|
89
|
+
handles both transparently — no configuration is needed, and neither mode is a "fallback" of the
|
|
90
|
+
other. If an SSE response ever ends without producing a message frame, the client makes one
|
|
91
|
+
resumption attempt (`GET /mcp` with `Last-Event-ID`) before raising.
|
|
92
|
+
|
|
93
|
+
Two additional APIs come with this support:
|
|
94
|
+
|
|
95
|
+
**`close_session()`** — explicitly tears down the MCP session on the Runtime (`DELETE /mcp`).
|
|
96
|
+
Best-effort: a 404 (session already gone) is not treated as an error. It's called automatically by
|
|
97
|
+
`close()` / `__aexit__`, so you typically don't need to call it directly:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
async with client:
|
|
101
|
+
tools = await client.get_tools()
|
|
102
|
+
# session is closed automatically on exit
|
|
103
|
+
|
|
104
|
+
# or explicitly, without closing the underlying HTTP client:
|
|
105
|
+
await client.close_session()
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
**`listen()`** — opens the Runtime's standalone server-push stream (`GET /mcp`) and yields each
|
|
109
|
+
message as a dict. It reconnects automatically on transient faults (using `Last-Event-ID` so the
|
|
110
|
+
Runtime can resume/replay), and stops immediately if the session is unknown/expired or a stream is
|
|
111
|
+
already open:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
async for message in client.listen():
|
|
115
|
+
print(message)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Correlation IDs
|
|
119
|
+
|
|
120
|
+
Send your application's own trace ID with each call and the Runtime records it against the execution
|
|
121
|
+
ID it generates, so you can retrieve the full platform audit trail for work you triggered. Configure
|
|
122
|
+
an ambient provider on the client options, or pass one per call. See the
|
|
123
|
+
[SDK correlation guide](https://github.com/CodedProjects/ApiMapper/blob/main/docs/SDK.md#correlation-ids).
|
|
124
|
+
|
|
125
|
+
## License
|
|
126
|
+
|
|
127
|
+
MIT
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# api-mapper-client
|
|
2
|
+
|
|
3
|
+
Python SDK for discovering and invoking AI ApiMapper Runtime tools from Python applications and agents.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install api-mapper-client
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Optional integrations:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install "api-mapper-client[langchain]"
|
|
15
|
+
pip install "api-mapper-client[langgraph]"
|
|
16
|
+
pip install "api-mapper-client[all]"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## What it provides
|
|
20
|
+
|
|
21
|
+
- runtime tool discovery,
|
|
22
|
+
- runtime system prompt loading,
|
|
23
|
+
- tool invocation over MCP-compatible HTTP endpoints,
|
|
24
|
+
- API key, delegated bearer token, and OAuth2 client credentials authentication helpers,
|
|
25
|
+
- on-demand hosted-agent executions (start, read, cancel) via `ApiMapperAgentClient`, and a webhook signing helper,
|
|
26
|
+
- optional LangChain and LangGraph integration helpers.
|
|
27
|
+
|
|
28
|
+
## Quick start
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
import uuid
|
|
32
|
+
|
|
33
|
+
from api_mapper_client import ApiMapperClient, ApiMapperClientOptions
|
|
34
|
+
from api_mapper_client.auth.api_key import ApiKeyCredentialProvider
|
|
35
|
+
|
|
36
|
+
client = ApiMapperClient(
|
|
37
|
+
ApiMapperClientOptions(
|
|
38
|
+
base_url="https://runtime.example.com",
|
|
39
|
+
tenant_id=uuid.UUID("11111111-1111-1111-1111-111111111111"),
|
|
40
|
+
client_id="my-ai-client",
|
|
41
|
+
credentials=ApiKeyCredentialProvider("replace-with-your-api-key"),
|
|
42
|
+
)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
tools = await client.get_tools()
|
|
46
|
+
print([tool.name for tool in tools])
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Streaming (Streamable HTTP / SSE)
|
|
50
|
+
|
|
51
|
+
The Runtime's `/mcp` endpoint may answer a request either with a plain JSON body or, when it
|
|
52
|
+
prefers SSE responses, with an SSE-framed body (`Content-Type: text/event-stream`). The client
|
|
53
|
+
handles both transparently — no configuration is needed, and neither mode is a "fallback" of the
|
|
54
|
+
other. If an SSE response ever ends without producing a message frame, the client makes one
|
|
55
|
+
resumption attempt (`GET /mcp` with `Last-Event-ID`) before raising.
|
|
56
|
+
|
|
57
|
+
Two additional APIs come with this support:
|
|
58
|
+
|
|
59
|
+
**`close_session()`** — explicitly tears down the MCP session on the Runtime (`DELETE /mcp`).
|
|
60
|
+
Best-effort: a 404 (session already gone) is not treated as an error. It's called automatically by
|
|
61
|
+
`close()` / `__aexit__`, so you typically don't need to call it directly:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
async with client:
|
|
65
|
+
tools = await client.get_tools()
|
|
66
|
+
# session is closed automatically on exit
|
|
67
|
+
|
|
68
|
+
# or explicitly, without closing the underlying HTTP client:
|
|
69
|
+
await client.close_session()
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**`listen()`** — opens the Runtime's standalone server-push stream (`GET /mcp`) and yields each
|
|
73
|
+
message as a dict. It reconnects automatically on transient faults (using `Last-Event-ID` so the
|
|
74
|
+
Runtime can resume/replay), and stops immediately if the session is unknown/expired or a stream is
|
|
75
|
+
already open:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
async for message in client.listen():
|
|
79
|
+
print(message)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Correlation IDs
|
|
83
|
+
|
|
84
|
+
Send your application's own trace ID with each call and the Runtime records it against the execution
|
|
85
|
+
ID it generates, so you can retrieve the full platform audit trail for work you triggered. Configure
|
|
86
|
+
an ambient provider on the client options, or pass one per call. See the
|
|
87
|
+
[SDK correlation guide](https://github.com/CodedProjects/ApiMapper/blob/main/docs/SDK.md#correlation-ids).
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
MIT
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from .client import ApiMapperClient, ApiMapperClientOptions, ApiMapperRequestError
|
|
2
|
+
from .agents import ApiMapperAgentClient, ApiMapperAgentRequestError
|
|
3
|
+
from .webhooks import AgentWebhookSignature
|
|
4
|
+
from .auth.api_key import ApiKeyCredentialProvider
|
|
5
|
+
from .auth.delegated_bearer import DelegatedBearerCredentialProvider
|
|
6
|
+
from .auth.oauth2_client_credentials import OAuth2ClientCredentialsProvider, OAuth2ClientCredentialsOptions
|
|
7
|
+
from .contracts import (
|
|
8
|
+
AgentExecutionCancelResult,
|
|
9
|
+
AgentExecutionInfo,
|
|
10
|
+
AgentExecutionStarted,
|
|
11
|
+
AgentExecutionStartRequest,
|
|
12
|
+
AgentExecutionSummary,
|
|
13
|
+
McpTool,
|
|
14
|
+
McpToolCallResult,
|
|
15
|
+
McpToolContent,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ApiMapperClient",
|
|
20
|
+
"ApiMapperClientOptions",
|
|
21
|
+
"ApiMapperRequestError",
|
|
22
|
+
"ApiMapperAgentClient",
|
|
23
|
+
"ApiMapperAgentRequestError",
|
|
24
|
+
"AgentWebhookSignature",
|
|
25
|
+
"ApiKeyCredentialProvider",
|
|
26
|
+
"DelegatedBearerCredentialProvider",
|
|
27
|
+
"OAuth2ClientCredentialsProvider",
|
|
28
|
+
"OAuth2ClientCredentialsOptions",
|
|
29
|
+
"McpTool",
|
|
30
|
+
"McpToolCallResult",
|
|
31
|
+
"McpToolContent",
|
|
32
|
+
"AgentExecutionStartRequest",
|
|
33
|
+
"AgentExecutionStarted",
|
|
34
|
+
"AgentExecutionInfo",
|
|
35
|
+
"AgentExecutionSummary",
|
|
36
|
+
"AgentExecutionCancelResult",
|
|
37
|
+
]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""On-demand hosted-agent executions through the Runtime's agent execution API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import timedelta
|
|
7
|
+
from typing import Any, Callable, TypeVar
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .client import CORRELATION_ID_HEADER, ApiMapperClientOptions, resolve_correlation_id
|
|
12
|
+
from .contracts import (
|
|
13
|
+
AgentExecutionCancelResult,
|
|
14
|
+
AgentExecutionInfo,
|
|
15
|
+
AgentExecutionStarted,
|
|
16
|
+
AgentExecutionStartRequest,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# Auth header values (Bearer tokens, API keys) and the message sent to the agent are never logged.
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
T = TypeVar("T")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ApiMapperAgentRequestError(RuntimeError):
|
|
26
|
+
"""The Runtime's agent execution API refused a request.
|
|
27
|
+
|
|
28
|
+
``status_code`` is the HTTP status: 400 (bad input or preset), 403 (the agent's policy refuses
|
|
29
|
+
this caller), 404 (no such agent, or an execution this caller may not see), 409 (the agent is
|
|
30
|
+
unavailable) and 429 (the agent is at capacity — honour ``retry_after``). ``problem_type`` is the
|
|
31
|
+
problem type, such as ``urn:apimapper:agents:preset-not-found``, when the Runtime sent one.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
operation: str,
|
|
37
|
+
status_code: int,
|
|
38
|
+
problem_type: str | None = None,
|
|
39
|
+
detail: str | None = None,
|
|
40
|
+
retry_after: timedelta | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
suffix = "." if detail is None else f": {detail}"
|
|
43
|
+
super().__init__(f"Agent request '{operation}' failed with HTTP {status_code}{suffix}")
|
|
44
|
+
self.operation = operation
|
|
45
|
+
self.status_code = status_code
|
|
46
|
+
self.problem_type = problem_type
|
|
47
|
+
self.retry_after = retry_after
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ApiMapperAgentClient:
|
|
51
|
+
"""Starts the tenant's hosted agents on demand, and reads or cancels what it started.
|
|
52
|
+
|
|
53
|
+
Calls ``{base_url}/runtime/{tenant_id}/agents/`` with the same :class:`ApiMapperClientOptions`
|
|
54
|
+
as :class:`ApiMapperClient` — base URL, tenant, credential and correlation ID provider; the
|
|
55
|
+
client id is not used. The agent runs as *this client's caller*: the agent's access policy
|
|
56
|
+
decides whether it may, exactly as for an A2A call, and a user token keeps its
|
|
57
|
+
delegated-credential semantics.
|
|
58
|
+
|
|
59
|
+
A refusal raises :class:`ApiMapperAgentRequestError`. Nothing is retried: starting an execution
|
|
60
|
+
is not idempotent, and a retried POST would start the agent twice.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, opts: ApiMapperClientOptions) -> None:
|
|
64
|
+
self._opts = opts
|
|
65
|
+
self._agent_root = f"{opts.base_url.rstrip('/')}/runtime/{opts.tenant_id}/agents/"
|
|
66
|
+
# httpx retries nothing by default, which is what a non-idempotent start needs.
|
|
67
|
+
self._http = httpx.AsyncClient()
|
|
68
|
+
|
|
69
|
+
async def start_agent_execution(
|
|
70
|
+
self,
|
|
71
|
+
agent_id: uuid.UUID,
|
|
72
|
+
request: AgentExecutionStartRequest,
|
|
73
|
+
) -> AgentExecutionStarted:
|
|
74
|
+
"""Start ``agent_id`` with ``request``. Never retried: a retry would start the agent twice."""
|
|
75
|
+
started = await self._send(
|
|
76
|
+
"start", "POST", f"{agent_id}/executions", request.to_json(), AgentExecutionStarted.from_json
|
|
77
|
+
)
|
|
78
|
+
logger.info("Started execution %s of agent %s: %s.", started.execution_id, agent_id, started.status)
|
|
79
|
+
return started
|
|
80
|
+
|
|
81
|
+
async def get_agent_execution(self, execution_id: uuid.UUID) -> AgentExecutionInfo:
|
|
82
|
+
"""Read an execution this caller started, or one of an agent this caller may call."""
|
|
83
|
+
return await self._send("get", "GET", f"executions/{execution_id}", None, AgentExecutionInfo.from_json)
|
|
84
|
+
|
|
85
|
+
async def cancel_agent_execution(self, execution_id: uuid.UUID) -> AgentExecutionCancelResult:
|
|
86
|
+
"""Cancel an execution this caller may see."""
|
|
87
|
+
result = await self._send(
|
|
88
|
+
"cancel", "POST", f"executions/{execution_id}/cancel", None, AgentExecutionCancelResult.from_json
|
|
89
|
+
)
|
|
90
|
+
logger.info("Cancel of execution %s: %s.", execution_id, result.outcome)
|
|
91
|
+
return result
|
|
92
|
+
|
|
93
|
+
async def close(self) -> None:
|
|
94
|
+
await self._http.aclose()
|
|
95
|
+
|
|
96
|
+
async def __aenter__(self) -> "ApiMapperAgentClient":
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
async def __aexit__(self, *_: Any) -> None:
|
|
100
|
+
await self.close()
|
|
101
|
+
|
|
102
|
+
# ── Internals ─────────────────────────────────────────────────────────
|
|
103
|
+
|
|
104
|
+
async def _send(
|
|
105
|
+
self,
|
|
106
|
+
operation: str,
|
|
107
|
+
method: str,
|
|
108
|
+
path: str,
|
|
109
|
+
body: dict[str, Any] | None,
|
|
110
|
+
parse: Callable[[dict[str, Any]], T],
|
|
111
|
+
) -> T:
|
|
112
|
+
headers: dict[str, str] = {"Accept": "application/json"}
|
|
113
|
+
correlation_id = resolve_correlation_id(self._opts, None)
|
|
114
|
+
if correlation_id:
|
|
115
|
+
headers[CORRELATION_ID_HEADER] = correlation_id
|
|
116
|
+
# Credential provider adds auth headers — values are never logged.
|
|
117
|
+
await self._opts.credentials.enrich(headers)
|
|
118
|
+
|
|
119
|
+
response = await self._http.request(method, self._agent_root + path, headers=headers, json=body)
|
|
120
|
+
if not response.is_success:
|
|
121
|
+
raise self._refusal(operation, response)
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
payload = response.json() if response.content else None
|
|
125
|
+
if not isinstance(payload, dict):
|
|
126
|
+
raise ApiMapperAgentRequestError(
|
|
127
|
+
operation, response.status_code, None, "The Runtime returned an empty body."
|
|
128
|
+
)
|
|
129
|
+
return parse(payload)
|
|
130
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
131
|
+
raise ApiMapperAgentRequestError(
|
|
132
|
+
operation, response.status_code, None, f"The Runtime returned a body that could not be read: {error}"
|
|
133
|
+
) from error
|
|
134
|
+
|
|
135
|
+
@staticmethod
|
|
136
|
+
def _refusal(operation: str, response: httpx.Response) -> ApiMapperAgentRequestError:
|
|
137
|
+
problem = _read_problem(response)
|
|
138
|
+
problem_type = _text_or_none(problem, "type")
|
|
139
|
+
# A route refusal is problem+json and says why in 'detail'. A start the agent refused (403,
|
|
140
|
+
# 409, 429) answers with the start response instead, whose 'failureReason' says why.
|
|
141
|
+
detail = _text_or_none(problem, "detail") or _text_or_none(problem, "failureReason")
|
|
142
|
+
logger.warning(
|
|
143
|
+
"Agent request '%s' was refused with HTTP %d (%s).", operation, response.status_code, problem_type
|
|
144
|
+
)
|
|
145
|
+
return ApiMapperAgentRequestError(
|
|
146
|
+
operation, response.status_code, problem_type, detail, _retry_after(response)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _read_problem(response: httpx.Response) -> dict[str, Any] | None:
|
|
151
|
+
try:
|
|
152
|
+
payload = response.json() if response.content else None
|
|
153
|
+
except ValueError:
|
|
154
|
+
# A refusal from the Gateway or a proxy may not be JSON; the status still says what happened.
|
|
155
|
+
return None
|
|
156
|
+
return payload if isinstance(payload, dict) else None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _text_or_none(problem: dict[str, Any] | None, key: str) -> str | None:
|
|
160
|
+
value = (problem or {}).get(key)
|
|
161
|
+
return value if isinstance(value, str) else None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _retry_after(response: httpx.Response) -> timedelta | None:
|
|
165
|
+
"""The ``Retry-After`` delay in seconds, as the Runtime sends it; ``None`` when absent or a date."""
|
|
166
|
+
value = (response.headers.get("Retry-After") or "").strip()
|
|
167
|
+
return timedelta(seconds=int(value)) if value.isascii() and value.isdigit() else None
|