openai-agents 0.2.7__py3-none-any.whl → 0.2.9__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/_run_impl.py CHANGED
@@ -961,7 +961,10 @@ class RunImpl:
961
961
  context_wrapper: RunContextWrapper[TContext],
962
962
  config: RunConfig,
963
963
  ) -> ToolsToFinalOutputResult:
964
- """Returns (i, final_output)."""
964
+ """Determine if tool results should produce a final output.
965
+ Returns:
966
+ ToolsToFinalOutputResult: Indicates whether final output is ready, and the output value.
967
+ """
965
968
  if not tool_results:
966
969
  return _NOT_FINAL_OUTPUT
967
970
 
agents/agent.py CHANGED
@@ -17,6 +17,11 @@ from .items import ItemHelpers
17
17
  from .logger import logger
18
18
  from .mcp import MCPUtil
19
19
  from .model_settings import ModelSettings
20
+ from .models.default_models import (
21
+ get_default_model_settings,
22
+ gpt_5_reasoning_settings_required,
23
+ is_gpt_5_default,
24
+ )
20
25
  from .models.interface import Model
21
26
  from .prompts import DynamicPromptFunction, Prompt, PromptUtil
22
27
  from .run_context import RunContextWrapper, TContext
@@ -168,10 +173,10 @@ class Agent(AgentBase, Generic[TContext]):
168
173
  """The model implementation to use when invoking the LLM.
169
174
 
170
175
  By default, if not set, the agent will use the default model configured in
171
- `openai_provider.DEFAULT_MODEL` (currently "gpt-4o").
176
+ `agents.models.get_default_model()` (currently "gpt-4.1").
172
177
  """
173
178
 
174
- model_settings: ModelSettings = field(default_factory=ModelSettings)
179
+ model_settings: ModelSettings = field(default_factory=get_default_model_settings)
175
180
  """Configures model-specific tuning parameters (e.g. temperature, top_p).
176
181
  """
177
182
 
@@ -205,8 +210,9 @@ class Agent(AgentBase, Generic[TContext]):
205
210
  This lets you configure how tool use is handled.
206
211
  - "run_llm_again": The default behavior. Tools are run, and then the LLM receives the results
207
212
  and gets to respond.
208
- - "stop_on_first_tool": The output of the first tool call is used as the final output. This
209
- means that the LLM does not process the result of the tool call.
213
+ - "stop_on_first_tool": The output from the first tool call is treated as the final result.
214
+ In other words, it isn’t sent back to the LLM for further processing but is used directly
215
+ as the final output.
210
216
  - A StopAtTools object: The agent will stop running if any of the tools listed in
211
217
  `stop_at_tool_names` is called.
212
218
  The final output will be the output of the first matching tool call.
@@ -285,6 +291,26 @@ class Agent(AgentBase, Generic[TContext]):
285
291
  f"got {type(self.model_settings).__name__}"
286
292
  )
287
293
 
294
+ if (
295
+ # The user sets a non-default model
296
+ self.model is not None
297
+ and (
298
+ # The default model is gpt-5
299
+ is_gpt_5_default() is True
300
+ # However, the specified model is not a gpt-5 model
301
+ and (
302
+ isinstance(self.model, str) is False
303
+ or gpt_5_reasoning_settings_required(self.model) is False # type: ignore
304
+ )
305
+ # The model settings are not customized for the specified model
306
+ and self.model_settings == get_default_model_settings()
307
+ )
308
+ ):
309
+ # In this scenario, we should use a generic model settings
310
+ # because non-gpt-5 models are not compatible with the default gpt-5 model settings.
311
+ # This is a best-effort attempt to make the agent work with non-gpt-5 models.
312
+ self.model_settings = ModelSettings()
313
+
288
314
  if not isinstance(self.input_guardrails, list):
289
315
  raise TypeError(
290
316
  f"Agent input_guardrails must be a list, got {type(self.input_guardrails).__name__}"
@@ -356,6 +382,8 @@ class Agent(AgentBase, Generic[TContext]):
356
382
  tool_name: str | None,
357
383
  tool_description: str | None,
358
384
  custom_output_extractor: Callable[[RunResult], Awaitable[str]] | None = None,
385
+ is_enabled: bool
386
+ | Callable[[RunContextWrapper[Any], AgentBase[Any]], MaybeAwaitable[bool]] = True,
359
387
  ) -> Tool:
