purra-openai 0.5.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.
- purra_openai-0.5.0/LICENSE +21 -0
- purra_openai-0.5.0/MANIFEST.in +1 -0
- purra_openai-0.5.0/PKG-INFO +69 -0
- purra_openai-0.5.0/README.md +57 -0
- purra_openai-0.5.0/README.zh-CN.md +54 -0
- purra_openai-0.5.0/pyproject.toml +20 -0
- purra_openai-0.5.0/setup.cfg +4 -0
- purra_openai-0.5.0/src/purra_openai/__init__.py +185 -0
- purra_openai-0.5.0/src/purra_openai/chat.py +172 -0
- purra_openai-0.5.0/src/purra_openai.egg-info/PKG-INFO +69 -0
- purra_openai-0.5.0/src/purra_openai.egg-info/SOURCES.txt +14 -0
- purra_openai-0.5.0/src/purra_openai.egg-info/dependency_links.txt +1 -0
- purra_openai-0.5.0/src/purra_openai.egg-info/requires.txt +2 -0
- purra_openai-0.5.0/src/purra_openai.egg-info/top_level.txt +1 -0
- purra_openai-0.5.0/tests/test_chat.py +77 -0
- purra_openai-0.5.0/tests/test_gateway.py +145 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lybrands
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
include README.zh-CN.md
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: purra-openai
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Official OpenAI Responses and Chat Completions SDK adapter for PurrA
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: purra==0.5.0
|
|
10
|
+
Requires-Dist: openai==3.7.0
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# purra-openai · Python
|
|
14
|
+
|
|
15
|
+
English | [简体中文](README.zh-CN.md)
|
|
16
|
+
|
|
17
|
+
OpenAI model gateways for PurrA using the official Python SDK. Supports text,
|
|
18
|
+
function tools, streaming, cancellation, and token usage. Requires Python 3.11+.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
From the repository root:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
python -m pip install . ./integrations/openai/python
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Choose an API
|
|
29
|
+
|
|
30
|
+
| Gateway | API |
|
|
31
|
+
| --- | --- |
|
|
32
|
+
| `OpenAIResponsesGateway` | Responses |
|
|
33
|
+
| `OpenAIChatCompletionsGateway` | Chat Completions |
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from openai import AsyncOpenAI
|
|
37
|
+
from purra_openai import OpenAIResponsesGateway
|
|
38
|
+
|
|
39
|
+
client = AsyncOpenAI()
|
|
40
|
+
gateway = OpenAIResponsesGateway(client, timeout_seconds=60)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
For Chat Completions, replace the gateway:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from purra_openai import OpenAIChatCompletionsGateway
|
|
47
|
+
|
|
48
|
+
gateway = OpenAIChatCompletionsGateway(client, timeout_seconds=60)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Pass `gateway` to `AgentCore(model_gateway=gateway, ...)`. In the Run's
|
|
52
|
+
`ModelRequest`, set `provider="openai"`, the model ID, and its capability snapshot.
|
|
53
|
+
The application supplies credentials and verified model limits.
|
|
54
|
+
|
|
55
|
+
## Options and behavior
|
|
56
|
+
|
|
57
|
+
`ModelRequest.options` accepts `max_tokens`, `temperature`, `top_p`, and
|
|
58
|
+
`reasoning_effort`. Choose options supported by the selected model.
|
|
59
|
+
Core resolves the output limit; the gateway applies it to the selected API.
|
|
60
|
+
|
|
61
|
+
SDK retries are disabled so Core controls retry and budget accounting.
|
|
62
|
+
Server-side response storage is disabled. Responses reasoning continuation is
|
|
63
|
+
kept in private message data; preserve it with the conversation when resuming.
|
|
64
|
+
|
|
65
|
+
These gateways support native OpenAI text and function-tool APIs. Images, audio,
|
|
66
|
+
and hosted tools are not supported. Other vendors require application adapters.
|
|
67
|
+
|
|
68
|
+
Close a supplied SDK client in the application. `await gateway.close()` closes
|
|
69
|
+
only a client created by the gateway itself.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# purra-openai · Python
|
|
2
|
+
|
|
3
|
+
English | [简体中文](README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
OpenAI model gateways for PurrA using the official Python SDK. Supports text,
|
|
6
|
+
function tools, streaming, cancellation, and token usage. Requires Python 3.11+.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
From the repository root:
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
python -m pip install . ./integrations/openai/python
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Choose an API
|
|
17
|
+
|
|
18
|
+
| Gateway | API |
|
|
19
|
+
| --- | --- |
|
|
20
|
+
| `OpenAIResponsesGateway` | Responses |
|
|
21
|
+
| `OpenAIChatCompletionsGateway` | Chat Completions |
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from openai import AsyncOpenAI
|
|
25
|
+
from purra_openai import OpenAIResponsesGateway
|
|
26
|
+
|
|
27
|
+
client = AsyncOpenAI()
|
|
28
|
+
gateway = OpenAIResponsesGateway(client, timeout_seconds=60)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
For Chat Completions, replace the gateway:
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from purra_openai import OpenAIChatCompletionsGateway
|
|
35
|
+
|
|
36
|
+
gateway = OpenAIChatCompletionsGateway(client, timeout_seconds=60)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Pass `gateway` to `AgentCore(model_gateway=gateway, ...)`. In the Run's
|
|
40
|
+
`ModelRequest`, set `provider="openai"`, the model ID, and its capability snapshot.
|
|
41
|
+
The application supplies credentials and verified model limits.
|
|
42
|
+
|
|
43
|
+
## Options and behavior
|
|
44
|
+
|
|
45
|
+
`ModelRequest.options` accepts `max_tokens`, `temperature`, `top_p`, and
|
|
46
|
+
`reasoning_effort`. Choose options supported by the selected model.
|
|
47
|
+
Core resolves the output limit; the gateway applies it to the selected API.
|
|
48
|
+
|
|
49
|
+
SDK retries are disabled so Core controls retry and budget accounting.
|
|
50
|
+
Server-side response storage is disabled. Responses reasoning continuation is
|
|
51
|
+
kept in private message data; preserve it with the conversation when resuming.
|
|
52
|
+
|
|
53
|
+
These gateways support native OpenAI text and function-tool APIs. Images, audio,
|
|
54
|
+
and hosted tools are not supported. Other vendors require application adapters.
|
|
55
|
+
|
|
56
|
+
Close a supplied SDK client in the application. `await gateway.close()` closes
|
|
57
|
+
only a client created by the gateway itself.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# purra-openai · Python
|
|
2
|
+
|
|
3
|
+
[English](README.md) | 简体中文
|
|
4
|
+
|
|
5
|
+
使用官方 Python SDK 将 OpenAI 接入 PurrA,支持文本、函数工具、流式输出、取消和 Token 用量。
|
|
6
|
+
要求 Python 3.11+。
|
|
7
|
+
|
|
8
|
+
## 安装
|
|
9
|
+
|
|
10
|
+
在仓库根目录执行:
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
python -m pip install . ./integrations/openai/python
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## 选择 API
|
|
17
|
+
|
|
18
|
+
| 网关 | API |
|
|
19
|
+
| --- | --- |
|
|
20
|
+
| `OpenAIResponsesGateway` | Responses |
|
|
21
|
+
| `OpenAIChatCompletionsGateway` | Chat Completions |
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from openai import AsyncOpenAI
|
|
25
|
+
from purra_openai import OpenAIResponsesGateway
|
|
26
|
+
|
|
27
|
+
client = AsyncOpenAI()
|
|
28
|
+
gateway = OpenAIResponsesGateway(client, timeout_seconds=60)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
使用 Chat Completions 时替换网关:
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from purra_openai import OpenAIChatCompletionsGateway
|
|
35
|
+
|
|
36
|
+
gateway = OpenAIChatCompletionsGateway(client, timeout_seconds=60)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
将 `gateway` 传给 `AgentCore(model_gateway=gateway, ...)`。
|
|
40
|
+
在 Run 的 `ModelRequest` 中设置 `provider="openai"`、模型 ID 和模型能力快照。
|
|
41
|
+
凭据与已核实的模型限制由应用提供。
|
|
42
|
+
|
|
43
|
+
## 参数与行为
|
|
44
|
+
|
|
45
|
+
`ModelRequest.options` 接受 `max_tokens`、`temperature`、`top_p` 和 `reasoning_effort`。
|
|
46
|
+
根据所选模型支持的能力设置参数。Core 计算输出上限,网关将其应用到对应 API。
|
|
47
|
+
|
|
48
|
+
SDK 自动重试已关闭,重试和预算核算由 Core 控制。服务端响应存储已关闭。
|
|
49
|
+
Responses 的推理续接信息保存在私有消息数据中,恢复时应与对话一同保留。
|
|
50
|
+
|
|
51
|
+
网关支持 OpenAI 原生文本和函数工具 API,不支持图片、音频及服务端托管工具。
|
|
52
|
+
其他厂商由应用提供适配。
|
|
53
|
+
|
|
54
|
+
传入的 SDK 客户端由应用关闭。`await gateway.close()` 只关闭网关自行创建的客户端。
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "purra-openai"
|
|
7
|
+
version = "0.5.0"
|
|
8
|
+
description = "Official OpenAI Responses and Chat Completions SDK adapter for PurrA"
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
dependencies = ["purra==0.5.0", "openai==3.7.0"]
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
license = "MIT"
|
|
13
|
+
|
|
14
|
+
[tool.setuptools.packages.find]
|
|
15
|
+
where = ["src"]
|
|
16
|
+
|
|
17
|
+
[tool.pytest.ini_options]
|
|
18
|
+
pythonpath = ["src", "../../../src"]
|
|
19
|
+
testpaths = ["tests"]
|
|
20
|
+
addopts = "-ra -q"
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""OpenAI Responses adapter; SDK retries are disabled for Core accounting."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
from openai import AsyncOpenAI, APIError, APIStatusError
|
|
6
|
+
from purra.cancellation import await_with_cancellation
|
|
7
|
+
from purra.contracts import (AgentMessage, MessageRole, ModelCompletion, ModelFinishReason,
|
|
8
|
+
ModelStream, ModelStreamActivity, ModelStreamActivityKind,
|
|
9
|
+
ModelStreamActivitySupport, ModelStreamChunk, ModelTokenUsage,
|
|
10
|
+
ToolCall, ToolCallDelta)
|
|
11
|
+
from purra.errors import ModelGatewayError
|
|
12
|
+
from purra.json_values import thaw_json_value, thaw_json_mapping
|
|
13
|
+
|
|
14
|
+
_REPLAY = "openai_reasoning_items"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _text(value):
|
|
18
|
+
if value is None:
|
|
19
|
+
return ""
|
|
20
|
+
if not isinstance(value, str):
|
|
21
|
+
raise ValueError("OpenAI adapter currently accepts text messages only")
|
|
22
|
+
return value
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _input(messages):
|
|
26
|
+
rows = []
|
|
27
|
+
for message in messages:
|
|
28
|
+
if message.tool_calls and message.role is not MessageRole.ASSISTANT:
|
|
29
|
+
raise ValueError("only assistant messages may carry function calls")
|
|
30
|
+
if message.role is MessageRole.ASSISTANT:
|
|
31
|
+
replay = thaw_json_value(message.provider_data.get(_REPLAY, ()))
|
|
32
|
+
if not isinstance(replay, list) or any(not isinstance(r, dict) or r.get("type") != "reasoning" for r in replay):
|
|
33
|
+
raise ValueError("invalid OpenAI reasoning continuation")
|
|
34
|
+
rows.extend(replay)
|
|
35
|
+
content = _text(message.content)
|
|
36
|
+
if message.role is MessageRole.TOOL:
|
|
37
|
+
rows.append({"type": "function_call_output", "call_id": message.tool_call_id, "output": content})
|
|
38
|
+
continue
|
|
39
|
+
if content or not message.tool_calls:
|
|
40
|
+
rows.append({"role": message.role.value, "content": content})
|
|
41
|
+
rows.extend({"type": "function_call", "call_id": call.id, "name": call.name,
|
|
42
|
+
"arguments": call.arguments_json} for call in message.tool_calls)
|
|
43
|
+
return rows
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _usage(response):
|
|
47
|
+
usage = response.usage
|
|
48
|
+
if usage is None:
|
|
49
|
+
return None
|
|
50
|
+
input_details = getattr(usage, "input_tokens_details", None)
|
|
51
|
+
output_details = getattr(usage, "output_tokens_details", None)
|
|
52
|
+
return ModelTokenUsage(input_tokens=usage.input_tokens, generation_tokens=usage.output_tokens,
|
|
53
|
+
total_tokens=usage.total_tokens,
|
|
54
|
+
cached_input_tokens=(getattr(input_details, "cached_tokens", 0) or 0),
|
|
55
|
+
reasoning_tokens=getattr(output_details, "reasoning_tokens", None))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _finish(response):
|
|
59
|
+
if response.status == "incomplete":
|
|
60
|
+
reason = response.incomplete_details.reason if response.incomplete_details else None
|
|
61
|
+
return ModelFinishReason.LENGTH if reason == "max_output_tokens" else ModelFinishReason.FILTERED if reason == "content_filter" else ModelFinishReason.OTHER
|
|
62
|
+
if response.status != "completed":
|
|
63
|
+
raise ModelGatewayError("OpenAI response failed", code="openai_response_failed")
|
|
64
|
+
if any(item.type == "function_call" for item in response.output):
|
|
65
|
+
return ModelFinishReason.TOOL_CALLS
|
|
66
|
+
if any(part.type == "refusal" for item in response.output if item.type == "message" for part in item.content):
|
|
67
|
+
return ModelFinishReason.FILTERED
|
|
68
|
+
return ModelFinishReason.STOP
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _attributes(response):
|
|
72
|
+
items = [item.model_dump(exclude_none=True) for item in response.output if item.type == "reasoning"]
|
|
73
|
+
return {_REPLAY: items} if items else {}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _error(error):
|
|
77
|
+
status = error.status_code if isinstance(error, APIStatusError) else None
|
|
78
|
+
return ModelGatewayError("OpenAI request failed", code=f"openai_http_{status}" if status else "openai_transport_error",
|
|
79
|
+
retryable=status is None or status in (408, 409, 429) or status >= 500)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class OpenAIResponsesGateway:
|
|
83
|
+
"""Text and function tools, with private encrypted reasoning continuity.
|
|
84
|
+
|
|
85
|
+
Pass a host-owned AsyncOpenAI to share its transport. The gateway makes one
|
|
86
|
+
HTTP attempt per managed invocation and reports actual usage/output limits.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(self, client: AsyncOpenAI | None = None, *, timeout_seconds: float = 60):
|
|
90
|
+
if not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
|
|
91
|
+
raise ValueError("timeout_seconds must be positive and finite")
|
|
92
|
+
self._owns_client = client is None
|
|
93
|
+
self._client = (client or AsyncOpenAI()).with_options(max_retries=0, timeout=timeout_seconds)
|
|
94
|
+
|
|
95
|
+
def _request(self, messages, invocation):
|
|
96
|
+
if invocation.request.provider != "openai":
|
|
97
|
+
raise ValueError("OpenAI gateway requires provider='openai'")
|
|
98
|
+
cap = invocation.max_generation_tokens
|
|
99
|
+
if cap is None:
|
|
100
|
+
raise ValueError("OpenAI gateway requires a resolved generation allowance")
|
|
101
|
+
options = thaw_json_mapping(invocation.request.options)
|
|
102
|
+
unknown = set(options) - {"temperature", "top_p", "reasoning_effort"}
|
|
103
|
+
if unknown:
|
|
104
|
+
raise ValueError("unsupported OpenAI model options: " + ", ".join(sorted(unknown)))
|
|
105
|
+
effort = options.get("reasoning_effort")
|
|
106
|
+
if invocation.reasoning_mode.value == "disabled" and effort not in (None, "none"):
|
|
107
|
+
raise ValueError("reasoning effort conflicts with disabled reasoning")
|
|
108
|
+
if invocation.reasoning_mode.value == "disabled":
|
|
109
|
+
effort = "none"
|
|
110
|
+
elif invocation.reasoning_mode.value == "enabled" and effort == "none":
|
|
111
|
+
raise ValueError("reasoning effort conflicts with enabled reasoning")
|
|
112
|
+
return dict(model=invocation.request.model, input=_input(messages),
|
|
113
|
+
tools=[{"type": "function", "name": t.name, "description": t.description,
|
|
114
|
+
"parameters": thaw_json_mapping(t.parameters), "strict": False} for t in invocation.tools],
|
|
115
|
+
tool_choice=invocation.tool_choice.value if invocation.tools else "none",
|
|
116
|
+
max_output_tokens=cap, store=False, include=["reasoning.encrypted_content"],
|
|
117
|
+
**({"reasoning": {"effort": effort}} if effort is not None else {}),
|
|
118
|
+
**{k: options[k] for k in ("temperature", "top_p") if k in options})
|
|
119
|
+
|
|
120
|
+
async def complete(self, messages, invocation, signal=None):
|
|
121
|
+
params = self._request(messages, invocation)
|
|
122
|
+
try:
|
|
123
|
+
response = await await_with_cancellation(self._client.responses.create(**params), signal)
|
|
124
|
+
except APIError as error:
|
|
125
|
+
raise _error(error) from None
|
|
126
|
+
return ModelCompletion(
|
|
127
|
+
AgentMessage(MessageRole.ASSISTANT, response.output_text,
|
|
128
|
+
tool_calls=tuple(ToolCall(id=i.call_id, name=i.name, arguments_json=i.arguments)
|
|
129
|
+
for i in response.output if i.type == "function_call"),
|
|
130
|
+
provider_data=_attributes(response)),
|
|
131
|
+
model=response.model, finish_reason=_finish(response), usage=_usage(response),
|
|
132
|
+
applied_generation_limit=params["max_output_tokens"],
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
async def stream(self, messages, invocation, signal=None):
|
|
136
|
+
params = self._request(messages, invocation)
|
|
137
|
+
async def chunks():
|
|
138
|
+
terminal = False
|
|
139
|
+
stream = None
|
|
140
|
+
try:
|
|
141
|
+
stream = await await_with_cancellation(self._client.responses.create(**params, stream=True), signal)
|
|
142
|
+
iterator = stream.__aiter__()
|
|
143
|
+
while True:
|
|
144
|
+
try:
|
|
145
|
+
event = await await_with_cancellation(anext(iterator), signal)
|
|
146
|
+
except StopAsyncIteration:
|
|
147
|
+
break
|
|
148
|
+
if event.type == "response.output_text.delta":
|
|
149
|
+
yield ModelStreamChunk(content_delta=event.delta)
|
|
150
|
+
elif event.type in ("response.reasoning_text.delta", "response.reasoning_summary_text.delta"):
|
|
151
|
+
yield ModelStreamActivity(ModelStreamActivityKind.WORKING)
|
|
152
|
+
elif event.type == "response.output_item.added" and event.item.type == "function_call":
|
|
153
|
+
yield ModelStreamChunk(tool_call_deltas=(ToolCallDelta(index=event.output_index,
|
|
154
|
+
id=event.item.call_id, name=event.item.name, type="function",
|
|
155
|
+
arguments_fragment=event.item.arguments),))
|
|
156
|
+
elif event.type == "response.function_call_arguments.delta":
|
|
157
|
+
yield ModelStreamChunk(tool_call_deltas=(ToolCallDelta(index=event.output_index, arguments_fragment=event.delta),))
|
|
158
|
+
elif event.type in ("response.completed", "response.incomplete", "response.failed"):
|
|
159
|
+
terminal = True
|
|
160
|
+
yield ModelStreamChunk(finish_reason=_finish(event.response), usage=_usage(event.response),
|
|
161
|
+
provider_data=_attributes(event.response))
|
|
162
|
+
break
|
|
163
|
+
elif event.type == "error":
|
|
164
|
+
raise ModelGatewayError("OpenAI stream failed", code="openai_stream_error")
|
|
165
|
+
else:
|
|
166
|
+
yield ModelStreamActivity(ModelStreamActivityKind.TRANSPORT)
|
|
167
|
+
if not terminal:
|
|
168
|
+
raise ModelGatewayError("OpenAI stream ended without a terminal response", code="upstream_stream_interrupted")
|
|
169
|
+
except APIError as error:
|
|
170
|
+
raise _error(error) from None
|
|
171
|
+
finally:
|
|
172
|
+
if stream is not None:
|
|
173
|
+
await stream.close()
|
|
174
|
+
|
|
175
|
+
return ModelStream(chunks(), invocation.request.model, applied_generation_limit=params["max_output_tokens"],
|
|
176
|
+
activity_support=ModelStreamActivitySupport.WORKING)
|
|
177
|
+
|
|
178
|
+
async def close(self):
|
|
179
|
+
if self._owns_client:
|
|
180
|
+
await self._client.close()
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
from .chat import OpenAIChatCompletionsGateway
|
|
184
|
+
|
|
185
|
+
__all__ = ["OpenAIResponsesGateway", "OpenAIChatCompletionsGateway"]
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Official OpenAI Chat Completions transport."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
from openai import APIError, APIStatusError, AsyncOpenAI
|
|
6
|
+
from purra.cancellation import await_with_cancellation
|
|
7
|
+
from purra.contracts import (AgentMessage, ModelCompletion, ModelFinishReason,
|
|
8
|
+
ModelStream, ModelStreamActivity, ModelStreamActivityKind,
|
|
9
|
+
ModelStreamActivitySupport, ModelStreamChunk, ModelTokenUsage,
|
|
10
|
+
ToolCall, ToolCallDelta)
|
|
11
|
+
from purra.errors import AgentCoreError, ModelGatewayError
|
|
12
|
+
from purra.json_values import thaw_json_mapping
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _text(value):
|
|
16
|
+
if value is None:
|
|
17
|
+
return ""
|
|
18
|
+
if not isinstance(value, str):
|
|
19
|
+
raise ValueError("OpenAI Chat Completions accepts text content only")
|
|
20
|
+
return value
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _usage(value):
|
|
24
|
+
if not value or value.get("prompt_tokens") is None or value.get("completion_tokens") is None:
|
|
25
|
+
return None
|
|
26
|
+
return ModelTokenUsage(
|
|
27
|
+
input_tokens=value["prompt_tokens"], generation_tokens=value["completion_tokens"],
|
|
28
|
+
total_tokens=value.get("total_tokens"),
|
|
29
|
+
cached_input_tokens=(value.get("prompt_tokens_details") or {}).get("cached_tokens", 0),
|
|
30
|
+
reasoning_tokens=(value.get("completion_tokens_details") or {}).get("reasoning_tokens"),
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _finish(reason):
|
|
35
|
+
values = {"stop": ModelFinishReason.STOP, "length": ModelFinishReason.LENGTH,
|
|
36
|
+
"tool_calls": ModelFinishReason.TOOL_CALLS, "content_filter": ModelFinishReason.FILTERED}
|
|
37
|
+
if reason not in values:
|
|
38
|
+
raise ModelGatewayError("Unknown OpenAI finish reason", code="invalid_model_response")
|
|
39
|
+
return values[reason]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _error(error):
|
|
43
|
+
if isinstance(error, AgentCoreError):
|
|
44
|
+
return error
|
|
45
|
+
if isinstance(error, APIError):
|
|
46
|
+
status = error.status_code if isinstance(error, APIStatusError) else None
|
|
47
|
+
return ModelGatewayError("OpenAI request failed", code=f"openai_http_{status}" if status else "openai_transport_error",
|
|
48
|
+
retryable=status is None or status in (408, 409, 429) or status >= 500)
|
|
49
|
+
return ModelGatewayError("Invalid OpenAI Chat Completions response", code="invalid_model_response")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class OpenAIChatCompletionsGateway:
|
|
53
|
+
"""Text and function tools; the host supplies model selection and capabilities."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, client: AsyncOpenAI | None = None, *, timeout_seconds: float = 60):
|
|
56
|
+
if not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
|
|
57
|
+
raise ValueError("timeout_seconds must be positive and finite")
|
|
58
|
+
self._owns_client = client is None
|
|
59
|
+
self._client = (client or AsyncOpenAI()).with_options(max_retries=0, timeout=timeout_seconds)
|
|
60
|
+
|
|
61
|
+
def _request(self, messages, invocation):
|
|
62
|
+
if invocation.request.provider != "openai":
|
|
63
|
+
raise ValueError("OpenAI gateway requires provider='openai'")
|
|
64
|
+
cap = invocation.max_generation_tokens
|
|
65
|
+
if cap is None:
|
|
66
|
+
raise ValueError("OpenAI gateway requires a resolved generation allowance")
|
|
67
|
+
options = thaw_json_mapping(invocation.request.options)
|
|
68
|
+
if set(options) - {"temperature", "top_p", "reasoning_effort"}:
|
|
69
|
+
raise ValueError("unsupported OpenAI model options")
|
|
70
|
+
effort = options.get("reasoning_effort")
|
|
71
|
+
if invocation.reasoning_mode.value == "disabled" and effort not in (None, "none"):
|
|
72
|
+
raise ValueError("reasoning effort conflicts with disabled reasoning")
|
|
73
|
+
if invocation.reasoning_mode.value == "disabled":
|
|
74
|
+
effort = "none"
|
|
75
|
+
elif invocation.reasoning_mode.value == "enabled" and effort == "none":
|
|
76
|
+
raise ValueError("reasoning effort conflicts with enabled reasoning")
|
|
77
|
+
rows = []
|
|
78
|
+
for message in messages:
|
|
79
|
+
if message.tool_calls and message.role.value != "assistant":
|
|
80
|
+
raise ValueError("only assistant messages may carry tool calls")
|
|
81
|
+
row = {"role": message.role.value, "content": _text(message.content)}
|
|
82
|
+
if message.role.value == "tool":
|
|
83
|
+
row["tool_call_id"] = message.tool_call_id
|
|
84
|
+
if message.tool_calls:
|
|
85
|
+
row["tool_calls"] = [{"id": call.id, "type": "function", "function": {
|
|
86
|
+
"name": call.name, "arguments": call.arguments_json}} for call in message.tool_calls]
|
|
87
|
+
rows.append(row)
|
|
88
|
+
params = dict(model=invocation.request.model, messages=rows, max_completion_tokens=cap, store=False,
|
|
89
|
+
**{key: options[key] for key in ("temperature", "top_p") if key in options})
|
|
90
|
+
if effort is not None:
|
|
91
|
+
params["reasoning_effort"] = effort
|
|
92
|
+
if invocation.tools:
|
|
93
|
+
params["tools"] = [{"type": "function", "function": {"name": t.name, "description": t.description,
|
|
94
|
+
"parameters": thaw_json_mapping(t.parameters), "strict": False}} for t in invocation.tools]
|
|
95
|
+
params["tool_choice"] = invocation.tool_choice.value
|
|
96
|
+
return params
|
|
97
|
+
|
|
98
|
+
async def complete(self, messages, invocation, signal=None):
|
|
99
|
+
params = self._request(messages, invocation)
|
|
100
|
+
try:
|
|
101
|
+
response = await await_with_cancellation(self._client.chat.completions.create(**params), signal)
|
|
102
|
+
raw = response.model_dump()
|
|
103
|
+
if len(raw["choices"]) != 1 or raw["choices"][0]["index"] != 0:
|
|
104
|
+
raise ValueError("expected one completion")
|
|
105
|
+
choice = raw["choices"][0]
|
|
106
|
+
message = choice["message"]
|
|
107
|
+
if message.get("role") != "assistant":
|
|
108
|
+
raise ValueError("expected assistant response")
|
|
109
|
+
return ModelCompletion(
|
|
110
|
+
AgentMessage("assistant", _text(message.get("content")), tool_calls=tuple(
|
|
111
|
+
ToolCall(id=c["id"], name=c["function"]["name"], arguments_json=c["function"]["arguments"])
|
|
112
|
+
for c in message.get("tool_calls") or ())),
|
|
113
|
+
model=response.model,
|
|
114
|
+
finish_reason=ModelFinishReason.FILTERED if message.get("refusal") else _finish(choice["finish_reason"]),
|
|
115
|
+
usage=_usage(raw.get("usage")), applied_generation_limit=params["max_completion_tokens"],
|
|
116
|
+
)
|
|
117
|
+
except Exception as error:
|
|
118
|
+
raise _error(error) from None
|
|
119
|
+
|
|
120
|
+
async def stream(self, messages, invocation, signal=None):
|
|
121
|
+
params = self._request(messages, invocation)
|
|
122
|
+
async def chunks():
|
|
123
|
+
stream = None
|
|
124
|
+
finish = None
|
|
125
|
+
usage = None
|
|
126
|
+
refused = False
|
|
127
|
+
try:
|
|
128
|
+
stream = await await_with_cancellation(self._client.chat.completions.create(
|
|
129
|
+
**params, stream=True, stream_options={"include_usage": True}), signal)
|
|
130
|
+
iterator = stream.__aiter__()
|
|
131
|
+
while True:
|
|
132
|
+
try:
|
|
133
|
+
chunk = await await_with_cancellation(anext(iterator), signal)
|
|
134
|
+
except StopAsyncIteration:
|
|
135
|
+
break
|
|
136
|
+
raw = chunk.model_dump()
|
|
137
|
+
if raw.get("usage") is not None:
|
|
138
|
+
usage = _usage(raw["usage"])
|
|
139
|
+
choices = raw.get("choices", [])
|
|
140
|
+
if not choices:
|
|
141
|
+
yield ModelStreamActivity(ModelStreamActivityKind.TRANSPORT)
|
|
142
|
+
continue
|
|
143
|
+
if len(choices) != 1 or choices[0].get("index") != 0 or finish is not None:
|
|
144
|
+
raise ValueError("invalid completion sequence")
|
|
145
|
+
choice = choices[0]
|
|
146
|
+
delta = choice["delta"]
|
|
147
|
+
refused = refused or bool(delta.get("refusal"))
|
|
148
|
+
calls = tuple(ToolCallDelta(index=c["index"], id=c.get("id"), type=c.get("type"),
|
|
149
|
+
name=(c.get("function") or {}).get("name"),
|
|
150
|
+
arguments_fragment=(c.get("function") or {}).get("arguments") or "")
|
|
151
|
+
for c in delta.get("tool_calls") or ())
|
|
152
|
+
content = _text(delta.get("content"))
|
|
153
|
+
if calls or content:
|
|
154
|
+
yield ModelStreamChunk(content_delta=content, tool_call_deltas=calls)
|
|
155
|
+
else:
|
|
156
|
+
yield ModelStreamActivity(ModelStreamActivityKind.TRANSPORT)
|
|
157
|
+
if choice.get("finish_reason") is not None:
|
|
158
|
+
finish = _finish(choice["finish_reason"])
|
|
159
|
+
if finish is None:
|
|
160
|
+
raise ModelGatewayError("OpenAI stream ended without a finish reason", code="upstream_stream_interrupted")
|
|
161
|
+
yield ModelStreamChunk(finish_reason=ModelFinishReason.FILTERED if refused else finish, usage=usage)
|
|
162
|
+
except Exception as error:
|
|
163
|
+
raise _error(error) from None
|
|
164
|
+
finally:
|
|
165
|
+
if stream is not None:
|
|
166
|
+
await stream.close()
|
|
167
|
+
return ModelStream(chunks(), invocation.request.model, applied_generation_limit=params["max_completion_tokens"],
|
|
168
|
+
activity_support=ModelStreamActivitySupport.TRANSPORT)
|
|
169
|
+
|
|
170
|
+
async def close(self):
|
|
171
|
+
if self._owns_client:
|
|
172
|
+
await self._client.close()
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: purra-openai
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Official OpenAI Responses and Chat Completions SDK adapter for PurrA
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: purra==0.5.0
|
|
10
|
+
Requires-Dist: openai==3.7.0
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# purra-openai · Python
|
|
14
|
+
|
|
15
|
+
English | [简体中文](README.zh-CN.md)
|
|
16
|
+
|
|
17
|
+
OpenAI model gateways for PurrA using the official Python SDK. Supports text,
|
|
18
|
+
function tools, streaming, cancellation, and token usage. Requires Python 3.11+.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
From the repository root:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
python -m pip install . ./integrations/openai/python
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Choose an API
|
|
29
|
+
|
|
30
|
+
| Gateway | API |
|
|
31
|
+
| --- | --- |
|
|
32
|
+
| `OpenAIResponsesGateway` | Responses |
|
|
33
|
+
| `OpenAIChatCompletionsGateway` | Chat Completions |
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from openai import AsyncOpenAI
|
|
37
|
+
from purra_openai import OpenAIResponsesGateway
|
|
38
|
+
|
|
39
|
+
client = AsyncOpenAI()
|
|
40
|
+
gateway = OpenAIResponsesGateway(client, timeout_seconds=60)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
For Chat Completions, replace the gateway:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from purra_openai import OpenAIChatCompletionsGateway
|
|
47
|
+
|
|
48
|
+
gateway = OpenAIChatCompletionsGateway(client, timeout_seconds=60)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Pass `gateway` to `AgentCore(model_gateway=gateway, ...)`. In the Run's
|
|
52
|
+
`ModelRequest`, set `provider="openai"`, the model ID, and its capability snapshot.
|
|
53
|
+
The application supplies credentials and verified model limits.
|
|
54
|
+
|
|
55
|
+
## Options and behavior
|
|
56
|
+
|
|
57
|
+
`ModelRequest.options` accepts `max_tokens`, `temperature`, `top_p`, and
|
|
58
|
+
`reasoning_effort`. Choose options supported by the selected model.
|
|
59
|
+
Core resolves the output limit; the gateway applies it to the selected API.
|
|
60
|
+
|
|
61
|
+
SDK retries are disabled so Core controls retry and budget accounting.
|
|
62
|
+
Server-side response storage is disabled. Responses reasoning continuation is
|
|
63
|
+
kept in private message data; preserve it with the conversation when resuming.
|
|
64
|
+
|
|
65
|
+
These gateways support native OpenAI text and function-tool APIs. Images, audio,
|
|
66
|
+
and hosted tools are not supported. Other vendors require application adapters.
|
|
67
|
+
|
|
68
|
+
Close a supplied SDK client in the application. `await gateway.close()` closes
|
|
69
|
+
only a client created by the gateway itself.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
README.zh-CN.md
|
|
5
|
+
pyproject.toml
|
|
6
|
+
src/purra_openai/__init__.py
|
|
7
|
+
src/purra_openai/chat.py
|
|
8
|
+
src/purra_openai.egg-info/PKG-INFO
|
|
9
|
+
src/purra_openai.egg-info/SOURCES.txt
|
|
10
|
+
src/purra_openai.egg-info/dependency_links.txt
|
|
11
|
+
src/purra_openai.egg-info/requires.txt
|
|
12
|
+
src/purra_openai.egg-info/top_level.txt
|
|
13
|
+
tests/test_chat.py
|
|
14
|
+
tests/test_gateway.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
purra_openai
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import httpx2
|
|
6
|
+
import pytest
|
|
7
|
+
from openai import AsyncOpenAI
|
|
8
|
+
from purra.cancellation import OperationCanceled
|
|
9
|
+
from purra.contracts import AgentMessage, ToolCallResult
|
|
10
|
+
from purra.runtime.model_round import ModelRoundAccumulator
|
|
11
|
+
from purra.runtime.tool_round import continuation_messages
|
|
12
|
+
from purra_openai import OpenAIChatCompletionsGateway
|
|
13
|
+
from test_gateway import invocation
|
|
14
|
+
|
|
15
|
+
FIXTURE = json.loads((Path(__file__).resolve().parents[2] / 'fixtures/chat.json').read_text())
|
|
16
|
+
MESSAGES = (AgentMessage('developer', 'instructions'), AgentMessage('user','check'))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def sse(events): return ''.join('data: '+json.dumps(e)+'\n\n' for e in events)+'data: [DONE]\n\n'
|
|
20
|
+
def gateway(http): return OpenAIChatCompletionsGateway(AsyncOpenAI(api_key='fixture-not-a-key', http_client=http, max_retries=5))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@pytest.mark.asyncio
|
|
24
|
+
async def test_completion_stream_tool_round_and_trailing_usage():
|
|
25
|
+
requests = []
|
|
26
|
+
def respond(request):
|
|
27
|
+
body=json.loads(request.content); requests.append(body)
|
|
28
|
+
assert request.url.path == '/v1/chat/completions'
|
|
29
|
+
return httpx2.Response(200, headers={'content-type':'text/event-stream'}, text=sse(FIXTURE['events'])) if body.get('stream') else httpx2.Response(200, json=FIXTURE['response'])
|
|
30
|
+
async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http:
|
|
31
|
+
model=gateway(http); call=invocation()
|
|
32
|
+
result=await model.complete(MESSAGES,call)
|
|
33
|
+
assert result.usage.reasoning_tokens == 4 and result.message.reasoning is None
|
|
34
|
+
stream=await model.stream(MESSAGES,call); acc=ModelRoundAccumulator(); terminal=[]
|
|
35
|
+
async for chunk in stream.chunks:
|
|
36
|
+
if hasattr(chunk,'finish_reason'):
|
|
37
|
+
acc.add(chunk)
|
|
38
|
+
if chunk.finish_reason: terminal.append(chunk)
|
|
39
|
+
assert len(terminal)==1 and terminal[0].usage == result.usage
|
|
40
|
+
calls,error=acc.tool_calls(); assert not error and calls==result.message.tool_calls
|
|
41
|
+
followup=continuation_messages(calls,(ToolCallResult(calls[0].id,'lookup','done'),),content=result.message.content,reasoning='')
|
|
42
|
+
await model.complete((*MESSAGES,*followup),call)
|
|
43
|
+
assert requests[-1]['messages'][0]['role']=='developer'
|
|
44
|
+
assert requests[-1]['messages'][-1]['tool_call_id']=='call_lookup'
|
|
45
|
+
assert requests[-1]['max_completion_tokens']==128 and 'max_tokens' not in requests[-1]
|
|
46
|
+
assert requests[-1]['store'] is False and requests[-1]['tools'][0]['function']['strict'] is False
|
|
47
|
+
await model.close(); assert not http.is_closed
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@pytest.mark.asyncio
|
|
51
|
+
@pytest.mark.parametrize('reason,expected',[('stop','stop'),('length','length'),('content_filter','filtered')])
|
|
52
|
+
async def test_stop_reasons_and_missing_usage(reason,expected):
|
|
53
|
+
response={**FIXTURE['response'],'usage':None,'choices':[{'index':0,'message':{'role':'assistant','content':'answer'},'finish_reason':reason}]}
|
|
54
|
+
async with httpx2.AsyncClient(transport=httpx2.MockTransport(lambda _:httpx2.Response(200,json=response))) as http:
|
|
55
|
+
result=await gateway(http).complete(MESSAGES,invocation())
|
|
56
|
+
assert result.finish_reason.value==expected and result.usage is None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@pytest.mark.asyncio
|
|
60
|
+
async def test_stream_truncation_error_privacy_and_cancellation():
|
|
61
|
+
attempts=[]
|
|
62
|
+
def respond(request):
|
|
63
|
+
attempts.append(request)
|
|
64
|
+
if json.loads(request.content).get('stream'):
|
|
65
|
+
return httpx2.Response(200,headers={'content-type':'text/event-stream'},text=sse(FIXTURE['events'][:2]))
|
|
66
|
+
return httpx2.Response(429,json={'error':{'message':'private-provider-error'}})
|
|
67
|
+
async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http:
|
|
68
|
+
model=gateway(http)
|
|
69
|
+
with pytest.raises(Exception) as error: await model.complete(MESSAGES,invocation())
|
|
70
|
+
assert error.value.code=='openai_http_429' and 'private-provider-error' not in str(error.value) and len(attempts)==1
|
|
71
|
+
with pytest.raises(Exception) as error:
|
|
72
|
+
async for _ in (await model.stream(MESSAGES,invocation())).chunks: pass
|
|
73
|
+
assert error.value.code=='upstream_stream_interrupted'
|
|
74
|
+
signal=asyncio.Event(); signal.set()
|
|
75
|
+
with pytest.raises(OperationCanceled): await model.complete(MESSAGES,invocation(),signal)
|
|
76
|
+
stream=await model.stream(MESSAGES,invocation()); await stream.chunks.aclose()
|
|
77
|
+
assert len(attempts)==2
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
from dataclasses import replace
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import httpx2
|
|
7
|
+
import pytest
|
|
8
|
+
from openai import AsyncOpenAI
|
|
9
|
+
from purra.contracts import AgentMessage, ModelRequest, ModelInvocation, ToolSchema, ToolHandlerResult, ToolCallResult
|
|
10
|
+
from purra.model_protocol import generic_capability_snapshot, resolve_invocation_output_budget
|
|
11
|
+
from purra.runtime.model_round import ModelRoundAccumulator
|
|
12
|
+
from purra.runtime.tool_round import continuation_messages
|
|
13
|
+
from purra_openai import OpenAIResponsesGateway
|
|
14
|
+
|
|
15
|
+
RESPONSE = json.loads((Path(__file__).resolve().parents[2] / "fixtures/response.json").read_text())
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def invocation():
|
|
19
|
+
model = ModelRequest(
|
|
20
|
+
"openai",
|
|
21
|
+
"fixture-model",
|
|
22
|
+
replace(generic_capability_snapshot(), max_generation_tokens=256),
|
|
23
|
+
max_generation_tokens=128,
|
|
24
|
+
)
|
|
25
|
+
return ModelInvocation(model, tools=(ToolSchema("lookup", "look up", {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}),),
|
|
26
|
+
output_budget=resolve_invocation_output_budget(
|
|
27
|
+
model.capability_snapshot,
|
|
28
|
+
max_generation_tokens=model.max_generation_tokens,
|
|
29
|
+
))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def sse():
|
|
33
|
+
events = [
|
|
34
|
+
{"type": "response.reasoning_summary_text.delta", "delta": "private-working-text"},
|
|
35
|
+
{"type": "response.output_item.added", "output_index": 1, "item": {**RESPONSE["output"][1], "arguments": ""}},
|
|
36
|
+
{"type": "response.function_call_arguments.delta", "output_index": 1, "delta": '{"query":"中文"}'},
|
|
37
|
+
{"type": "response.completed", "response": RESPONSE},
|
|
38
|
+
]
|
|
39
|
+
return "".join("data: " + json.dumps(e) + "\n\n" for e in events)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@pytest.mark.asyncio
|
|
43
|
+
async def test_sdk_completion_stream_and_tool_continuation_preserve_private_state():
|
|
44
|
+
requests = []
|
|
45
|
+
def respond(request):
|
|
46
|
+
body = json.loads(request.content)
|
|
47
|
+
requests.append(body)
|
|
48
|
+
return httpx2.Response(200, headers={"content-type": "text/event-stream"}, text=sse()) if body.get("stream") else httpx2.Response(200, json=RESPONSE)
|
|
49
|
+
async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http:
|
|
50
|
+
gateway = OpenAIResponsesGateway(AsyncOpenAI(api_key="fixture-not-a-key", http_client=http))
|
|
51
|
+
call = invocation()
|
|
52
|
+
messages = (AgentMessage("user", "check"),)
|
|
53
|
+
completion = await gateway.complete(messages, call)
|
|
54
|
+
assert completion.finish_reason.value == "tool_calls"
|
|
55
|
+
assert completion.applied_generation_limit == 128 and completion.usage.reasoning_tokens == 6
|
|
56
|
+
assert completion.message.reasoning is None
|
|
57
|
+
stream = await gateway.stream(messages, call)
|
|
58
|
+
accumulator = ModelRoundAccumulator()
|
|
59
|
+
activity = []
|
|
60
|
+
async for chunk in stream.chunks:
|
|
61
|
+
if hasattr(chunk, "finish_reason"):
|
|
62
|
+
accumulator.add(chunk)
|
|
63
|
+
else:
|
|
64
|
+
activity.append(chunk.kind.value)
|
|
65
|
+
assert "private-working-text" not in str(chunk)
|
|
66
|
+
assert activity == ["working"]
|
|
67
|
+
from purra.api import AgentExecutionCheckpoint
|
|
68
|
+
checkpoint = AgentExecutionCheckpoint(run_id="fixture", next_round=2, messages=(completion.message,), round_limit=4)
|
|
69
|
+
assert AgentExecutionCheckpoint.from_mapping(checkpoint.to_mapping()).messages[0].provider_data == completion.message.provider_data
|
|
70
|
+
calls, error = accumulator.tool_calls()
|
|
71
|
+
assert not error and calls == completion.message.tool_calls
|
|
72
|
+
followup = continuation_messages(calls, (ToolCallResult(calls[0].id, "lookup", "found"),),
|
|
73
|
+
content="", reasoning="", provider_data=accumulator.provider_data)
|
|
74
|
+
await gateway.complete((*messages, *followup), call)
|
|
75
|
+
assert requests[-1]["input"][1]["encrypted_content"] == "opaque-encrypted-state"
|
|
76
|
+
assert requests[-1]["input"][-1]["type"] == "function_call_output"
|
|
77
|
+
assert requests[-1]["store"] is False and requests[-1]["max_output_tokens"] == 128
|
|
78
|
+
assert requests[-1]["tools"][0]["strict"] is False
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@pytest.mark.asyncio
|
|
82
|
+
async def test_sdk_does_not_hide_retries_or_provider_error_payloads():
|
|
83
|
+
count = 0
|
|
84
|
+
def respond(request):
|
|
85
|
+
nonlocal count
|
|
86
|
+
count += 1
|
|
87
|
+
return httpx2.Response(429, json={"error": {"message": "private-provider-error", "type": "rate_limit_error"}})
|
|
88
|
+
async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http:
|
|
89
|
+
gateway = OpenAIResponsesGateway(AsyncOpenAI(api_key="fixture-not-a-key", http_client=http, max_retries=5))
|
|
90
|
+
with pytest.raises(Exception, match="OpenAI request failed") as error:
|
|
91
|
+
await gateway.complete((AgentMessage("user", "check"),), invocation())
|
|
92
|
+
assert count == 1 and "private-provider-error" not in str(error.value)
|
|
93
|
+
assert error.value.code == "openai_http_429"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@pytest.mark.asyncio
|
|
97
|
+
async def test_cancel_before_call_does_not_dispatch():
|
|
98
|
+
def respond(request):
|
|
99
|
+
raise AssertionError("request must not be sent")
|
|
100
|
+
async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http:
|
|
101
|
+
signal = asyncio.Event(); signal.set()
|
|
102
|
+
gateway = OpenAIResponsesGateway(AsyncOpenAI(api_key="fixture-not-a-key", http_client=http))
|
|
103
|
+
unused = await gateway.stream((AgentMessage("user", "check"),), invocation())
|
|
104
|
+
await unused.chunks.aclose()
|
|
105
|
+
with pytest.raises(Exception, match="canceled"):
|
|
106
|
+
await gateway.complete((AgentMessage("user", "check"),), invocation(), signal)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@pytest.mark.asyncio
|
|
110
|
+
async def test_core_tool_round_keeps_encrypted_state_out_of_public_output():
|
|
111
|
+
from purra.api import AgentCore, AgentPreset, InMemoryAgentAdapters
|
|
112
|
+
from purra.contracts import AgentRunRequest, DomainContext
|
|
113
|
+
from purra.retrieval import RetrieverTool, RetrievalHit
|
|
114
|
+
from purra.tools import InMemoryToolCatalog
|
|
115
|
+
from purra.contracts import RuntimeLimits
|
|
116
|
+
class Retriever:
|
|
117
|
+
async def retrieve(self, request, signal=None):
|
|
118
|
+
return (RetrievalHit(id="one", content="found", source="fixture"),)
|
|
119
|
+
requests = []
|
|
120
|
+
def respond(request):
|
|
121
|
+
body = json.loads(request.content); requests.append(body)
|
|
122
|
+
if any(item.get("type") == "function_call_output" for item in body["input"]):
|
|
123
|
+
final = {**RESPONSE, "output": [{"type": "message", "id": "msg_fixture", "role": "assistant", "status": "completed", "content": [{"type": "output_text", "text": "Found it.", "annotations": []}]}]}
|
|
124
|
+
data = [{"type": "response.output_text.delta", "delta": "Found it."}, {"type": "response.completed", "response": final}]
|
|
125
|
+
payload = "".join("data: " + json.dumps(e) + "\n\n" for e in data)
|
|
126
|
+
else:
|
|
127
|
+
payload = sse()
|
|
128
|
+
return httpx2.Response(200, headers={"content-type": "text/event-stream"}, text=payload)
|
|
129
|
+
async with httpx2.AsyncClient(transport=httpx2.MockTransport(respond)) as http:
|
|
130
|
+
adapters = InMemoryAgentAdapters()
|
|
131
|
+
lookup = RetrieverTool(retriever=Retriever(), name="lookup", description="lookup", scope={})
|
|
132
|
+
core = AgentCore(model_gateway=OpenAIResponsesGateway(AsyncOpenAI(api_key="fixture-not-a-key", http_client=http)),
|
|
133
|
+
run_repository=adapters.runs, output_repository=adapters.outputs, output_publisher=adapters.publisher,
|
|
134
|
+
preset=AgentPreset(id="openai-fixture", revision="1", tool_catalog=InMemoryToolCatalog((lookup.registration,)),
|
|
135
|
+
runtime_limits=RuntimeLimits(max_run_generation_tokens=1000)))
|
|
136
|
+
try:
|
|
137
|
+
handle = await core.submit(AgentRunRequest(messages=(AgentMessage("user", "lookup"),), model=invocation().request,
|
|
138
|
+
domain_context=DomainContext("fixture"), context_window=65536, tools_enabled=True))
|
|
139
|
+
result = await handle.wait()
|
|
140
|
+
assert result.final_response == "Found it.", (result.status, result.error)
|
|
141
|
+
assert any(item.get("encrypted_content") == "opaque-encrypted-state" for item in requests[1]["input"])
|
|
142
|
+
events = await adapters.outputs.list_events(handle.run_id, after_sequence=0)
|
|
143
|
+
assert all("opaque-encrypted-state" not in str(e.payload) for e in events if e.visibility.value == "public")
|
|
144
|
+
finally:
|
|
145
|
+
await core.close()
|