-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Export user_agent_override
contextmanager
#1768
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+248
−6
Merged
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
3653a40
Add user_agent_override helper contextmanager
jiwon-oai 329d9b4
add tests
jiwon-oai d0b63b4
update docstring
jiwon-oai c8b933c
Added tests for no ua override cases too
jiwon-oai 544b5a3
type fixes
jiwon-oai f051182
make format
jiwon-oai 449c461
Use ContextVar colocated with model instead of adding top level export
jiwon-oai a490e62
delete unused code
jiwon-oai 122ec73
undo auto newline added by make format
jiwon-oai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
from __future__ import annotations | ||
|
||
from typing import Any | ||
|
||
import pytest | ||
|
||
from agents import ModelSettings, ModelTracing, __version__ | ||
from agents.models.chatcmpl_helpers import USER_AGENT_OVERRIDE | ||
|
||
|
||
@pytest.mark.allow_call_model_methods | ||
@pytest.mark.asyncio | ||
@pytest.mark.parametrize("override_ua", [None, "test_user_agent"]) | ||
async def test_user_agent_header_litellm(override_ua: str | None, monkeypatch): | ||
called_kwargs: dict[str, Any] = {} | ||
expected_ua = override_ua or f"Agents/Python {__version__}" | ||
|
||
import importlib | ||
import sys | ||
import types as pytypes | ||
|
||
litellm_fake: Any = pytypes.ModuleType("litellm") | ||
|
||
class DummyMessage: | ||
role = "assistant" | ||
content = "Hello" | ||
tool_calls: list[Any] | None = None | ||
|
||
def get(self, _key, _default=None): | ||
return None | ||
|
||
def model_dump(self): | ||
return {"role": self.role, "content": self.content} | ||
|
||
class Choices: # noqa: N801 - mimic litellm naming | ||
def __init__(self): | ||
self.message = DummyMessage() | ||
|
||
class DummyModelResponse: | ||
def __init__(self): | ||
self.choices = [Choices()] | ||
|
||
async def acompletion(**kwargs): | ||
nonlocal called_kwargs | ||
called_kwargs = kwargs | ||
return DummyModelResponse() | ||
|
||
utils_ns = pytypes.SimpleNamespace() | ||
utils_ns.Choices = Choices | ||
utils_ns.ModelResponse = DummyModelResponse | ||
|
||
litellm_types = pytypes.SimpleNamespace( | ||
utils=utils_ns, | ||
llms=pytypes.SimpleNamespace(openai=pytypes.SimpleNamespace(ChatCompletionAnnotation=dict)), | ||
) | ||
litellm_fake.acompletion = acompletion | ||
litellm_fake.types = litellm_types | ||
|
||
monkeypatch.setitem(sys.modules, "litellm", litellm_fake) | ||
|
||
litellm_mod = importlib.import_module("agents.extensions.models.litellm_model") | ||
monkeypatch.setattr(litellm_mod, "litellm", litellm_fake, raising=True) | ||
LitellmModel = litellm_mod.LitellmModel | ||
|
||
model = LitellmModel(model="gpt-4") | ||
|
||
if override_ua is not None: | ||
token = USER_AGENT_OVERRIDE.set(override_ua) | ||
else: | ||
token = None | ||
try: | ||
await model.get_response( | ||
system_instructions=None, | ||
input="hi", | ||
model_settings=ModelSettings(), | ||
tools=[], | ||
output_schema=None, | ||
handoffs=[], | ||
tracing=ModelTracing.DISABLED, | ||
previous_response_id=None, | ||
conversation_id=None, | ||
prompt=None, | ||
) | ||
finally: | ||
if token is not None: | ||
USER_AGENT_OVERRIDE.reset(token) | ||
|
||
assert "extra_headers" in called_kwargs | ||
assert called_kwargs["extra_headers"]["User-Agent"] == expected_ua |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
from __future__ import annotations | ||
|
||
from typing import Any | ||
|
||
import pytest | ||
from openai.types.responses import ResponseCompletedEvent | ||
|
||
from agents import ModelSettings, ModelTracing, __version__ | ||
from agents.models.openai_responses import _USER_AGENT_OVERRIDE as RESP_UA, OpenAIResponsesModel | ||
from tests.fake_model import get_response_obj | ||
|
||
|
||
@pytest.mark.allow_call_model_methods | ||
@pytest.mark.asyncio | ||
@pytest.mark.parametrize("override_ua", [None, "test_user_agent"]) | ||
async def test_user_agent_header_responses(override_ua: str | None): | ||
called_kwargs: dict[str, Any] = {} | ||
expected_ua = override_ua or f"Agents/Python {__version__}" | ||
|
||
class DummyStream: | ||
def __aiter__(self): | ||
async def gen(): | ||
yield ResponseCompletedEvent( | ||
type="response.completed", | ||
response=get_response_obj([]), | ||
sequence_number=0, | ||
) | ||
|
||
return gen() | ||
|
||
class DummyResponses: | ||
async def create(self, **kwargs): | ||
nonlocal called_kwargs | ||
called_kwargs = kwargs | ||
return DummyStream() | ||
|
||
class DummyResponsesClient: | ||
def __init__(self): | ||
self.responses = DummyResponses() | ||
|
||
model = OpenAIResponsesModel(model="gpt-4", openai_client=DummyResponsesClient()) # type: ignore | ||
|
||
if override_ua is not None: | ||
token = RESP_UA.set(override_ua) | ||
else: | ||
token = None | ||
|
||
try: | ||
stream = model.stream_response( | ||
system_instructions=None, | ||
input="hi", | ||
model_settings=ModelSettings(), | ||
tools=[], | ||
output_schema=None, | ||
handoffs=[], | ||
tracing=ModelTracing.DISABLED, | ||
) | ||
async for _ in stream: | ||
pass | ||
finally: | ||
if token is not None: | ||
RESP_UA.reset(token) | ||
|
||
assert "extra_headers" in called_kwargs | ||
assert called_kwargs["extra_headers"]["User-Agent"] == expected_ua |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
undo plz?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ack! fyi this got added when I ran
make format
- I'll undo it but it might reappear on other unrelated PRs!