File tree Expand file tree Collapse file tree 2 files changed +20
-2
lines changed
pydantic_ai_slim/pydantic_ai/models Expand file tree Collapse file tree 2 files changed +20
-2
lines changed Original file line number Diff line number Diff line change 1
1
from __future__ import annotations as _annotations
2
2
3
+ import os
3
4
from collections .abc import AsyncIterable , AsyncIterator , Iterable
4
5
from contextlib import asynccontextmanager
5
6
from dataclasses import dataclass , field
@@ -101,7 +102,11 @@ def __init__(
101
102
In the future, this may be inferred from the model name.
102
103
"""
103
104
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 :
105
110
assert http_client is None , 'Cannot provide both `openai_client` and `http_client`'
106
111
assert base_url is None , 'Cannot provide both `openai_client` and `base_url`'
107
112
assert api_key is None , 'Cannot provide both `openai_client` and `api_key`'
Original file line number Diff line number Diff line change 29
29
from .mock_async_stream import MockAsyncStream
30
30
31
31
with try_import () as imports_successful :
32
- from openai import NOT_GIVEN , AsyncOpenAI
32
+ from openai import NOT_GIVEN , AsyncOpenAI , OpenAIError
33
33
from openai .types import chat
34
34
from openai .types .chat .chat_completion import Choice
35
35
from openai .types .chat .chat_completion_chunk import (
@@ -65,6 +65,19 @@ def test_init_with_base_url():
65
65
m .name ()
66
66
67
67
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
+
68
81
@dataclass
69
82
class MockOpenAI :
70
83
completions : chat .ChatCompletion | list [chat .ChatCompletion ] | None = None
You can’t perform that action at this time.
0 commit comments