sovara-openai-agents 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ """Record OpenAI Agents SDK tool calls in Sovara traces.
2
+
3
+ Call ``instrument()`` once at startup, after importing ``agents``. Function tools are recorded as
4
+ tool steps; agent tools open a child trace. Model calls are recorded by ``sovara.auto_instrument()``
5
+ through the HTTP client.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ __all__ = ["instrument"]
11
+
12
+
13
+ def instrument() -> None:
14
+ """Record OpenAI Agents function and agent tools inside Sovara traces; idempotent."""
15
+ from sovara_openai_agents._patch import openai_agents_patch
16
+
17
+ openai_agents_patch()
@@ -0,0 +1,231 @@
1
+ """Record OpenAI Agents function tools and nested agent-tool traces."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from functools import wraps
8
+ from typing import Any, Literal
9
+
10
+ from sovara import Step, ToolCall
11
+ from sovara import integration as instrumentation
12
+ from sovara.integration import json_value, subtrace
13
+
14
+ logger = logging.getLogger("sovara_openai_agents")
15
+
16
+ _STEP_ATTR = "_sovara_openai_agents_step"
17
+
18
+
19
+ def _is_agent_tool(func_tool: Any) -> bool:
20
+ return bool(getattr(func_tool, "_is_agent_tool", False))
21
+
22
+
23
+ def _agent_tool_name(func_tool: Any) -> str:
24
+ agent_name = getattr(getattr(func_tool, "_agent_instance", None), "name", None)
25
+ return str(agent_name or func_tool.name)
26
+
27
+
28
+ def _agent_tool_input(arguments: str) -> str:
29
+ parsed, parse_error = _parse_tool_arguments(arguments)
30
+ if parse_error is None and parsed is not None:
31
+ input_value = parsed.get("input")
32
+ if set(parsed) == {"input"} and isinstance(input_value, str):
33
+ return input_value
34
+ return arguments
35
+
36
+
37
+ def _trace_io_text(value: Any) -> str:
38
+ if isinstance(value, str):
39
+ return value
40
+ return json.dumps(json_value(value), ensure_ascii=False, sort_keys=True)
41
+
42
+
43
+ def _tool_namespace(tool_call: Any, func_tool: Any) -> str | None:
44
+ namespace = getattr(tool_call, "namespace", None) or getattr(func_tool, "_tool_namespace", None)
45
+ return namespace if isinstance(namespace, str) and namespace else None
46
+
47
+
48
+ def _qualified_tool_name(tool_name: str, namespace: str | None) -> str:
49
+ return f"{namespace}.{tool_name}" if namespace else tool_name
50
+
51
+
52
+ def _parse_tool_arguments(arguments: str) -> tuple[dict[str, Any] | None, str | None]:
53
+ if not arguments:
54
+ return {}, None
55
+
56
+ try:
57
+ parsed = json.loads(arguments)
58
+ except Exception as exc:
59
+ return None, f"Invalid JSON arguments: {exc}"
60
+
61
+ if not isinstance(parsed, dict):
62
+ return None, "Tool arguments must decode to a JSON object."
63
+
64
+ return parsed, None
65
+
66
+
67
+ def _tool_call(func_tool: Any, tool_call: Any) -> ToolCall:
68
+ tool_name = str(func_tool.name)
69
+ namespace = _tool_namespace(tool_call, func_tool)
70
+ arguments = str(getattr(tool_call, "arguments", "") or "")
71
+ parsed_input, parse_error = _parse_tool_arguments(arguments)
72
+ metadata: dict[str, Any] = {
73
+ "tool_class": func_tool.__class__.__name__,
74
+ "strict_json_schema": bool(getattr(func_tool, "strict_json_schema", False)),
75
+ "is_agent_tool": bool(getattr(func_tool, "_is_agent_tool", False)),
76
+ "defer_loading": bool(getattr(func_tool, "defer_loading", False)),
77
+ }
78
+ if namespace:
79
+ metadata["tool_namespace"] = namespace
80
+ if parse_error is not None:
81
+ metadata["tool_arguments_raw"] = arguments
82
+ metadata["arguments_error"] = parse_error
83
+ return ToolCall(
84
+ name=_qualified_tool_name(tool_name, namespace),
85
+ arguments=json_value(parsed_input),
86
+ call_id=str(getattr(tool_call, "call_id", "") or "").strip() or None,
87
+ metadata=metadata,
88
+ )
89
+
90
+
91
+ def _step_of(task_state: Any) -> Step | None:
92
+ return getattr(task_state, _STEP_ATTR, None)
93
+
94
+
95
+ async def _log_trace_io(kind: Literal["input", "output"], text: str) -> None:
96
+ await instrumentation.alog_trace_io(kind, text)
97
+
98
+
99
+ def openai_agents_patch() -> None:
100
+ """Install OpenAI Agents function-tool and agent-tool instrumentation once.
101
+
102
+ Missing agents support is a no-op. Wrap the batch executor and supported invoker
103
+ variant; capture is gated by the recording and tracing flag. Agent tools use child
104
+ traces; ordinary function tools are recorded as tool steps. Tool arguments and
105
+ results pass through unchanged.
106
+ """
107
+ try:
108
+ from agents.run_internal import tool_execution
109
+ except ImportError:
110
+ logger.info("openai-agents not installed, skipping openai-agents patches")
111
+ return
112
+
113
+ batch_executor_cls = tool_execution._FunctionToolBatchExecutor
114
+ if getattr(batch_executor_cls, "__sovara_openai_agents_patched__", False):
115
+ return
116
+
117
+ original_execute_single_tool_body = batch_executor_cls._execute_single_tool_body
118
+ original_invoke_tool_and_run_post_invoke = batch_executor_cls._invoke_tool_and_run_post_invoke
119
+ invoker_name = (
120
+ "_invoke_function_tool_with_metadata"
121
+ if hasattr(tool_execution, "_invoke_function_tool_with_metadata")
122
+ else "invoke_function_tool"
123
+ )
124
+ original_invoke_function_tool = getattr(tool_execution, invoker_name)
125
+ invoker_returns_metadata = invoker_name == "_invoke_function_tool_with_metadata"
126
+
127
+ @wraps(original_invoke_function_tool)
128
+ async def patched_invoke_function_tool(*, function_tool, context, arguments):
129
+ if not instrumentation.capture_active() or not _is_agent_tool(function_tool):
130
+ return await original_invoke_function_tool(
131
+ function_tool=function_tool,
132
+ context=context,
133
+ arguments=arguments,
134
+ )
135
+
136
+ async with subtrace(_agent_tool_name(function_tool)) as child_trace_id:
137
+ if child_trace_id:
138
+ await _log_trace_io("input", _agent_tool_input(arguments))
139
+ result = await original_invoke_function_tool(
140
+ function_tool=function_tool,
141
+ context=context,
142
+ arguments=arguments,
143
+ )
144
+ output = result.output if invoker_returns_metadata else result
145
+ if child_trace_id and output is not None:
146
+ await _log_trace_io("output", _trace_io_text(output))
147
+ return result
148
+
149
+ @wraps(original_execute_single_tool_body)
150
+ async def patched_execute_single_tool_body(
151
+ self,
152
+ *,
153
+ outer_task,
154
+ task_state,
155
+ func_tool,
156
+ tool_call,
157
+ tool_context,
158
+ agent_hooks,
159
+ ):
160
+ if not instrumentation.capture_active() or _is_agent_tool(func_tool):
161
+ return await original_execute_single_tool_body(
162
+ self,
163
+ outer_task=outer_task,
164
+ task_state=task_state,
165
+ func_tool=func_tool,
166
+ tool_call=tool_call,
167
+ tool_context=tool_context,
168
+ agent_hooks=agent_hooks,
169
+ )
170
+
171
+ step = await instrumentation.abegin(_tool_call(func_tool, tool_call))
172
+ if step is not None:
173
+ setattr(task_state, _STEP_ATTR, step)
174
+
175
+ return await original_execute_single_tool_body(
176
+ self,
177
+ outer_task=outer_task,
178
+ task_state=task_state,
179
+ func_tool=func_tool,
180
+ tool_call=tool_call,
181
+ tool_context=tool_context,
182
+ agent_hooks=agent_hooks,
183
+ )
184
+
185
+ @wraps(original_invoke_tool_and_run_post_invoke)
186
+ async def patched_invoke_tool_and_run_post_invoke(
187
+ self,
188
+ *,
189
+ outer_task,
190
+ task_state,
191
+ func_tool,
192
+ tool_call,
193
+ tool_context,
194
+ agent_hooks,
195
+ ):
196
+ step = _step_of(task_state)
197
+ if step is None:
198
+ return await original_invoke_tool_and_run_post_invoke(
199
+ self,
200
+ outer_task=outer_task,
201
+ task_state=task_state,
202
+ func_tool=func_tool,
203
+ tool_call=tool_call,
204
+ tool_context=tool_context,
205
+ agent_hooks=agent_hooks,
206
+ )
207
+
208
+ try:
209
+ final_result = await original_invoke_tool_and_run_post_invoke(
210
+ self,
211
+ outer_task=outer_task,
212
+ task_state=task_state,
213
+ func_tool=func_tool,
214
+ tool_call=tool_call,
215
+ tool_context=tool_context,
216
+ agent_hooks=agent_hooks,
217
+ )
218
+ except Exception as exc:
219
+ await instrumentation.areport(step, "fail", exc, propagating=True)
220
+ raise
221
+ except BaseException as exc:
222
+ instrumentation.report_in_background(step, "cancel", exc.__class__.__name__)
223
+ raise
224
+ await instrumentation.areport(step, "finish", json_value(final_result))
225
+ return final_result
226
+
227
+ batch_executor_cls._execute_single_tool_body = patched_execute_single_tool_body
228
+ batch_executor_cls._invoke_tool_and_run_post_invoke = patched_invoke_tool_and_run_post_invoke
229
+ setattr(tool_execution, invoker_name, patched_invoke_function_tool)
230
+ batch_executor_cls.__sovara_openai_agents_patched__ = True
231
+ logger.info("openai-agents patches applied")
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: sovara-openai-agents
3
+ Version: 0.1.0
4
+ Summary: Sovara recording for the OpenAI Agents SDK
5
+ License-Expression: MIT
6
+ Project-URL: Documentation, https://docs.sovara-labs.com/integrations/openai-agents
7
+ Project-URL: Repository, https://github.com/SovaraLabs/sovara-openai-agents/tree/main/python
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: sovara<0.11,>=0.10
12
+ Requires-Dist: openai-agents<0.14,>=0.13.6
13
+ Dynamic: license-file
14
+
15
+ # Sovara for the OpenAI Agents SDK (Python)
16
+
17
+ Record OpenAI Agents tool calls in Sovara traces.
18
+
19
+ ```bash
20
+ uv add sovara-openai-agents
21
+ # or: pip install sovara-openai-agents
22
+ ```
23
+
24
+ ```python
25
+ import sovara
26
+ import sovara_openai_agents
27
+
28
+ sovara.auto_instrument() # model calls, through the HTTP client
29
+ sovara_openai_agents.instrument() # function tools as tool steps, agent tools as child traces
30
+ ```
31
+
32
+ Call both once at startup, before creating agents. Inside a Sovara trace, function tools are
33
+ recorded as tool steps and agent tools (`agent.as_tool()`) open a child trace with their input
34
+ and output. Outside a trace, tools run unrecorded. Requires `openai-agents` 0.13.6 (the supported 0.13 series).
35
+
36
+ ## License
37
+
38
+ MIT.
@@ -0,0 +1,7 @@
1
+ sovara_openai_agents/__init__.py,sha256=54Di1o19cwSwm7z8YzO8oanyJPldusWX7swizIrU-2U,557
2
+ sovara_openai_agents/_patch.py,sha256=uC0mX_uYVzoNEFSbuLUJhg-EXtbK0eVb1f5odJQK40M,8425
3
+ sovara_openai_agents-0.1.0.dist-info/licenses/LICENSE,sha256=pHqKd1w5Do29Q1QUMye-4Tz6olJxRgwzNYqcjjfN524,1068
4
+ sovara_openai_agents-0.1.0.dist-info/METADATA,sha256=xgL_OdfbdT2HFwfYjd4qGPVAWscYvjwIJQLCJbc1cs8,1215
5
+ sovara_openai_agents-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ sovara_openai_agents-0.1.0.dist-info/top_level.txt,sha256=LyO3o-Y76ZwWPnYGf8jqxZb7xhrS2IGN6icCSf3zJxw,21
7
+ sovara_openai_agents-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sovara Labs
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
+ sovara_openai_agents