360
388
  """Transform this agent into a tool, callable by other agents.
361
389
 
@@ -371,11 +399,15 @@ class Agent(AgentBase, Generic[TContext]):
371
399
  when to use it.
372
400
  custom_output_extractor: A function that extracts the output from the agent. If not
373
401
  provided, the last message from the agent will be used.
402
+ is_enabled: Whether the tool is enabled. Can be a bool or a callable that takes the run
403
+ context and agent and returns whether the tool is enabled. Disabled tools are hidden
404
+ from the LLM at runtime.
374
405
  """
375
406
 
376
407
  @function_tool(
377
408
  name_override=tool_name or _transforms.transform_string_function_style(self.name),
378
409
  description_override=tool_description or "",
410
+ is_enabled=is_enabled,
379
411
  )
380
412
  async def run_agent(context: RunContextWrapper, input: str) -> str:
381
413
  from .run import Runner
@@ -0,0 +1,15 @@
1
+
2
+ """Session memory backends living in the extensions namespace.
3
+
4
+ This package contains optional, production-grade session implementations that
5
+ introduce extra third-party dependencies (database drivers, ORMs, etc.). They
6
+ conform to the :class:`agents.memory.session.Session` protocol so they can be
7
+ used as a drop-in replacement for :class:`agents.memory.session.SQLiteSession`.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from .sqlalchemy_session import SQLAlchemySession # noqa: F401
12
+
13
+ __all__: list[str] = [
14
+ "SQLAlchemySession",
15
+ ]
@@ -0,0 +1,298 @@
1
+ """SQLAlchemy-powered Session backend.
2
+
3
+ Usage::
4
+
5
+ from agents.extensions.memory import SQLAlchemySession
6
+
7
+ # Create from SQLAlchemy URL (uses asyncpg driver under the hood for Postgres)
8
+ session = SQLAlchemySession.from_url(
9
+ session_id="user-123",
10
+ url="postgresql+asyncpg://app:secret@db.example.com/agents",
11
+ create_tables=True, # If you want to auto-create tables, set to True.
12
+ )
13
+
14
+ # Or pass an existing AsyncEngine that your application already manages
15
+ session = SQLAlchemySession(
16
+ session_id="user-123",
17
+ engine=my_async_engine,
18
+ create_tables=True, # If you want to auto-create tables, set to True.
19
+ )
20
+
21
+ await Runner.run(agent, "Hello", session=session)
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import json
28
+ from typing import Any
29
+
30
+ from sqlalchemy import (
31
+ TIMESTAMP,
32
+ Column,
33
+ ForeignKey,
34
+ Index,
35
+ Integer,
36
+ MetaData,
37
+ String,
38
+ Table,
39
+ Text,
40
+ delete,
41
+ insert,
42
+ select,
43
+ text as sql_text,
44
+ update,
45
+ )
46
+ from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
47
+
48
+ from ...items import TResponseInputItem
49
+ from ...memory.session import SessionABC
50
+
51
+
52
+ class SQLAlchemySession(SessionABC):
53
+ """SQLAlchemy implementation of :pyclass:`agents.memory.session.Session`."""
54
+
55
+ _metadata: MetaData
56
+ _sessions: Table
57
+ _messages: Table
58
+
59
+ def __init__(
60
+ self,
61
+ session_id: str,
62
+ *,
63
+ engine: AsyncEngine,
64
+ create_tables: bool = False,
65
+ sessions_table: str = "agent_sessions",
66
+ messages_table: str = "agent_messages",
67
+ ): # noqa: D401 – short description on the class-level docstring
68
+ """Create a new session.
69
+
70
+ Parameters
71
+ ----------
72
+ session_id
73
+ Unique identifier for the conversation.
74
+ engine
75
+ A pre-configured SQLAlchemy *async* engine. The engine **must** be
76
+ created with an async driver (``postgresql+asyncpg://``,
77
+ ``mysql+aiomysql://`` or ``sqlite+aiosqlite://``).
78
+ create_tables
79
+ Whether to automatically create the required tables & indexes.
80
+ Defaults to *False* for production use. Set to *True* for development
81
+ and testing when migrations aren't used.
82
+ sessions_table, messages_table
83
+ Override default table names if needed.
84
+ """
85
+ self.session_id = session_id
86
+ self._engine = engine
87
+ self._lock = asyncio.Lock()
88
+
89
+ self._metadata = MetaData()
90
+ self._sessions = Table(
91
+ sessions_table,
92
+ self._metadata,
93
+ Column("session_id", String, primary_key=True),
94
+ Column(
95
+ "created_at",
96
+ TIMESTAMP(timezone=False),
97
+ server_default=sql_text("CURRENT_TIMESTAMP"),
98
+ nullable=False,
99
+ ),
100
+ Column(
101
+ "updated_at",
102
+ TIMESTAMP(timezone=False),
103
+ server_default=sql_text("CURRENT_TIMESTAMP"),
104
+ onupdate=sql_text("CURRENT_TIMESTAMP"),
105
+ nullable=False,
106
+ ),
107
+ )
108
+
109
+ self._messages = Table(
110
+ messages_table,
111
+ self._metadata,
112
+ Column("id", Integer, primary_key=True, autoincrement=True),
113
+ Column(
114
+ "session_id",
115
+ String,
116
+ ForeignKey(f"{sessions_table}.session_id", ondelete="CASCADE"),
117
+ nullable=False,
118
+ ),
119
+ Column("message_data", Text, nullable=False),
120
+ Column(
121
+ "created_at",
122
+ TIMESTAMP(timezone=False),
123
+ server_default=sql_text("CURRENT_TIMESTAMP"),
124
+ nullable=False,
125
+ ),
126
+ Index(
127
+ f"idx_{messages_table}_session_time",
128
+ "session_id",
129
+ "created_at",
130
+ ),
131
+ sqlite_autoincrement=True,
132
+ )
133
+
134
+ # Async session factory
135
+ self._session_factory = async_sessionmaker(
136
+ self._engine, expire_on_commit=False
137
+ )
138
+
139
+ self._create_tables = create_tables
140
+
141
+ # ---------------------------------------------------------------------
142
+ # Convenience constructors
143
+ # ---------------------------------------------------------------------
144
+ @classmethod
145
+ def from_url(
146
+ cls,
147
+ session_id: str,
148
+ *,
149
+ url: str,
150
+ engine_kwargs: dict[str, Any] | None = None,
151
+ **kwargs: Any,
152
+ ) -> SQLAlchemySession:
153
+ """Create a session from a database URL string.
154
+
155
+ Parameters
156
+ ----------
157
+ session_id
158
+ Conversation ID.
159
+ url
160
+ Any SQLAlchemy async URL – e.g. ``"postgresql+asyncpg://user:pass@host/db"``.
161
+ engine_kwargs
162
+ Additional kwargs forwarded to :pyfunc:`sqlalchemy.ext.asyncio.create_async_engine`.
163
+ kwargs
164
+ Forwarded to the main constructor (``create_tables``, custom table names, …).
165
+ """
166
+ engine_kwargs = engine_kwargs or {}
167
+ engine = create_async_engine(url, **engine_kwargs)
168
+ return cls(session_id, engine=engine, **kwargs)
169
+
170
+ async def _serialize_item(self, item: TResponseInputItem) -> str:
171
+ """Serialize an item to JSON string. Can be overridden by subclasses."""
172
+ return json.dumps(item, separators=(",", ":"))
173
+
174
+ async def _deserialize_item(self, item: str) -> TResponseInputItem:
175
+ """Deserialize a JSON string to an item. Can be overridden by subclasses."""
176
+ return json.loads(item) # type: ignore[no-any-return]
177
+
178
+ # ------------------------------------------------------------------
179
+ # Session protocol implementation
180
+ # ------------------------------------------------------------------
181
+ async def _ensure_tables(self) -> None:
182
+ """Ensure tables are created before any database operations."""
183
+ if self._create_tables:
184
+ async with self._engine.begin() as conn:
185
+ await conn.run_sync(self._metadata.create_all)
186
+ self._create_tables = False # Only create once
187
+
188
+ async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
189
+ await self._ensure_tables()
190
+ async with self._session_factory() as sess:
191
+ if limit is None:
192
+ stmt = (
193
+ select(self._messages.c.message_data)
194
+ .where(self._messages.c.session_id == self.session_id)
195
+ .order_by(self._messages.c.created_at.asc())
196
+ )
197
+ else:
198
+ stmt = (
199
+ select(self._messages.c.message_data)
200
+ .where(self._messages.c.session_id == self.session_id)
201
+ # Use DESC + LIMIT to get the latest N
202
+ # then reverse later for chronological order.
203
+ .order_by(self._messages.c.created_at.desc())
204
+ .limit(limit)
205
+ )
206
+
207
+ result = await sess.execute(stmt)
208
+ rows: list[str] = [row[0] for row in result.all()]
209
+
210
+ if limit is not None:
211
+ rows.reverse()
212
+
213
+ items: list[TResponseInputItem] = []
214
+ for raw in rows:
215
+ try:
216
+ items.append(await self._deserialize_item(raw))
217
+ except json.JSONDecodeError:
218
+ # Skip corrupted rows
219
+ continue
220
+ return items
221
+
222
+ async def add_items(self, items: list[TResponseInputItem]) -> None:
223
+ if not items:
224
+ return
225
+
226
+ await self._ensure_tables()
227
+ payload = [
228
+ {
229
+ "session_id": self.session_id,
230
+ "message_data": await self._serialize_item(item),
231
+ }
232
+ for item in items
233
+ ]
234
+
235
+ async with self._session_factory() as sess:
236
+ async with sess.begin():
237
+ # Ensure the parent session row exists - use merge for cross-DB compatibility
238
+ # Check if session exists
239
+ existing = await sess.execute(
240
+ select(self._sessions.c.session_id).where(
241
+ self._sessions.c.session_id == self.session_id
242
+ )
243
+ )
244
+ if not existing.scalar_one_or_none():
245
+ # Session doesn't exist, create it
246
+ await sess.execute(
247
+ insert(self._sessions).values({"session_id": self.session_id})
248
+ )
249
+
250
+ # Insert messages in bulk
251
+ await sess.execute(insert(self._messages), payload)
252
+
253
+ # Touch updated_at column
254
+ await sess.execute(
255
+ update(self._sessions)
256
+ .where(self._sessions.c.session_id == self.session_id)
257
+ .values(updated_at=sql_text("CURRENT_TIMESTAMP"))
258
+ )
259
+
260
+ async def pop_item(self) -> TResponseInputItem | None:
261
+ await self._ensure_tables()
262
+ async with self._session_factory() as sess:
263
+ async with sess.begin():
264
+ # Fallback for all dialects - get ID first, then delete
265
+ subq = (
266
+ select(self._messages.c.id)
267
+ .where(self._messages.c.session_id == self.session_id)
268
+ .order_by(self._messages.c.created_at.desc())
269
+ .limit(1)
270
+ )
271
+ res = await sess.execute(subq)
272
+ row_id = res.scalar_one_or_none()
273
+ if row_id is None:
274
+ return None
275
+ # Fetch data before deleting
276
+ res_data = await sess.execute(
277
+ select(self._messages.c.message_data).where(self._messages.c.id == row_id)
278
+ )
279
+ row = res_data.scalar_one_or_none()
280
+ await sess.execute(delete(self._messages).where(self._messages.c.id == row_id))
281
+
282
+ if row is None:
283
+ return None
284
+ try:
285
+ return await self._deserialize_item(row)
286
+ except json.JSONDecodeError:
287
+ return None
288
+
289
+ async def clear_session(self) -> None: # noqa: D401 – imperative mood is fine
290
+ await self._ensure_tables()
291
+ async with self._session_factory() as sess:
292
+ async with sess.begin():
293
+ await sess.execute(
294
+ delete(self._messages).where(self._messages.c.session_id == self.session_id)
295
+ )
296
+ await sess.execute(
297
+ delete(self._sessions).where(self._sessions.c.session_id == self.session_id)
298
+ )
@@ -20,6 +20,7 @@ except ImportError as _e:
20
20
  from openai import NOT_GIVEN, AsyncStream, NotGiven
