openai-agents 0.0.19__py3-none-any.whl → 0.2.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.
Potentially problematic release.
This version of openai-agents might be problematic. Click here for more details.
- agents/__init__.py +5 -2
- agents/_run_impl.py +35 -1
- agents/agent.py +65 -29
- agents/extensions/models/litellm_model.py +7 -3
- agents/function_schema.py +11 -1
- agents/guardrail.py +5 -1
- agents/handoffs.py +14 -0
- agents/lifecycle.py +26 -17
- agents/mcp/__init__.py +13 -1
- agents/mcp/server.py +173 -16
- agents/mcp/util.py +89 -6
- agents/memory/__init__.py +3 -0
- agents/memory/session.py +369 -0
- agents/model_settings.py +60 -6
- agents/models/chatcmpl_converter.py +31 -2
- agents/models/chatcmpl_stream_handler.py +128 -16
- agents/models/openai_chatcompletions.py +12 -10
- agents/models/openai_responses.py +25 -8
- agents/realtime/README.md +3 -0
- agents/realtime/__init__.py +174 -0
- agents/realtime/agent.py +80 -0
- agents/realtime/config.py +128 -0
- agents/realtime/events.py +216 -0
- agents/realtime/items.py +91 -0
- agents/realtime/model.py +69 -0
- agents/realtime/model_events.py +159 -0
- agents/realtime/model_inputs.py +100 -0
- agents/realtime/openai_realtime.py +584 -0
- agents/realtime/runner.py +118 -0
- agents/realtime/session.py +502 -0
- agents/repl.py +1 -4
- agents/run.py +131 -10
- agents/tool.py +30 -6
- agents/tool_context.py +16 -3
- agents/tracing/__init__.py +1 -2
- agents/tracing/processor_interface.py +1 -1
- agents/voice/models/openai_stt.py +1 -1
- agents/voice/pipeline.py +6 -0
- agents/voice/workflow.py +8 -0
- {openai_agents-0.0.19.dist-info → openai_agents-0.2.0.dist-info}/METADATA +133 -8
- {openai_agents-0.0.19.dist-info → openai_agents-0.2.0.dist-info}/RECORD +43 -29
- {openai_agents-0.0.19.dist-info → openai_agents-0.2.0.dist-info}/WHEEL +0 -0
- {openai_agents-0.0.19.dist-info → openai_agents-0.2.0.dist-info}/licenses/LICENSE +0 -0
agents/memory/session.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import sqlite3
|
|
6
|
+
import threading
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Protocol, runtime_checkable
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from ..items import TResponseInputItem
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@runtime_checkable
|
|
16
|
+
class Session(Protocol):
|
|
17
|
+
"""Protocol for session implementations.
|
|
18
|
+
|
|
19
|
+
Session stores conversation history for a specific session, allowing
|
|
20
|
+
agents to maintain context without requiring explicit manual memory management.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
session_id: str
|
|
24
|
+
|
|
25
|
+
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
|
|
26
|
+
"""Retrieve the conversation history for this session.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
limit: Maximum number of items to retrieve. If None, retrieves all items.
|
|
30
|
+
When specified, returns the latest N items in chronological order.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
List of input items representing the conversation history
|
|
34
|
+
"""
|
|
35
|
+
...
|
|
36
|
+
|
|
37
|
+
async def add_items(self, items: list[TResponseInputItem]) -> None:
|
|
38
|
+
"""Add new items to the conversation history.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
items: List of input items to add to the history
|
|
42
|
+
"""
|
|
43
|
+
...
|
|
44
|
+
|
|
45
|
+
async def pop_item(self) -> TResponseInputItem | None:
|
|
46
|
+
"""Remove and return the most recent item from the session.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
The most recent item if it exists, None if the session is empty
|
|
50
|
+
"""
|
|
51
|
+
...
|
|
52
|
+
|
|
53
|
+
async def clear_session(self) -> None:
|
|
54
|
+
"""Clear all items for this session."""
|
|
55
|
+
...
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SessionABC(ABC):
|
|
59
|
+
"""Abstract base class for session implementations.
|
|
60
|
+
|
|
61
|
+
Session stores conversation history for a specific session, allowing
|
|
62
|
+
agents to maintain context without requiring explicit manual memory management.
|
|
63
|
+
|
|
64
|
+
This ABC is intended for internal use and as a base class for concrete implementations.
|
|
65
|
+
Third-party libraries should implement the Session protocol instead.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
session_id: str
|
|
69
|
+
|
|
70
|
+
@abstractmethod
|
|
71
|
+
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
|
|
72
|
+
"""Retrieve the conversation history for this session.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
limit: Maximum number of items to retrieve. If None, retrieves all items.
|
|
76
|
+
When specified, returns the latest N items in chronological order.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
List of input items representing the conversation history
|
|
80
|
+
"""
|
|
81
|
+
...
|
|
82
|
+
|
|
83
|
+
@abstractmethod
|
|
84
|
+
async def add_items(self, items: list[TResponseInputItem]) -> None:
|
|
85
|
+
"""Add new items to the conversation history.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
items: List of input items to add to the history
|
|
89
|
+
"""
|
|
90
|
+
...
|
|
91
|
+
|
|
92
|
+
@abstractmethod
|
|
93
|
+
async def pop_item(self) -> TResponseInputItem | None:
|
|
94
|
+
"""Remove and return the most recent item from the session.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
The most recent item if it exists, None if the session is empty
|
|
98
|
+
"""
|
|
99
|
+
...
|
|
100
|
+
|
|
101
|
+
@abstractmethod
|
|
102
|
+
async def clear_session(self) -> None:
|
|
103
|
+
"""Clear all items for this session."""
|
|
104
|
+
...
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class SQLiteSession(SessionABC):
|
|
108
|
+
"""SQLite-based implementation of session storage.
|
|
109
|
+
|
|
110
|
+
This implementation stores conversation history in a SQLite database.
|
|
111
|
+
By default, uses an in-memory database that is lost when the process ends.
|
|
112
|
+
For persistent storage, provide a file path.
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
def __init__(
|
|
116
|
+
self,
|
|
117
|
+
session_id: str,
|
|
118
|
+
db_path: str | Path = ":memory:",
|
|
119
|
+
sessions_table: str = "agent_sessions",
|
|
120
|
+
messages_table: str = "agent_messages",
|
|
121
|
+
):
|
|
122
|
+
"""Initialize the SQLite session.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
session_id: Unique identifier for the conversation session
|
|
126
|
+
db_path: Path to the SQLite database file. Defaults to ':memory:' (in-memory database)
|
|
127
|
+
sessions_table: Name of the table to store session metadata. Defaults to
|
|
128
|
+
'agent_sessions'
|
|
129
|
+
messages_table: Name of the table to store message data. Defaults to 'agent_messages'
|
|
130
|
+
"""
|
|
131
|
+
self.session_id = session_id
|
|
132
|
+
self.db_path = db_path
|
|
133
|
+
self.sessions_table = sessions_table
|
|
134
|
+
self.messages_table = messages_table
|
|
135
|
+
self._local = threading.local()
|
|
136
|
+
self._lock = threading.Lock()
|
|
137
|
+
|
|
138
|
+
# For in-memory databases, we need a shared connection to avoid thread isolation
|
|
139
|
+
# For file databases, we use thread-local connections for better concurrency
|
|
140
|
+
self._is_memory_db = str(db_path) == ":memory:"
|
|
141
|
+
if self._is_memory_db:
|
|
142
|
+
self._shared_connection = sqlite3.connect(":memory:", check_same_thread=False)
|
|
143
|
+
self._shared_connection.execute("PRAGMA journal_mode=WAL")
|
|
144
|
+
self._init_db_for_connection(self._shared_connection)
|
|
145
|
+
else:
|
|
146
|
+
# For file databases, initialize the schema once since it persists
|
|
147
|
+
init_conn = sqlite3.connect(str(self.db_path), check_same_thread=False)
|
|
148
|
+
init_conn.execute("PRAGMA journal_mode=WAL")
|
|
149
|
+
self._init_db_for_connection(init_conn)
|
|
150
|
+
init_conn.close()
|
|
151
|
+
|
|
152
|
+
def _get_connection(self) -> sqlite3.Connection:
|
|
153
|
+
"""Get a database connection."""
|
|
154
|
+
if self._is_memory_db:
|
|
155
|
+
# Use shared connection for in-memory database to avoid thread isolation
|
|
156
|
+
return self._shared_connection
|
|
157
|
+
else:
|
|
158
|
+
# Use thread-local connections for file databases
|
|
159
|
+
if not hasattr(self._local, "connection"):
|
|
160
|
+
self._local.connection = sqlite3.connect(
|
|
161
|
+
str(self.db_path),
|
|
162
|
+
check_same_thread=False,
|
|
163
|
+
)
|
|
164
|
+
self._local.connection.execute("PRAGMA journal_mode=WAL")
|
|
165
|
+
assert isinstance(self._local.connection, sqlite3.Connection), (
|
|
166
|
+
f"Expected sqlite3.Connection, got {type(self._local.connection)}"
|
|
167
|
+
)
|
|
168
|
+
return self._local.connection
|
|
169
|
+
|
|
170
|
+
def _init_db_for_connection(self, conn: sqlite3.Connection) -> None:
|
|
171
|
+
"""Initialize the database schema for a specific connection."""
|
|
172
|
+
conn.execute(
|
|
173
|
+
f"""
|
|
174
|
+
CREATE TABLE IF NOT EXISTS {self.sessions_table} (
|
|
175
|
+
session_id TEXT PRIMARY KEY,
|
|
176
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
177
|
+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
178
|
+
)
|
|
179
|
+
"""
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
conn.execute(
|
|
183
|
+
f"""
|
|
184
|
+
CREATE TABLE IF NOT EXISTS {self.messages_table} (
|
|
185
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
186
|
+
session_id TEXT NOT NULL,
|
|
187
|
+
message_data TEXT NOT NULL,
|
|
188
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
189
|
+
FOREIGN KEY (session_id) REFERENCES {self.sessions_table} (session_id)
|
|
190
|
+
ON DELETE CASCADE
|
|
191
|
+
)
|
|
192
|
+
"""
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
conn.execute(
|
|
196
|
+
f"""
|
|
197
|
+
CREATE INDEX IF NOT EXISTS idx_{self.messages_table}_session_id
|
|
198
|
+
ON {self.messages_table} (session_id, created_at)
|
|
199
|
+
"""
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
conn.commit()
|
|
203
|
+
|
|
204
|
+
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
|
|
205
|
+
"""Retrieve the conversation history for this session.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
limit: Maximum number of items to retrieve. If None, retrieves all items.
|
|
209
|
+
When specified, returns the latest N items in chronological order.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
List of input items representing the conversation history
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
def _get_items_sync():
|
|
216
|
+
conn = self._get_connection()
|
|
217
|
+
with self._lock if self._is_memory_db else threading.Lock():
|
|
218
|
+
if limit is None:
|
|
219
|
+
# Fetch all items in chronological order
|
|
220
|
+
cursor = conn.execute(
|
|
221
|
+
f"""
|
|
222
|
+
SELECT message_data FROM {self.messages_table}
|
|
223
|
+
WHERE session_id = ?
|
|
224
|
+
ORDER BY created_at ASC
|
|
225
|
+
""",
|
|
226
|
+
(self.session_id,),
|
|
227
|
+
)
|
|
228
|
+
else:
|
|
229
|
+
# Fetch the latest N items in chronological order
|
|
230
|
+
cursor = conn.execute(
|
|
231
|
+
f"""
|
|
232
|
+
SELECT message_data FROM {self.messages_table}
|
|
233
|
+
WHERE session_id = ?
|
|
234
|
+
ORDER BY created_at DESC
|
|
235
|
+
LIMIT ?
|
|
236
|
+
""",
|
|
237
|
+
(self.session_id, limit),
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
rows = cursor.fetchall()
|
|
241
|
+
|
|
242
|
+
# Reverse to get chronological order when using DESC
|
|
243
|
+
if limit is not None:
|
|
244
|
+
rows = list(reversed(rows))
|
|
245
|
+
|
|
246
|
+
items = []
|
|
247
|
+
for (message_data,) in rows:
|
|
248
|
+
try:
|
|
249
|
+
item = json.loads(message_data)
|
|
250
|
+
items.append(item)
|
|
251
|
+
except json.JSONDecodeError:
|
|
252
|
+
# Skip invalid JSON entries
|
|
253
|
+
continue
|
|
254
|
+
|
|
255
|
+
return items
|
|
256
|
+
|
|
257
|
+
return await asyncio.to_thread(_get_items_sync)
|
|
258
|
+
|
|
259
|
+
async def add_items(self, items: list[TResponseInputItem]) -> None:
|
|
260
|
+
"""Add new items to the conversation history.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
items: List of input items to add to the history
|
|
264
|
+
"""
|
|
265
|
+
if not items:
|
|
266
|
+
return
|
|
267
|
+
|
|
268
|
+
def _add_items_sync():
|
|
269
|
+
conn = self._get_connection()
|
|
270
|
+
|
|
271
|
+
with self._lock if self._is_memory_db else threading.Lock():
|
|
272
|
+
# Ensure session exists
|
|
273
|
+
conn.execute(
|
|
274
|
+
f"""
|
|
275
|
+
INSERT OR IGNORE INTO {self.sessions_table} (session_id) VALUES (?)
|
|
276
|
+
""",
|
|
277
|
+
(self.session_id,),
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
# Add items
|
|
281
|
+
message_data = [(self.session_id, json.dumps(item)) for item in items]
|
|
282
|
+
conn.executemany(
|
|
283
|
+
f"""
|
|
284
|
+
INSERT INTO {self.messages_table} (session_id, message_data) VALUES (?, ?)
|
|
285
|
+
""",
|
|
286
|
+
message_data,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
# Update session timestamp
|
|
290
|
+
conn.execute(
|
|
291
|
+
f"""
|
|
292
|
+
UPDATE {self.sessions_table}
|
|
293
|
+
SET updated_at = CURRENT_TIMESTAMP
|
|
294
|
+
WHERE session_id = ?
|
|
295
|
+
""",
|
|
296
|
+
(self.session_id,),
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
conn.commit()
|
|
300
|
+
|
|
301
|
+
await asyncio.to_thread(_add_items_sync)
|
|
302
|
+
|
|
303
|
+
async def pop_item(self) -> TResponseInputItem | None:
|
|
304
|
+
"""Remove and return the most recent item from the session.
|
|
305
|
+
|
|
306
|
+
Returns:
|
|
307
|
+
The most recent item if it exists, None if the session is empty
|
|
308
|
+
"""
|
|
309
|
+
|
|
310
|
+
def _pop_item_sync():
|
|
311
|
+
conn = self._get_connection()
|
|
312
|
+
with self._lock if self._is_memory_db else threading.Lock():
|
|
313
|
+
# Use DELETE with RETURNING to atomically delete and return the most recent item
|
|
314
|
+
cursor = conn.execute(
|
|
315
|
+
f"""
|
|
316
|
+
DELETE FROM {self.messages_table}
|
|
317
|
+
WHERE id = (
|
|
318
|
+
SELECT id FROM {self.messages_table}
|
|
319
|
+
WHERE session_id = ?
|
|
320
|
+
ORDER BY created_at DESC
|
|
321
|
+
LIMIT 1
|
|
322
|
+
)
|
|
323
|
+
RETURNING message_data
|
|
324
|
+
""",
|
|
325
|
+
(self.session_id,),
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
result = cursor.fetchone()
|
|
329
|
+
conn.commit()
|
|
330
|
+
|
|
331
|
+
if result:
|
|
332
|
+
message_data = result[0]
|
|
333
|
+
try:
|
|
334
|
+
item = json.loads(message_data)
|
|
335
|
+
return item
|
|
336
|
+
except json.JSONDecodeError:
|
|
337
|
+
# Return None for corrupted JSON entries (already deleted)
|
|
338
|
+
return None
|
|
339
|
+
|
|
340
|
+
return None
|
|
341
|
+
|
|
342
|
+
return await asyncio.to_thread(_pop_item_sync)
|
|
343
|
+
|
|
344
|
+
async def clear_session(self) -> None:
|
|
345
|
+
"""Clear all items for this session."""
|
|
346
|
+
|
|
347
|
+
def _clear_session_sync():
|
|
348
|
+
conn = self._get_connection()
|
|
349
|
+
with self._lock if self._is_memory_db else threading.Lock():
|
|
350
|
+
conn.execute(
|
|
351
|
+
f"DELETE FROM {self.messages_table} WHERE session_id = ?",
|
|
352
|
+
(self.session_id,),
|
|
353
|
+
)
|
|
354
|
+
conn.execute(
|
|
355
|
+
f"DELETE FROM {self.sessions_table} WHERE session_id = ?",
|
|
356
|
+
(self.session_id,),
|
|
357
|
+
)
|
|
358
|
+
conn.commit()
|
|
359
|
+
|
|
360
|
+
await asyncio.to_thread(_clear_session_sync)
|
|
361
|
+
|
|
362
|
+
def close(self) -> None:
|
|
363
|
+
"""Close the database connection."""
|
|
364
|
+
if self._is_memory_db:
|
|
365
|
+
if hasattr(self, "_shared_connection"):
|
|
366
|
+
self._shared_connection.close()
|
|
367
|
+
else:
|
|
368
|
+
if hasattr(self._local, "connection"):
|
|
369
|
+
self._local.connection.close()
|
agents/model_settings.py
CHANGED
|
@@ -1,12 +1,57 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import dataclasses
|
|
4
|
+
from collections.abc import Mapping
|
|
4
5
|
from dataclasses import dataclass, fields, replace
|
|
5
|
-
from typing import Any, Literal
|
|
6
|
+
from typing import Annotated, Any, Literal, Union
|
|
6
7
|
|
|
7
|
-
from openai
|
|
8
|
+
from openai import Omit as _Omit
|
|
9
|
+
from openai._types import Body, Query
|
|
10
|
+
from openai.types.responses import ResponseIncludable
|
|
8
11
|
from openai.types.shared import Reasoning
|
|
9
|
-
from pydantic import BaseModel
|
|
12
|
+
from pydantic import BaseModel, GetCoreSchemaHandler
|
|
13
|
+
from pydantic_core import core_schema
|
|
14
|
+
from typing_extensions import TypeAlias
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _OmitTypeAnnotation:
|
|
18
|
+
@classmethod
|
|
19
|
+
def __get_pydantic_core_schema__(
|
|
20
|
+
cls,
|
|
21
|
+
_source_type: Any,
|
|
22
|
+
_handler: GetCoreSchemaHandler,
|
|
23
|
+
) -> core_schema.CoreSchema:
|
|
24
|
+
def validate_from_none(value: None) -> _Omit:
|
|
25
|
+
return _Omit()
|
|
26
|
+
|
|
27
|
+
from_none_schema = core_schema.chain_schema(
|
|
28
|
+
[
|
|
29
|
+
core_schema.none_schema(),
|
|
30
|
+
core_schema.no_info_plain_validator_function(validate_from_none),
|
|
31
|
+
]
|
|
32
|
+
)
|
|
33
|
+
return core_schema.json_or_python_schema(
|
|
34
|
+
json_schema=from_none_schema,
|
|
35
|
+
python_schema=core_schema.union_schema(
|
|
36
|
+
[
|
|
37
|
+
# check if it's an instance first before doing any further work
|
|
38
|
+
core_schema.is_instance_schema(_Omit),
|
|
39
|
+
from_none_schema,
|
|
40
|
+
]
|
|
41
|
+
),
|
|
42
|
+
serialization=core_schema.plain_serializer_function_ser_schema(lambda instance: None),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class MCPToolChoice:
|
|
48
|
+
server_label: str
|
|
49
|
+
name: str
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
Omit = Annotated[_Omit, _OmitTypeAnnotation]
|
|
53
|
+
Headers: TypeAlias = Mapping[str, Union[str, Omit]]
|
|
54
|
+
ToolChoice: TypeAlias = Union[Literal["auto", "required", "none"], str, MCPToolChoice, None]
|
|
10
55
|
|
|
11
56
|
|
|
12
57
|
@dataclass
|
|
@@ -32,12 +77,17 @@ class ModelSettings:
|
|
|
32
77
|
presence_penalty: float | None = None
|
|
33
78
|
"""The presence penalty to use when calling the model."""
|
|
34
79
|
|
|
35
|
-
tool_choice:
|
|
80
|
+
tool_choice: ToolChoice | None = None
|
|
36
81
|
"""The tool choice to use when calling the model."""
|
|
37
82
|
|
|
38
83
|
parallel_tool_calls: bool | None = None
|
|
39
|
-
"""
|
|
40
|
-
|
|
84
|
+
"""Controls whether the model can make multiple parallel tool calls in a single turn.
|
|
85
|
+
If not provided (i.e., set to None), this behavior defers to the underlying
|
|
86
|
+
model provider's default. For most current providers (e.g., OpenAI), this typically
|
|
87
|
+
means parallel tool calls are enabled (True).
|
|
88
|
+
Set to True to explicitly enable parallel tool calls, or False to restrict the
|
|
89
|
+
model to at most one tool call per turn.
|
|
90
|
+
"""
|
|
41
91
|
|
|
42
92
|
truncation: Literal["auto", "disabled"] | None = None
|
|
43
93
|
"""The truncation strategy to use when calling the model."""
|
|
@@ -61,6 +111,10 @@ class ModelSettings:
|
|
|
61
111
|
"""Whether to include usage chunk.
|
|
62
112
|
Defaults to True if not provided."""
|
|
63
113
|
|
|
114
|
+
response_include: list[ResponseIncludable] | None = None
|
|
115
|
+
"""Additional output data to include in the model response.
|
|
116
|
+
[include parameter](https://platform.openai.com/docs/api-reference/responses/create#responses-create-include)"""
|
|
117
|
+
|
|
64
118
|
extra_query: Query | None = None
|
|
65
119
|
"""Additional query fields to provide with the request.
|
|
66
120
|
Defaults to None if not provided."""
|
|
@@ -19,6 +19,7 @@ from openai.types.chat import (
|
|
|
19
19
|
ChatCompletionToolMessageParam,
|
|
20
20
|
ChatCompletionUserMessageParam,
|
|
21
21
|
)
|
|
22
|
+
from openai.types.chat.chat_completion_content_part_param import File, FileFile
|
|
22
23
|
from openai.types.chat.chat_completion_tool_param import ChatCompletionToolParam
|
|
23
24
|
from openai.types.chat.completion_create_params import ResponseFormat
|
|
24
25
|
from openai.types.responses import (
|
|
@@ -27,19 +28,23 @@ from openai.types.responses import (
|
|
|
27
28
|
ResponseFunctionToolCall,
|
|
28
29
|
ResponseFunctionToolCallParam,
|
|
29
30
|
ResponseInputContentParam,
|
|
31
|
+
ResponseInputFileParam,
|
|
30
32
|
ResponseInputImageParam,
|
|
31
33
|
ResponseInputTextParam,
|
|
32
34
|
ResponseOutputMessage,
|
|
33
35
|
ResponseOutputMessageParam,
|
|
34
36
|
ResponseOutputRefusal,
|
|
35
37
|
ResponseOutputText,
|
|
38
|
+
ResponseReasoningItem,
|
|
36
39
|
)
|
|
37
40
|
from openai.types.responses.response_input_param import FunctionCallOutput, ItemReference, Message
|
|
41
|
+
from openai.types.responses.response_reasoning_item import Summary
|
|
38
42
|
|
|
39
43
|
from ..agent_output import AgentOutputSchemaBase
|
|
40
44
|
from ..exceptions import AgentsException, UserError
|
|
41
45
|
from ..handoffs import Handoff
|
|
42
46
|
from ..items import TResponseInputItem, TResponseOutputItem
|
|
47
|
+
from ..model_settings import MCPToolChoice
|
|
43
48
|
from ..tool import FunctionTool, Tool
|
|
44
49
|
from .fake_id import FAKE_RESPONSES_ID
|
|
45
50
|
|
|
@@ -47,10 +52,12 @@ from .fake_id import FAKE_RESPONSES_ID
|
|
|
47
52
|
class Converter:
|
|
48
53
|
@classmethod
|
|
49
54
|
def convert_tool_choice(
|
|
50
|
-
cls, tool_choice: Literal["auto", "required", "none"] | str | None
|
|
55
|
+
cls, tool_choice: Literal["auto", "required", "none"] | str | MCPToolChoice | None
|
|
51
56
|
) -> ChatCompletionToolChoiceOptionParam | NotGiven:
|
|
52
57
|
if tool_choice is None:
|
|
53
58
|
return NOT_GIVEN
|
|
59
|
+
elif isinstance(tool_choice, MCPToolChoice):
|
|
60
|
+
raise UserError("MCPToolChoice is not supported for Chat Completions models")
|
|
54
61
|
elif tool_choice == "auto":
|
|
55
62
|
return "auto"
|
|
56
63
|
elif tool_choice == "required":
|
|
@@ -85,6 +92,16 @@ class Converter:
|
|
|
85
92
|
def message_to_output_items(cls, message: ChatCompletionMessage) -> list[TResponseOutputItem]:
|
|
86
93
|
items: list[TResponseOutputItem] = []
|
|
87
94
|
|
|
95
|
+
# Handle reasoning content if available
|
|
96
|
+
if hasattr(message, "reasoning_content") and message.reasoning_content:
|
|
97
|
+
items.append(
|
|
98
|
+
ResponseReasoningItem(
|
|
99
|
+
id=FAKE_RESPONSES_ID,
|
|
100
|
+
summary=[Summary(text=message.reasoning_content, type="summary_text")],
|
|
101
|
+
type="reasoning",
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
|
|
88
105
|
message_item = ResponseOutputMessage(
|
|
89
106
|
id=FAKE_RESPONSES_ID,
|
|
90
107
|
content=[],
|
|
@@ -239,7 +256,19 @@ class Converter:
|
|
|
239
256
|
)
|
|
240
257
|
)
|
|
241
258
|
elif isinstance(c, dict) and c.get("type") == "input_file":
|
|
242
|
-
|
|
259
|
+
casted_file_param = cast(ResponseInputFileParam, c)
|
|
260
|
+
if "file_data" not in casted_file_param or not casted_file_param["file_data"]:
|
|
261
|
+
raise UserError(
|
|
262
|
+
f"Only file_data is supported for input_file {casted_file_param}"
|
|
263
|
+
)
|
|
264
|
+
out.append(
|
|
265
|
+
File(
|
|
266
|
+
type="file",
|
|
267
|
+
file=FileFile(
|
|
268
|
+
file_data=casted_file_param["file_data"],
|
|
269
|
+
),
|
|
270
|
+
)
|
|
271
|
+
)
|
|
243
272
|
else:
|
|
244
273
|
raise UserError(f"Unknown content: {c}")
|
|
245
274
|
return out
|