openai-agents 0.0.5__py3-none-any.whl → 0.0.6__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/voice/model.py ADDED
@@ -0,0 +1,193 @@
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ from collections.abc import AsyncIterator
5
+ from dataclasses import dataclass
6
+ from typing import Any, Callable, Literal
7
+
8
+ from .imports import np, npt
9
+ from .input import AudioInput, StreamedAudioInput
10
+ from .utils import get_sentence_based_splitter
11
+
12
+ DEFAULT_TTS_INSTRUCTIONS = (
13
+ "You will receive partial sentences. Do not complete the sentence, just read out the text."
14
+ )
15
+ DEFAULT_TTS_BUFFER_SIZE = 120
16
+
17
+
18
+ @dataclass
19
+ class TTSModelSettings:
20
+ """Settings for a TTS model."""
21
+
22
+ voice: (
23
+ Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"] | None
24
+ ) = None
25
+ """
26
+ The voice to use for the TTS model. If not provided, the default voice for the respective model
27
+ will be used.
28
+ """
29
+
30
+ buffer_size: int = 120
31
+ """The minimal size of the chunks of audio data that are being streamed out."""
32
+
33
+ dtype: npt.DTypeLike = np.int16
34
+ """The data type for the audio data to be returned in."""
35
+
36
+ transform_data: (
37
+ Callable[[npt.NDArray[np.int16 | np.float32]], npt.NDArray[np.int16 | np.float32]] | None
38
+ ) = None
39
+ """
40
+ A function to transform the data from the TTS model. This is useful if you want the resulting
41
+ audio stream to have the data in a specific shape already.
42
+ """
43
+
44
+ instructions: str = (
45
+ "You will receive partial sentences. Do not complete the sentence just read out the text."
46
+ )
47
+ """
48
+ The instructions to use for the TTS model. This is useful if you want to control the tone of the
49
+ audio output.
50
+ """
51
+
52
+ text_splitter: Callable[[str], tuple[str, str]] = get_sentence_based_splitter()
53
+ """
54
+ A function to split the text into chunks. This is useful if you want to split the text into
55
+ chunks before sending it to the TTS model rather than waiting for the whole text to be
56
+ processed.
57
+ """
58
+
59
+ speed: float | None = None
60
+ """The speed with which the TTS model will read the text. Between 0.25 and 4.0."""
61
+
62
+
63
+ class TTSModel(abc.ABC):
64
+ """A text-to-speech model that can convert text into audio output."""
65
+
66
+ @property
67
+ @abc.abstractmethod
68
+ def model_name(self) -> str:
69
+ """The name of the TTS model."""
70
+ pass
71
+
72
+ @abc.abstractmethod
73
+ def run(self, text: str, settings: TTSModelSettings) -> AsyncIterator[bytes]:
74
+ """Given a text string, produces a stream of audio bytes, in PCM format.
75
+
76
+ Args:
77
+ text: The text to convert to audio.
78
+
79
+ Returns:
80
+ An async iterator of audio bytes, in PCM format.
81
+ """
82
+ pass
83
+
84
+
85
+ class StreamedTranscriptionSession(abc.ABC):
86
+ """A streamed transcription of audio input."""
87
+
88
+ @abc.abstractmethod
89
+ def transcribe_turns(self) -> AsyncIterator[str]:
90
+ """Yields a stream of text transcriptions. Each transcription is a turn in the conversation.
91
+
92
+ This method is expected to return only after `close()` is called.
93
+ """
94
+ pass
95
+
96
+ @abc.abstractmethod
97
+ async def close(self) -> None:
98
+ """Closes the session."""
99
+ pass
100
+
101
+
102
+ @dataclass
103
+ class STTModelSettings:
104
+ """Settings for a speech-to-text model."""
105
+
106
+ prompt: str | None = None
107
+ """Instructions for the model to follow."""
108
+
109
+ language: str | None = None
110
+ """The language of the audio input."""
111
+
112
+ temperature: float | None = None
113
+ """The temperature of the model."""
114
+
115
+ turn_detection: dict[str, Any] | None = None
116
+ """The turn detection settings for the model when using streamed audio input."""
117
+
118
+
119
+ class STTModel(abc.ABC):
120
+ """A speech-to-text model that can convert audio input into text."""
121
+
122
+ @property
123
+ @abc.abstractmethod
124
+ def model_name(self) -> str:
125
+ """The name of the STT model."""
126
+ pass
127
+
128
+ @abc.abstractmethod
129
+ async def transcribe(
130
+ self,
131
+ input: AudioInput,
132
+ settings: STTModelSettings,
133
+ trace_include_sensitive_data: bool,
134
+ trace_include_sensitive_audio_data: bool,
135
+ ) -> str:
136
+ """Given an audio input, produces a text transcription.
137
+
138
+ Args:
139
+ input: The audio input to transcribe.
140
+ settings: The settings to use for the transcription.
141
+ trace_include_sensitive_data: Whether to include sensitive data in traces.
142
+ trace_include_sensitive_audio_data: Whether to include sensitive audio data in traces.
143
+
144
+ Returns:
145
+ The text transcription of the audio input.
146
+ """
147
+ pass
148
+
149
+ @abc.abstractmethod
150
+ async def create_session(
151
+ self,
152
+ input: StreamedAudioInput,
153
+ settings: STTModelSettings,
154
+ trace_include_sensitive_data: bool,
155
+ trace_include_sensitive_audio_data: bool,
156
+ ) -> StreamedTranscriptionSession:
157
+ """Creates a new transcription session, which you can push audio to, and receive a stream
158
+ of text transcriptions.
159
+
160
+ Args:
161
+ input: The audio input to transcribe.
162
+ settings: The settings to use for the transcription.
163
+ trace_include_sensitive_data: Whether to include sensitive data in traces.
164
+ trace_include_sensitive_audio_data: Whether to include sensitive audio data in traces.
165
+
166
+ Returns:
167
+ A new transcription session.
168
+ """
169
+ pass
170
+
171
+
172
+ class VoiceModelProvider(abc.ABC):
173
+ """The base interface for a voice model provider.
174
+
175
+ A model provider is responsible for creating speech-to-text and text-to-speech models, given a
176
+ name.
177
+ """
178
+
179
+ @abc.abstractmethod
180
+ def get_stt_model(self, model_name: str | None) -> STTModel:
181
+ """Get a speech-to-text model by name.
182
+
183
+ Args:
184
+ model_name: The name of the model to get.
185
+
186
+ Returns:
187
+ The speech-to-text model.
188
+ """
189
+ pass
190
+
191
+ @abc.abstractmethod
192
+ def get_tts_model(self, model_name: str | None) -> TTSModel:
193
+ """Get a text-to-speech model by name."""
File without changes
@@ -0,0 +1,97 @@
1
+ from __future__ import annotations
2
+
3
+ import httpx
4
+ from openai import AsyncOpenAI, DefaultAsyncHttpxClient
5
+
6
+ from ...models import _openai_shared
7
+ from ..model import STTModel, TTSModel, VoiceModelProvider
8
+ from .openai_stt import OpenAISTTModel
9
+ from .openai_tts import OpenAITTSModel
10
+
11
+ _http_client: httpx.AsyncClient | None = None
12
+
13
+
14
+ # If we create a new httpx client for each request, that would mean no sharing of connection pools,
15
+ # which would mean worse latency and resource usage. So, we share the client across requests.
16
+ def shared_http_client() -> httpx.AsyncClient:
17
+ global _http_client
18
+ if _http_client is None:
19
+ _http_client = DefaultAsyncHttpxClient()
20
+ return _http_client
21
+
22
+
23
+ DEFAULT_STT_MODEL = "gpt-4o-transcribe"
24
+ DEFAULT_TTS_MODEL = "gpt-4o-mini-tts"
25
+
26
+
27
+ class OpenAIVoiceModelProvider(VoiceModelProvider):
28
+ """A voice model provider that uses OpenAI models."""
29
+
30
+ def __init__(
31
+ self,
32
+ *,
33
+ api_key: str | None = None,
34
+ base_url: str | None = None,
35
+ openai_client: AsyncOpenAI | None = None,
36
+ organization: str | None = None,
37
+ project: str | None = None,
38
+ ) -> None:
39
+ """Create a new OpenAI voice model provider.
40
+
41
+ Args:
42
+ api_key: The API key to use for the OpenAI client. If not provided, we will use the
43
+ default API key.
44
+ base_url: The base URL to use for the OpenAI client. If not provided, we will use the
45
+ default base URL.
46
+ openai_client: An optional OpenAI client to use. If not provided, we will create a new
47
+ OpenAI client using the api_key and base_url.
48
+ organization: The organization to use for the OpenAI client.
49
+ project: The project to use for the OpenAI client.
50
+ """
51
+ if openai_client is not None:
52
+ assert api_key is None and base_url is None, (
53
+ "Don't provide api_key or base_url if you provide openai_client"
54
+ )
55
+ self._client: AsyncOpenAI | None = openai_client
56
+ else:
57
+ self._client = None
58
+ self._stored_api_key = api_key
59
+ self._stored_base_url = base_url
60
+ self._stored_organization = organization
61
+ self._stored_project = project
62
+
63
+ # We lazy load the client in case you never actually use OpenAIProvider(). Otherwise
64
+ # AsyncOpenAI() raises an error if you don't have an API key set.
65
+ def _get_client(self) -> AsyncOpenAI:
66
+ if self._client is None:
67
+ self._client = _openai_shared.get_default_openai_client() or AsyncOpenAI(
68
+ api_key=self._stored_api_key or _openai_shared.get_default_openai_key(),
69
+ base_url=self._stored_base_url,
70
+ organization=self._stored_organization,
71
+ project=self._stored_project,
72
+ http_client=shared_http_client(),
73
+ )
74
+
75
+ return self._client
76
+
77
+ def get_stt_model(self, model_name: str | None) -> STTModel:
78
+ """Get a speech-to-text model by name.
79
+
80
+ Args:
81
+ model_name: The name of the model to get.
82
+
83
+ Returns:
84
+ The speech-to-text model.
85
+ """
86
+ return OpenAISTTModel(model_name or DEFAULT_STT_MODEL, self._get_client())
87
+
88
+ def get_tts_model(self, model_name: str | None) -> TTSModel:
89
+ """Get a text-to-speech model by name.
90
+
91
+ Args:
92
+ model_name: The name of the model to get.
93
+
94
+ Returns:
95
+ The text-to-speech model.
96
+ """
97
+ return OpenAITTSModel(model_name or DEFAULT_TTS_MODEL, self._get_client())