21
21
  from openai.types.chat import (
22
22
  ChatCompletionChunk,
23
+ ChatCompletionMessageCustomToolCall,
23
24
  ChatCompletionMessageFunctionToolCall,
24
25
  )
25
26
  from openai.types.chat.chat_completion_message import (
@@ -28,7 +29,6 @@ from openai.types.chat.chat_completion_message import (
28
29
  ChatCompletionMessage,
29
30
  )
30
31
  from openai.types.chat.chat_completion_message_function_tool_call import Function
31
- from openai.types.chat.chat_completion_message_tool_call import ChatCompletionMessageToolCall
32
32
  from openai.types.responses import Response
33
33
 
34
34
  from ... import _debug
@@ -366,7 +366,9 @@ class LitellmConverter:
366
366
  if message.role != "assistant":
367
367
  raise ModelBehaviorError(f"Unsupported role: {message.role}")
368
368
 
369
- tool_calls: list[ChatCompletionMessageToolCall] | None = (
369
+ tool_calls: list[
370
+ ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall
371
+ ] | None = (
370
372
  [LitellmConverter.convert_tool_call_to_openai(tool) for tool in message.tool_calls]
371
373
  if message.tool_calls
372
374
  else None
@@ -1,6 +1,8 @@
1
+ from ...models.default_models import get_default_model
1
2
  from ...models.interface import Model, ModelProvider
2
3
  from .litellm_model import LitellmModel
3
4
 
5
+ # This is kept for backward compatiblity but using get_default_model() method is recommended.
4
6
  DEFAULT_MODEL: str = "gpt-4.1"
5
7
 
6
8
 
@@ -18,4 +20,4 @@ class LitellmProvider(ModelProvider):
18
20
  """
19
21
 
20
22
  def get_model(self, model_name: str | None) -> Model:
21
- return LitellmModel(model_name or DEFAULT_MODEL)
23
+ return LitellmModel(model_name or get_default_model())
agents/function_schema.py CHANGED
@@ -291,7 +291,7 @@ def function_schema(
291
291
  # Default factory to empty list
292
292
  fields[name] = (
293
293
  ann,
294
- Field(default_factory=list, description=field_description), # type: ignore
294
+ Field(default_factory=list, description=field_description),
295
295
  )
296
296
 
297
297
  elif param.kind == param.VAR_KEYWORD:
@@ -309,7 +309,7 @@ def function_schema(
309
309
 
310
310
  fields[name] = (
311
311
  ann,
312
- Field(default_factory=dict, description=field_description), # type: ignore
312
+ Field(default_factory=dict, description=field_description),
313
313
  )
314
314
 
315
315
  else:
agents/items.py CHANGED
@@ -1,7 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import abc
4
- import copy
5
4
  from dataclasses import dataclass
6
5
  from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, Union
7
6
 
@@ -277,7 +276,7 @@ class ItemHelpers:
277
276
  "role": "user",
278
277
  }
279
278
  ]
280
- return copy.deepcopy(input)
279
+ return input.copy()
281
280
 
282
281
  @classmethod
283
282
  def text_message_outputs(cls, items: list[RunItem]) -> str:
agents/lifecycle.py CHANGED
@@ -1,8 +1,9 @@
1
- from typing import Any, Generic
1
+ from typing import Any, Generic, Optional
2
2
 
3
3
  from typing_extensions import TypeVar
4
4
 
5
5
  from .agent import Agent, AgentBase
6
+ from .items import ModelResponse, TResponseInputItem
6
7
  from .run_context import RunContextWrapper, TContext
7
8
  from .tool import Tool
8
9
 
@@ -14,6 +15,25 @@ class RunHooksBase(Generic[TContext, TAgent]):
14
15
  override the methods you need.
15
16
  """
16
17
 
18
+ async def on_llm_start(
19
+ self,
20
+ context: RunContextWrapper[TContext],
21
+ agent: Agent[TContext],
22
+ system_prompt: Optional[str],
23
+ input_items: list[TResponseInputItem],
24
+ ) -> None:
25
+ """Called just before invoking the LLM for this agent."""
26
+ pass
27
+
28
+ async def on_llm_end(
29
+ self,
30
+ context: RunContextWrapper[TContext],
31
+ agent: Agent[TContext],
32
+ response: ModelResponse,
33
+ ) -> None:
34
+ """Called immediately after the LLM call returns for this agent."""
35
+ pass
36
+
17
37
  async def on_agent_start(self, context: RunContextWrapper[TContext], agent: TAgent) -> None:
18
38
  """Called before the agent is invoked. Called each time the current agent changes."""
19
39
  pass
@@ -106,6 +126,25 @@ class AgentHooksBase(Generic[TContext, TAgent]):
106
126
  """Called after a tool is invoked."""
107
127
  pass
108
128
 
129
+ async def on_llm_start(
130
+ self,
131
+ context: RunContextWrapper[TContext],
132
+ agent: Agent[TContext],
133
+ system_prompt: Optional[str],
134
+ input_items: list[TResponseInputItem],
135
+ ) -> None:
136
+ """Called immediately before the agent issues an LLM call."""
137
+ pass
138
+
139
+ async def on_llm_end(
140
+ self,
141
+ context: RunContextWrapper[TContext],
142
+ agent: Agent[TContext],
143
+ response: ModelResponse,
144
+ ) -> None:
145
+ """Called immediately after the agent receives the LLM response."""
146
+ pass
147
+
109
148
 
110
149
  RunHooks = RunHooksBase[TContext, Agent]
111
150
  """Run hooks when using `Agent`."""