quraite 0.0.1__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.
- quraite/__init__.py +3 -0
- quraite/adapters/__init__.py +134 -0
- quraite/adapters/agno_adapter.py +159 -0
- quraite/adapters/base.py +123 -0
- quraite/adapters/bedrock_agents_adapter.py +343 -0
- quraite/adapters/flowise_adapter.py +275 -0
- quraite/adapters/google_adk_adapter.py +209 -0
- quraite/adapters/http_adapter.py +239 -0
- quraite/adapters/langflow_adapter.py +192 -0
- quraite/adapters/langgraph_adapter.py +304 -0
- quraite/adapters/langgraph_server_adapter.py +252 -0
- quraite/adapters/n8n_adapter.py +220 -0
- quraite/adapters/openai_agents_adapter.py +269 -0
- quraite/adapters/pydantic_ai_adapter.py +312 -0
- quraite/adapters/smolagents_adapter.py +152 -0
- quraite/logger.py +62 -0
- quraite/schema/__init__.py +0 -0
- quraite/schema/message.py +54 -0
- quraite/schema/response.py +16 -0
- quraite/serve/__init__.py +1 -0
- quraite/serve/cloudflared.py +210 -0
- quraite/serve/local_agent.py +360 -0
- quraite/traces/traces_adk_openinference.json +379 -0
- quraite/traces/traces_agno_multi_agent.json +669 -0
- quraite/traces/traces_agno_openinference.json +321 -0
- quraite/traces/traces_crewai_openinference.json +155 -0
- quraite/traces/traces_langgraph_openinference.json +349 -0
- quraite/traces/traces_langgraph_openinference_multi_agent.json +2705 -0
- quraite/traces/traces_langgraph_traceloop.json +510 -0
- quraite/traces/traces_openai_agents_multi_agent_1.json +402 -0
- quraite/traces/traces_openai_agents_openinference.json +341 -0
- quraite/traces/traces_pydantic_openinference.json +286 -0
- quraite/traces/traces_pydantic_openinference_multi_agent_1.json +399 -0
- quraite/traces/traces_pydantic_openinference_multi_agent_2.json +398 -0
- quraite/traces/traces_smol_agents_openinference.json +397 -0
- quraite/traces/traces_smol_agents_tool_calling_openinference.json +704 -0
- quraite/tracing/__init__.py +24 -0
- quraite/tracing/constants.py +16 -0
- quraite/tracing/span_exporter.py +115 -0
- quraite/tracing/span_processor.py +49 -0
- quraite/tracing/tool_extractors.py +290 -0
- quraite/tracing/trace.py +494 -0
- quraite/tracing/types.py +179 -0
- quraite/tracing/utils.py +170 -0
- quraite/utils/__init__.py +0 -0
- quraite/utils/json_utils.py +269 -0
- quraite-0.0.1.dist-info/METADATA +44 -0
- quraite-0.0.1.dist-info/RECORD +49 -0
- quraite-0.0.1.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import uuid
|
|
4
|
+
from typing import Any, Dict, List, Optional, Union
|
|
5
|
+
|
|
6
|
+
import aiohttp
|
|
7
|
+
|
|
8
|
+
from quraite.adapters.base import BaseAdapter
|
|
9
|
+
from quraite.logger import get_logger
|
|
10
|
+
from quraite.schema.message import (
|
|
11
|
+
AgentMessage,
|
|
12
|
+
AssistantMessage,
|
|
13
|
+
MessageContentText,
|
|
14
|
+
ToolCall,
|
|
15
|
+
ToolMessage,
|
|
16
|
+
)
|
|
17
|
+
from quraite.schema.response import AgentInvocationResponse
|
|
18
|
+
|
|
19
|
+
logger = get_logger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class N8nAdapter(BaseAdapter):
|
|
23
|
+
def __init__(
|
|
24
|
+
self, api_url: str, headers: Optional[Dict[str, str]] = None, timeout: int = 60
|
|
25
|
+
):
|
|
26
|
+
self.api_url = api_url
|
|
27
|
+
self.headers = headers or {}
|
|
28
|
+
self.timeout = timeout
|
|
29
|
+
|
|
30
|
+
if "Content-Type" not in self.headers:
|
|
31
|
+
self.headers["Content-Type"] = "application/json"
|
|
32
|
+
logger.info(
|
|
33
|
+
"N8nAdapter initialized (api_url=%s, timeout=%s)", self.api_url, timeout
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def _convert_api_output_to_messages(
|
|
37
|
+
self,
|
|
38
|
+
response: Dict[str, Any],
|
|
39
|
+
) -> List[AgentMessage]:
|
|
40
|
+
logger.debug(
|
|
41
|
+
"Converting n8n response (steps=%d)",
|
|
42
|
+
len(response[0].get("intermediateSteps", [])),
|
|
43
|
+
)
|
|
44
|
+
messages: List[AgentMessage] = []
|
|
45
|
+
output = response[0]["output"]
|
|
46
|
+
intermediateSteps = response[0]["intermediateSteps"]
|
|
47
|
+
|
|
48
|
+
if not intermediateSteps:
|
|
49
|
+
return [
|
|
50
|
+
AssistantMessage(
|
|
51
|
+
content=[MessageContentText(type="text", text=output)],
|
|
52
|
+
)
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
def flush_messages(tool_calls_dict: Dict[str, Any]):
|
|
56
|
+
nonlocal messages
|
|
57
|
+
tool_calls_list: List[ToolCall] = []
|
|
58
|
+
tool_results: List[ToolMessage] = []
|
|
59
|
+
|
|
60
|
+
for tool_call_id, tool_call_dict in tool_calls_dict.items():
|
|
61
|
+
tool_name = tool_call_dict.get("name", "")
|
|
62
|
+
tool_args = tool_call_dict.get("arguments", {})
|
|
63
|
+
if not isinstance(tool_args, dict):
|
|
64
|
+
tool_args = {}
|
|
65
|
+
|
|
66
|
+
tool_calls_list.append(
|
|
67
|
+
ToolCall(
|
|
68
|
+
id=tool_call_id,
|
|
69
|
+
name=tool_name,
|
|
70
|
+
arguments=tool_args,
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
tool_result = tool_call_dict.get("result", "")
|
|
75
|
+
tool_results.append(
|
|
76
|
+
ToolMessage(
|
|
77
|
+
tool_name=tool_name,
|
|
78
|
+
tool_call_id=tool_call_id,
|
|
79
|
+
content=[
|
|
80
|
+
MessageContentText(type="text", text=str(tool_result))
|
|
81
|
+
],
|
|
82
|
+
)
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if tool_calls_list:
|
|
86
|
+
messages.append(AssistantMessage(tool_calls=tool_calls_list))
|
|
87
|
+
|
|
88
|
+
messages.extend(tool_results)
|
|
89
|
+
|
|
90
|
+
current_step_tool_calls_dict: Dict[str, Any] = {}
|
|
91
|
+
for step in intermediateSteps:
|
|
92
|
+
message_log = step.get("action", {}).get("messageLog", {})
|
|
93
|
+
if message_log:
|
|
94
|
+
tool_calls = message_log[0].get("kwargs", {}).get("tool_calls", [])
|
|
95
|
+
|
|
96
|
+
if tool_calls:
|
|
97
|
+
# this condition means that we are at the start of a new step,
|
|
98
|
+
# so we need to flush the previous step's tool calls and tool results
|
|
99
|
+
if current_step_tool_calls_dict:
|
|
100
|
+
flush_messages(current_step_tool_calls_dict)
|
|
101
|
+
current_step_tool_calls_dict = {}
|
|
102
|
+
|
|
103
|
+
for tool_call in tool_calls:
|
|
104
|
+
current_step_tool_calls_dict[tool_call.get("id")] = {
|
|
105
|
+
"name": tool_call.get("name"),
|
|
106
|
+
"arguments": tool_call.get("args"),
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
tool_id = step.get("action", {}).get("toolCallId")
|
|
110
|
+
if tool_id not in current_step_tool_calls_dict:
|
|
111
|
+
continue
|
|
112
|
+
|
|
113
|
+
current_step_tool_calls_dict[tool_id]["result"] = step.get("observation")
|
|
114
|
+
|
|
115
|
+
# flush the last step's tool calls and tool results
|
|
116
|
+
flush_messages(current_step_tool_calls_dict)
|
|
117
|
+
messages.append(
|
|
118
|
+
AssistantMessage(
|
|
119
|
+
content=[MessageContentText(type="text", text=output)],
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
logger.info(
|
|
124
|
+
"n8n conversion produced %d messages (final_output_length=%d)",
|
|
125
|
+
len(messages),
|
|
126
|
+
len(str(output)),
|
|
127
|
+
)
|
|
128
|
+
return messages
|
|
129
|
+
|
|
130
|
+
def _prepare_input(self, input: List[AgentMessage]) -> str:
|
|
131
|
+
logger.debug("Preparing n8n input from %d messages", len(input))
|
|
132
|
+
if not input or input[-1].role != "user":
|
|
133
|
+
logger.error("n8n input missing user message")
|
|
134
|
+
raise ValueError("No user message found in the input")
|
|
135
|
+
|
|
136
|
+
last_user_message = input[-1]
|
|
137
|
+
if not last_user_message.content:
|
|
138
|
+
logger.error("n8n user message missing content")
|
|
139
|
+
raise ValueError("User message has no content")
|
|
140
|
+
|
|
141
|
+
text_content = None
|
|
142
|
+
for content_item in last_user_message.content:
|
|
143
|
+
if content_item.type == "text" and content_item.text:
|
|
144
|
+
text_content = content_item.text
|
|
145
|
+
break
|
|
146
|
+
|
|
147
|
+
if not text_content:
|
|
148
|
+
logger.error("n8n user message missing text content")
|
|
149
|
+
raise ValueError("No text content found in user message")
|
|
150
|
+
|
|
151
|
+
logger.debug("Prepared n8n input (text_length=%d)", len(text_content))
|
|
152
|
+
return text_content
|
|
153
|
+
|
|
154
|
+
async def _aapi_call(
|
|
155
|
+
self,
|
|
156
|
+
query: str,
|
|
157
|
+
sessionId: str,
|
|
158
|
+
) -> Dict[str, Any]:
|
|
159
|
+
payload = {
|
|
160
|
+
"query": query,
|
|
161
|
+
"sessionId": sessionId,
|
|
162
|
+
}
|
|
163
|
+
logger.debug(
|
|
164
|
+
"Calling n8n API (sessionId=%s, query_length=%d)", sessionId, len(query)
|
|
165
|
+
)
|
|
166
|
+
async with aiohttp.ClientSession() as session:
|
|
167
|
+
try:
|
|
168
|
+
async with session.post(
|
|
169
|
+
self.api_url,
|
|
170
|
+
headers=self.headers,
|
|
171
|
+
json=payload,
|
|
172
|
+
timeout=aiohttp.ClientTimeout(total=self.timeout),
|
|
173
|
+
) as response:
|
|
174
|
+
response.raise_for_status()
|
|
175
|
+
logger.info("n8n API call succeeded (status=%s)", response.status)
|
|
176
|
+
return await response.json()
|
|
177
|
+
|
|
178
|
+
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
|
|
179
|
+
logger.exception("n8n API request failed")
|
|
180
|
+
raise aiohttp.ClientError(f"Async API request failed: {str(e)}") from e
|
|
181
|
+
|
|
182
|
+
except json.JSONDecodeError as e:
|
|
183
|
+
logger.exception("n8n API response decoding failed")
|
|
184
|
+
raise ValueError(f"Failed to decode JSON response: {e}") from e
|
|
185
|
+
|
|
186
|
+
async def ainvoke(
|
|
187
|
+
self,
|
|
188
|
+
input: List[AgentMessage],
|
|
189
|
+
session_id: Union[str, None],
|
|
190
|
+
) -> AgentInvocationResponse:
|
|
191
|
+
logger.info(
|
|
192
|
+
"n8n ainvoke called (session_id=%s, input_messages=%d)",
|
|
193
|
+
session_id,
|
|
194
|
+
len(input),
|
|
195
|
+
)
|
|
196
|
+
agent_input = self._prepare_input(input)
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
agent_output = await self._aapi_call(
|
|
200
|
+
query=agent_input,
|
|
201
|
+
sessionId=session_id if session_id else uuid.uuid4(),
|
|
202
|
+
)
|
|
203
|
+
logger.debug(
|
|
204
|
+
"n8n API returned payload keys: %s", list(agent_output[0].keys())
|
|
205
|
+
)
|
|
206
|
+
except Exception as e:
|
|
207
|
+
logger.exception("Error calling n8n endpoint")
|
|
208
|
+
raise RuntimeError(f"Error calling n8n endpoint: {e}") from e
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
agent_trajectory = self._convert_api_output_to_messages(agent_output)
|
|
212
|
+
logger.info(
|
|
213
|
+
"n8n conversion produced %d trajectory messages", len(agent_trajectory)
|
|
214
|
+
)
|
|
215
|
+
return AgentInvocationResponse(
|
|
216
|
+
agent_trajectory=agent_trajectory,
|
|
217
|
+
)
|
|
218
|
+
except Exception as e:
|
|
219
|
+
logger.exception("Error processing n8n response")
|
|
220
|
+
raise RuntimeError(f"Error processing n8n response: {e}") from e
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import uuid
|
|
3
|
+
from typing import Dict, List, Optional, Union
|
|
4
|
+
|
|
5
|
+
from agents import (
|
|
6
|
+
Agent,
|
|
7
|
+
MessageOutputItem,
|
|
8
|
+
ReasoningItem,
|
|
9
|
+
RunItem,
|
|
10
|
+
Runner,
|
|
11
|
+
SQLiteSession,
|
|
12
|
+
ToolCallItem,
|
|
13
|
+
ToolCallOutputItem,
|
|
14
|
+
TResponseInputItem,
|
|
15
|
+
)
|
|
16
|
+
from agents.memory import Session
|
|
17
|
+
from opentelemetry.trace import TracerProvider
|
|
18
|
+
|
|
19
|
+
from quraite.adapters.base import BaseAdapter
|
|
20
|
+
from quraite.logger import get_logger
|
|
21
|
+
from quraite.schema.message import (
|
|
22
|
+
AgentMessage,
|
|
23
|
+
AssistantMessage,
|
|
24
|
+
MessageContentReasoning,
|
|
25
|
+
MessageContentText,
|
|
26
|
+
ToolCall,
|
|
27
|
+
ToolMessage,
|
|
28
|
+
)
|
|
29
|
+
from quraite.schema.response import AgentInvocationResponse
|
|
30
|
+
from quraite.tracing.constants import QURAITE_ADAPTER_TRACE_PREFIX, Framework
|
|
31
|
+
from quraite.tracing.trace import AgentSpan, AgentTrace
|
|
32
|
+
|
|
33
|
+
logger = get_logger(__name__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class OpenaiAgentsAdapter(BaseAdapter):
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
agent: Agent,
|
|
40
|
+
agent_name: str = "OpenAI Agents",
|
|
41
|
+
tracer_provider: Optional[TracerProvider] = None,
|
|
42
|
+
):
|
|
43
|
+
self.agent = agent
|
|
44
|
+
self.sessions: Dict[str, Session] = {}
|
|
45
|
+
self._init_tracing(tracer_provider, required=False)
|
|
46
|
+
self.agent_name = agent_name
|
|
47
|
+
logger.info(
|
|
48
|
+
"OpenaiAgentsAdapter initialized (agent_name=%s, tracing_enabled=%s)",
|
|
49
|
+
agent_name,
|
|
50
|
+
bool(tracer_provider),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def _convert_run_items_to_messages(
|
|
54
|
+
self, run_items: List[RunItem]
|
|
55
|
+
) -> List[AgentMessage]:
|
|
56
|
+
logger.debug("Converting %d OpenAI run items to messages", len(run_items))
|
|
57
|
+
messages: List[AgentMessage] = []
|
|
58
|
+
text_content: List[MessageContentText] = []
|
|
59
|
+
reasoning_content: List[MessageContentReasoning] = []
|
|
60
|
+
tool_calls: List[ToolCall] = []
|
|
61
|
+
|
|
62
|
+
def flush_assistant_message():
|
|
63
|
+
nonlocal text_content, reasoning_content, tool_calls
|
|
64
|
+
if text_content or reasoning_content or tool_calls:
|
|
65
|
+
content = []
|
|
66
|
+
if text_content:
|
|
67
|
+
content.extend(text_content)
|
|
68
|
+
if reasoning_content:
|
|
69
|
+
content.extend(reasoning_content)
|
|
70
|
+
messages.append(
|
|
71
|
+
AssistantMessage(
|
|
72
|
+
content=content if content else None,
|
|
73
|
+
tool_calls=tool_calls if tool_calls else None,
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
text_content = []
|
|
77
|
+
reasoning_content = []
|
|
78
|
+
tool_calls = []
|
|
79
|
+
|
|
80
|
+
for item in run_items:
|
|
81
|
+
if item.type in [
|
|
82
|
+
"handoff_call_item",
|
|
83
|
+
"handoff_output_item",
|
|
84
|
+
"mcp_list_tools_item",
|
|
85
|
+
"mcp_approval_request_item",
|
|
86
|
+
"mcp_approval_response_item",
|
|
87
|
+
]:
|
|
88
|
+
continue
|
|
89
|
+
|
|
90
|
+
if isinstance(item, MessageOutputItem):
|
|
91
|
+
text_parts = []
|
|
92
|
+
for content_item in item.raw_item.content:
|
|
93
|
+
if hasattr(content_item, "text"):
|
|
94
|
+
text_parts.append(content_item.text)
|
|
95
|
+
if text_parts:
|
|
96
|
+
text_content.append(
|
|
97
|
+
MessageContentText(type="text", text="".join(text_parts))
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
elif isinstance(item, ReasoningItem):
|
|
101
|
+
if item.raw_item.summary:
|
|
102
|
+
summary = ""
|
|
103
|
+
for summary_item in item.raw_item.summary:
|
|
104
|
+
summary += summary_item.text
|
|
105
|
+
summary += "\n"
|
|
106
|
+
reasoning_content.append(
|
|
107
|
+
MessageContentReasoning(type="reasoning", reasoning=summary)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
elif isinstance(item, ToolCallItem):
|
|
111
|
+
raw = item.raw_item
|
|
112
|
+
arguments = None
|
|
113
|
+
if hasattr(raw, "arguments"):
|
|
114
|
+
try:
|
|
115
|
+
arguments = (
|
|
116
|
+
json.loads(raw.arguments)
|
|
117
|
+
if isinstance(raw.arguments, str)
|
|
118
|
+
else raw.arguments
|
|
119
|
+
)
|
|
120
|
+
except:
|
|
121
|
+
arguments = {"raw": str(raw.arguments)}
|
|
122
|
+
tool_calls.append(
|
|
123
|
+
ToolCall(
|
|
124
|
+
id=getattr(raw, "call_id", ""),
|
|
125
|
+
name=getattr(raw, "name", ""),
|
|
126
|
+
arguments=arguments or {},
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
elif isinstance(item, ToolCallOutputItem):
|
|
131
|
+
flush_assistant_message()
|
|
132
|
+
tool_result = json.dumps({"output": item.output})
|
|
133
|
+
messages.append(
|
|
134
|
+
ToolMessage(
|
|
135
|
+
tool_call_id=item.raw_item.get("call_id", ""),
|
|
136
|
+
content=[MessageContentText(type="text", text=tool_result)],
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
continue
|
|
140
|
+
|
|
141
|
+
flush_assistant_message()
|
|
142
|
+
logger.info("Converted OpenAI agent run into %d messages", len(messages))
|
|
143
|
+
return messages
|
|
144
|
+
|
|
145
|
+
def _prepare_input(self, input: List[AgentMessage]) -> str:
|
|
146
|
+
logger.debug("Preparing OpenAI input from %d messages", len(input))
|
|
147
|
+
if not input or input[-1].role != "user":
|
|
148
|
+
logger.error("OpenAI input missing user message")
|
|
149
|
+
raise ValueError("No user message found in the input")
|
|
150
|
+
|
|
151
|
+
last_user_message = input[-1]
|
|
152
|
+
if not last_user_message.content:
|
|
153
|
+
logger.error("OpenAI user message missing content")
|
|
154
|
+
raise ValueError("User message has no content")
|
|
155
|
+
|
|
156
|
+
text_content = None
|
|
157
|
+
for content_item in last_user_message.content:
|
|
158
|
+
if content_item.type == "text" and content_item.text:
|
|
159
|
+
text_content = content_item.text
|
|
160
|
+
break
|
|
161
|
+
|
|
162
|
+
if not text_content:
|
|
163
|
+
logger.error("OpenAI user message missing text content")
|
|
164
|
+
raise ValueError("No text content found in user message")
|
|
165
|
+
|
|
166
|
+
logger.debug("Prepared OpenAI input (text_length=%d)", len(text_content))
|
|
167
|
+
return text_content
|
|
168
|
+
|
|
169
|
+
async def ainvoke(
|
|
170
|
+
self,
|
|
171
|
+
input: List[AgentMessage],
|
|
172
|
+
session_id: Union[str, None] = None,
|
|
173
|
+
) -> AgentInvocationResponse:
|
|
174
|
+
"""Asynchronous invocation method - invokes the OpenAI Agents agent and converts to List[AgentMessage]."""
|
|
175
|
+
try:
|
|
176
|
+
logger.info(
|
|
177
|
+
"OpenAI ainvoke called (session_id=%s, input_messages=%d)",
|
|
178
|
+
session_id,
|
|
179
|
+
len(input),
|
|
180
|
+
)
|
|
181
|
+
agent_input: Union[str, List[TResponseInputItem]] = self._prepare_input(
|
|
182
|
+
input
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
if session_id not in self.sessions:
|
|
186
|
+
self.sessions[session_id] = SQLiteSession(session_id=session_id)
|
|
187
|
+
session = self.sessions[session_id]
|
|
188
|
+
|
|
189
|
+
if self.tracer_provider:
|
|
190
|
+
return await self._ainvoke_with_tracing(agent_input, session)
|
|
191
|
+
|
|
192
|
+
return await self._ainvoke_without_tracing(agent_input, session)
|
|
193
|
+
except Exception as exc:
|
|
194
|
+
logger.exception("Error invoking OpenAI agent")
|
|
195
|
+
raise Exception(f"Error invoking Openai agent: {exc}") from exc
|
|
196
|
+
|
|
197
|
+
async def _ainvoke_with_tracing(
|
|
198
|
+
self,
|
|
199
|
+
agent_input: Union[str, List[TResponseInputItem]],
|
|
200
|
+
session: Session,
|
|
201
|
+
) -> AgentInvocationResponse:
|
|
202
|
+
"""Execute ainvoke with tracing enabled."""
|
|
203
|
+
adapter_trace_id = f"{QURAITE_ADAPTER_TRACE_PREFIX}-{uuid.uuid4()}"
|
|
204
|
+
logger.debug(
|
|
205
|
+
"Starting OpenAI traced invocation (trace_id=%s, session_id=%s)",
|
|
206
|
+
adapter_trace_id,
|
|
207
|
+
session.session_id if session else None,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
with self.tracer.start_as_current_span(name=adapter_trace_id):
|
|
211
|
+
await Runner.run(
|
|
212
|
+
self.agent,
|
|
213
|
+
input=agent_input,
|
|
214
|
+
session=session,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
trace_readable_spans = self.quraite_span_exporter.get_trace_by_testcase(
|
|
218
|
+
adapter_trace_id
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
if trace_readable_spans:
|
|
222
|
+
agent_trace = AgentTrace(
|
|
223
|
+
spans=[
|
|
224
|
+
AgentSpan.from_readable_oi_span(span)
|
|
225
|
+
for span in trace_readable_spans
|
|
226
|
+
]
|
|
227
|
+
)
|
|
228
|
+
logger.info(
|
|
229
|
+
"OpenAI trace collected %d spans for trace_id=%s",
|
|
230
|
+
len(trace_readable_spans),
|
|
231
|
+
adapter_trace_id,
|
|
232
|
+
)
|
|
233
|
+
else:
|
|
234
|
+
logger.warning(
|
|
235
|
+
"No spans exported for OpenAI trace_id=%s",
|
|
236
|
+
adapter_trace_id,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
return AgentInvocationResponse(
|
|
240
|
+
agent_trace=agent_trace,
|
|
241
|
+
agent_trajectory=agent_trace.to_agent_trajectory(
|
|
242
|
+
framework=Framework.OPENAI_AGENTS
|
|
243
|
+
),
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
async def _ainvoke_without_tracing(
|
|
247
|
+
self,
|
|
248
|
+
agent_input: Union[str, List[TResponseInputItem]],
|
|
249
|
+
session: Session,
|
|
250
|
+
) -> AgentInvocationResponse:
|
|
251
|
+
"""Execute ainvoke without tracing."""
|
|
252
|
+
result = await Runner.run(
|
|
253
|
+
self.agent,
|
|
254
|
+
input=agent_input,
|
|
255
|
+
session=session,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
try:
|
|
259
|
+
agent_trajectory = self._convert_run_items_to_messages(result.new_items)
|
|
260
|
+
logger.info(
|
|
261
|
+
"OpenAI agent produced %d trajectory messages (no tracing)",
|
|
262
|
+
len(agent_trajectory),
|
|
263
|
+
)
|
|
264
|
+
return AgentInvocationResponse(
|
|
265
|
+
agent_trajectory=agent_trajectory,
|
|
266
|
+
)
|
|
267
|
+
except Exception as exc:
|
|
268
|
+
logger.exception("Error converting OpenAI run items to messages")
|
|
269
|
+
raise Exception(f"Error converting run items to messages: {exc}") from exc
|