Skip to content

Commit 442011c

Browse files
Support locally served models which do not require an api key (#814)
Co-authored-by: JONEMI21 <[email protected]> Co-authored-by: Samuel Colvin <[email protected]>
1 parent fa1625d commit 442011c

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

pydantic_ai_slim/pydantic_ai/models/openai.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations as _annotations
22

3+
import os
34
from collections.abc import AsyncIterable, AsyncIterator, Iterable
45
from contextlib import asynccontextmanager
56
from dataclasses import dataclass, field
@@ -101,7 +102,11 @@ def __init__(
101102
In the future, this may be inferred from the model name.
102103
"""
103104
self.model_name: OpenAIModelName = model_name
104-
if openai_client is not None:
105+
# This is a workaround for the OpenAI client requiring an API key, whilst locally served,
106+
# openai compatible models do not always need an API key.
107+
if api_key is None and 'OPENAI_API_KEY' not in os.environ and base_url is not None and openai_client is None:
108+
api_key = ''
109+
elif openai_client is not None:
105110
assert http_client is None, 'Cannot provide both `openai_client` and `http_client`'
106111
assert base_url is None, 'Cannot provide both `openai_client` and `base_url`'
107112
assert api_key is None, 'Cannot provide both `openai_client` and `api_key`'

tests/models/test_openai.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from .mock_async_stream import MockAsyncStream
3030

3131
with try_import() as imports_successful:
32-
from openai import NOT_GIVEN, AsyncOpenAI
32+
from openai import NOT_GIVEN, AsyncOpenAI, OpenAIError
3333
from openai.types import chat
3434
from openai.types.chat.chat_completion import Choice
3535
from openai.types.chat.chat_completion_chunk import (
@@ -65,6 +65,19 @@ def test_init_with_base_url():
6565
m.name()
6666

6767

68+
def test_init_with_non_openai_model():
69+
m = OpenAIModel('llama3.2-vision:latest', base_url='https://example.com/v1/')
70+
m.name()
71+
72+
73+
def test_init_of_openai_without_api_key_raises_error():
74+
with pytest.raises(
75+
OpenAIError,
76+
match='^The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable$',
77+
):
78+
OpenAIModel('gpt-4o')
79+
80+
6881
@dataclass
6982
class MockOpenAI:
7083
completions: chat.ChatCompletion | list[chat.ChatCompletion] | None = None

0 commit comments

Comments
 (0)