openai-agents 0.3.2__py3-none-any.whl → 0.4.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.

@@ -0,0 +1,267 @@
1
+ """Redis-powered Session backend.
2
+
3
+ Usage::
4
+
5
+ from agents.extensions.memory import RedisSession
6
+
7
+ # Create from Redis URL
8
+ session = RedisSession.from_url(
9
+ session_id="user-123",
10
+ url="redis://localhost:6379/0",
11
+ )
12
+
13
+ # Or pass an existing Redis client that your application already manages
14
+ session = RedisSession(
15
+ session_id="user-123",
16
+ redis_client=my_redis_client,
17
+ )
18
+
19
+ await Runner.run(agent, "Hello", session=session)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import json
26
+ import time
27
+ from typing import Any
28
+ from urllib.parse import urlparse
29
+
30
+ try:
31
+ import redis.asyncio as redis
32
+ from redis.asyncio import Redis
33
+ except ImportError as e:
34
+ raise ImportError(
35
+ "RedisSession requires the 'redis' package. Install it with: pip install redis"
36
+ ) from e
37
+
38
+ from ...items import TResponseInputItem
39
+ from ...memory.session import SessionABC
40
+
41
+
42
+ class RedisSession(SessionABC):
43
+ """Redis implementation of :pyclass:`agents.memory.session.Session`."""
44
+
45
+ def __init__(
46
+ self,
47
+ session_id: str,
48
+ *,
49
+ redis_client: Redis,
50
+ key_prefix: str = "agents:session",
51
+ ttl: int | None = None,
52
+ ):
53
+ """Initializes a new RedisSession.
54
+
55
+ Args:
56
+ session_id (str): Unique identifier for the conversation.
57
+ redis_client (Redis[bytes]): A pre-configured Redis async client.
58
+ key_prefix (str, optional): Prefix for Redis keys to avoid collisions.
59
+ Defaults to "agents:session".
60
+ ttl (int | None, optional): Time-to-live in seconds for session data.
61
+ If None, data persists indefinitely. Defaults to None.
62
+ """
63
+ self.session_id = session_id
64
+ self._redis = redis_client
65
+ self._key_prefix = key_prefix
66
+ self._ttl = ttl
67
+ self._lock = asyncio.Lock()
68
+ self._owns_client = False # Track if we own the Redis client
69
+
70
+ # Redis key patterns
71
+ self._session_key = f"{self._key_prefix}:{self.session_id}"
72
+ self._messages_key = f"{self._session_key}:messages"
73
+ self._counter_key = f"{self._session_key}:counter"
74
+
75
+ @classmethod
76
+ def from_url(
77
+ cls,
78
+ session_id: str,
79
+ *,
80
+ url: str,
81
+ redis_kwargs: dict[str, Any] | None = None,
82
+ **kwargs: Any,
83
+ ) -> RedisSession:
84
+ """Create a session from a Redis URL string.
85
+
86
+ Args:
87
+ session_id (str): Conversation ID.
88
+ url (str): Redis URL, e.g. "redis://localhost:6379/0" or "rediss://host:6380".
89
+ redis_kwargs (dict[str, Any] | None): Additional keyword arguments forwarded to
90
+ redis.asyncio.from_url.
91
+ **kwargs: Additional keyword arguments forwarded to the main constructor
92
+ (e.g., key_prefix, ttl, etc.).
93
+
94
+ Returns:
95
+ RedisSession: An instance of RedisSession connected to the specified Redis server.
96
+ """
97
+ redis_kwargs = redis_kwargs or {}
98
+
99
+ # Parse URL to determine if we need SSL
100
+ parsed = urlparse(url)
101
+ if parsed.scheme == "rediss":
102
+ redis_kwargs.setdefault("ssl", True)
103
+
104
+ redis_client = redis.from_url(url, **redis_kwargs)
105
+ session = cls(session_id, redis_client=redis_client, **kwargs)
106
+ session._owns_client = True # We created the client, so we own it
107
+ return session
108
+
109
+ async def _serialize_item(self, item: TResponseInputItem) -> str:
110
+ """Serialize an item to JSON string. Can be overridden by subclasses."""
111
+ return json.dumps(item, separators=(",", ":"))
112
+
113
+ async def _deserialize_item(self, item: str) -> TResponseInputItem:
114
+ """Deserialize a JSON string to an item. Can be overridden by subclasses."""
115
+ return json.loads(item) # type: ignore[no-any-return] # json.loads returns Any but we know the structure
116
+
117
+ async def _get_next_id(self) -> int:
118
+ """Get the next message ID using Redis INCR for atomic increment."""
119
+ result = await self._redis.incr(self._counter_key)
120
+ return int(result)
121
+
122
+ async def _set_ttl_if_configured(self, *keys: str) -> None:
123
+ """Set TTL on keys if configured."""
124
+ if self._ttl is not None:
125
+ pipe = self._redis.pipeline()
126
+ for key in keys:
127
+ pipe.expire(key, self._ttl)
128
+ await pipe.execute()
129
+
130
+ # ------------------------------------------------------------------
131
+ # Session protocol implementation
132
+ # ------------------------------------------------------------------
133
+
134
+ async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
135
+ """Retrieve the conversation history for this session.
136
+
137
+ Args:
138
+ limit: Maximum number of items to retrieve. If None, retrieves all items.
139
+ When specified, returns the latest N items in chronological order.
140
+
141
+ Returns:
142
+ List of input items representing the conversation history
143
+ """
144
+ async with self._lock:
145
+ if limit is None:
146
+ # Get all messages in chronological order
147
+ raw_messages = await self._redis.lrange(self._messages_key, 0, -1) # type: ignore[misc] # Redis library returns Union[Awaitable[T], T] in async context
148
+ else:
149
+ if limit <= 0:
150
+ return []
151
+ # Get the latest N messages (Redis list is ordered chronologically)
152
+ # Use negative indices to get from the end - Redis uses -N to -1 for last N items
153
+ raw_messages = await self._redis.lrange(self._messages_key, -limit, -1) # type: ignore[misc] # Redis library returns Union[Awaitable[T], T] in async context
154
+
155
+ items: list[TResponseInputItem] = []
156
+ for raw_msg in raw_messages:
157
+ try:
158
+ # Handle both bytes (default) and str (decode_responses=True) Redis clients
159
+ if isinstance(raw_msg, bytes):
160
+ msg_str = raw_msg.decode("utf-8")
161
+ else:
162
+ msg_str = raw_msg # Already a string
163
+ item = await self._deserialize_item(msg_str)
164
+ items.append(item)
165
+ except (json.JSONDecodeError, UnicodeDecodeError):
166
+ # Skip corrupted messages
167
+ continue
168
+
169
+ return items
170
+
171
+ async def add_items(self, items: list[TResponseInputItem]) -> None:
172
+ """Add new items to the conversation history.
173
+
174
+ Args:
175
+ items: List of input items to add to the history
176
+ """
177
+ if not items:
178
+ return
179
+
180
+ async with self._lock:
181
+ pipe = self._redis.pipeline()
182
+
183
+ # Set session metadata with current timestamp
184
+ pipe.hset(
185
+ self._session_key,
186
+ mapping={
187
+ "session_id": self.session_id,
188
+ "created_at": str(int(time.time())),
189
+ "updated_at": str(int(time.time())),
190
+ },
191
+ )
192
+
193
+ # Add all items to the messages list
194
+ serialized_items = []
195
+ for item in items:
196
+ serialized = await self._serialize_item(item)
197
+ serialized_items.append(serialized)
198
+
199
+ if serialized_items:
200
+ pipe.rpush(self._messages_key, *serialized_items)
201
+
202
+ # Update the session timestamp
203
+ pipe.hset(self._session_key, "updated_at", str(int(time.time())))
204
+
205
+ # Execute all commands
206
+ await pipe.execute()
207
+
208
+ # Set TTL if configured
209
+ await self._set_ttl_if_configured(
210
+ self._session_key, self._messages_key, self._counter_key
211
+ )
212
+
213
+ async def pop_item(self) -> TResponseInputItem | None:
214
+ """Remove and return the most recent item from the session.
215
+
216
+ Returns:
217
+ The most recent item if it exists, None if the session is empty
218
+ """
219
+ async with self._lock:
220
+ # Use RPOP to atomically remove and return the rightmost (most recent) item
221
+ raw_msg = await self._redis.rpop(self._messages_key) # type: ignore[misc] # Redis library returns Union[Awaitable[T], T] in async context
222
+
223
+ if raw_msg is None:
224
+ return None
225
+
226
+ try:
227
+ # Handle both bytes (default) and str (decode_responses=True) Redis clients
228
+ if isinstance(raw_msg, bytes):
229
+ msg_str = raw_msg.decode("utf-8")
230
+ else:
231
+ msg_str = raw_msg # Already a string
232
+ return await self._deserialize_item(msg_str)
233
+ except (json.JSONDecodeError, UnicodeDecodeError):
234
+ # Return None for corrupted messages (already removed)
235
+ return None
236
+
237
+ async def clear_session(self) -> None:
238
+ """Clear all items for this session."""
239
+ async with self._lock:
240
+ # Delete all keys associated with this session
241
+ await self._redis.delete(
242
+ self._session_key,
243
+ self._messages_key,
244
+ self._counter_key,
245
+ )
246
+
247
+ async def close(self) -> None:
248
+ """Close the Redis connection.
249
+
250
+ Only closes the connection if this session owns the Redis client
251
+ (i.e., created via from_url). If the client was injected externally,
252
+ the caller is responsible for managing its lifecycle.
253
+ """
254
+ if self._owns_client:
255
+ await self._redis.aclose()
256
+
257
+ async def ping(self) -> bool:
258
+ """Test Redis connectivity.
259
+
260
+ Returns:
261
+ True if Redis is reachable, False otherwise.
262
+ """
263
+ try:
264
+ await self._redis.ping()
265
+ return True
266
+ except Exception:
267
+ return False
@@ -195,7 +195,10 @@ class SQLAlchemySession(SessionABC):
195
195
  stmt = (
196
196
  select(self._messages.c.message_data)
197
197
  .where(self._messages.c.session_id == self.session_id)
198
- .order_by(self._messages.c.created_at.asc())
198
+ .order_by(
199
+ self._messages.c.created_at.asc(),
200
+ self._messages.c.id.asc(),
201
+ )
199
202
  )
200
203
  else:
201
204
  stmt = (
@@ -203,7 +206,10 @@ class SQLAlchemySession(SessionABC):
203
206
  .where(self._messages.c.session_id == self.session_id)
204
207
  # Use DESC + LIMIT to get the latest N
205
208
  # then reverse later for chronological order.
206
- .order_by(self._messages.c.created_at.desc())
209
+ .order_by(
210
+ self._messages.c.created_at.desc(),
211
+ self._messages.c.id.desc(),
212
+ )
207
213
  .limit(limit)
208
214
  )
209
215
 
@@ -278,7 +284,10 @@ class SQLAlchemySession(SessionABC):
278
284
  subq = (
279
285
  select(self._messages.c.id)
280
286
  .where(self._messages.c.session_id == self.session_id)
281
- .order_by(self._messages.c.created_at.desc())
287
+ .order_by(
288
+ self._messages.c.created_at.desc(),
289
+ self._messages.c.id.desc(),
290
+ )
282
291
  .limit(1)
283
292
  )
284
293
  res = await sess.execute(subq)
@@ -18,11 +18,12 @@ except ImportError as _e:
18
18
  "dependency group: `pip install 'openai-agents[litellm]'`."
19
19
  ) from _e
20
20
 
21
- from openai import NOT_GIVEN, AsyncStream, NotGiven
21
+ from openai import AsyncStream, NotGiven, omit
22
22
  from openai.types.chat import (
23
23
  ChatCompletionChunk,
24
24
  ChatCompletionMessageCustomToolCall,
25
25
  ChatCompletionMessageFunctionToolCall,
26
+ ChatCompletionMessageParam,
26
27
  )
27
28
  from openai.types.chat.chat_completion_message import (
28
29
  Annotation,
@@ -267,6 +268,10 @@ class LitellmModel(Model):
267
268
  input, preserve_thinking_blocks=preserve_thinking_blocks
268
269
  )
269
270
 
271
+ # Fix for interleaved thinking bug: reorder messages to ensure tool_use comes before tool_result # noqa: E501
272
+ if preserve_thinking_blocks:
273
+ converted_messages = self._fix_tool_message_ordering(converted_messages)
274
+
270
275
  if system_instructions:
271
276
  converted_messages.insert(
272
277
  0,
@@ -369,7 +374,7 @@ class LitellmModel(Model):
369
374
  object="response",
370
375
  output=[],
371
376
  tool_choice=cast(Literal["auto", "required", "none"], tool_choice)
372
- if tool_choice != NOT_GIVEN
377
+ if tool_choice is not omit
373
378
  else "auto",
374
379
  top_p=model_settings.top_p,
375
380
  temperature=model_settings.temperature,
@@ -379,8 +384,123 @@ class LitellmModel(Model):
379
384
  )
380
385
  return response, ret
381
386
 
387
+ def _fix_tool_message_ordering(
388
+ self, messages: list[ChatCompletionMessageParam]
389
+ ) -> list[ChatCompletionMessageParam]:
390
+ """
391
+ Fix the ordering of tool messages to ensure tool_use messages come before tool_result messages.
392
+
393
+ This addresses the interleaved thinking bug where conversation histories may contain
394
+ tool results before their corresponding tool calls, causing Anthropic API to reject the request.
395
+ """ # noqa: E501
396
+ if not messages:
397
+ return messages
398
+
399
+ # Collect all tool calls and tool results
400
+ tool_call_messages = {} # tool_id -> (index, message)
401
+ tool_result_messages = {} # tool_id -> (index, message)
402
+ other_messages = [] # (index, message) for non-tool messages
403
+
404
+ for i, message in enumerate(messages):
405
+ if not isinstance(message, dict):
406
+ other_messages.append((i, message))
407
+ continue
408
+
409
+ role = message.get("role")
410
+
411
+ if role == "assistant" and message.get("tool_calls"):
412
+ # Extract tool calls from this assistant message
413
+ tool_calls = message.get("tool_calls", [])
414
+ if isinstance(tool_calls, list):
415
+ for tool_call in tool_calls:
416
+ if isinstance(tool_call, dict):
417
+ tool_id = tool_call.get("id")
418
+ if tool_id:
419
+ # Create a separate assistant message for each tool call
420
+ single_tool_msg = cast(dict[str, Any], message.copy())
421
+ single_tool_msg["tool_calls"] = [tool_call]
422
+ tool_call_messages[tool_id] = (
423
+ i,
424
+ cast(ChatCompletionMessageParam, single_tool_msg),
425
+ )
426
+
427
+ elif role == "tool":
428
+ tool_call_id = message.get("tool_call_id")
429
+ if tool_call_id:
430
+ tool_result_messages[tool_call_id] = (i, message)
431
+ else:
432
+ other_messages.append((i, message))
433
+ else:
434
+ other_messages.append((i, message))
435
+
436
+ # First, identify which tool results will be paired to avoid duplicates
437
+ paired_tool_result_indices = set()
438
+ for tool_id in tool_call_messages:
439
+ if tool_id in tool_result_messages:
440
+ tool_result_idx, _ = tool_result_messages[tool_id]
441
+ paired_tool_result_indices.add(tool_result_idx)
442
+
443
+ # Create the fixed message sequence
444
+ fixed_messages: list[ChatCompletionMessageParam] = []
445
+ used_indices = set()
446
+
447
+ # Add messages in their original order, but ensure tool_use → tool_result pairing
448
+ for i, original_message in enumerate(messages):
449
+ if i in used_indices:
450
+ continue
451
+
452
+ if not isinstance(original_message, dict):
453
+ fixed_messages.append(original_message)
454
+ used_indices.add(i)
455
+ continue
456
+
457
+ role = original_message.get("role")
458
+
459
+ if role == "assistant" and original_message.get("tool_calls"):
460
+ # Process each tool call in this assistant message
461
+ tool_calls = original_message.get("tool_calls", [])
462
+ if isinstance(tool_calls, list):
463
+ for tool_call in tool_calls:
464
+ if isinstance(tool_call, dict):
465
+ tool_id = tool_call.get("id")
466
+ if (
467
+ tool_id
468
+ and tool_id in tool_call_messages
469
+ and tool_id in tool_result_messages
470
+ ):
471
+ # Add tool_use → tool_result pair
472
+ _, tool_call_msg = tool_call_messages[tool_id]
473
+ tool_result_idx, tool_result_msg = tool_result_messages[tool_id]
474
+
475
+ fixed_messages.append(tool_call_msg)
476
+ fixed_messages.append(tool_result_msg)
477
+
478
+ # Mark both as used
479
+ used_indices.add(tool_call_messages[tool_id][0])
480
+ used_indices.add(tool_result_idx)
481
+ elif tool_id and tool_id in tool_call_messages:
482
+ # Tool call without result - add just the tool call
483
+ _, tool_call_msg = tool_call_messages[tool_id]
484
+ fixed_messages.append(tool_call_msg)
485
+ used_indices.add(tool_call_messages[tool_id][0])
486
+
487
+ used_indices.add(i) # Mark original multi-tool message as used
488
+
489
+ elif role == "tool":
490
+ # Only preserve unmatched tool results to avoid duplicates
491
+ if i not in paired_tool_result_indices:
492
+ fixed_messages.append(original_message)
493
+ used_indices.add(i)
494
+
495
+ else:
496
+ # Regular message - add it normally
497
+ fixed_messages.append(original_message)
498
+ used_indices.add(i)
499
+
500
+ return fixed_messages
501
+
382
502
  def _remove_not_given(self, value: Any) -> Any:
383
- if isinstance(value, NotGiven):
503
+ if value is omit or isinstance(value, NotGiven):
384
504
  return None
385
505
  return value
386
506
 
agents/items.py CHANGED
@@ -21,6 +21,12 @@ from openai.types.responses import (
21
21
  from openai.types.responses.response_code_interpreter_tool_call import (
22
22
  ResponseCodeInterpreterToolCall,
23
23
  )
24
+ from openai.types.responses.response_function_call_output_item_list_param import (
25
+ ResponseFunctionCallOutputItemListParam,
26
+ ResponseFunctionCallOutputItemParam,
27
+ )
28
+ from openai.types.responses.response_input_file_content_param import ResponseInputFileContentParam
29
+ from openai.types.responses.response_input_image_content_param import ResponseInputImageContentParam
24
30
  from openai.types.responses.response_input_item_param import (
25
31
  ComputerCallOutput,
26
32
  FunctionCallOutput,
@@ -36,9 +42,17 @@ from openai.types.responses.response_output_item import (
36
42
  )
37
43
  from openai.types.responses.response_reasoning_item import ResponseReasoningItem
38
44
  from pydantic import BaseModel
39
- from typing_extensions import TypeAlias
45
+ from typing_extensions import TypeAlias, assert_never
40
46
 
41
47
  from .exceptions import AgentsException, ModelBehaviorError
48
+ from .logger import logger
49
+ from .tool import (
50
+ ToolOutputFileContent,
51
+ ToolOutputImage,
52
+ ToolOutputText,
53
+ ValidToolOutputPydanticModels,
54
+ ValidToolOutputPydanticModelsTypeAdapter,
55
+ )
42
56
  from .usage import Usage
43
57
 
44
58
  if TYPE_CHECKING:
@@ -298,11 +312,93 @@ class ItemHelpers:
298
312
 
299
313
  @classmethod
300
314
  def tool_call_output_item(
301
- cls, tool_call: ResponseFunctionToolCall, output: str
315
+ cls, tool_call: ResponseFunctionToolCall, output: Any
302
316
  ) -> FunctionCallOutput:
303
- """Creates a tool call output item from a tool call and its output."""
317
+ """Creates a tool call output item from a tool call and its output.
318
+
319
+ Accepts either plain values (stringified) or structured outputs using
320
+ input_text/input_image/input_file shapes. Structured outputs may be
321
+ provided as Pydantic models or dicts, or an iterable of such items.
322
+ """
323
+
324
+ converted_output = cls._convert_tool_output(output)
325
+
304
326
  return {
305
327
  "call_id": tool_call.call_id,
306
- "output": output,
328
+ "output": converted_output,
307
329
  "type": "function_call_output",
308
330
  }
331
+
332
+ @classmethod
333
+ def _convert_tool_output(cls, output: Any) -> str | ResponseFunctionCallOutputItemListParam:
334
+ """Converts a tool return value into an output acceptable by the Responses API."""
335
+
336
+ # If the output is either a single or list of the known structured output types, convert to
337
+ # ResponseFunctionCallOutputItemListParam. Else, just stringify.
338
+ if isinstance(output, (list, tuple)):
339
+ maybe_converted_output_list = [
340
+ cls._maybe_get_output_as_structured_function_output(item) for item in output
341
+ ]
342
+ if all(maybe_converted_output_list):
343
+ return [
344
+ cls._convert_single_tool_output_pydantic_model(item)
345
+ for item in maybe_converted_output_list
346
+ if item is not None
347
+ ]
348
+ else:
349
+ return str(output)
350
+ else:
351
+ maybe_converted_output = cls._maybe_get_output_as_structured_function_output(output)
352
+ if maybe_converted_output:
353
+ return [cls._convert_single_tool_output_pydantic_model(maybe_converted_output)]
354
+ else:
355
+ return str(output)
356
+
357
+ @classmethod
358
+ def _maybe_get_output_as_structured_function_output(
359
+ cls, output: Any
360
+ ) -> ValidToolOutputPydanticModels | None:
361
+ if isinstance(output, (ToolOutputText, ToolOutputImage, ToolOutputFileContent)):
362
+ return output
363
+ elif isinstance(output, dict):
364
+ try:
365
+ return ValidToolOutputPydanticModelsTypeAdapter.validate_python(output)
366
+ except pydantic.ValidationError:
367
+ logger.debug("dict was not a valid tool output pydantic model")
368
+ return None
369
+
370
+ return None
371
+
372
+ @classmethod
373
+ def _convert_single_tool_output_pydantic_model(
374
+ cls, output: ValidToolOutputPydanticModels
375
+ ) -> ResponseFunctionCallOutputItemParam:
376
+ if isinstance(output, ToolOutputText):
377
+ return {"type": "input_text", "text": output.text}
378
+ elif isinstance(output, ToolOutputImage):
379
+ # Forward all provided optional fields so the Responses API receives
380
+ # the correct identifiers and settings for the image resource.
381
+ result: ResponseInputImageContentParam = {"type": "input_image"}
382
+ if output.image_url is not None:
383
+ result["image_url"] = output.image_url
384
+ if output.file_id is not None:
385
+ result["file_id"] = output.file_id
386
+ if output.detail is not None:
387
+ result["detail"] = output.detail
388
+ return result
389
+ elif isinstance(output, ToolOutputFileContent):
390
+ # Forward all provided optional fields so the Responses API receives
391
+ # the correct identifiers and metadata for the file resource.
392
+ result_file: ResponseInputFileContentParam = {"type": "input_file"}
393
+ if output.file_data is not None:
394
+ result_file["file_data"] = output.file_data
395
+ if output.file_url is not None:
396
+ result_file["file_url"] = output.file_url
397
+ if output.file_id is not None:
398
+ result_file["file_id"] = output.file_id
399
+ if output.filename is not None:
400
+ result_file["filename"] = output.filename
401
+ return result_file
402
+ else:
403
+ assert_never(output)
404
+ raise ValueError(f"Unexpected tool output type: {output}")