Skip to content

GPT API

The GPT isolates OpenAI-specific SDK calls from the Streamlit application shell. The wrapper should expose typed, documented methods for text, image, audio, embedding, file, and vector-store workflows while keeping provider-specific request and response handling out of app.py.

Provider Scope

The GPT module may support the following workflow families depending on the current source code:

Workflow Description
Chat/Text Sends user prompts and optional conversation context to an OpenAI text-capable model.
Images Generates, edits, or analyzes images where supported by the configured OpenAI model.
Audio Handles text-to-speech, transcription, and translation workflows where implemented.
Embeddings Converts text or document chunks into embedding vectors.
Files Uploads, lists, retrieves, or deletes provider-managed files.
Vector Stores Creates, lists, updates, searches, or deletes vector stores and related file batches.
Assistants or Responses Executes higher-level assistant workflows where the wrapper exposes them.

Design Contract

The wrapper should follow these conventions:

Contract Expected Pattern
Configuration Assign API keys and reusable configuration values from config.py or environment-derived config.
Validation Validate mandatory method arguments before provider calls.
Client lifecycle Create the OpenAI client inside the method that uses it, after credential validation.
Error handling Capture exceptions using the project Error and Logger pattern.
Return values Return provider responses, normalized dictionaries, files, IDs, or rendered-safe payloads.
Documentation Use Google-style docstrings for every public class and method.

Common Configuration Values

Value Purpose
OPENAI_API_KEY OpenAI credential used by GPT workflows.
GPT model constants Default text or multimodal model names.
Image model constants Default image-generation or image-editing model names.
Audio model constants Default text-to-speech, transcription, or translation model names.
Embedding model constants Default embedding model names.
Vector-store constants Default vector-store names, IDs, or lookup values.

Usage Pattern

A Streamlit workflow should call the GPT wrapper through a narrow method boundary:

wrapper = GPT()
response = wrapper.create_response( text=prompt_text, model=model_name )

The exact class and method names should match the source code. The important architectural rule is that Streamlit should not need to know the low-level OpenAI request shape.

Documentation Guidance

Every public method should document:

  • the purpose of the operation;
  • every input parameter and accepted value shape;
  • the return type and meaning;
  • whether the method creates remote resources;
  • whether the method returns provider-managed IDs;
  • any important limitations or provider-specific behavior.

API Reference

The section below is generated from the source module when mkdocs build runs.

gpt


Assembly:                Boo
Filename:                Boo.py
Author:                  Terry D. Eppler
Created:                 05-31-2022

Last Modified By:        Terry D. Eppler
Last Modified On:        05-01-2025

       Boo is a df analysis tool integrating various Generative GPT, GptText-Processing,
       and
       Machine-Learning algorithms for federal analysts.
       Copyright ©  2022  Terry Eppler

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You can contact me at: terryeppler@gmail.com or eppler.terry@epa.gov

Boo.py

GPT

Provide GPT workflow support.

Purpose

Provides the shared OpenAI wrapper base used by Gipity provider workflows. The class stores common model, prompt, request, response, and compatibility fields inherited by text, image, audio, embedding, file, and vector-store wrappers.

Attributes:

Name Type Description
api_key Optional[str]

Api key retained by the provider wrapper.

client Optional[OpenAI]

Client retained by the provider wrapper.

prompt Optional[str]

Prompt retained by the provider wrapper.

temperature Optional[float]

Temperature retained by the provider wrapper.

top_percent Optional[float]

Top percent retained by the provider wrapper.

frequency_penalty Optional[float]

Frequency penalty retained by the provider wrapper.

presence_penalty Optional[float]

Presence penalty retained by the provider wrapper.

max_tokens Optional[int]

Max tokens retained by the provider wrapper.

stops Optional[List[str]]

Stops retained by the provider wrapper.

store Optional[bool]

Store retained by the provider wrapper.

stream Optional[bool]

Stream retained by the provider wrapper.

background Optional[bool]

Background retained by the provider wrapper.

number Optional[int]

Number retained by the provider wrapper.

response_format Optional[Dict[str, str]]

Response format retained by the provider wrapper.

context Optional[List[Dict[str, str]]]

Context retained by the provider wrapper.

instructions Optional[str]

Instructions retained by the provider wrapper.

Source code in gpt.py
class GPT:
	"""Provide GPT workflow support.

	Purpose:
		Provides the shared OpenAI wrapper base used by Gipity provider workflows. The class
		stores common model, prompt, request, response, and compatibility fields inherited by
		text, image, audio, embedding, file, and vector-store wrappers.

	Attributes:
		api_key (Optional[str]): Api key retained by the provider wrapper.
		client (Optional[OpenAI]): Client retained by the provider wrapper.
		prompt (Optional[str]): Prompt retained by the provider wrapper.
		temperature (Optional[float]): Temperature retained by the provider wrapper.
		top_percent (Optional[float]): Top percent retained by the provider wrapper.
		frequency_penalty (Optional[float]): Frequency penalty retained by the provider wrapper.
		presence_penalty (Optional[float]): Presence penalty retained by the provider wrapper.
		max_tokens (Optional[int]): Max tokens retained by the provider wrapper.
		stops (Optional[List[str]]): Stops retained by the provider wrapper.
		store (Optional[bool]): Store retained by the provider wrapper.
		stream (Optional[bool]): Stream retained by the provider wrapper.
		background (Optional[bool]): Background retained by the provider wrapper.
		number (Optional[int]): Number retained by the provider wrapper.
		response_format (Optional[Dict[str, str]]): Response format retained by the provider
			wrapper.
		context (Optional[List[Dict[str, str]]]): Context retained by the provider wrapper.
		instructions (Optional[str]): Instructions retained by the provider wrapper.
	"""
	api_key: Optional[ str ]
	client: Optional[ OpenAI ]
	prompt: Optional[ str ]
	temperature: Optional[ float ]
	top_percent: Optional[ float ]
	frequency_penalty: Optional[ float ]
	presence_penalty: Optional[ float ]
	max_tokens: Optional[ int ]
	stops: Optional[ List[ str ] ]
	store: Optional[ bool ]
	stream: Optional[ bool ]
	background: Optional[ bool ]
	number: Optional[ int ]
	response_format: Optional[ Dict[ str, str ] ]
	context: Optional[ List[ Dict[ str, str ] ] ]
	instructions: Optional[ str ]

	def __init__( self ):
		"""Initialize instance.

		Purpose:
			Initializes the GPT object with default configuration, runtime state, provider
			settings,
			and compatibility fields. This constructor prepares the instance for later method calls
			without performing external work beyond local attribute assignment.
		"""
		self.api_key = cfg.OPENAI_API_KEY
		self.model = None
		self.client = None
		self.number = None
		self.stops = [ ]
		self.response_format = { }
		self.number = None
		self.temperature = None
		self.top_percent = None
		self.frequency_penalty = None
		self.presence_penalty = None
		self.max_tokens = None
		self.prompt = None
		self.store = None
		self.stream = None
		self.background = None
		self.instructions = None
		self.context = [ ]

__init__

__init__()

Initialize instance.

Purpose

Initializes the GPT object with default configuration, runtime state, provider settings, and compatibility fields. This constructor prepares the instance for later method calls without performing external work beyond local attribute assignment.

Source code in gpt.py
def __init__( self ):
	"""Initialize instance.

	Purpose:
		Initializes the GPT object with default configuration, runtime state, provider
		settings,
		and compatibility fields. This constructor prepares the instance for later method calls
		without performing external work beyond local attribute assignment.
	"""
	self.api_key = cfg.OPENAI_API_KEY
	self.model = None
	self.client = None
	self.number = None
	self.stops = [ ]
	self.response_format = { }
	self.number = None
	self.temperature = None
	self.top_percent = None
	self.frequency_penalty = None
	self.presence_penalty = None
	self.max_tokens = None
	self.prompt = None
	self.store = None
	self.stream = None
	self.background = None
	self.instructions = None
	self.context = [ ]

Chat

Bases: GPT

Provide OpenAI Responses API text-generation support.

Purpose

Provides the OpenAI Responses API implementation used by Text mode. The class stores request arguments as object members, constructs provider-specific input, tool, response- format, reasoning, and continuation payloads, executes synchronous or streaming requests, and exposes response text and usage information to the application.

Attributes:

Name Type Description
include List[str]

Additional response fields requested from the provider.

tool_choice str

Tool-selection behavior used by the request.

previous_id str

Previous response identifier used for continuation.

conversation_id str

Conversation identifier used for continuation.

parallel_tools bool

Indicates whether parallel tool calls are permitted.

max_tools int

Maximum number of built-in tool calls permitted.

input List[Dict[str, Any]]

Input messages sent to the provider.

tools List[Dict[str, Any]]

Provider-ready tool definitions.

reasoning Dict[str, str]

Provider-ready reasoning configuration.

allowed_domains List[str]

Domains allowed by the web-search tool.

output_text str

Text extracted from the latest response.

vector_store_ids List[str]

Vector store identifiers used by file search.

response Optional[Response]

Latest OpenAI response object.

Source code in gpt.py
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
class Chat( GPT ):
	"""Provide OpenAI Responses API text-generation support.

	Purpose:
		Provides the OpenAI Responses API implementation used by Text mode. The class stores
		request arguments as object members, constructs provider-specific input, tool, response-
		format, reasoning, and continuation payloads, executes synchronous or streaming requests,
		and exposes response text and usage information to the application.

	Attributes:
		include (List[str]): Additional response fields requested from the provider.
		tool_choice (str): Tool-selection behavior used by the request.
		previous_id (str): Previous response identifier used for continuation.
		conversation_id (str): Conversation identifier used for continuation.
		parallel_tools (bool): Indicates whether parallel tool calls are permitted.
		max_tools (int): Maximum number of built-in tool calls permitted.
		input (List[Dict[str, Any]]): Input messages sent to the provider.
		tools (List[Dict[str, Any]]): Provider-ready tool definitions.
		reasoning (Dict[str, str]): Provider-ready reasoning configuration.
		allowed_domains (List[str]): Domains allowed by the web-search tool.
		output_text (str): Text extracted from the latest response.
		vector_store_ids (List[str]): Vector store identifiers used by file search.
		response (Optional[Response]): Latest OpenAI response object.
	"""
	include: List[ str ]
	tool_choice: str
	previous_id: str
	conversation_id: str
	parallel_tools: bool
	max_tools: int
	input: List[ Dict[ str, Any ] ]
	tools: List[ Dict[ str, Any ] ]
	reasoning: Dict[ str, str ]
	allowed_domains: List[ str ]
	output_text: str
	vector_store_ids: List[ str ]
	response: Optional[ Response ]

	def __init__( self, model: str = 'gpt-5-nano', prompt: str = '', temperature: float = 0.0,
		top_p: float = 0.0, frequency: float = 0.0, presence: float = 0.0, max_tokens: int = 0,
		max_tools: int = 0, store: bool = False, stream: bool = False, background: bool = False,
		is_parallel: bool = False, instruct: str = '', tool_choice: str = '', previous_id: str =
		'',
		conversation_id: str = '', reasoning: str = '',
		response_format: Optional[ Dict[ str, Any ] ] = None,
		context: Optional[ List[ Dict[ str, Any ] ] ] = None,
		allowed_domains: Optional[ List[ str ] ] = None, include: Optional[ List[ str ] ] = None,
		tools: Optional[ List[ str | Dict[ str, Any ] ] ] = None,
		input_data: Optional[ List[ Dict[ str, Any ] ] ] = None,
		vector_store_ids: Optional[ List[ str ] ] = None ) -> None:
		"""Initialize instance.

		Purpose:
			Initializes the OpenAI Chat wrapper with explicit defaults and provider-request
			state. The constructor performs local assignment only and does not execute an API
			request.

		Args:
			model (str): OpenAI model identifier.
			prompt (str): User prompt retained for a later request.
			temperature (float): Sampling temperature retained for supported models.
			top_p (float): Nucleus-sampling value retained for supported models.
			frequency (float): Frequency penalty retained for supported models.
			presence (float): Presence penalty retained for supported models.
			max_tokens (int): Maximum output-token count.
			max_tools (int): Maximum number of built-in tool calls.
			store (bool): Indicates whether the response should be stored.
			stream (bool): Indicates whether response events should be streamed.
			background (bool): Indicates whether the response should run in background mode.
			is_parallel (bool): Indicates whether parallel tool calls are permitted.
			instruct (str): System or developer instructions.
			tool_choice (str): Tool-selection behavior.
			previous_id (str): Previous response identifier.
			conversation_id (str): Conversation identifier.
			reasoning (str): Reasoning effort.
			response_format (Optional[Dict[str, Any]]): Text-format configuration.
			context (Optional[List[Dict[str, Any]]]): Prior application messages.
			allowed_domains (Optional[List[str]]): Domains allowed by web search.
			include (Optional[List[str]]): Additional response fields to include.
			tools (Optional[List[str | Dict[str, Any]]]): Selected provider tools.
			input_data (Optional[List[Dict[str, Any]]]): Prebuilt Responses API input items.
			vector_store_ids (Optional[List[str]]): Vector stores used by file search.

		Returns:
			None: This method initializes object state.
		"""
		super( ).__init__( )
		self.api_key = cfg.OPENAI_API_KEY
		self.client = None
		self.model = model
		self.prompt = prompt
		self.temperature = temperature
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.max_tools = max_tools
		self.store = store
		self.stream = stream
		self.background = background
		self.parallel_tools = is_parallel
		self.instructions = instruct
		self.tool_choice = tool_choice
		self.previous_id = previous_id
		self.conversation_id = conversation_id
		self.reasoning_effort = reasoning
		self.reasoning = { }
		self.response_format = response_format if response_format is not None else { }
		self.context = context if context is not None else [ ]
		self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
		self.include = include if include is not None else [ ]
		self.selected_tools = tools if tools is not None else [ ]
		self.tools = [ ]
		self.input = input_data if input_data is not None else [ ]
		self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]
		self.response = None
		self.output_text = ''
		self.request = { }
		self.messages = [ ]
		self.stream_events = [ ]
		self.response_stream = None
		self.requested_format = None
		self.effective_context = [ ]
		self.vector_stores = { 'Governance': 'vs_6a1850a9bdc08191912353eedf59aede',
			'Public Laws': 'vs_699506f7d5348191990e0557c717fa9d',
			'Explanatory Statements': 'vs_699505df9ac48191a525c0ecb86fef66',
			'Army Techniques Publications': 'vs_699356ef052c81918da14c4ed3bcea17',
			'Army Field Manuals': 'vs_69935542863481918d150c1e89c38633',
			'Army Regulations': 'vs_6993550488408191919cd70968ba8be8',
			'DoD Armory': 'vs_697f86ad98888191b967685ae558bfc0',
			'Army Style Guides': 'vs_68f4efd7d4c4819191458dd6cde6f2cc',
			'Apportionments': 'vs_68a34aaff93481918c3b3fef8c4e8fea',
			'Financial Regulations': 'vs_712r5W5833G6aLxIYIbuvVcK', }
		self.files = { 'Account_Balances.csv': 'file-U6wFeRGSeg38Db5uJzo5sj',
			'SF133.csv': 'file-WT2h2F5SNxqK2CxyAMSDg6',
			'Authority.csv': 'file-Qi2rw2QsdxKBX1iiaQxY3m',
			'Outlays.csv': 'file-GHEwSWR7ezMvHrQ3X648wn', }

	@property
	def model_options( self ) -> List[ str ]:
		"""Get model options.

		Purpose:
			Returns model identifiers exposed to the application for OpenAI Text mode.

		Returns:
			List[str]: Available OpenAI text-generation models.
		"""
		return [ 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.4-nano', 'gpt-5.1', 'gpt-5', 'gpt-5-mini',
			'gpt-5-nano', 'gpt-4.1', 'gpt-4.1-mini', 'gpt-4.1-nano', 'gpt-4o', 'gpt-4o-mini', ]

	@property
	def include_options( self ) -> List[ str ]:
		"""Get include options.

		Purpose:
			Returns additional response fields supported by the Responses API workflow.

		Returns:
			List[str]: Supported include-path values.
		"""
		return [ 'file_search_call.results', 'web_search_call.action.sources',
			'code_interpreter_call.outputs', 'reasoning.encrypted_content',
			'message.output_text.logprobs', ]

	@property
	def tool_options( self ) -> List[ str ]:
		"""Get tool options.

		Purpose:
			Returns built-in tools implemented by this wrapper.

		Returns:
			List[str]: Supported built-in tool names.
		"""
		return [ 'web_search', 'file_search', ]

	@property
	def choice_options( self ) -> List[ str ]:
		"""Get tool-choice options.

		Purpose:
			Returns tool-selection values accepted by the Responses API workflow.

		Returns:
			List[str]: Supported tool-choice values.
		"""
		return [ 'auto', 'required', 'none', ]

	@property
	def purpose_options( self ) -> List[ str ]:
		"""Get file-purpose options.

		Purpose:
			Returns file-purpose values retained for compatibility with file workflows.

		Returns:
			List[str]: Supported file-purpose values.
		"""
		return [ 'assistants', 'batch', 'fine-tune', 'vision', 'user_data', 'evals', ]

	@property
	def format_options( self ) -> List[ str ]:
		"""Get response-format options.

		Purpose:
			Returns text-format values implemented by the Responses API request builder.

		Returns:
			List[str]: Supported response-format values.
		"""
		return [ 'text', 'json_object', 'json_schema', ]

	@property
	def reasoning_options( self ) -> List[ str ]:
		"""Get reasoning options.

		Purpose:
			Returns reasoning-effort values supported by current OpenAI reasoning models.

		Returns:
			List[str]: Supported reasoning-effort values.
		"""
		return [ 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', ]

	@property
	def modality_options( self ) -> List[ str ]:
		"""Get modality options.

		Purpose:
			Returns the output modality implemented by the Text-mode wrapper.

		Returns:
			List[str]: Supported output modalities.
		"""
		return [ 'text' ]

	def supports_reasoning_model( self, model: str = '' ) -> bool:
		"""Determine reasoning-model support.

		Purpose:
			Determines whether the selected model accepts a Responses API reasoning object.

		Args:
			model (str): Model identifier to inspect.

		Returns:
			bool: True when the model supports reasoning configuration.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.model = model if model else self.model
			return self.model.startswith( 'gpt-5' ) or self.model.startswith( 'o' )
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = 'supports_reasoning_model( self, model: str = "" ) -> bool'
			Logger( ).write( ex )
			raise ex

	def build_reasoning( self, reasoning: str = '', model: str = '' ) -> Dict[ str, str ]:
		"""Build reasoning configuration.

		Purpose:
			Builds the provider-ready reasoning object for a supported model and effort value.

		Args:
			reasoning (str): Requested reasoning effort.
			model (str): OpenAI model identifier.

		Returns:
			Dict[str, str]: Provider-ready reasoning configuration or an empty dictionary.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.reasoning_effort = reasoning
			self.model = model if model else self.model
			self.reasoning = { }

			if not self.reasoning_effort:
				return self.reasoning

			if self.reasoning_effort == 'none':
				return self.reasoning

			if not self.supports_reasoning_model( self.model ):
				return self.reasoning

			if self.reasoning_effort not in self.reasoning_options:
				return self.reasoning

			if self.model.startswith( 'gpt-5.1' ):
				if self.reasoning_effort in [ 'minimal', 'xhigh' ]:
					return self.reasoning

			if self.reasoning_effort == 'xhigh':
				if not self.model.startswith( 'gpt-5.4' ):
					self.reasoning_effort = 'high'

			self.reasoning = { 'effort': self.reasoning_effort, }
			return self.reasoning
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = ('build_reasoning( self, reasoning: str = "", '
			             'model: str = "" ) -> Dict[ str, str ]')
			Logger( ).write( ex )
			raise ex

	def build_input( self, prompt: str, context: Optional[ List[ Dict[ str, Any ] ] ] = None,
		input_data: Optional[ List[ Dict[ str, Any ] ] ] = None ) -> List[ Dict[ str, Any ] ]:
		"""Build input messages.

		Purpose:
			Builds Responses API input items from prebuilt input data or application history and
			appends the current user prompt.

		Args:
			prompt (str): Current user prompt.
			context (Optional[List[Dict[str, Any]]]): Prior application messages.
			input_data (Optional[List[Dict[str, Any]]]): Prebuilt Responses API input items.

		Returns:
			List[Dict[str, Any]]: Provider-ready Responses API input items.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			self.prompt = prompt
			self.context = context if context is not None else [ ]
			self.input = input_data if input_data is not None else [ ]
			self.messages = [ ]

			if self.input:
				self.messages.extend( self.input )
			else:
				for item in self.context:
					if not isinstance( item, dict ):
						continue

					self.message_role = item.get( 'role', '' )
					self.message_content = item.get( 'content', '' )

					if self.message_role not in [ 'user', 'assistant', 'system', 'developer', ]:
						continue

					if not self.message_content:
						continue

					self.messages.append( { 'role': self.message_role,
						'content': [ { 'type': 'input_text', 'text': self.message_content, }, ],
					} )

			self.messages.append( { 'role': 'user',
				'content': [ { 'type': 'input_text', 'text': self.prompt, }, ], } )
			self.input = self.messages
			return self.input
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = ('build_input( self, prompt: str, context: Optional[ List[ '
			             'Dict[ str, Any ] ] ] = None, input_data: Optional[ List[ '
			             'Dict[ str, Any ] ] ] = None ) -> List[ Dict[ str, Any ] ]')
			Logger( ).write( ex )
			raise ex

	def build_tools( self, tools: Optional[ List[ str | Dict[ str, Any ] ] ] = None,
		allowed_domains: Optional[ List[ str ] ] = None,
		vector_store_ids: Optional[ List[ str ] ] = None ) -> List[ Dict[ str, Any ] ]:
		"""Build tool definitions.

		Purpose:
			Builds OpenAI web-search and file-search tool definitions from application-selected
			tool names.

		Args:
			tools (Optional[List[str | Dict[str, Any]]]): Selected provider tools.
			allowed_domains (Optional[List[str]]): Domains permitted by web search.
			vector_store_ids (Optional[List[str]]): Vector stores used by file search.

		Returns:
			List[Dict[str, Any]]: Provider-ready OpenAI tool definitions.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.selected_tools = tools if tools is not None else [ ]
			self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
			self.vector_store_ids = (vector_store_ids if vector_store_ids is not None else [ ])
			self.tools = [ ]

			for selected_tool in self.selected_tools:
				if isinstance( selected_tool, dict ):
					self.tool_name = selected_tool.get( 'type', '' )
				else:
					self.tool_name = selected_tool

				if self.tool_name in [ 'web_search', 'web_search_preview',
					'web_search_preview_2025_03_11', ]:
					self.web_search_tool = { 'type': 'web_search', }

					if self.allowed_domains:
						self.web_search_tool[ 'filters' ] = {
							'allowed_domains': self.allowed_domains, }

					self.tools.append( self.web_search_tool )
					continue

				if self.tool_name == 'file_search':
					throw_if( 'vector_store_ids', self.vector_store_ids )
					self.tools.append(
						{ 'type': 'file_search', 'vector_store_ids': self.vector_store_ids, } )

			return self.tools
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = ('build_tools( self, tools: Optional[ List[ str | Dict[ str, '
			             'Any ] ] ] = None, allowed_domains: Optional[ List[ str ] ] = '
			             'None, vector_store_ids: Optional[ List[ str ] ] = None ) -> '
			             'List[ Dict[ str, Any ] ]')
			Logger( ).write( ex )
			raise ex

	def build_text_format( self, format: Optional[ Dict[ str, Any ] | str ] = None ) -> Dict[
		str, Any ]:
		"""Build text-format configuration.

		Purpose:
			Builds the Responses API text-format object from a supported format name or a
			complete provider-ready format dictionary.

		Args:
			format (Optional[Dict[str, Any] | str]): Requested response format.

		Returns:
			Dict[str, Any]: Provider-ready text configuration or an empty dictionary.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.requested_format = format
			self.response_format = { }

			if self.requested_format is None:
				return self.response_format

			if isinstance( self.requested_format, dict ):
				if 'format' in self.requested_format:
					self.response_format = self.requested_format
					return self.response_format

				if 'type' in self.requested_format:
					self.response_format = { 'format': self.requested_format, }
					return self.response_format

				return self.response_format

			if self.requested_format == 'text':
				self.response_format = { 'format': { 'type': 'text', }, }
				return self.response_format

			if self.requested_format == 'json_object':
				self.response_format = { 'format': { 'type': 'json_object', }, }
				return self.response_format

			return self.response_format
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = ('build_text_format( self, format: Optional[ Dict[ str, Any ] '
			             '| str ] = None ) -> Dict[ str, Any ]')
			Logger( ).write( ex )
			raise ex

	def build_request( self, prompt: str, model: str, temperature: float = 0.0,
		format: Optional[ Dict[ str, Any ] | str ] = None, top_p: float = 0.0,
		frequency: float = 0.0, max_tools: int = 0, presence: float = 0.0, max_tokens: int = 0,
		store: bool = False, stream: bool = False, instruct: str = '', background: bool = False,
		reasoning: str = '', include: Optional[ List[ str ] ] = None,
		tools: Optional[ List[ str | Dict[ str, Any ] ] ] = None,
		allowed_domains: Optional[ List[ str ] ] = None, previous_id: str = '',
		tool_choice: str = '', is_parallel: bool = False,
		context: Optional[ List[ Dict[ str, Any ] ] ] = None,
		input_data: Optional[ List[ Dict[ str, Any ] ] ] = None,
		vector_store_ids: Optional[ List[ str ] ] = None, conversation_id: str = '' ) -> Dict[
		str, Any ]:
		"""Build request.

		Purpose:
			Builds the complete OpenAI Responses API request from values assigned to object
			members.

		Args:
			prompt (str): Current user prompt.
			model (str): OpenAI model identifier.
			temperature (float): Sampling temperature for supported models.
			format (Optional[Dict[str, Any] | str]): Text-format configuration.
			top_p (float): Nucleus-sampling value for supported models.
			frequency (float): Frequency penalty for supported models.
			max_tools (int): Maximum number of built-in tool calls.
			presence (float): Presence penalty for supported models.
			max_tokens (int): Maximum output-token count.
			store (bool): Indicates whether the response should be stored.
			stream (bool): Indicates whether response events should be streamed.
			instruct (str): System or developer instructions.
			background (bool): Indicates whether the response runs in background mode.
			reasoning (str): Reasoning effort.
			include (Optional[List[str]]): Additional response fields to include.
			tools (Optional[List[str | Dict[str, Any]]]): Selected provider tools.
			allowed_domains (Optional[List[str]]): Domains allowed by web search.
			previous_id (str): Previous response identifier.
			tool_choice (str): Tool-selection behavior.
			is_parallel (bool): Indicates whether parallel tool calls are permitted.
			context (Optional[List[Dict[str, Any]]]): Prior application messages.
			input_data (Optional[List[Dict[str, Any]]]): Prebuilt Responses API input items.
			vector_store_ids (Optional[List[str]]): Vector stores used by file search.
			conversation_id (str): Conversation identifier.

		Returns:
			Dict[str, Any]: Provider-ready Responses API request.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.prompt = prompt
			self.model = model
			self.temperature = temperature
			self.requested_format = format
			self.top_percent = top_p
			self.frequency_penalty = frequency
			self.max_tools = max_tools
			self.presence_penalty = presence
			self.max_tokens = max_tokens
			self.store = store
			self.stream = stream
			self.instructions = instruct
			self.background = background
			self.reasoning_effort = reasoning
			self.include = include if include is not None else [ ]
			self.selected_tools = tools if tools is not None else [ ]
			self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
			self.previous_id = previous_id
			self.tool_choice = tool_choice
			self.parallel_tools = is_parallel
			self.context = context if context is not None else [ ]
			self.input = input_data if input_data is not None else [ ]
			self.vector_store_ids = (vector_store_ids if vector_store_ids is not None else [ ])
			self.conversation_id = conversation_id
			self.reasoning = self.build_reasoning( self.reasoning_effort, self.model, )
			self.tools = self.build_tools( self.selected_tools, self.allowed_domains,
				self.vector_store_ids, )
			self.response_format = self.build_text_format( self.requested_format, )
			self.effective_context = ([ ] if self.conversation_id else self.context)
			self.input = self.build_input( self.prompt, self.effective_context, self.input, )
			self.request = { 'model': self.model, 'input': self.input, }

			if self.instructions:
				self.request[ 'instructions' ] = self.instructions

			if self.reasoning:
				self.request[ 'reasoning' ] = self.reasoning

			if self.max_tokens > 0:
				self.request[ 'max_output_tokens' ] = self.max_tokens

			if not self.model.startswith( 'gpt-5' ):
				self.request[ 'temperature' ] = self.temperature
				self.request[ 'top_p' ] = self.top_percent
				self.request[ 'frequency_penalty' ] = self.frequency_penalty
				self.request[ 'presence_penalty' ] = self.presence_penalty

			self.request[ 'store' ] = self.store
			self.request[ 'stream' ] = self.stream
			self.request[ 'background' ] = self.background

			if self.include:
				self.request[ 'include' ] = self.include

			if self.tools:
				self.request[ 'tools' ] = self.tools
				self.request[ 'parallel_tool_calls' ] = self.parallel_tools

				if self.max_tools > 0:
					self.request[ 'max_tool_calls' ] = self.max_tools

			if self.tool_choice:
				self.request[ 'tool_choice' ] = self.tool_choice

			if self.previous_id:
				self.request[ 'previous_response_id' ] = self.previous_id

			if self.conversation_id:
				self.request[ 'conversation' ] = self.conversation_id

			if self.response_format:
				self.request[ 'text' ] = self.response_format

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = ('build_request( self, prompt: str, model: str, '
			             'temperature: float = 0.0, format: Optional[ Dict[ str, Any ] '
			             '| str ] = None, top_p: float = 0.0, frequency: float = 0.0, '
			             'max_tools: int = 0, presence: float = 0.0, max_tokens: int = '
			             '0, store: bool = False, stream: bool = False, instruct: str '
			             '= "", background: bool = False, reasoning: str = "", '
			             'include: Optional[ List[ str ] ] = None, tools: Optional[ '
			             'List[ str | Dict[ str, Any ] ] ] = None, allowed_domains: '
			             'Optional[ List[ str ] ] = None, previous_id: str = "", '
			             'tool_choice: str = "", is_parallel: bool = False, context: '
			             'Optional[ List[ Dict[ str, Any ] ] ] = None, input_data: '
			             'Optional[ List[ Dict[ str, Any ] ] ] = None, '
			             'vector_store_ids: Optional[ List[ str ] ] = None, '
			             'conversation_id: str = "" ) -> Dict[ str, Any ]')
			Logger( ).write( ex )
			raise ex

	def get_output_text( self ) -> str:
		"""Get output text.

		Purpose:
			Extracts aggregated text from the latest synchronous or completed background response.

		Returns:
			str: Extracted response text or an empty string.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.output_text = ''

			if self.response is None:
				return self.output_text

			self.response_text = getattr( self.response, 'output_text', '' )

			if self.response_text:
				self.output_text = self.response_text
				return self.output_text

			self.text_parts = [ ]

			for item in getattr( self.response, 'output', [ ] ) or [ ]:
				if getattr( item, 'type', '' ) != 'message':
					continue

				for block in getattr( item, 'content', [ ] ) or [ ]:
					if getattr( block, 'type', '' ) != 'output_text':
						continue

					self.block_text = getattr( block, 'text', '' )

					if self.block_text:
						self.text_parts.append( self.block_text )

			self.output_text = ''.join( self.text_parts ).strip( )
			return self.output_text
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = 'get_output_text( self ) -> str'
			Logger( ).write( ex )
			raise ex

	def get_usage( self ) -> Any:
		"""Get response usage.

		Purpose:
			Returns token usage from the latest completed response.

		Returns:
			Any: Provider usage object or None when unavailable.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			if self.response is None:
				return None

			return getattr( self.response, 'usage', None )
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = 'get_usage( self ) -> Any'
			Logger( ).write( ex )
			raise ex

	def generate_text( self, prompt: str, model: str, temperature: float = 0.0,
		format: Optional[ Dict[ str, Any ] | str ] = None, top_p: float = 0.0,
		frequency: float = 0.0, max_tools: int = 0, presence: float = 0.0, max_tokens: int = 0,
		store: bool = False, stream: bool = False, instruct: str = '', background: bool = False,
		reasoning: str = '', include: Optional[ List[ str ] ] = None,
		tools: Optional[ List[ str | Dict[ str, Any ] ] ] = None,
		allowed_domains: Optional[ List[ str ] ] = None, previous_id: str = '',
		tool_choice: str = '', is_parallel: bool = False,
		context: Optional[ List[ Dict[ str, Any ] ] ] = None,
		input_data: Optional[ List[ Dict[ str, Any ] ] ] = None,
		vector_store_ids: Optional[ List[ str ] ] = None, conversation_id: str = '' ) -> str:
		"""Generate text.

		Purpose:
			Executes a synchronous, streaming, or background OpenAI Responses API request using
			arguments assigned to wrapper members.

		Args:
			prompt (str): Current user prompt.
			model (str): OpenAI model identifier.
			temperature (float): Sampling temperature for supported models.
			format (Optional[Dict[str, Any] | str]): Text-format configuration.
			top_p (float): Nucleus-sampling value for supported models.
			frequency (float): Frequency penalty for supported models.
			max_tools (int): Maximum number of built-in tool calls.
			presence (float): Presence penalty for supported models.
			max_tokens (int): Maximum output-token count.
			store (bool): Indicates whether the response should be stored.
			stream (bool): Indicates whether response events should be streamed.
			instruct (str): System or developer instructions.
			background (bool): Indicates whether the response runs in background mode.
			reasoning (str): Reasoning effort.
			include (Optional[List[str]]): Additional response fields to include.
			tools (Optional[List[str | Dict[str, Any]]]): Selected provider tools.
			allowed_domains (Optional[List[str]]): Domains allowed by web search.
			previous_id (str): Previous response identifier.
			tool_choice (str): Tool-selection behavior.
			is_parallel (bool): Indicates whether parallel tool calls are permitted.
			context (Optional[List[Dict[str, Any]]]): Prior application messages.
			input_data (Optional[List[Dict[str, Any]]]): Prebuilt Responses API input items.
			vector_store_ids (Optional[List[str]]): Vector stores used by file search.
			conversation_id (str): Conversation identifier.

		Returns:
			str: Generated text, streamed text, or an empty string for an incomplete background
			response.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.prompt = prompt
			self.model = model
			self.temperature = temperature
			self.requested_format = format
			self.top_percent = top_p
			self.frequency_penalty = frequency
			self.max_tools = max_tools
			self.presence_penalty = presence
			self.max_tokens = max_tokens
			self.store = store
			self.stream = stream
			self.instructions = instruct
			self.background = background
			self.reasoning_effort = reasoning
			self.include = include if include is not None else [ ]
			self.selected_tools = tools if tools is not None else [ ]
			self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
			self.previous_id = previous_id
			self.tool_choice = tool_choice
			self.parallel_tools = is_parallel
			self.context = context if context is not None else [ ]
			self.input = input_data if input_data is not None else [ ]
			self.vector_store_ids = (vector_store_ids if vector_store_ids is not None else [ ])
			self.conversation_id = conversation_id
			self.client = OpenAI( api_key=self.api_key, )
			self.request = self.build_request( self.prompt, self.model, self.temperature,
				self.requested_format, self.top_percent, self.frequency_penalty, self.max_tools,
				self.presence_penalty, self.max_tokens, self.store, self.stream, self.instructions,
				self.background, self.reasoning_effort, self.include, self.selected_tools,
				self.allowed_domains, self.previous_id, self.tool_choice, self.parallel_tools,
				self.context, self.input, self.vector_store_ids, self.conversation_id, )

			if self.stream:
				self.stream_events = [ ]
				self.text_parts = [ ]
				self.response_stream = self.client.responses.create( **self.request )

				for event in self.response_stream:
					self.stream_events.append( event )
					self.event_type = getattr( event, 'type', '' )

					if self.event_type == 'response.output_text.delta':
						self.delta = getattr( event, 'delta', '' )

						if self.delta:
							self.text_parts.append( self.delta )

					elif self.event_type == 'response.completed':
						self.response = getattr( event, 'response', None )

				self.output_text = ''.join( self.text_parts ).strip( )

				if self.response is not None:
					self.previous_id = getattr( self.response, 'id', self.previous_id, )

				return self.output_text

			self.response = self.client.responses.create( **self.request )
			self.previous_id = getattr( self.response, 'id', self.previous_id, )
			self.output_text = self.get_output_text( )
			return self.output_text
		except Exception as e:
			ex = Error( e )
			ex.module = 'gpt'
			ex.cause = 'Chat'
			ex.method = ('generate_text( self, prompt: str, model: str, temperature: '
			             'float = 0.0, format: Optional[ Dict[ str, Any ] | str ] = '
			             'None, top_p: float = 0.0, frequency: float = 0.0, max_tools: '
			             'int = 0, presence: float = 0.0, max_tokens: int = 0, store: '
			             'bool = False, stream: bool = False, instruct: str = "", '
			             'background: bool = False, reasoning: str = "", include: '
			             'Optional[ List[ str ] ] = None, tools: Optional[ List[ str | '
			             'Dict[ str, Any ] ] ] = None, allowed_domains: Optional[ '
			             'List[ str ] ] = None, previous_id: str = "", tool_choice: str '
			             '= "", is_parallel: bool = False, context: Optional[ List[ '
			             'Dict[ str, Any ] ] ] = None, input_data: Optional[ List[ '
			             'Dict[ str, Any ] ] ] = None, vector_store_ids: Optional[ '
			             'List[ str ] ] = None, conversation_id: str = "" ) -> str')
			Logger( ).write( ex )
			raise ex

	def __dir__( self ) -> List[ str ]:
		"""Return member names.

		Purpose:
			Returns public members exposed by the OpenAI Chat wrapper.

		Returns:
			List[str]: Public member names.
		"""
		return [ 'api_key', 'client', 'model', 'prompt', 'temperature', 'top_percent',
			'frequency_penalty', 'presence_penalty', 'max_tokens', 'store', 'stream', 'background',
			'response_format', 'context', 'instructions', 'include', 'tool_choice', 'previous_id',
			'conversation_id', 'parallel_tools', 'max_tools', 'input', 'tools', 'reasoning',
			'allowed_domains', 'output_text', 'vector_store_ids', 'response', 'model_options',
			'include_options', 'tool_options', 'choice_options', 'purpose_options',
			'format_options', 'reasoning_options', 'modality_options', 'supports_reasoning_model',
			'build_reasoning', 'build_input', 'build_tools', 'build_text_format', 'build_request',
			'get_output_text', 'get_usage', 'generate_text', ]

model_options property

model_options: List[str]

Get model options.

Purpose

Returns model identifiers exposed to the application for OpenAI Text mode.

Returns:

Type Description
List[str]

List[str]: Available OpenAI text-generation models.

include_options property

include_options: List[str]

Get include options.

Purpose

Returns additional response fields supported by the Responses API workflow.

Returns:

Type Description
List[str]

List[str]: Supported include-path values.

tool_options property

tool_options: List[str]

Get tool options.

Purpose

Returns built-in tools implemented by this wrapper.

Returns:

Type Description
List[str]

List[str]: Supported built-in tool names.

choice_options property

choice_options: List[str]

Get tool-choice options.

Purpose

Returns tool-selection values accepted by the Responses API workflow.

Returns:

Type Description
List[str]

List[str]: Supported tool-choice values.

purpose_options property

purpose_options: List[str]

Get file-purpose options.

Purpose

Returns file-purpose values retained for compatibility with file workflows.

Returns:

Type Description
List[str]

List[str]: Supported file-purpose values.

format_options property

format_options: List[str]

Get response-format options.

Purpose

Returns text-format values implemented by the Responses API request builder.

Returns:

Type Description
List[str]

List[str]: Supported response-format values.

reasoning_options property

reasoning_options: List[str]

Get reasoning options.

Purpose

Returns reasoning-effort values supported by current OpenAI reasoning models.

Returns:

Type Description
List[str]

List[str]: Supported reasoning-effort values.

modality_options property

modality_options: List[str]

Get modality options.

Purpose

Returns the output modality implemented by the Text-mode wrapper.

Returns:

Type Description
List[str]

List[str]: Supported output modalities.

__init__

__init__(
    model: str = "gpt-5-nano",
    prompt: str = "",
    temperature: float = 0.0,
    top_p: float = 0.0,
    frequency: float = 0.0,
    presence: float = 0.0,
    max_tokens: int = 0,
    max_tools: int = 0,
    store: bool = False,
    stream: bool = False,
    background: bool = False,
    is_parallel: bool = False,
    instruct: str = "",
    tool_choice: str = "",
    previous_id: str = "",
    conversation_id: str = "",
    reasoning: str = "",
    response_format: Optional[Dict[str, Any]] = None,
    context: Optional[List[Dict[str, Any]]] = None,
    allowed_domains: Optional[List[str]] = None,
    include: Optional[List[str]] = None,
    tools: Optional[List[str | Dict[str, Any]]] = None,
    input_data: Optional[List[Dict[str, Any]]] = None,
    vector_store_ids: Optional[List[str]] = None,
) -> None

Initialize instance.

Purpose

Initializes the OpenAI Chat wrapper with explicit defaults and provider-request state. The constructor performs local assignment only and does not execute an API request.

Parameters:

Name Type Description Default
model str

OpenAI model identifier.

'gpt-5-nano'
prompt str

User prompt retained for a later request.

''
temperature float

Sampling temperature retained for supported models.

0.0
top_p float

Nucleus-sampling value retained for supported models.

0.0
frequency float

Frequency penalty retained for supported models.

0.0
presence float

Presence penalty retained for supported models.

0.0
max_tokens int

Maximum output-token count.

0
max_tools int

Maximum number of built-in tool calls.

0
store bool

Indicates whether the response should be stored.

False
stream bool

Indicates whether response events should be streamed.

False
background bool

Indicates whether the response should run in background mode.

False
is_parallel bool

Indicates whether parallel tool calls are permitted.

False
instruct str

System or developer instructions.

''
tool_choice str

Tool-selection behavior.

''
previous_id str

Previous response identifier.

''
conversation_id str

Conversation identifier.

''
reasoning str

Reasoning effort.

''
response_format Optional[Dict[str, Any]]

Text-format configuration.

None
context Optional[List[Dict[str, Any]]]

Prior application messages.

None
allowed_domains Optional[List[str]]

Domains allowed by web search.

None
include Optional[List[str]]

Additional response fields to include.

None
tools Optional[List[str | Dict[str, Any]]]

Selected provider tools.

None
input_data Optional[List[Dict[str, Any]]]

Prebuilt Responses API input items.

None
vector_store_ids Optional[List[str]]

Vector stores used by file search.

None

Returns:

Name Type Description
None None

This method initializes object state.

Source code in gpt.py
def __init__( self, model: str = 'gpt-5-nano', prompt: str = '', temperature: float = 0.0,
	top_p: float = 0.0, frequency: float = 0.0, presence: float = 0.0, max_tokens: int = 0,
	max_tools: int = 0, store: bool = False, stream: bool = False, background: bool = False,
	is_parallel: bool = False, instruct: str = '', tool_choice: str = '', previous_id: str =
	'',
	conversation_id: str = '', reasoning: str = '',
	response_format: Optional[ Dict[ str, Any ] ] = None,
	context: Optional[ List[ Dict[ str, Any ] ] ] = None,
	allowed_domains: Optional[ List[ str ] ] = None, include: Optional[ List[ str ] ] = None,
	tools: Optional[ List[ str | Dict[ str, Any ] ] ] = None,
	input_data: Optional[ List[ Dict[ str, Any ] ] ] = None,
	vector_store_ids: Optional[ List[ str ] ] = None ) -> None:
	"""Initialize instance.

	Purpose:
		Initializes the OpenAI Chat wrapper with explicit defaults and provider-request
		state. The constructor performs local assignment only and does not execute an API
		request.

	Args:
		model (str): OpenAI model identifier.
		prompt (str): User prompt retained for a later request.
		temperature (float): Sampling temperature retained for supported models.
		top_p (float): Nucleus-sampling value retained for supported models.
		frequency (float): Frequency penalty retained for supported models.
		presence (float): Presence penalty retained for supported models.
		max_tokens (int): Maximum output-token count.
		max_tools (int): Maximum number of built-in tool calls.
		store (bool): Indicates whether the response should be stored.
		stream (bool): Indicates whether response events should be streamed.
		background (bool): Indicates whether the response should run in background mode.
		is_parallel (bool): Indicates whether parallel tool calls are permitted.
		instruct (str): System or developer instructions.
		tool_choice (str): Tool-selection behavior.
		previous_id (str): Previous response identifier.
		conversation_id (str): Conversation identifier.
		reasoning (str): Reasoning effort.
		response_format (Optional[Dict[str, Any]]): Text-format configuration.
		context (Optional[List[Dict[str, Any]]]): Prior application messages.
		allowed_domains (Optional[List[str]]): Domains allowed by web search.
		include (Optional[List[str]]): Additional response fields to include.
		tools (Optional[List[str | Dict[str, Any]]]): Selected provider tools.
		input_data (Optional[List[Dict[str, Any]]]): Prebuilt Responses API input items.
		vector_store_ids (Optional[List[str]]): Vector stores used by file search.

	Returns:
		None: This method initializes object state.
	"""
	super( ).__init__( )
	self.api_key = cfg.OPENAI_API_KEY
	self.client = None
	self.model = model
	self.prompt = prompt
	self.temperature = temperature
	self.top_percent = top_p
	self.frequency_penalty = frequency
	self.presence_penalty = presence
	self.max_tokens = max_tokens
	self.max_tools = max_tools
	self.store = store
	self.stream = stream
	self.background = background
	self.parallel_tools = is_parallel
	self.instructions = instruct
	self.tool_choice = tool_choice
	self.previous_id = previous_id
	self.conversation_id = conversation_id
	self.reasoning_effort = reasoning
	self.reasoning = { }
	self.response_format = response_format if response_format is not None else { }
	self.context = context if context is not None else [ ]
	self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
	self.include = include if include is not None else [ ]
	self.selected_tools = tools if tools is not None else [ ]
	self.tools = [ ]
	self.input = input_data if input_data is not None else [ ]
	self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]
	self.response = None
	self.output_text = ''
	self.request = { }
	self.messages = [ ]
	self.stream_events = [ ]
	self.response_stream = None
	self.requested_format = None
	self.effective_context = [ ]
	self.vector_stores = { 'Governance': 'vs_6a1850a9bdc08191912353eedf59aede',
		'Public Laws': 'vs_699506f7d5348191990e0557c717fa9d',
		'Explanatory Statements': 'vs_699505df9ac48191a525c0ecb86fef66',
		'Army Techniques Publications': 'vs_699356ef052c81918da14c4ed3bcea17',
		'Army Field Manuals': 'vs_69935542863481918d150c1e89c38633',
		'Army Regulations': 'vs_6993550488408191919cd70968ba8be8',
		'DoD Armory': 'vs_697f86ad98888191b967685ae558bfc0',
		'Army Style Guides': 'vs_68f4efd7d4c4819191458dd6cde6f2cc',
		'Apportionments': 'vs_68a34aaff93481918c3b3fef8c4e8fea',
		'Financial Regulations': 'vs_712r5W5833G6aLxIYIbuvVcK', }
	self.files = { 'Account_Balances.csv': 'file-U6wFeRGSeg38Db5uJzo5sj',
		'SF133.csv': 'file-WT2h2F5SNxqK2CxyAMSDg6',
		'Authority.csv': 'file-Qi2rw2QsdxKBX1iiaQxY3m',
		'Outlays.csv': 'file-GHEwSWR7ezMvHrQ3X648wn', }

supports_reasoning_model

supports_reasoning_model(model: str = '') -> bool

Determine reasoning-model support.

Purpose

Determines whether the selected model accepts a Responses API reasoning object.

Parameters:

Name Type Description Default
model str

Model identifier to inspect.

''

Returns:

Name Type Description
bool bool

True when the model supports reasoning configuration.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def supports_reasoning_model( self, model: str = '' ) -> bool:
	"""Determine reasoning-model support.

	Purpose:
		Determines whether the selected model accepts a Responses API reasoning object.

	Args:
		model (str): Model identifier to inspect.

	Returns:
		bool: True when the model supports reasoning configuration.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.model = model if model else self.model
		return self.model.startswith( 'gpt-5' ) or self.model.startswith( 'o' )
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = 'supports_reasoning_model( self, model: str = "" ) -> bool'
		Logger( ).write( ex )
		raise ex

build_reasoning

build_reasoning(
    reasoning: str = "", model: str = ""
) -> Dict[str, str]

Build reasoning configuration.

Purpose

Builds the provider-ready reasoning object for a supported model and effort value.

Parameters:

Name Type Description Default
reasoning str

Requested reasoning effort.

''
model str

OpenAI model identifier.

''

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Provider-ready reasoning configuration or an empty dictionary.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def build_reasoning( self, reasoning: str = '', model: str = '' ) -> Dict[ str, str ]:
	"""Build reasoning configuration.

	Purpose:
		Builds the provider-ready reasoning object for a supported model and effort value.

	Args:
		reasoning (str): Requested reasoning effort.
		model (str): OpenAI model identifier.

	Returns:
		Dict[str, str]: Provider-ready reasoning configuration or an empty dictionary.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.reasoning_effort = reasoning
		self.model = model if model else self.model
		self.reasoning = { }

		if not self.reasoning_effort:
			return self.reasoning

		if self.reasoning_effort == 'none':
			return self.reasoning

		if not self.supports_reasoning_model( self.model ):
			return self.reasoning

		if self.reasoning_effort not in self.reasoning_options:
			return self.reasoning

		if self.model.startswith( 'gpt-5.1' ):
			if self.reasoning_effort in [ 'minimal', 'xhigh' ]:
				return self.reasoning

		if self.reasoning_effort == 'xhigh':
			if not self.model.startswith( 'gpt-5.4' ):
				self.reasoning_effort = 'high'

		self.reasoning = { 'effort': self.reasoning_effort, }
		return self.reasoning
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = ('build_reasoning( self, reasoning: str = "", '
		             'model: str = "" ) -> Dict[ str, str ]')
		Logger( ).write( ex )
		raise ex

build_input

build_input(
    prompt: str,
    context: Optional[List[Dict[str, Any]]] = None,
    input_data: Optional[List[Dict[str, Any]]] = None,
) -> List[Dict[str, Any]]

Build input messages.

Purpose

Builds Responses API input items from prebuilt input data or application history and appends the current user prompt.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
context Optional[List[Dict[str, Any]]]

Prior application messages.

None
input_data Optional[List[Dict[str, Any]]]

Prebuilt Responses API input items.

None

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Provider-ready Responses API input items.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def build_input( self, prompt: str, context: Optional[ List[ Dict[ str, Any ] ] ] = None,
	input_data: Optional[ List[ Dict[ str, Any ] ] ] = None ) -> List[ Dict[ str, Any ] ]:
	"""Build input messages.

	Purpose:
		Builds Responses API input items from prebuilt input data or application history and
		appends the current user prompt.

	Args:
		prompt (str): Current user prompt.
		context (Optional[List[Dict[str, Any]]]): Prior application messages.
		input_data (Optional[List[Dict[str, Any]]]): Prebuilt Responses API input items.

	Returns:
		List[Dict[str, Any]]: Provider-ready Responses API input items.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		self.prompt = prompt
		self.context = context if context is not None else [ ]
		self.input = input_data if input_data is not None else [ ]
		self.messages = [ ]

		if self.input:
			self.messages.extend( self.input )
		else:
			for item in self.context:
				if not isinstance( item, dict ):
					continue

				self.message_role = item.get( 'role', '' )
				self.message_content = item.get( 'content', '' )

				if self.message_role not in [ 'user', 'assistant', 'system', 'developer', ]:
					continue

				if not self.message_content:
					continue

				self.messages.append( { 'role': self.message_role,
					'content': [ { 'type': 'input_text', 'text': self.message_content, }, ],
				} )

		self.messages.append( { 'role': 'user',
			'content': [ { 'type': 'input_text', 'text': self.prompt, }, ], } )
		self.input = self.messages
		return self.input
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = ('build_input( self, prompt: str, context: Optional[ List[ '
		             'Dict[ str, Any ] ] ] = None, input_data: Optional[ List[ '
		             'Dict[ str, Any ] ] ] = None ) -> List[ Dict[ str, Any ] ]')
		Logger( ).write( ex )
		raise ex

build_tools

build_tools(
    tools: Optional[List[str | Dict[str, Any]]] = None,
    allowed_domains: Optional[List[str]] = None,
    vector_store_ids: Optional[List[str]] = None,
) -> List[Dict[str, Any]]

Build tool definitions.

Purpose

Builds OpenAI web-search and file-search tool definitions from application-selected tool names.

Parameters:

Name Type Description Default
tools Optional[List[str | Dict[str, Any]]]

Selected provider tools.

None
allowed_domains Optional[List[str]]

Domains permitted by web search.

None
vector_store_ids Optional[List[str]]

Vector stores used by file search.

None

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Provider-ready OpenAI tool definitions.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def build_tools( self, tools: Optional[ List[ str | Dict[ str, Any ] ] ] = None,
	allowed_domains: Optional[ List[ str ] ] = None,
	vector_store_ids: Optional[ List[ str ] ] = None ) -> List[ Dict[ str, Any ] ]:
	"""Build tool definitions.

	Purpose:
		Builds OpenAI web-search and file-search tool definitions from application-selected
		tool names.

	Args:
		tools (Optional[List[str | Dict[str, Any]]]): Selected provider tools.
		allowed_domains (Optional[List[str]]): Domains permitted by web search.
		vector_store_ids (Optional[List[str]]): Vector stores used by file search.

	Returns:
		List[Dict[str, Any]]: Provider-ready OpenAI tool definitions.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.selected_tools = tools if tools is not None else [ ]
		self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
		self.vector_store_ids = (vector_store_ids if vector_store_ids is not None else [ ])
		self.tools = [ ]

		for selected_tool in self.selected_tools:
			if isinstance( selected_tool, dict ):
				self.tool_name = selected_tool.get( 'type', '' )
			else:
				self.tool_name = selected_tool

			if self.tool_name in [ 'web_search', 'web_search_preview',
				'web_search_preview_2025_03_11', ]:
				self.web_search_tool = { 'type': 'web_search', }

				if self.allowed_domains:
					self.web_search_tool[ 'filters' ] = {
						'allowed_domains': self.allowed_domains, }

				self.tools.append( self.web_search_tool )
				continue

			if self.tool_name == 'file_search':
				throw_if( 'vector_store_ids', self.vector_store_ids )
				self.tools.append(
					{ 'type': 'file_search', 'vector_store_ids': self.vector_store_ids, } )

		return self.tools
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = ('build_tools( self, tools: Optional[ List[ str | Dict[ str, '
		             'Any ] ] ] = None, allowed_domains: Optional[ List[ str ] ] = '
		             'None, vector_store_ids: Optional[ List[ str ] ] = None ) -> '
		             'List[ Dict[ str, Any ] ]')
		Logger( ).write( ex )
		raise ex

build_text_format

build_text_format(
    format: Optional[Dict[str, Any] | str] = None,
) -> Dict[str, Any]

Build text-format configuration.

Purpose

Builds the Responses API text-format object from a supported format name or a complete provider-ready format dictionary.

Parameters:

Name Type Description Default
format Optional[Dict[str, Any] | str]

Requested response format.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Provider-ready text configuration or an empty dictionary.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def build_text_format( self, format: Optional[ Dict[ str, Any ] | str ] = None ) -> Dict[
	str, Any ]:
	"""Build text-format configuration.

	Purpose:
		Builds the Responses API text-format object from a supported format name or a
		complete provider-ready format dictionary.

	Args:
		format (Optional[Dict[str, Any] | str]): Requested response format.

	Returns:
		Dict[str, Any]: Provider-ready text configuration or an empty dictionary.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.requested_format = format
		self.response_format = { }

		if self.requested_format is None:
			return self.response_format

		if isinstance( self.requested_format, dict ):
			if 'format' in self.requested_format:
				self.response_format = self.requested_format
				return self.response_format

			if 'type' in self.requested_format:
				self.response_format = { 'format': self.requested_format, }
				return self.response_format

			return self.response_format

		if self.requested_format == 'text':
			self.response_format = { 'format': { 'type': 'text', }, }
			return self.response_format

		if self.requested_format == 'json_object':
			self.response_format = { 'format': { 'type': 'json_object', }, }
			return self.response_format

		return self.response_format
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = ('build_text_format( self, format: Optional[ Dict[ str, Any ] '
		             '| str ] = None ) -> Dict[ str, Any ]')
		Logger( ).write( ex )
		raise ex

build_request

build_request(
    prompt: str,
    model: str,
    temperature: float = 0.0,
    format: Optional[Dict[str, Any] | str] = None,
    top_p: float = 0.0,
    frequency: float = 0.0,
    max_tools: int = 0,
    presence: float = 0.0,
    max_tokens: int = 0,
    store: bool = False,
    stream: bool = False,
    instruct: str = "",
    background: bool = False,
    reasoning: str = "",
    include: Optional[List[str]] = None,
    tools: Optional[List[str | Dict[str, Any]]] = None,
    allowed_domains: Optional[List[str]] = None,
    previous_id: str = "",
    tool_choice: str = "",
    is_parallel: bool = False,
    context: Optional[List[Dict[str, Any]]] = None,
    input_data: Optional[List[Dict[str, Any]]] = None,
    vector_store_ids: Optional[List[str]] = None,
    conversation_id: str = "",
) -> Dict[str, Any]

Build request.

Purpose

Builds the complete OpenAI Responses API request from values assigned to object members.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
model str

OpenAI model identifier.

required
temperature float

Sampling temperature for supported models.

0.0
format Optional[Dict[str, Any] | str]

Text-format configuration.

None
top_p float

Nucleus-sampling value for supported models.

0.0
frequency float

Frequency penalty for supported models.

0.0
max_tools int

Maximum number of built-in tool calls.

0
presence float

Presence penalty for supported models.

0.0
max_tokens int

Maximum output-token count.

0
store bool

Indicates whether the response should be stored.

False
stream bool

Indicates whether response events should be streamed.

False
instruct str

System or developer instructions.

''
background bool

Indicates whether the response runs in background mode.

False
reasoning str

Reasoning effort.

''
include Optional[List[str]]

Additional response fields to include.

None
tools Optional[List[str | Dict[str, Any]]]

Selected provider tools.

None
allowed_domains Optional[List[str]]

Domains allowed by web search.

None
previous_id str

Previous response identifier.

''
tool_choice str

Tool-selection behavior.

''
is_parallel bool

Indicates whether parallel tool calls are permitted.

False
context Optional[List[Dict[str, Any]]]

Prior application messages.

None
input_data Optional[List[Dict[str, Any]]]

Prebuilt Responses API input items.

None
vector_store_ids Optional[List[str]]

Vector stores used by file search.

None
conversation_id str

Conversation identifier.

''

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Provider-ready Responses API request.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def build_request( self, prompt: str, model: str, temperature: float = 0.0,
	format: Optional[ Dict[ str, Any ] | str ] = None, top_p: float = 0.0,
	frequency: float = 0.0, max_tools: int = 0, presence: float = 0.0, max_tokens: int = 0,
	store: bool = False, stream: bool = False, instruct: str = '', background: bool = False,
	reasoning: str = '', include: Optional[ List[ str ] ] = None,
	tools: Optional[ List[ str | Dict[ str, Any ] ] ] = None,
	allowed_domains: Optional[ List[ str ] ] = None, previous_id: str = '',
	tool_choice: str = '', is_parallel: bool = False,
	context: Optional[ List[ Dict[ str, Any ] ] ] = None,
	input_data: Optional[ List[ Dict[ str, Any ] ] ] = None,
	vector_store_ids: Optional[ List[ str ] ] = None, conversation_id: str = '' ) -> Dict[
	str, Any ]:
	"""Build request.

	Purpose:
		Builds the complete OpenAI Responses API request from values assigned to object
		members.

	Args:
		prompt (str): Current user prompt.
		model (str): OpenAI model identifier.
		temperature (float): Sampling temperature for supported models.
		format (Optional[Dict[str, Any] | str]): Text-format configuration.
		top_p (float): Nucleus-sampling value for supported models.
		frequency (float): Frequency penalty for supported models.
		max_tools (int): Maximum number of built-in tool calls.
		presence (float): Presence penalty for supported models.
		max_tokens (int): Maximum output-token count.
		store (bool): Indicates whether the response should be stored.
		stream (bool): Indicates whether response events should be streamed.
		instruct (str): System or developer instructions.
		background (bool): Indicates whether the response runs in background mode.
		reasoning (str): Reasoning effort.
		include (Optional[List[str]]): Additional response fields to include.
		tools (Optional[List[str | Dict[str, Any]]]): Selected provider tools.
		allowed_domains (Optional[List[str]]): Domains allowed by web search.
		previous_id (str): Previous response identifier.
		tool_choice (str): Tool-selection behavior.
		is_parallel (bool): Indicates whether parallel tool calls are permitted.
		context (Optional[List[Dict[str, Any]]]): Prior application messages.
		input_data (Optional[List[Dict[str, Any]]]): Prebuilt Responses API input items.
		vector_store_ids (Optional[List[str]]): Vector stores used by file search.
		conversation_id (str): Conversation identifier.

	Returns:
		Dict[str, Any]: Provider-ready Responses API request.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.prompt = prompt
		self.model = model
		self.temperature = temperature
		self.requested_format = format
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.max_tools = max_tools
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.store = store
		self.stream = stream
		self.instructions = instruct
		self.background = background
		self.reasoning_effort = reasoning
		self.include = include if include is not None else [ ]
		self.selected_tools = tools if tools is not None else [ ]
		self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
		self.previous_id = previous_id
		self.tool_choice = tool_choice
		self.parallel_tools = is_parallel
		self.context = context if context is not None else [ ]
		self.input = input_data if input_data is not None else [ ]
		self.vector_store_ids = (vector_store_ids if vector_store_ids is not None else [ ])
		self.conversation_id = conversation_id
		self.reasoning = self.build_reasoning( self.reasoning_effort, self.model, )
		self.tools = self.build_tools( self.selected_tools, self.allowed_domains,
			self.vector_store_ids, )
		self.response_format = self.build_text_format( self.requested_format, )
		self.effective_context = ([ ] if self.conversation_id else self.context)
		self.input = self.build_input( self.prompt, self.effective_context, self.input, )
		self.request = { 'model': self.model, 'input': self.input, }

		if self.instructions:
			self.request[ 'instructions' ] = self.instructions

		if self.reasoning:
			self.request[ 'reasoning' ] = self.reasoning

		if self.max_tokens > 0:
			self.request[ 'max_output_tokens' ] = self.max_tokens

		if not self.model.startswith( 'gpt-5' ):
			self.request[ 'temperature' ] = self.temperature
			self.request[ 'top_p' ] = self.top_percent
			self.request[ 'frequency_penalty' ] = self.frequency_penalty
			self.request[ 'presence_penalty' ] = self.presence_penalty

		self.request[ 'store' ] = self.store
		self.request[ 'stream' ] = self.stream
		self.request[ 'background' ] = self.background

		if self.include:
			self.request[ 'include' ] = self.include

		if self.tools:
			self.request[ 'tools' ] = self.tools
			self.request[ 'parallel_tool_calls' ] = self.parallel_tools

			if self.max_tools > 0:
				self.request[ 'max_tool_calls' ] = self.max_tools

		if self.tool_choice:
			self.request[ 'tool_choice' ] = self.tool_choice

		if self.previous_id:
			self.request[ 'previous_response_id' ] = self.previous_id

		if self.conversation_id:
			self.request[ 'conversation' ] = self.conversation_id

		if self.response_format:
			self.request[ 'text' ] = self.response_format

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = ('build_request( self, prompt: str, model: str, '
		             'temperature: float = 0.0, format: Optional[ Dict[ str, Any ] '
		             '| str ] = None, top_p: float = 0.0, frequency: float = 0.0, '
		             'max_tools: int = 0, presence: float = 0.0, max_tokens: int = '
		             '0, store: bool = False, stream: bool = False, instruct: str '
		             '= "", background: bool = False, reasoning: str = "", '
		             'include: Optional[ List[ str ] ] = None, tools: Optional[ '
		             'List[ str | Dict[ str, Any ] ] ] = None, allowed_domains: '
		             'Optional[ List[ str ] ] = None, previous_id: str = "", '
		             'tool_choice: str = "", is_parallel: bool = False, context: '
		             'Optional[ List[ Dict[ str, Any ] ] ] = None, input_data: '
		             'Optional[ List[ Dict[ str, Any ] ] ] = None, '
		             'vector_store_ids: Optional[ List[ str ] ] = None, '
		             'conversation_id: str = "" ) -> Dict[ str, Any ]')
		Logger( ).write( ex )
		raise ex

get_output_text

get_output_text() -> str

Get output text.

Purpose

Extracts aggregated text from the latest synchronous or completed background response.

Returns:

Name Type Description
str str

Extracted response text or an empty string.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_output_text( self ) -> str:
	"""Get output text.

	Purpose:
		Extracts aggregated text from the latest synchronous or completed background response.

	Returns:
		str: Extracted response text or an empty string.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.output_text = ''

		if self.response is None:
			return self.output_text

		self.response_text = getattr( self.response, 'output_text', '' )

		if self.response_text:
			self.output_text = self.response_text
			return self.output_text

		self.text_parts = [ ]

		for item in getattr( self.response, 'output', [ ] ) or [ ]:
			if getattr( item, 'type', '' ) != 'message':
				continue

			for block in getattr( item, 'content', [ ] ) or [ ]:
				if getattr( block, 'type', '' ) != 'output_text':
					continue

				self.block_text = getattr( block, 'text', '' )

				if self.block_text:
					self.text_parts.append( self.block_text )

		self.output_text = ''.join( self.text_parts ).strip( )
		return self.output_text
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = 'get_output_text( self ) -> str'
		Logger( ).write( ex )
		raise ex

get_usage

get_usage() -> Any

Get response usage.

Purpose

Returns token usage from the latest completed response.

Returns:

Name Type Description
Any Any

Provider usage object or None when unavailable.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_usage( self ) -> Any:
	"""Get response usage.

	Purpose:
		Returns token usage from the latest completed response.

	Returns:
		Any: Provider usage object or None when unavailable.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		if self.response is None:
			return None

		return getattr( self.response, 'usage', None )
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = 'get_usage( self ) -> Any'
		Logger( ).write( ex )
		raise ex

generate_text

generate_text(
    prompt: str,
    model: str,
    temperature: float = 0.0,
    format: Optional[Dict[str, Any] | str] = None,
    top_p: float = 0.0,
    frequency: float = 0.0,
    max_tools: int = 0,
    presence: float = 0.0,
    max_tokens: int = 0,
    store: bool = False,
    stream: bool = False,
    instruct: str = "",
    background: bool = False,
    reasoning: str = "",
    include: Optional[List[str]] = None,
    tools: Optional[List[str | Dict[str, Any]]] = None,
    allowed_domains: Optional[List[str]] = None,
    previous_id: str = "",
    tool_choice: str = "",
    is_parallel: bool = False,
    context: Optional[List[Dict[str, Any]]] = None,
    input_data: Optional[List[Dict[str, Any]]] = None,
    vector_store_ids: Optional[List[str]] = None,
    conversation_id: str = "",
) -> str

Generate text.

Purpose

Executes a synchronous, streaming, or background OpenAI Responses API request using arguments assigned to wrapper members.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
model str

OpenAI model identifier.

required
temperature float

Sampling temperature for supported models.

0.0
format Optional[Dict[str, Any] | str]

Text-format configuration.

None
top_p float

Nucleus-sampling value for supported models.

0.0
frequency float

Frequency penalty for supported models.

0.0
max_tools int

Maximum number of built-in tool calls.

0
presence float

Presence penalty for supported models.

0.0
max_tokens int

Maximum output-token count.

0
store bool

Indicates whether the response should be stored.

False
stream bool

Indicates whether response events should be streamed.

False
instruct str

System or developer instructions.

''
background bool

Indicates whether the response runs in background mode.

False
reasoning str

Reasoning effort.

''
include Optional[List[str]]

Additional response fields to include.

None
tools Optional[List[str | Dict[str, Any]]]

Selected provider tools.

None
allowed_domains Optional[List[str]]

Domains allowed by web search.

None
previous_id str

Previous response identifier.

''
tool_choice str

Tool-selection behavior.

''
is_parallel bool

Indicates whether parallel tool calls are permitted.

False
context Optional[List[Dict[str, Any]]]

Prior application messages.

None
input_data Optional[List[Dict[str, Any]]]

Prebuilt Responses API input items.

None
vector_store_ids Optional[List[str]]

Vector stores used by file search.

None
conversation_id str

Conversation identifier.

''

Returns:

Name Type Description
str str

Generated text, streamed text, or an empty string for an incomplete background

str

response.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def generate_text( self, prompt: str, model: str, temperature: float = 0.0,
	format: Optional[ Dict[ str, Any ] | str ] = None, top_p: float = 0.0,
	frequency: float = 0.0, max_tools: int = 0, presence: float = 0.0, max_tokens: int = 0,
	store: bool = False, stream: bool = False, instruct: str = '', background: bool = False,
	reasoning: str = '', include: Optional[ List[ str ] ] = None,
	tools: Optional[ List[ str | Dict[ str, Any ] ] ] = None,
	allowed_domains: Optional[ List[ str ] ] = None, previous_id: str = '',
	tool_choice: str = '', is_parallel: bool = False,
	context: Optional[ List[ Dict[ str, Any ] ] ] = None,
	input_data: Optional[ List[ Dict[ str, Any ] ] ] = None,
	vector_store_ids: Optional[ List[ str ] ] = None, conversation_id: str = '' ) -> str:
	"""Generate text.

	Purpose:
		Executes a synchronous, streaming, or background OpenAI Responses API request using
		arguments assigned to wrapper members.

	Args:
		prompt (str): Current user prompt.
		model (str): OpenAI model identifier.
		temperature (float): Sampling temperature for supported models.
		format (Optional[Dict[str, Any] | str]): Text-format configuration.
		top_p (float): Nucleus-sampling value for supported models.
		frequency (float): Frequency penalty for supported models.
		max_tools (int): Maximum number of built-in tool calls.
		presence (float): Presence penalty for supported models.
		max_tokens (int): Maximum output-token count.
		store (bool): Indicates whether the response should be stored.
		stream (bool): Indicates whether response events should be streamed.
		instruct (str): System or developer instructions.
		background (bool): Indicates whether the response runs in background mode.
		reasoning (str): Reasoning effort.
		include (Optional[List[str]]): Additional response fields to include.
		tools (Optional[List[str | Dict[str, Any]]]): Selected provider tools.
		allowed_domains (Optional[List[str]]): Domains allowed by web search.
		previous_id (str): Previous response identifier.
		tool_choice (str): Tool-selection behavior.
		is_parallel (bool): Indicates whether parallel tool calls are permitted.
		context (Optional[List[Dict[str, Any]]]): Prior application messages.
		input_data (Optional[List[Dict[str, Any]]]): Prebuilt Responses API input items.
		vector_store_ids (Optional[List[str]]): Vector stores used by file search.
		conversation_id (str): Conversation identifier.

	Returns:
		str: Generated text, streamed text, or an empty string for an incomplete background
		response.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.prompt = prompt
		self.model = model
		self.temperature = temperature
		self.requested_format = format
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.max_tools = max_tools
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.store = store
		self.stream = stream
		self.instructions = instruct
		self.background = background
		self.reasoning_effort = reasoning
		self.include = include if include is not None else [ ]
		self.selected_tools = tools if tools is not None else [ ]
		self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
		self.previous_id = previous_id
		self.tool_choice = tool_choice
		self.parallel_tools = is_parallel
		self.context = context if context is not None else [ ]
		self.input = input_data if input_data is not None else [ ]
		self.vector_store_ids = (vector_store_ids if vector_store_ids is not None else [ ])
		self.conversation_id = conversation_id
		self.client = OpenAI( api_key=self.api_key, )
		self.request = self.build_request( self.prompt, self.model, self.temperature,
			self.requested_format, self.top_percent, self.frequency_penalty, self.max_tools,
			self.presence_penalty, self.max_tokens, self.store, self.stream, self.instructions,
			self.background, self.reasoning_effort, self.include, self.selected_tools,
			self.allowed_domains, self.previous_id, self.tool_choice, self.parallel_tools,
			self.context, self.input, self.vector_store_ids, self.conversation_id, )

		if self.stream:
			self.stream_events = [ ]
			self.text_parts = [ ]
			self.response_stream = self.client.responses.create( **self.request )

			for event in self.response_stream:
				self.stream_events.append( event )
				self.event_type = getattr( event, 'type', '' )

				if self.event_type == 'response.output_text.delta':
					self.delta = getattr( event, 'delta', '' )

					if self.delta:
						self.text_parts.append( self.delta )

				elif self.event_type == 'response.completed':
					self.response = getattr( event, 'response', None )

			self.output_text = ''.join( self.text_parts ).strip( )

			if self.response is not None:
				self.previous_id = getattr( self.response, 'id', self.previous_id, )

			return self.output_text

		self.response = self.client.responses.create( **self.request )
		self.previous_id = getattr( self.response, 'id', self.previous_id, )
		self.output_text = self.get_output_text( )
		return self.output_text
	except Exception as e:
		ex = Error( e )
		ex.module = 'gpt'
		ex.cause = 'Chat'
		ex.method = ('generate_text( self, prompt: str, model: str, temperature: '
		             'float = 0.0, format: Optional[ Dict[ str, Any ] | str ] = '
		             'None, top_p: float = 0.0, frequency: float = 0.0, max_tools: '
		             'int = 0, presence: float = 0.0, max_tokens: int = 0, store: '
		             'bool = False, stream: bool = False, instruct: str = "", '
		             'background: bool = False, reasoning: str = "", include: '
		             'Optional[ List[ str ] ] = None, tools: Optional[ List[ str | '
		             'Dict[ str, Any ] ] ] = None, allowed_domains: Optional[ '
		             'List[ str ] ] = None, previous_id: str = "", tool_choice: str '
		             '= "", is_parallel: bool = False, context: Optional[ List[ '
		             'Dict[ str, Any ] ] ] = None, input_data: Optional[ List[ '
		             'Dict[ str, Any ] ] ] = None, vector_store_ids: Optional[ '
		             'List[ str ] ] = None, conversation_id: str = "" ) -> str')
		Logger( ).write( ex )
		raise ex

__dir__

__dir__() -> List[str]

Return member names.

Purpose

Returns public members exposed by the OpenAI Chat wrapper.

Returns:

Type Description
List[str]

List[str]: Public member names.

Source code in gpt.py
def __dir__( self ) -> List[ str ]:
	"""Return member names.

	Purpose:
		Returns public members exposed by the OpenAI Chat wrapper.

	Returns:
		List[str]: Public member names.
	"""
	return [ 'api_key', 'client', 'model', 'prompt', 'temperature', 'top_percent',
		'frequency_penalty', 'presence_penalty', 'max_tokens', 'store', 'stream', 'background',
		'response_format', 'context', 'instructions', 'include', 'tool_choice', 'previous_id',
		'conversation_id', 'parallel_tools', 'max_tools', 'input', 'tools', 'reasoning',
		'allowed_domains', 'output_text', 'vector_store_ids', 'response', 'model_options',
		'include_options', 'tool_options', 'choice_options', 'purpose_options',
		'format_options', 'reasoning_options', 'modality_options', 'supports_reasoning_model',
		'build_reasoning', 'build_input', 'build_tools', 'build_text_format', 'build_request',
		'get_output_text', 'get_usage', 'generate_text', ]

Images

Bases: GPT

Provide OpenAI image workflow support.

Purpose

Provides OpenAI image generation, image analysis, and image editing functionality. The class stores each accepted method argument as an object member before constructing and executing the corresponding Images API or Responses API request.

Attributes:

Name Type Description
api_key str

OpenAI API key used by the wrapper.

client Optional[OpenAI]

OpenAI client used by the wrapper.

model str

Model used by the current image operation.

prompt str

Prompt used by the current image operation.

number int

Number of images requested.

size str

Requested image dimensions.

quality str

Requested image quality.

detail str

Image-analysis detail level.

background str

Requested image background behavior.

output_format str

Requested image output format.

output_compression int

Requested image compression percentage.

image_path str

Local source-image path.

mask_path str

Local mask-image path.

response Any

Latest provider response.

outputs List[str | bytes]

Extracted image outputs.

output_text str

Extracted image-analysis text.

request Dict[str, Any]

Provider-ready request payload.

Source code in gpt.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
class Images( GPT ):
	"""Provide OpenAI image workflow support.

	Purpose:
		Provides OpenAI image generation, image analysis, and image editing functionality.
		The class stores each accepted method argument as an object member before constructing
		and executing the corresponding Images API or Responses API request.

	Attributes:
		api_key (str): OpenAI API key used by the wrapper.
		client (Optional[OpenAI]): OpenAI client used by the wrapper.
		model (str): Model used by the current image operation.
		prompt (str): Prompt used by the current image operation.
		number (int): Number of images requested.
		size (str): Requested image dimensions.
		quality (str): Requested image quality.
		detail (str): Image-analysis detail level.
		background (str): Requested image background behavior.
		output_format (str): Requested image output format.
		output_compression (int): Requested image compression percentage.
		image_path (str): Local source-image path.
		mask_path (str): Local mask-image path.
		response (Any): Latest provider response.
		outputs (List[str | bytes]): Extracted image outputs.
		output_text (str): Extracted image-analysis text.
		request (Dict[str, Any]): Provider-ready request payload.
	"""
	api_key: str
	client: Optional[ OpenAI ]
	model: str
	prompt: str
	number: int
	size: str
	quality: str
	detail: str
	background: str
	output_format: str
	output_compression: int
	image_path: str
	mask_path: str
	response: Any
	outputs: List[ str | bytes ]
	output_text: str
	request: Dict[ str, Any ]

	def __init__( self, model: str = 'gpt-image-1-mini' ) -> None:
		"""Initialize instance.

		Purpose:
			Initializes OpenAI image-wrapper state without executing a provider request.

		Args:
			model (str): Default OpenAI image model.

		Returns:
			None: This method initializes object state.
		"""
		super( ).__init__( )
		self.api_key = cfg.OPENAI_API_KEY
		self.client = None
		self.model = model
		self.prompt = ''
		self.input_text = ''
		self.instructions = ''
		self.number = 1
		self.size = '1024x1024'
		self.quality = 'auto'
		self.detail = 'auto'
		self.background = 'auto'
		self.output_format = 'png'
		self.output_compression = 0
		self.image_path = ''
		self.mask_path = ''
		self.image_url = ''
		self.file = None
		self.file_id = ''
		self.response = None
		self.outputs = [ ]
		self.output_text = ''
		self.request = { }
		self.input = [ ]
		self.image_content = { }
		self.max_tokens = 0
		self.temperature = 0.0
		self.store = False
		self.stream = False
		self.include = [ ]
		self.data = None

	@property
	def model_options( self ) -> List[ str ]:
		"""Get generation-model options.

		Purpose:
			Returns the OpenAI image-generation models exposed by the wrapper.

		Returns:
			List[str]: Supported image-generation model identifiers.
		"""
		return [ 'gpt-image-2', 'gpt-image-1.5', 'gpt-image-1', 'gpt-image-1-mini', ]

	@property
	def analysis_model_options( self ) -> List[ str ]:
		"""Get analysis-model options.

		Purpose:
			Returns vision-capable text models exposed for image analysis.

		Returns:
			List[str]: Supported image-analysis model identifiers.
		"""
		return [ 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5', 'gpt-5-mini', 'gpt-4.1', 'gpt-4.1-mini',
			'gpt-4o', 'gpt-4o-mini', ]

	@property
	def size_options( self ) -> List[ str ]:
		"""Get image-size options.

		Purpose:
			Returns image sizes exposed for OpenAI image generation and editing.

		Returns:
			List[str]: Supported image-size values.
		"""
		return [ 'auto', '1024x1024', '1024x1536', '1536x1024', ]

	@property
	def quality_options( self ) -> List[ str ]:
		"""Get image-quality options.

		Purpose:
			Returns image-quality values exposed by the wrapper.

		Returns:
			List[str]: Supported image-quality values.
		"""
		return [ 'auto', 'low', 'medium', 'high', ]

	@property
	def detail_options( self ) -> List[ str ]:
		"""Get image-detail options.

		Purpose:
			Returns detail levels supported by image-analysis requests.

		Returns:
			List[str]: Supported image-analysis detail values.
		"""
		return [ 'auto', 'low', 'high', 'original', ]

	@property
	def backcolor_options( self ) -> List[ str ]:
		"""Get background options.

		Purpose:
			Returns background values exposed for image generation and editing.

		Returns:
			List[str]: Supported background values.
		"""
		return [ 'auto', 'transparent', 'opaque', ]

	@property
	def format_options( self ) -> List[ str ]:
		"""Get output-format options.

		Purpose:
			Returns image output formats supported by the wrapper.

		Returns:
			List[str]: Supported output-format values.
		"""
		return [ 'png', 'jpeg', 'webp', ]

	@property
	def mime_options( self ) -> List[ str ]:
		"""Get MIME-format options.

		Purpose:
			Returns image format values used by the application selector.

		Returns:
			List[str]: Supported image format values.
		"""
		return [ 'png', 'jpeg', 'webp', ]

	@property
	def style_options( self ) -> List[ str ]:
		"""Get style options.

		Purpose:
			Returns legacy image-style options retained for application compatibility.

		Returns:
			List[str]: Available style values.
		"""
		return [ 'vivid', 'natural', ]

	@property
	def include_options( self ) -> List[ str ]:
		"""Get analysis-include options.

		Purpose:
			Returns additional response fields supported by image-analysis requests.

		Returns:
			List[str]: Supported Responses API include values.
		"""
		return [ 'message.input_image.image_url', 'message.output_text.logprobs', ]

	@property
	def tool_options( self ) -> List[ str ]:
		"""Get image-tool options.

		Purpose:
			Returns tools applicable to the current OpenAI image wrapper.

		Returns:
			List[str]: Supported image-related tool names.
		"""
		return [ 'image_generation', ]

	@property
	def choice_options( self ) -> List[ str ]:
		"""Get tool-choice options.

		Purpose:
			Returns tool-choice values retained for application selector compatibility.

		Returns:
			List[str]: Supported tool-choice values.
		"""
		return [ 'auto', 'required', 'none', ]

	@property
	def reasoning_options( self ) -> List[ str ]:
		"""Get reasoning options.

		Purpose:
			Returns reasoning-effort options exposed for vision-capable reasoning models.

		Returns:
			List[str]: Supported reasoning-effort values.
		"""
		return [ 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', ]

	@property
	def modality_options( self ) -> List[ str ]:
		"""Get modality options.

		Purpose:
			Returns modalities produced or consumed by image workflows.

		Returns:
			List[str]: Supported modality values.
		"""
		return [ 'text', 'image', ]

	def supports_original_detail( self, model: str ) -> bool:
		"""Determine original-detail support.

		Purpose:
			Determines whether a selected image-analysis model supports the original image-detail
			setting.

		Args:
			model (str): Image-analysis model identifier.

		Returns:
			bool: True when the selected model supports original detail.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'model', model )
			self.model = model

			return self.model.startswith( 'gpt-5.4' )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Images'
			exception.method = 'supports_original_detail( self, model: str ) -> bool'
			Logger( ).write( exception )
			raise exception

	def get_analysis_detail( self, detail: str, model: str ) -> str:
		"""Get effective analysis detail.

		Purpose:
			Returns the image-detail value permitted by the selected analysis model.

		Args:
			detail (str): Requested image-detail level.
			model (str): Image-analysis model identifier.

		Returns:
			str: Effective image-detail value.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'detail', detail )
			throw_if( 'model', model )
			self.detail = detail
			self.model = model

			if self.detail not in self.detail_options:
				self.detail = 'auto'

			if self.detail == 'original':
				if not self.supports_original_detail( self.model ):
					self.detail = 'high'

			return self.detail
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Images'
			exception.method = 'get_analysis_detail( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def get_output_compression( self, compression: float, output_format: str ) -> int:
		"""Get effective output compression.

		Purpose:
			Returns an integer compression percentage for JPEG and WebP image output.

		Args:
			compression (float): Requested compression percentage.
			output_format (str): Requested image output format.

		Returns:
			int: Effective compression percentage or zero when compression is not applicable.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.compression = compression
			self.output_format = output_format
			self.output_compression = 0

			if self.output_format not in [ 'jpeg', 'webp' ]:
				return self.output_compression

			if self.compression <= 0:
				return self.output_compression

			if self.compression > 100:
				self.compression = 100

			self.output_compression = int( self.compression )
			return self.output_compression
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Images'
			exception.method = 'get_output_compression( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def extract_image_outputs( self ) -> str | bytes | List[ str | bytes ] | None:
		"""Extract image outputs.

		Purpose:
			Extracts URLs or decoded base64 image bytes from the latest Images API response.

		Returns:
			str | bytes | List[str | bytes] | None: Extracted image output or outputs.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.outputs = [ ]
			if self.response is None:
				return None

			self.data = getattr( self.response, 'data', None )
			if not self.data:
				return None

			for item in self.data:
				self.image_url = getattr( item, 'url', '' )
				self.image_base64 = getattr( item, 'b64_json', '' )

				if self.image_url:
					self.outputs.append( self.image_url )
					continue

				if self.image_base64:
					self.outputs.append( base64.b64decode( self.image_base64 ) )

			if len( self.outputs ) == 0:
				return None

			if len( self.outputs ) == 1:
				return self.outputs[ 0 ]

			return self.outputs
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Images'
			exception.method = 'extract_image_outputs( self )'
			Logger( ).write( exception )
			raise exception

	def get_output_text( self ) -> str:
		"""Get analysis output text.

		Purpose:
			Extracts text from the latest image-analysis Responses API response.

		Returns:
			str: Extracted image-analysis text.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.output_text = ''
			if self.response is None:
				return self.output_text

			self.response_text = getattr( self.response, 'output_text', '', )

			if self.response_text:
				self.output_text = self.response_text
				return self.output_text

			self.text_parts = [ ]

			for item in getattr( self.response, 'output', [ ] ) or [ ]:
				if getattr( item, 'type', '' ) != 'message':
					continue

				for block in getattr( item, 'content', [ ] ) or [ ]:
					if getattr( block, 'type', '' ) != 'output_text':
						continue

					self.block_text = getattr( block, 'text', '' )

					if self.block_text:
						self.text_parts.append( self.block_text )

			self.output_text = ''.join( self.text_parts ).strip( )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Images'
			exception.method = 'get_output_text( self ) -> str'
			Logger( ).write( exception )
			raise exception

	def generate( self, prompt: str, model: str, number: int = 1, size: str = '1024x1024',
		quality: str = 'auto', fmt: str = 'png', compression: float = 0.0,
		background: str = 'auto' ) -> str | bytes | List[ str | bytes ] | None:
		"""Generate images.

		Purpose:
			Generates one or more images from a required text prompt using the selected OpenAI
			image model.

		Args:
			prompt (str): Required image-generation prompt.
			model (str): Required OpenAI image model.
			number (int): Number of images requested.
			size (str): Requested image dimensions.
			quality (str): Requested image quality.
			fmt (str): Requested output format.
			compression (float): Requested JPEG or WebP compression percentage.
			background (str): Requested background behavior.

		Returns:
			str | bytes | List[str | bytes] | None: Generated image output or outputs.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			throw_if( 'size', size )
			throw_if( 'quality', quality )
			throw_if( 'fmt', fmt )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.prompt = prompt
			self.model = model
			self.number = number
			self.size = size
			self.quality = quality
			self.output_format = fmt
			self.compression = compression
			self.background = background
			self.output_compression = self.get_output_compression( self.compression,
				self.output_format, )

			if self.number <= 0:
				self.number = 1

			if self.number > 10:
				self.number = 10

			if self.model == 'gpt-image-2':
				if self.background == 'transparent':
					self.background = 'auto'

			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'model': self.model, 'prompt': self.prompt, 'n': self.number,
				'size': self.size, 'quality': self.quality, 'output_format': self.output_format, }

			if self.background:
				self.request[ 'background' ] = self.background

			if self.output_compression > 0:
				self.request[ 'output_compression' ] = self.output_compression

			self.response = self.client.images.generate( **self.request )
			return self.extract_image_outputs( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Images'
			exception.method = 'generate( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def analyze( self, text: str, path: str, model: str, instruct: str = '', max_tokens: int = 0,
		temperature: float = 0.0, include: Optional[ List[ str ] ] = None, store: bool = False,
		stream: bool = False, detail: str = 'auto' ) -> str:
		"""Analyze an image.

		Purpose:
			Uploads a required local image and analyzes it with a required vision-capable model
			through the OpenAI Responses API.

		Args:
			text (str): Required question or instruction for image analysis.
			path (str): Required local image path.
			model (str): Required vision-capable OpenAI model.
			instruct (str): Optional system or developer instructions.
			max_tokens (int): Maximum output-token count.
			temperature (float): Sampling temperature for supported models.
			include (Optional[List[str]]): Additional response fields to include.
			store (bool): Indicates whether the response should be stored.
			stream (bool): Indicates whether response events should be streamed.
			detail (str): Requested image-detail level.

		Returns:
			str: Image-analysis response text.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'text', text )
			throw_if( 'path', path )
			throw_if( 'model', model )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.input_text = text
			self.image_path = path
			self.model = model
			self.instructions = instruct
			self.max_tokens = max_tokens
			self.temperature = temperature
			self.include = include if include is not None else [ ]
			self.store = store
			self.stream = stream
			self.detail = self.get_analysis_detail( detail, self.model, )
			self.client = OpenAI( api_key=self.api_key, )

			with open( self.image_path, 'rb' ) as source:
				self.file = self.client.files.create( file=source, purpose='vision', )

			self.file_id = self.file.id
			self.image_content = { 'type': 'input_image', 'file_id': self.file_id,
				'detail': self.detail, }
			self.input = [ { 'role': 'user',
				'content': [ { 'type': 'input_text', 'text': self.input_text, },
					self.image_content, ], }, ]
			self.request = { 'model': self.model, 'input': self.input, 'store': self.store,
				'stream': self.stream, }

			if self.instructions:
				self.request[ 'instructions' ] = self.instructions

			if self.max_tokens > 0:
				self.request[ 'max_output_tokens' ] = self.max_tokens

			if not self.model.startswith( 'gpt-5' ):
				self.request[ 'temperature' ] = self.temperature

			if self.include:
				self.request[ 'include' ] = self.include

			self.response = self.client.responses.create( **self.request )
			if self.stream:
				self.text_parts = [ ]
				for event in self.response:
					self.event_type = getattr( event, 'type', '' )

					if self.event_type == 'response.output_text.delta':
						self.delta = getattr( event, 'delta', '' )

						if self.delta:
							self.text_parts.append( self.delta )

					elif self.event_type == 'response.completed':
						self.response = getattr( event, 'response', None )

				self.output_text = ''.join( self.text_parts ).strip( )
				return self.output_text

			return self.get_output_text( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Images'
			exception.method = 'analyze( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def edit( self, prompt: str, path: str, model: str, number: int=1, size: str='1024x1024',
		quality: str='auto', fmt: str='png', compression: float=0.0, background: str='auto',
		mask_path: str = '' ) -> str | bytes | List[ str | bytes ] | None:
		"""Edit an image.

		Purpose:
			Edits a required local image using a required prompt and OpenAI image model.

		Args:
			prompt (str): Required image-editing instruction.
			path (str): Required local source-image path.
			model (str): Required OpenAI image model.
			number (int): Number of edited images requested.
			size (str): Requested image dimensions.
			quality (str): Requested image quality.
			fmt (str): Requested output format.
			compression (float): Requested JPEG or WebP compression percentage.
			background (str): Requested background behavior.
			mask_path (str): Optional local image-mask path.

		Returns:
			str | bytes | List[str | bytes] | None: Edited image output or outputs.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'path', path )
			throw_if( 'model', model )
			throw_if( 'size', size )
			throw_if( 'quality', quality )
			throw_if( 'fmt', fmt )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.prompt = prompt
			self.image_path = path
			self.model = model
			self.number = number
			self.size = size
			self.quality = quality
			self.output_format = fmt
			self.compression = compression
			self.background = background
			self.mask_path = mask_path
			self.output_compression = self.get_output_compression( self.compression,
				self.output_format, )

			if self.number <= 0:
				self.number = 1

			if self.number > 10:
				self.number = 10

			if self.model == 'gpt-image-2':
				if self.background == 'transparent':
					self.background = 'auto'

			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'model': self.model, 'prompt': self.prompt, 'n': self.number,
				'size': self.size, 'quality': self.quality, 'output_format': self.output_format, }

			if self.background:
				self.request[ 'background' ] = self.background

			if self.output_compression > 0:
				self.request[ 'output_compression' ] = self.output_compression

			with open( self.image_path, 'rb' ) as source:
				if self.mask_path:
					with open( self.mask_path, 'rb' ) as mask:
						self.response = self.client.images.edit( image=source, mask=mask,
							**self.request )
				else:
					self.response = self.client.images.edit( image=source, **self.request )

			return self.extract_image_outputs( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Images'
			exception.method = 'edit( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def __dir__( self ) -> List[ str ]:
		"""Return member names.

		Purpose:
			Returns public members exposed by the OpenAI Images wrapper.

		Returns:
			List[str]: Public member names.
		"""
		return [ 'api_key', 'client', 'model', 'prompt', 'input_text', 'instructions', 'number',
			'size', 'quality', 'detail', 'background', 'output_format', 'output_compression',
			'image_path', 'mask_path', 'image_url', 'file', 'file_id', 'response', 'outputs',
			'output_text', 'request', 'input', 'image_content', 'max_tokens', 'temperature',
			'store', 'stream', 'include', 'model_options', 'analysis_model_options',
			'size_options',
			'quality_options', 'detail_options', 'backcolor_options', 'format_options',
			'mime_options', 'style_options', 'include_options', 'tool_options', 'choice_options',
			'reasoning_options', 'modality_options', 'supports_original_detail',
			'get_analysis_detail', 'get_output_compression', 'extract_image_outputs',
			'get_output_text', 'generate', 'analyze', 'edit', ]

model_options property

model_options: List[str]

Get generation-model options.

Purpose

Returns the OpenAI image-generation models exposed by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported image-generation model identifiers.

analysis_model_options property

analysis_model_options: List[str]

Get analysis-model options.

Purpose

Returns vision-capable text models exposed for image analysis.

Returns:

Type Description
List[str]

List[str]: Supported image-analysis model identifiers.

size_options property

size_options: List[str]

Get image-size options.

Purpose

Returns image sizes exposed for OpenAI image generation and editing.

Returns:

Type Description
List[str]

List[str]: Supported image-size values.

quality_options property

quality_options: List[str]

Get image-quality options.

Purpose

Returns image-quality values exposed by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported image-quality values.

detail_options property

detail_options: List[str]

Get image-detail options.

Purpose

Returns detail levels supported by image-analysis requests.

Returns:

Type Description
List[str]

List[str]: Supported image-analysis detail values.

backcolor_options property

backcolor_options: List[str]

Get background options.

Purpose

Returns background values exposed for image generation and editing.

Returns:

Type Description
List[str]

List[str]: Supported background values.

format_options property

format_options: List[str]

Get output-format options.

Purpose

Returns image output formats supported by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported output-format values.

mime_options property

mime_options: List[str]

Get MIME-format options.

Purpose

Returns image format values used by the application selector.

Returns:

Type Description
List[str]

List[str]: Supported image format values.

style_options property

style_options: List[str]

Get style options.

Purpose

Returns legacy image-style options retained for application compatibility.

Returns:

Type Description
List[str]

List[str]: Available style values.

include_options property

include_options: List[str]

Get analysis-include options.

Purpose

Returns additional response fields supported by image-analysis requests.

Returns:

Type Description
List[str]

List[str]: Supported Responses API include values.

tool_options property

tool_options: List[str]

Get image-tool options.

Purpose

Returns tools applicable to the current OpenAI image wrapper.

Returns:

Type Description
List[str]

List[str]: Supported image-related tool names.

choice_options property

choice_options: List[str]

Get tool-choice options.

Purpose

Returns tool-choice values retained for application selector compatibility.

Returns:

Type Description
List[str]

List[str]: Supported tool-choice values.

reasoning_options property

reasoning_options: List[str]

Get reasoning options.

Purpose

Returns reasoning-effort options exposed for vision-capable reasoning models.

Returns:

Type Description
List[str]

List[str]: Supported reasoning-effort values.

modality_options property

modality_options: List[str]

Get modality options.

Purpose

Returns modalities produced or consumed by image workflows.

Returns:

Type Description
List[str]

List[str]: Supported modality values.

__init__

__init__(model: str = 'gpt-image-1-mini') -> None

Initialize instance.

Purpose

Initializes OpenAI image-wrapper state without executing a provider request.

Parameters:

Name Type Description Default
model str

Default OpenAI image model.

'gpt-image-1-mini'

Returns:

Name Type Description
None None

This method initializes object state.

Source code in gpt.py
def __init__( self, model: str = 'gpt-image-1-mini' ) -> None:
	"""Initialize instance.

	Purpose:
		Initializes OpenAI image-wrapper state without executing a provider request.

	Args:
		model (str): Default OpenAI image model.

	Returns:
		None: This method initializes object state.
	"""
	super( ).__init__( )
	self.api_key = cfg.OPENAI_API_KEY
	self.client = None
	self.model = model
	self.prompt = ''
	self.input_text = ''
	self.instructions = ''
	self.number = 1
	self.size = '1024x1024'
	self.quality = 'auto'
	self.detail = 'auto'
	self.background = 'auto'
	self.output_format = 'png'
	self.output_compression = 0
	self.image_path = ''
	self.mask_path = ''
	self.image_url = ''
	self.file = None
	self.file_id = ''
	self.response = None
	self.outputs = [ ]
	self.output_text = ''
	self.request = { }
	self.input = [ ]
	self.image_content = { }
	self.max_tokens = 0
	self.temperature = 0.0
	self.store = False
	self.stream = False
	self.include = [ ]
	self.data = None

supports_original_detail

supports_original_detail(model: str) -> bool

Determine original-detail support.

Purpose

Determines whether a selected image-analysis model supports the original image-detail setting.

Parameters:

Name Type Description Default
model str

Image-analysis model identifier.

required

Returns:

Name Type Description
bool bool

True when the selected model supports original detail.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def supports_original_detail( self, model: str ) -> bool:
	"""Determine original-detail support.

	Purpose:
		Determines whether a selected image-analysis model supports the original image-detail
		setting.

	Args:
		model (str): Image-analysis model identifier.

	Returns:
		bool: True when the selected model supports original detail.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'model', model )
		self.model = model

		return self.model.startswith( 'gpt-5.4' )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Images'
		exception.method = 'supports_original_detail( self, model: str ) -> bool'
		Logger( ).write( exception )
		raise exception

get_analysis_detail

get_analysis_detail(detail: str, model: str) -> str

Get effective analysis detail.

Purpose

Returns the image-detail value permitted by the selected analysis model.

Parameters:

Name Type Description Default
detail str

Requested image-detail level.

required
model str

Image-analysis model identifier.

required

Returns:

Name Type Description
str str

Effective image-detail value.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_analysis_detail( self, detail: str, model: str ) -> str:
	"""Get effective analysis detail.

	Purpose:
		Returns the image-detail value permitted by the selected analysis model.

	Args:
		detail (str): Requested image-detail level.
		model (str): Image-analysis model identifier.

	Returns:
		str: Effective image-detail value.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'detail', detail )
		throw_if( 'model', model )
		self.detail = detail
		self.model = model

		if self.detail not in self.detail_options:
			self.detail = 'auto'

		if self.detail == 'original':
			if not self.supports_original_detail( self.model ):
				self.detail = 'high'

		return self.detail
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Images'
		exception.method = 'get_analysis_detail( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

get_output_compression

get_output_compression(
    compression: float, output_format: str
) -> int

Get effective output compression.

Purpose

Returns an integer compression percentage for JPEG and WebP image output.

Parameters:

Name Type Description Default
compression float

Requested compression percentage.

required
output_format str

Requested image output format.

required

Returns:

Name Type Description
int int

Effective compression percentage or zero when compression is not applicable.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_output_compression( self, compression: float, output_format: str ) -> int:
	"""Get effective output compression.

	Purpose:
		Returns an integer compression percentage for JPEG and WebP image output.

	Args:
		compression (float): Requested compression percentage.
		output_format (str): Requested image output format.

	Returns:
		int: Effective compression percentage or zero when compression is not applicable.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.compression = compression
		self.output_format = output_format
		self.output_compression = 0

		if self.output_format not in [ 'jpeg', 'webp' ]:
			return self.output_compression

		if self.compression <= 0:
			return self.output_compression

		if self.compression > 100:
			self.compression = 100

		self.output_compression = int( self.compression )
		return self.output_compression
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Images'
		exception.method = 'get_output_compression( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

extract_image_outputs

extract_image_outputs() -> (
    str | bytes | List[str | bytes] | None
)

Extract image outputs.

Purpose

Extracts URLs or decoded base64 image bytes from the latest Images API response.

Returns:

Type Description
str | bytes | List[str | bytes] | None

str | bytes | List[str | bytes] | None: Extracted image output or outputs.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def extract_image_outputs( self ) -> str | bytes | List[ str | bytes ] | None:
	"""Extract image outputs.

	Purpose:
		Extracts URLs or decoded base64 image bytes from the latest Images API response.

	Returns:
		str | bytes | List[str | bytes] | None: Extracted image output or outputs.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.outputs = [ ]
		if self.response is None:
			return None

		self.data = getattr( self.response, 'data', None )
		if not self.data:
			return None

		for item in self.data:
			self.image_url = getattr( item, 'url', '' )
			self.image_base64 = getattr( item, 'b64_json', '' )

			if self.image_url:
				self.outputs.append( self.image_url )
				continue

			if self.image_base64:
				self.outputs.append( base64.b64decode( self.image_base64 ) )

		if len( self.outputs ) == 0:
			return None

		if len( self.outputs ) == 1:
			return self.outputs[ 0 ]

		return self.outputs
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Images'
		exception.method = 'extract_image_outputs( self )'
		Logger( ).write( exception )
		raise exception

get_output_text

get_output_text() -> str

Get analysis output text.

Purpose

Extracts text from the latest image-analysis Responses API response.

Returns:

Name Type Description
str str

Extracted image-analysis text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_output_text( self ) -> str:
	"""Get analysis output text.

	Purpose:
		Extracts text from the latest image-analysis Responses API response.

	Returns:
		str: Extracted image-analysis text.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.output_text = ''
		if self.response is None:
			return self.output_text

		self.response_text = getattr( self.response, 'output_text', '', )

		if self.response_text:
			self.output_text = self.response_text
			return self.output_text

		self.text_parts = [ ]

		for item in getattr( self.response, 'output', [ ] ) or [ ]:
			if getattr( item, 'type', '' ) != 'message':
				continue

			for block in getattr( item, 'content', [ ] ) or [ ]:
				if getattr( block, 'type', '' ) != 'output_text':
					continue

				self.block_text = getattr( block, 'text', '' )

				if self.block_text:
					self.text_parts.append( self.block_text )

		self.output_text = ''.join( self.text_parts ).strip( )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Images'
		exception.method = 'get_output_text( self ) -> str'
		Logger( ).write( exception )
		raise exception

generate

generate(
    prompt: str,
    model: str,
    number: int = 1,
    size: str = "1024x1024",
    quality: str = "auto",
    fmt: str = "png",
    compression: float = 0.0,
    background: str = "auto",
) -> str | bytes | List[str | bytes] | None

Generate images.

Purpose

Generates one or more images from a required text prompt using the selected OpenAI image model.

Parameters:

Name Type Description Default
prompt str

Required image-generation prompt.

required
model str

Required OpenAI image model.

required
number int

Number of images requested.

1
size str

Requested image dimensions.

'1024x1024'
quality str

Requested image quality.

'auto'
fmt str

Requested output format.

'png'
compression float

Requested JPEG or WebP compression percentage.

0.0
background str

Requested background behavior.

'auto'

Returns:

Type Description
str | bytes | List[str | bytes] | None

str | bytes | List[str | bytes] | None: Generated image output or outputs.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def generate( self, prompt: str, model: str, number: int = 1, size: str = '1024x1024',
	quality: str = 'auto', fmt: str = 'png', compression: float = 0.0,
	background: str = 'auto' ) -> str | bytes | List[ str | bytes ] | None:
	"""Generate images.

	Purpose:
		Generates one or more images from a required text prompt using the selected OpenAI
		image model.

	Args:
		prompt (str): Required image-generation prompt.
		model (str): Required OpenAI image model.
		number (int): Number of images requested.
		size (str): Requested image dimensions.
		quality (str): Requested image quality.
		fmt (str): Requested output format.
		compression (float): Requested JPEG or WebP compression percentage.
		background (str): Requested background behavior.

	Returns:
		str | bytes | List[str | bytes] | None: Generated image output or outputs.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		throw_if( 'size', size )
		throw_if( 'quality', quality )
		throw_if( 'fmt', fmt )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.prompt = prompt
		self.model = model
		self.number = number
		self.size = size
		self.quality = quality
		self.output_format = fmt
		self.compression = compression
		self.background = background
		self.output_compression = self.get_output_compression( self.compression,
			self.output_format, )

		if self.number <= 0:
			self.number = 1

		if self.number > 10:
			self.number = 10

		if self.model == 'gpt-image-2':
			if self.background == 'transparent':
				self.background = 'auto'

		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'model': self.model, 'prompt': self.prompt, 'n': self.number,
			'size': self.size, 'quality': self.quality, 'output_format': self.output_format, }

		if self.background:
			self.request[ 'background' ] = self.background

		if self.output_compression > 0:
			self.request[ 'output_compression' ] = self.output_compression

		self.response = self.client.images.generate( **self.request )
		return self.extract_image_outputs( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Images'
		exception.method = 'generate( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

analyze

analyze(
    text: str,
    path: str,
    model: str,
    instruct: str = "",
    max_tokens: int = 0,
    temperature: float = 0.0,
    include: Optional[List[str]] = None,
    store: bool = False,
    stream: bool = False,
    detail: str = "auto",
) -> str

Analyze an image.

Purpose

Uploads a required local image and analyzes it with a required vision-capable model through the OpenAI Responses API.

Parameters:

Name Type Description Default
text str

Required question or instruction for image analysis.

required
path str

Required local image path.

required
model str

Required vision-capable OpenAI model.

required
instruct str

Optional system or developer instructions.

''
max_tokens int

Maximum output-token count.

0
temperature float

Sampling temperature for supported models.

0.0
include Optional[List[str]]

Additional response fields to include.

None
store bool

Indicates whether the response should be stored.

False
stream bool

Indicates whether response events should be streamed.

False
detail str

Requested image-detail level.

'auto'

Returns:

Name Type Description
str str

Image-analysis response text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def analyze( self, text: str, path: str, model: str, instruct: str = '', max_tokens: int = 0,
	temperature: float = 0.0, include: Optional[ List[ str ] ] = None, store: bool = False,
	stream: bool = False, detail: str = 'auto' ) -> str:
	"""Analyze an image.

	Purpose:
		Uploads a required local image and analyzes it with a required vision-capable model
		through the OpenAI Responses API.

	Args:
		text (str): Required question or instruction for image analysis.
		path (str): Required local image path.
		model (str): Required vision-capable OpenAI model.
		instruct (str): Optional system or developer instructions.
		max_tokens (int): Maximum output-token count.
		temperature (float): Sampling temperature for supported models.
		include (Optional[List[str]]): Additional response fields to include.
		store (bool): Indicates whether the response should be stored.
		stream (bool): Indicates whether response events should be streamed.
		detail (str): Requested image-detail level.

	Returns:
		str: Image-analysis response text.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'text', text )
		throw_if( 'path', path )
		throw_if( 'model', model )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.input_text = text
		self.image_path = path
		self.model = model
		self.instructions = instruct
		self.max_tokens = max_tokens
		self.temperature = temperature
		self.include = include if include is not None else [ ]
		self.store = store
		self.stream = stream
		self.detail = self.get_analysis_detail( detail, self.model, )
		self.client = OpenAI( api_key=self.api_key, )

		with open( self.image_path, 'rb' ) as source:
			self.file = self.client.files.create( file=source, purpose='vision', )

		self.file_id = self.file.id
		self.image_content = { 'type': 'input_image', 'file_id': self.file_id,
			'detail': self.detail, }
		self.input = [ { 'role': 'user',
			'content': [ { 'type': 'input_text', 'text': self.input_text, },
				self.image_content, ], }, ]
		self.request = { 'model': self.model, 'input': self.input, 'store': self.store,
			'stream': self.stream, }

		if self.instructions:
			self.request[ 'instructions' ] = self.instructions

		if self.max_tokens > 0:
			self.request[ 'max_output_tokens' ] = self.max_tokens

		if not self.model.startswith( 'gpt-5' ):
			self.request[ 'temperature' ] = self.temperature

		if self.include:
			self.request[ 'include' ] = self.include

		self.response = self.client.responses.create( **self.request )
		if self.stream:
			self.text_parts = [ ]
			for event in self.response:
				self.event_type = getattr( event, 'type', '' )

				if self.event_type == 'response.output_text.delta':
					self.delta = getattr( event, 'delta', '' )

					if self.delta:
						self.text_parts.append( self.delta )

				elif self.event_type == 'response.completed':
					self.response = getattr( event, 'response', None )

			self.output_text = ''.join( self.text_parts ).strip( )
			return self.output_text

		return self.get_output_text( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Images'
		exception.method = 'analyze( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

edit

edit(
    prompt: str,
    path: str,
    model: str,
    number: int = 1,
    size: str = "1024x1024",
    quality: str = "auto",
    fmt: str = "png",
    compression: float = 0.0,
    background: str = "auto",
    mask_path: str = "",
) -> str | bytes | List[str | bytes] | None

Edit an image.

Purpose

Edits a required local image using a required prompt and OpenAI image model.

Parameters:

Name Type Description Default
prompt str

Required image-editing instruction.

required
path str

Required local source-image path.

required
model str

Required OpenAI image model.

required
number int

Number of edited images requested.

1
size str

Requested image dimensions.

'1024x1024'
quality str

Requested image quality.

'auto'
fmt str

Requested output format.

'png'
compression float

Requested JPEG or WebP compression percentage.

0.0
background str

Requested background behavior.

'auto'
mask_path str

Optional local image-mask path.

''

Returns:

Type Description
str | bytes | List[str | bytes] | None

str | bytes | List[str | bytes] | None: Edited image output or outputs.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def edit( self, prompt: str, path: str, model: str, number: int=1, size: str='1024x1024',
	quality: str='auto', fmt: str='png', compression: float=0.0, background: str='auto',
	mask_path: str = '' ) -> str | bytes | List[ str | bytes ] | None:
	"""Edit an image.

	Purpose:
		Edits a required local image using a required prompt and OpenAI image model.

	Args:
		prompt (str): Required image-editing instruction.
		path (str): Required local source-image path.
		model (str): Required OpenAI image model.
		number (int): Number of edited images requested.
		size (str): Requested image dimensions.
		quality (str): Requested image quality.
		fmt (str): Requested output format.
		compression (float): Requested JPEG or WebP compression percentage.
		background (str): Requested background behavior.
		mask_path (str): Optional local image-mask path.

	Returns:
		str | bytes | List[str | bytes] | None: Edited image output or outputs.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'path', path )
		throw_if( 'model', model )
		throw_if( 'size', size )
		throw_if( 'quality', quality )
		throw_if( 'fmt', fmt )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.prompt = prompt
		self.image_path = path
		self.model = model
		self.number = number
		self.size = size
		self.quality = quality
		self.output_format = fmt
		self.compression = compression
		self.background = background
		self.mask_path = mask_path
		self.output_compression = self.get_output_compression( self.compression,
			self.output_format, )

		if self.number <= 0:
			self.number = 1

		if self.number > 10:
			self.number = 10

		if self.model == 'gpt-image-2':
			if self.background == 'transparent':
				self.background = 'auto'

		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'model': self.model, 'prompt': self.prompt, 'n': self.number,
			'size': self.size, 'quality': self.quality, 'output_format': self.output_format, }

		if self.background:
			self.request[ 'background' ] = self.background

		if self.output_compression > 0:
			self.request[ 'output_compression' ] = self.output_compression

		with open( self.image_path, 'rb' ) as source:
			if self.mask_path:
				with open( self.mask_path, 'rb' ) as mask:
					self.response = self.client.images.edit( image=source, mask=mask,
						**self.request )
			else:
				self.response = self.client.images.edit( image=source, **self.request )

		return self.extract_image_outputs( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Images'
		exception.method = 'edit( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

__dir__

__dir__() -> List[str]

Return member names.

Purpose

Returns public members exposed by the OpenAI Images wrapper.

Returns:

Type Description
List[str]

List[str]: Public member names.

Source code in gpt.py
def __dir__( self ) -> List[ str ]:
	"""Return member names.

	Purpose:
		Returns public members exposed by the OpenAI Images wrapper.

	Returns:
		List[str]: Public member names.
	"""
	return [ 'api_key', 'client', 'model', 'prompt', 'input_text', 'instructions', 'number',
		'size', 'quality', 'detail', 'background', 'output_format', 'output_compression',
		'image_path', 'mask_path', 'image_url', 'file', 'file_id', 'response', 'outputs',
		'output_text', 'request', 'input', 'image_content', 'max_tokens', 'temperature',
		'store', 'stream', 'include', 'model_options', 'analysis_model_options',
		'size_options',
		'quality_options', 'detail_options', 'backcolor_options', 'format_options',
		'mime_options', 'style_options', 'include_options', 'tool_options', 'choice_options',
		'reasoning_options', 'modality_options', 'supports_original_detail',
		'get_analysis_detail', 'get_output_compression', 'extract_image_outputs',
		'get_output_text', 'generate', 'analyze', 'edit', ]

TTS

Bases: GPT

Provide OpenAI text-to-speech workflow support.

Purpose

Provides text-to-speech generation through the OpenAI Audio Speech API. The class stores speech request arguments as object members, creates provider-ready requests from those members, streams generated audio to a temporary file, returns the resulting audio bytes, and optionally writes the audio to a caller-specified output path.

Attributes:

Name Type Description
api_key str

OpenAI API key used by the wrapper.

client Optional[OpenAI]

OpenAI client used by the wrapper.

model str

Text-to-speech model used by the current request.

input str

Text converted to speech.

voice str

Voice used to generate speech.

response_format str

Audio format returned by the provider.

speed float

Speech playback speed.

instructions str

Model instructions controlling speech delivery.

file_path str

Optional output path used to persist generated audio.

response Any

Latest streaming speech response.

audio_bytes bytes

Audio bytes produced by the latest request.

request Dict[str, Any]

Provider-ready speech request.

temp_path str

Temporary audio file path used during response streaming.

Source code in gpt.py
class TTS( GPT ):
	"""Provide OpenAI text-to-speech workflow support.

	Purpose:
		Provides text-to-speech generation through the OpenAI Audio Speech API. The class
		stores speech request arguments as object members, creates provider-ready requests from
		those members, streams generated audio to a temporary file, returns the resulting audio
		bytes, and optionally writes the audio to a caller-specified output path.

	Attributes:
		api_key (str): OpenAI API key used by the wrapper.
		client (Optional[OpenAI]): OpenAI client used by the wrapper.
		model (str): Text-to-speech model used by the current request.
		input (str): Text converted to speech.
		voice (str): Voice used to generate speech.
		response_format (str): Audio format returned by the provider.
		speed (float): Speech playback speed.
		instructions (str): Model instructions controlling speech delivery.
		file_path (str): Optional output path used to persist generated audio.
		response (Any): Latest streaming speech response.
		audio_bytes (bytes): Audio bytes produced by the latest request.
		request (Dict[str, Any]): Provider-ready speech request.
		temp_path (str): Temporary audio file path used during response streaming.
	"""
	api_key: str
	client: Optional[ OpenAI ]
	model: str
	input: str
	voice: str
	response_format: str
	speed: float
	instructions: str
	file_path: str
	response: Any
	audio_bytes: bytes
	request: Dict[ str, Any ]
	temp_path: str

	def __init__( self, model: str='gpt-4o-mini-tts', format: str = 'mp3', voice: str = 'alloy',
		speed: float = 1.0 ) -> None:
		"""Initialize instance.

		Purpose:
			Initializes OpenAI text-to-speech configuration and request state without executing
			a provider request.

		Args:
			model (str): Default OpenAI text-to-speech model.
			format (str): Default audio response format.
			voice (str): Default speech voice.
			speed (float): Default speech speed.

		Returns:
			None: This method initializes object state.
		"""
		super( ).__init__( )
		self.api_key = cfg.OPENAI_API_KEY
		self.client = None
		self.model = model
		self.input = ''
		self.voice = voice
		self.response_format = format
		self.speed = speed
		self.instructions = ''
		self.file_path = ''
		self.response = None
		self.audio_bytes = b''
		self.request = { }
		self.temp_path = ''

	@property
	def model_options( self ) -> List[ str ]:
		"""Get text-to-speech model options.

		Purpose:
			Returns OpenAI models supported by the Audio Speech API workflow.

		Returns:
			List[str]: Supported text-to-speech model identifiers.
		"""
		return [ 'gpt-4o-mini-tts', 'gpt-4o-mini-tts-2025-12-15', 'tts-1', 'tts-1-hd', ]

	@property
	def mime_options( self ) -> List[ str ]:
		"""Get audio-format options.

		Purpose:
			Returns audio response formats supported by the OpenAI Speech API.

		Returns:
			List[str]: Supported audio response-format values.
		"""
		return [ 'mp3', 'opus', 'aac', 'flac', 'wav', 'pcm', ]

	@property
	def format_options( self ) -> List[ str ]:
		"""Get audio-format options.

		Purpose:
			Returns audio response formats supported by the OpenAI Speech API.

		Returns:
			List[str]: Supported audio response-format values.
		"""
		return self.mime_options

	@property
	def voice_options( self ) -> List[ str ]:
		"""Get speech-voice options.

		Purpose:
			Returns built-in OpenAI voices exposed by the text-to-speech wrapper.

		Returns:
			List[str]: Supported built-in voice identifiers.
		"""
		return [ 'alloy', 'ash', 'ballad', 'coral', 'echo', 'fable', 'onyx', 'nova', 'sage',
			'shimmer', 'verse', 'marin', 'cedar', ]

	@property
	def speed_options( self ) -> List[ float ]:
		"""Get speech-speed options.

		Purpose:
			Returns speech-speed values exposed by the text-to-speech wrapper.

		Returns:
			List[float]: Supported speech-speed selections.
		"""
		return [ 0.25, 0.50, 0.75, 1.0, 1.25, 1.50, 2.0, 3.0, 4.0, ]

	def create_speech( self, text: str, model: str = 'gpt-4o-mini-tts', format: str = 'mp3',
		speed: float = 1.0, voice: str = 'alloy', instruct: str = '',
		file_path: str = '' ) -> bytes:
		"""Create speech.

		Purpose:
			Generates speech audio from required input text using the selected OpenAI speech
			model, voice, format, speed, and optional delivery instructions. The method streams
			the provider response to a temporary file, reads the generated audio bytes, and
			optionally persists those bytes to a caller-specified path.

		Args:
			text (str): Required text converted to speech.
			model (str): OpenAI text-to-speech model.
			format (str): Audio response format.
			speed (float): Speech playback speed.
			voice (str): Voice used to generate speech.
			instruct (str): Optional instructions controlling speech delivery.
			file_path (str): Optional destination path for generated audio.

		Returns:
			bytes: Generated speech audio.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'text', text )
			throw_if( 'model', model )
			throw_if( 'format', format )
			throw_if( 'voice', voice )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.input = text
			self.model = model
			self.response_format = format
			self.speed = speed
			self.voice = voice
			self.instructions = instruct
			self.file_path = file_path
			self.client = OpenAI( api_key=self.api_key, )
			self.response = None
			self.audio_bytes = b''
			self.request = { 'model': self.model, 'input': self.input, 'voice': self.voice,
				'response_format': self.response_format, 'speed': self.speed, }

			if self.instructions:
				if self.model not in [ 'tts-1', 'tts-1-hd', ]:
					self.request[ 'instructions' ] = self.instructions

			with tempfile.NamedTemporaryFile( suffix=f'.{self.response_format}',
					delete=False, ) as temporary_file:
				self.temp_path = temporary_file.name

			try:
				with self.client.audio.speech.with_streaming_response.create(
						**self.request ) as response:
					self.response = response
					self.response.stream_to_file( self.temp_path, )

				with open( self.temp_path, 'rb' ) as source:
					self.audio_bytes = source.read( )

				throw_if( 'audio_bytes', self.audio_bytes )

				if self.file_path:
					with open( self.file_path, 'wb' ) as target:
						target.write( self.audio_bytes )

				return self.audio_bytes
			finally:
				if self.temp_path:
					if os.path.exists( self.temp_path ):
						os.remove( self.temp_path )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'TTS'
			exception.method = 'create_speech( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def __dir__( self ) -> List[ str ]:
		"""Return member names.

		Purpose:
			Returns public members exposed by the OpenAI text-to-speech wrapper.

		Returns:
			List[str]: Public member names.
		"""
		return [ 'api_key', 'client', 'model', 'input', 'voice', 'response_format', 'speed',
			'instructions', 'file_path', 'response', 'audio_bytes', 'request', 'temp_path',
			'model_options', 'mime_options', 'format_options', 'voice_options', 'speed_options',
			'create_speech', ]

model_options property

model_options: List[str]

Get text-to-speech model options.

Purpose

Returns OpenAI models supported by the Audio Speech API workflow.

Returns:

Type Description
List[str]

List[str]: Supported text-to-speech model identifiers.

mime_options property

mime_options: List[str]

Get audio-format options.

Purpose

Returns audio response formats supported by the OpenAI Speech API.

Returns:

Type Description
List[str]

List[str]: Supported audio response-format values.

format_options property

format_options: List[str]

Get audio-format options.

Purpose

Returns audio response formats supported by the OpenAI Speech API.

Returns:

Type Description
List[str]

List[str]: Supported audio response-format values.

voice_options property

voice_options: List[str]

Get speech-voice options.

Purpose

Returns built-in OpenAI voices exposed by the text-to-speech wrapper.

Returns:

Type Description
List[str]

List[str]: Supported built-in voice identifiers.

speed_options property

speed_options: List[float]

Get speech-speed options.

Purpose

Returns speech-speed values exposed by the text-to-speech wrapper.

Returns:

Type Description
List[float]

List[float]: Supported speech-speed selections.

__init__

__init__(
    model: str = "gpt-4o-mini-tts",
    format: str = "mp3",
    voice: str = "alloy",
    speed: float = 1.0,
) -> None

Initialize instance.

Purpose

Initializes OpenAI text-to-speech configuration and request state without executing a provider request.

Parameters:

Name Type Description Default
model str

Default OpenAI text-to-speech model.

'gpt-4o-mini-tts'
format str

Default audio response format.

'mp3'
voice str

Default speech voice.

'alloy'
speed float

Default speech speed.

1.0

Returns:

Name Type Description
None None

This method initializes object state.

Source code in gpt.py
def __init__( self, model: str='gpt-4o-mini-tts', format: str = 'mp3', voice: str = 'alloy',
	speed: float = 1.0 ) -> None:
	"""Initialize instance.

	Purpose:
		Initializes OpenAI text-to-speech configuration and request state without executing
		a provider request.

	Args:
		model (str): Default OpenAI text-to-speech model.
		format (str): Default audio response format.
		voice (str): Default speech voice.
		speed (float): Default speech speed.

	Returns:
		None: This method initializes object state.
	"""
	super( ).__init__( )
	self.api_key = cfg.OPENAI_API_KEY
	self.client = None
	self.model = model
	self.input = ''
	self.voice = voice
	self.response_format = format
	self.speed = speed
	self.instructions = ''
	self.file_path = ''
	self.response = None
	self.audio_bytes = b''
	self.request = { }
	self.temp_path = ''

create_speech

create_speech(
    text: str,
    model: str = "gpt-4o-mini-tts",
    format: str = "mp3",
    speed: float = 1.0,
    voice: str = "alloy",
    instruct: str = "",
    file_path: str = "",
) -> bytes

Create speech.

Purpose

Generates speech audio from required input text using the selected OpenAI speech model, voice, format, speed, and optional delivery instructions. The method streams the provider response to a temporary file, reads the generated audio bytes, and optionally persists those bytes to a caller-specified path.

Parameters:

Name Type Description Default
text str

Required text converted to speech.

required
model str

OpenAI text-to-speech model.

'gpt-4o-mini-tts'
format str

Audio response format.

'mp3'
speed float

Speech playback speed.

1.0
voice str

Voice used to generate speech.

'alloy'
instruct str

Optional instructions controlling speech delivery.

''
file_path str

Optional destination path for generated audio.

''

Returns:

Name Type Description
bytes bytes

Generated speech audio.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def create_speech( self, text: str, model: str = 'gpt-4o-mini-tts', format: str = 'mp3',
	speed: float = 1.0, voice: str = 'alloy', instruct: str = '',
	file_path: str = '' ) -> bytes:
	"""Create speech.

	Purpose:
		Generates speech audio from required input text using the selected OpenAI speech
		model, voice, format, speed, and optional delivery instructions. The method streams
		the provider response to a temporary file, reads the generated audio bytes, and
		optionally persists those bytes to a caller-specified path.

	Args:
		text (str): Required text converted to speech.
		model (str): OpenAI text-to-speech model.
		format (str): Audio response format.
		speed (float): Speech playback speed.
		voice (str): Voice used to generate speech.
		instruct (str): Optional instructions controlling speech delivery.
		file_path (str): Optional destination path for generated audio.

	Returns:
		bytes: Generated speech audio.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'text', text )
		throw_if( 'model', model )
		throw_if( 'format', format )
		throw_if( 'voice', voice )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.input = text
		self.model = model
		self.response_format = format
		self.speed = speed
		self.voice = voice
		self.instructions = instruct
		self.file_path = file_path
		self.client = OpenAI( api_key=self.api_key, )
		self.response = None
		self.audio_bytes = b''
		self.request = { 'model': self.model, 'input': self.input, 'voice': self.voice,
			'response_format': self.response_format, 'speed': self.speed, }

		if self.instructions:
			if self.model not in [ 'tts-1', 'tts-1-hd', ]:
				self.request[ 'instructions' ] = self.instructions

		with tempfile.NamedTemporaryFile( suffix=f'.{self.response_format}',
				delete=False, ) as temporary_file:
			self.temp_path = temporary_file.name

		try:
			with self.client.audio.speech.with_streaming_response.create(
					**self.request ) as response:
				self.response = response
				self.response.stream_to_file( self.temp_path, )

			with open( self.temp_path, 'rb' ) as source:
				self.audio_bytes = source.read( )

			throw_if( 'audio_bytes', self.audio_bytes )

			if self.file_path:
				with open( self.file_path, 'wb' ) as target:
					target.write( self.audio_bytes )

			return self.audio_bytes
		finally:
			if self.temp_path:
				if os.path.exists( self.temp_path ):
					os.remove( self.temp_path )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'TTS'
		exception.method = 'create_speech( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

__dir__

__dir__() -> List[str]

Return member names.

Purpose

Returns public members exposed by the OpenAI text-to-speech wrapper.

Returns:

Type Description
List[str]

List[str]: Public member names.

Source code in gpt.py
def __dir__( self ) -> List[ str ]:
	"""Return member names.

	Purpose:
		Returns public members exposed by the OpenAI text-to-speech wrapper.

	Returns:
		List[str]: Public member names.
	"""
	return [ 'api_key', 'client', 'model', 'input', 'voice', 'response_format', 'speed',
		'instructions', 'file_path', 'response', 'audio_bytes', 'request', 'temp_path',
		'model_options', 'mime_options', 'format_options', 'voice_options', 'speed_options',
		'create_speech', ]

Transcription

Bases: GPT

Provide OpenAI audio-transcription workflow support.

Purpose

Provides audio transcription through the OpenAI Audio Transcriptions API. The class stores each accepted transcription argument as an object member before constructing and executing the provider request. It supports plain-text, JSON, verbose JSON, subtitle, and diarized transcription responses where supported by the selected model.

Attributes:

Name Type Description
api_key str

OpenAI API key used by the wrapper.

client Optional[OpenAI]

OpenAI client used by the wrapper.

model str

Transcription model used by the current request.

audio_file str

Local audio-file path used by the current request.

language str

Optional ISO-639-1 source-language hint.

prompt str

Optional transcription prompt.

response_format str

Requested transcription response format.

temperature float

Sampling temperature used by the transcription request.

include List[str]

Additional transcription response fields.

timestamp_granularities List[str]

Requested timestamp granularities.

chunking_strategy str

Diarization chunking strategy.

response Any

Latest provider transcription response.

transcript str

Text extracted from the latest response.

result Dict[str, Any]

Structured transcription result.

request Dict[str, Any]

Provider-ready transcription request.

Source code in gpt.py
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
class Transcription( GPT ):
	"""Provide OpenAI audio-transcription workflow support.

	Purpose:
		Provides audio transcription through the OpenAI Audio Transcriptions API. The class
		stores each accepted transcription argument as an object member before constructing and
		executing the provider request. It supports plain-text, JSON, verbose JSON, subtitle,
		and diarized transcription responses where supported by the selected model.

	Attributes:
		api_key (str): OpenAI API key used by the wrapper.
		client (Optional[OpenAI]): OpenAI client used by the wrapper.
		model (str): Transcription model used by the current request.
		audio_file (str): Local audio-file path used by the current request.
		language (str): Optional ISO-639-1 source-language hint.
		prompt (str): Optional transcription prompt.
		response_format (str): Requested transcription response format.
		temperature (float): Sampling temperature used by the transcription request.
		include (List[str]): Additional transcription response fields.
		timestamp_granularities (List[str]): Requested timestamp granularities.
		chunking_strategy (str): Diarization chunking strategy.
		response (Any): Latest provider transcription response.
		transcript (str): Text extracted from the latest response.
		result (Dict[str, Any]): Structured transcription result.
		request (Dict[str, Any]): Provider-ready transcription request.
	"""
	api_key: str
	client: Optional[ OpenAI ]
	model: str
	audio_file: str
	language: str
	prompt: str
	response_format: str
	temperature: float
	include: List[ str ]
	timestamp_granularities: List[ str ]
	chunking_strategy: str
	response: Any
	transcript: str
	result: Dict[ str, Any ]
	request: Dict[ str, Any ]

	def __init__( self, model: str = 'gpt-4o-transcribe', format: str = 'json',
		temperature: float = 0.0 ) -> None:
		"""Initialize instance.

		Purpose:
			Initializes OpenAI transcription configuration and runtime state without executing
			a provider request.

		Args:
			model (str): Default OpenAI transcription model.
			format (str): Default transcription response format.
			temperature (float): Default transcription sampling temperature.

		Returns:
			None: This method initializes object state.
		"""
		super( ).__init__( )
		self.api_key = cfg.OPENAI_API_KEY
		self.client = None
		self.model = model
		self.audio_file = ''
		self.language = ''
		self.prompt = ''
		self.response_format = format
		self.temperature = temperature
		self.include = [ ]
		self.timestamp_granularities = [ ]
		self.chunking_strategy = 'auto'
		self.response = None
		self.transcript = ''
		self.result = { }
		self.request = { }
		self.segments = [ ]
		self.words = [ ]
		self.speakers = [ ]
		self.duration = 0.0

	@property
	def model_options( self ) -> List[ str ]:
		"""Get transcription-model options.

		Purpose:
			Returns OpenAI models implemented by the audio-transcription wrapper.

		Returns:
			List[str]: Supported transcription model identifiers.
		"""
		return [ 'gpt-4o-transcribe', 'gpt-4o-mini-transcribe',
			'gpt-4o-mini-transcribe-2025-12-15',
			'gpt-4o-transcribe-diarize', 'whisper-1', ]

	@property
	def mime_options( self ) -> List[ str ]:
		"""Get supported audio-file extensions.

		Purpose:
			Returns audio formats accepted by the OpenAI transcription workflow.

		Returns:
			List[str]: Supported audio-file extensions.
		"""
		return [ 'flac', 'mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'ogg', 'wav', 'webm', ]

	@property
	def language_options( self ) -> List[ str ]:
		"""Get language options.

		Purpose:
			Returns ISO-639-1 source-language hints exposed by the transcription wrapper.

		Returns:
			List[str]: Supported source-language selections.
		"""
		return [ '', 'en', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'pl', 'ru', 'uk', 'tr', 'ar', 'hi',
			'ja', 'ko', 'zh', ]

	@property
	def format_options( self ) -> List[ str ]:
		"""Get transcription-format options.

		Purpose:
			Returns transcription response formats supported by the wrapper.

		Returns:
			List[str]: Supported transcription response formats.
		"""
		return [ 'json', 'text', 'verbose_json', 'srt', 'vtt', 'diarized_json', ]

	@property
	def include_options( self ) -> List[ str ]:
		"""Get transcription-include options.

		Purpose:
			Returns additional response fields supported by compatible transcription models.

		Returns:
			List[str]: Supported transcription include values.
		"""
		return [ 'logprobs', ]

	@property
	def timestamp_options( self ) -> List[ str ]:
		"""Get timestamp-granularity options.

		Purpose:
			Returns timestamp granularities supported by verbose Whisper transcription output.

		Returns:
			List[str]: Supported timestamp-granularity values.
		"""
		return [ 'word', 'segment', ]

	def build_result( self, response: Any ) -> Dict[ str, Any ]:
		"""Build transcription result.

		Purpose:
			Extracts text, language, duration, segment, word, and speaker information from the
			provider response and stores the resulting application-facing transcription record.

		Args:
			response (Any): Provider transcription response.

		Returns:
			Dict[str, Any]: Structured transcription result.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'response', response )
			self.response = response
			self.transcript = ''
			self.segments = [ ]
			self.words = [ ]
			self.speakers = [ ]
			self.duration = 0.0
			self.result = { 'text': '', 'language': '', 'duration': 0.0, 'segments': [ ],
				'words': [ ], 'speakers': [ ], 'raw': None, }

			if isinstance( self.response, str ):
				self.transcript = self.response
				self.result[ 'text' ] = self.transcript
				self.result[ 'raw' ] = self.response
				return self.result

			self.transcript = getattr( self.response, 'text', '', )
			self.language = getattr( self.response, 'language', self.language, )
			self.duration = getattr( self.response, 'duration', 0.0, )
			self.response_segments = getattr( self.response, 'segments', [ ], ) or [ ]
			self.response_words = getattr( self.response, 'words', [ ], ) or [ ]

			for segment in self.response_segments:
				if hasattr( segment, 'model_dump' ):
					self.segments.append( segment.model_dump( ) )
				elif isinstance( segment, dict ):
					self.segments.append( segment )
				else:
					self.segments.append( { 'text': str( segment ), } )

			for word in self.response_words:
				if hasattr( word, 'model_dump' ):
					self.words.append( word.model_dump( ) )
				elif isinstance( word, dict ):
					self.words.append( word )
				else:
					self.words.append( { 'word': str( word ), } )

			for segment in self.segments:
				if not isinstance( segment, dict ):
					continue

				self.speaker = segment.get( 'speaker', '' )

				if self.speaker:
					if self.speaker not in self.speakers:
						self.speakers.append( self.speaker )

			if not self.transcript:
				self.text_parts = [ ]

				for segment in self.segments:
					if not isinstance( segment, dict ):
						continue

					self.segment_text = segment.get( 'text', '' )

					if self.segment_text:
						self.text_parts.append( self.segment_text )

				self.transcript = '\n'.join( self.text_parts ).strip( )

			if hasattr( self.response, 'model_dump' ):
				self.raw_response = self.response.model_dump( )
			else:
				self.raw_response = str( self.response )

			self.result = { 'text': self.transcript, 'language': self.language,
				'duration': self.duration, 'segments': self.segments, 'words': self.words,
				'speakers': self.speakers, 'raw': self.raw_response, }
			return self.result
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Transcription'
			exception.method = 'build_result( self, response: Any )'
			Logger( ).write( exception )
			raise exception

	def transcribe( self, path: str, model: str = 'gpt-4o-transcribe', language: str = '',
		prompt: str = '', format: str = 'json', temperature: float = 0.0,
		include: Optional[ List[ str ] ] = None,
		timestamp_granularities: Optional[ List[ str ] ] = None,
		chunking_strategy: str = 'auto' ) -> str:
		"""Transcribe audio.

		Purpose:
			Transcribes a required local audio file through the OpenAI Audio Transcriptions API
			using the selected model, source-language hint, prompt, response format, temperature,
			include fields, timestamp granularities, and diarization chunking strategy.

		Args:
			path (str): Required local audio-file path.
			model (str): OpenAI transcription model.
			language (str): Optional ISO-639-1 source-language hint.
			prompt (str): Optional transcription prompt.
			format (str): Transcription response format.
			temperature (float): Transcription sampling temperature.
			include (Optional[List[str]]): Additional response fields.
			timestamp_granularities (Optional[List[str]]): Requested timestamp granularities.
			chunking_strategy (str): Diarization chunking strategy.

		Returns:
			str: Extracted transcript text.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'path', path )
			throw_if( 'model', model )
			throw_if( 'format', format )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.audio_file = path
			self.model = model
			self.language = language
			self.prompt = prompt
			self.response_format = format
			self.temperature = temperature
			self.include = include if include is not None else [ ]
			self.timestamp_granularities = (
				timestamp_granularities if timestamp_granularities is not None else [ ])
			self.chunking_strategy = chunking_strategy
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'model': self.model, 'response_format': self.response_format,
				'temperature': self.temperature, }

			if self.language:
				self.request[ 'language' ] = self.language

			if self.prompt:
				self.request[ 'prompt' ] = self.prompt

			if self.include:
				if self.model != 'whisper-1':
					self.request[ 'include' ] = self.include

			if self.timestamp_granularities:
				if self.model == 'whisper-1':
					if self.response_format == 'verbose_json':
						self.request[ 'timestamp_granularities' ] = (self.timestamp_granularities)

			if self.model == 'gpt-4o-transcribe-diarize':
				self.response_format = 'diarized_json'
				self.request[ 'response_format' ] = self.response_format
				self.request[ 'chunking_strategy' ] = self.chunking_strategy

			with open( self.audio_file, 'rb' ) as source:
				self.response = self.client.audio.transcriptions.create( file=source,
					**self.request )

			self.result = self.build_result( self.response )
			self.transcript = self.result.get( 'text', '', )
			return self.transcript
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Transcription'
			exception.method = 'transcribe( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def __dir__( self ) -> List[ str ]:
		"""Return member names.

		Purpose:
			Returns public members exposed by the OpenAI transcription wrapper.

		Returns:
			List[str]: Public member names.
		"""
		return [ 'api_key', 'client', 'model', 'audio_file', 'language', 'prompt',
			'response_format', 'temperature', 'include', 'timestamp_granularities',
			'chunking_strategy', 'response', 'transcript', 'result', 'request', 'segments',
			'words',
			'speakers', 'duration', 'model_options', 'mime_options', 'language_options',
			'format_options', 'include_options', 'timestamp_options', 'build_result',
			'transcribe', ]

model_options property

model_options: List[str]

Get transcription-model options.

Purpose

Returns OpenAI models implemented by the audio-transcription wrapper.

Returns:

Type Description
List[str]

List[str]: Supported transcription model identifiers.

mime_options property

mime_options: List[str]

Get supported audio-file extensions.

Purpose

Returns audio formats accepted by the OpenAI transcription workflow.

Returns:

Type Description
List[str]

List[str]: Supported audio-file extensions.

language_options property

language_options: List[str]

Get language options.

Purpose

Returns ISO-639-1 source-language hints exposed by the transcription wrapper.

Returns:

Type Description
List[str]

List[str]: Supported source-language selections.

format_options property

format_options: List[str]

Get transcription-format options.

Purpose

Returns transcription response formats supported by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported transcription response formats.

include_options property

include_options: List[str]

Get transcription-include options.

Purpose

Returns additional response fields supported by compatible transcription models.

Returns:

Type Description
List[str]

List[str]: Supported transcription include values.

timestamp_options property

timestamp_options: List[str]

Get timestamp-granularity options.

Purpose

Returns timestamp granularities supported by verbose Whisper transcription output.

Returns:

Type Description
List[str]

List[str]: Supported timestamp-granularity values.

__init__

__init__(
    model: str = "gpt-4o-transcribe",
    format: str = "json",
    temperature: float = 0.0,
) -> None

Initialize instance.

Purpose

Initializes OpenAI transcription configuration and runtime state without executing a provider request.

Parameters:

Name Type Description Default
model str

Default OpenAI transcription model.

'gpt-4o-transcribe'
format str

Default transcription response format.

'json'
temperature float

Default transcription sampling temperature.

0.0

Returns:

Name Type Description
None None

This method initializes object state.

Source code in gpt.py
def __init__( self, model: str = 'gpt-4o-transcribe', format: str = 'json',
	temperature: float = 0.0 ) -> None:
	"""Initialize instance.

	Purpose:
		Initializes OpenAI transcription configuration and runtime state without executing
		a provider request.

	Args:
		model (str): Default OpenAI transcription model.
		format (str): Default transcription response format.
		temperature (float): Default transcription sampling temperature.

	Returns:
		None: This method initializes object state.
	"""
	super( ).__init__( )
	self.api_key = cfg.OPENAI_API_KEY
	self.client = None
	self.model = model
	self.audio_file = ''
	self.language = ''
	self.prompt = ''
	self.response_format = format
	self.temperature = temperature
	self.include = [ ]
	self.timestamp_granularities = [ ]
	self.chunking_strategy = 'auto'
	self.response = None
	self.transcript = ''
	self.result = { }
	self.request = { }
	self.segments = [ ]
	self.words = [ ]
	self.speakers = [ ]
	self.duration = 0.0

build_result

build_result(response: Any) -> Dict[str, Any]

Build transcription result.

Purpose

Extracts text, language, duration, segment, word, and speaker information from the provider response and stores the resulting application-facing transcription record.

Parameters:

Name Type Description Default
response Any

Provider transcription response.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Structured transcription result.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def build_result( self, response: Any ) -> Dict[ str, Any ]:
	"""Build transcription result.

	Purpose:
		Extracts text, language, duration, segment, word, and speaker information from the
		provider response and stores the resulting application-facing transcription record.

	Args:
		response (Any): Provider transcription response.

	Returns:
		Dict[str, Any]: Structured transcription result.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'response', response )
		self.response = response
		self.transcript = ''
		self.segments = [ ]
		self.words = [ ]
		self.speakers = [ ]
		self.duration = 0.0
		self.result = { 'text': '', 'language': '', 'duration': 0.0, 'segments': [ ],
			'words': [ ], 'speakers': [ ], 'raw': None, }

		if isinstance( self.response, str ):
			self.transcript = self.response
			self.result[ 'text' ] = self.transcript
			self.result[ 'raw' ] = self.response
			return self.result

		self.transcript = getattr( self.response, 'text', '', )
		self.language = getattr( self.response, 'language', self.language, )
		self.duration = getattr( self.response, 'duration', 0.0, )
		self.response_segments = getattr( self.response, 'segments', [ ], ) or [ ]
		self.response_words = getattr( self.response, 'words', [ ], ) or [ ]

		for segment in self.response_segments:
			if hasattr( segment, 'model_dump' ):
				self.segments.append( segment.model_dump( ) )
			elif isinstance( segment, dict ):
				self.segments.append( segment )
			else:
				self.segments.append( { 'text': str( segment ), } )

		for word in self.response_words:
			if hasattr( word, 'model_dump' ):
				self.words.append( word.model_dump( ) )
			elif isinstance( word, dict ):
				self.words.append( word )
			else:
				self.words.append( { 'word': str( word ), } )

		for segment in self.segments:
			if not isinstance( segment, dict ):
				continue

			self.speaker = segment.get( 'speaker', '' )

			if self.speaker:
				if self.speaker not in self.speakers:
					self.speakers.append( self.speaker )

		if not self.transcript:
			self.text_parts = [ ]

			for segment in self.segments:
				if not isinstance( segment, dict ):
					continue

				self.segment_text = segment.get( 'text', '' )

				if self.segment_text:
					self.text_parts.append( self.segment_text )

			self.transcript = '\n'.join( self.text_parts ).strip( )

		if hasattr( self.response, 'model_dump' ):
			self.raw_response = self.response.model_dump( )
		else:
			self.raw_response = str( self.response )

		self.result = { 'text': self.transcript, 'language': self.language,
			'duration': self.duration, 'segments': self.segments, 'words': self.words,
			'speakers': self.speakers, 'raw': self.raw_response, }
		return self.result
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Transcription'
		exception.method = 'build_result( self, response: Any )'
		Logger( ).write( exception )
		raise exception

transcribe

transcribe(
    path: str,
    model: str = "gpt-4o-transcribe",
    language: str = "",
    prompt: str = "",
    format: str = "json",
    temperature: float = 0.0,
    include: Optional[List[str]] = None,
    timestamp_granularities: Optional[List[str]] = None,
    chunking_strategy: str = "auto",
) -> str

Transcribe audio.

Purpose

Transcribes a required local audio file through the OpenAI Audio Transcriptions API using the selected model, source-language hint, prompt, response format, temperature, include fields, timestamp granularities, and diarization chunking strategy.

Parameters:

Name Type Description Default
path str

Required local audio-file path.

required
model str

OpenAI transcription model.

'gpt-4o-transcribe'
language str

Optional ISO-639-1 source-language hint.

''
prompt str

Optional transcription prompt.

''
format str

Transcription response format.

'json'
temperature float

Transcription sampling temperature.

0.0
include Optional[List[str]]

Additional response fields.

None
timestamp_granularities Optional[List[str]]

Requested timestamp granularities.

None
chunking_strategy str

Diarization chunking strategy.

'auto'

Returns:

Name Type Description
str str

Extracted transcript text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def transcribe( self, path: str, model: str = 'gpt-4o-transcribe', language: str = '',
	prompt: str = '', format: str = 'json', temperature: float = 0.0,
	include: Optional[ List[ str ] ] = None,
	timestamp_granularities: Optional[ List[ str ] ] = None,
	chunking_strategy: str = 'auto' ) -> str:
	"""Transcribe audio.

	Purpose:
		Transcribes a required local audio file through the OpenAI Audio Transcriptions API
		using the selected model, source-language hint, prompt, response format, temperature,
		include fields, timestamp granularities, and diarization chunking strategy.

	Args:
		path (str): Required local audio-file path.
		model (str): OpenAI transcription model.
		language (str): Optional ISO-639-1 source-language hint.
		prompt (str): Optional transcription prompt.
		format (str): Transcription response format.
		temperature (float): Transcription sampling temperature.
		include (Optional[List[str]]): Additional response fields.
		timestamp_granularities (Optional[List[str]]): Requested timestamp granularities.
		chunking_strategy (str): Diarization chunking strategy.

	Returns:
		str: Extracted transcript text.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'path', path )
		throw_if( 'model', model )
		throw_if( 'format', format )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.audio_file = path
		self.model = model
		self.language = language
		self.prompt = prompt
		self.response_format = format
		self.temperature = temperature
		self.include = include if include is not None else [ ]
		self.timestamp_granularities = (
			timestamp_granularities if timestamp_granularities is not None else [ ])
		self.chunking_strategy = chunking_strategy
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'model': self.model, 'response_format': self.response_format,
			'temperature': self.temperature, }

		if self.language:
			self.request[ 'language' ] = self.language

		if self.prompt:
			self.request[ 'prompt' ] = self.prompt

		if self.include:
			if self.model != 'whisper-1':
				self.request[ 'include' ] = self.include

		if self.timestamp_granularities:
			if self.model == 'whisper-1':
				if self.response_format == 'verbose_json':
					self.request[ 'timestamp_granularities' ] = (self.timestamp_granularities)

		if self.model == 'gpt-4o-transcribe-diarize':
			self.response_format = 'diarized_json'
			self.request[ 'response_format' ] = self.response_format
			self.request[ 'chunking_strategy' ] = self.chunking_strategy

		with open( self.audio_file, 'rb' ) as source:
			self.response = self.client.audio.transcriptions.create( file=source,
				**self.request )

		self.result = self.build_result( self.response )
		self.transcript = self.result.get( 'text', '', )
		return self.transcript
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Transcription'
		exception.method = 'transcribe( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

__dir__

__dir__() -> List[str]

Return member names.

Purpose

Returns public members exposed by the OpenAI transcription wrapper.

Returns:

Type Description
List[str]

List[str]: Public member names.

Source code in gpt.py
def __dir__( self ) -> List[ str ]:
	"""Return member names.

	Purpose:
		Returns public members exposed by the OpenAI transcription wrapper.

	Returns:
		List[str]: Public member names.
	"""
	return [ 'api_key', 'client', 'model', 'audio_file', 'language', 'prompt',
		'response_format', 'temperature', 'include', 'timestamp_granularities',
		'chunking_strategy', 'response', 'transcript', 'result', 'request', 'segments',
		'words',
		'speakers', 'duration', 'model_options', 'mime_options', 'language_options',
		'format_options', 'include_options', 'timestamp_options', 'build_result',
		'transcribe', ]

Translation

Bases: GPT

Provide OpenAI audio-translation workflow support.

Purpose

Provides audio translation through the OpenAI Audio Translations API. The class stores each accepted translation argument as an object member before constructing and executing the provider request. OpenAI audio translation converts supported spoken audio into English.

Attributes:

Name Type Description
api_key str

OpenAI API key used by the wrapper.

client Optional[OpenAI]

OpenAI client used by the wrapper.

model str

Translation model used by the current request.

audio_file str

Local audio-file path used by the current request.

prompt str

Optional English prompt used to guide translation.

response_format str

Requested translation response format.

temperature float

Sampling temperature used by the translation request.

response Any

Latest provider translation response.

translation str

English text extracted from the latest response.

result Dict[str, Any]

Structured translation result.

request Dict[str, Any]

Provider-ready translation request.

Source code in gpt.py
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
class Translation( GPT ):
	"""Provide OpenAI audio-translation workflow support.

	Purpose:
		Provides audio translation through the OpenAI Audio Translations API. The class stores
		each accepted translation argument as an object member before constructing and executing
		the provider request. OpenAI audio translation converts supported spoken audio into
		English.

	Attributes:
		api_key (str): OpenAI API key used by the wrapper.
		client (Optional[OpenAI]): OpenAI client used by the wrapper.
		model (str): Translation model used by the current request.
		audio_file (str): Local audio-file path used by the current request.
		prompt (str): Optional English prompt used to guide translation.
		response_format (str): Requested translation response format.
		temperature (float): Sampling temperature used by the translation request.
		response (Any): Latest provider translation response.
		translation (str): English text extracted from the latest response.
		result (Dict[str, Any]): Structured translation result.
		request (Dict[str, Any]): Provider-ready translation request.
	"""
	api_key: str
	client: Optional[ OpenAI ]
	model: str
	audio_file: str
	prompt: str
	response_format: str
	temperature: float
	response: Any
	translation: str
	result: Dict[ str, Any ]
	request: Dict[ str, Any ]

	def __init__( self, model: str = 'whisper-1',
		format: str = 'json', temperature: float = 0.0 ) -> None:
		"""Initialize instance.

		Purpose:
			Initializes OpenAI audio-translation configuration and runtime state without
			executing a provider request.

		Args:
			model (str): Default OpenAI audio-translation model.
			format (str): Default translation response format.
			temperature (float): Default translation sampling temperature.

		Returns:
			None: This method initializes object state.
		"""
		super( ).__init__( )
		self.api_key = cfg.OPENAI_API_KEY
		self.client = None
		self.model = model
		self.audio_file = ''
		self.prompt = ''
		self.response_format = format
		self.temperature = temperature
		self.response = None
		self.translation = ''
		self.result = { }
		self.request = { }
		self.segments = [ ]
		self.language = 'English'
		self.duration = 0.0

	@property
	def model_options( self ) -> List[ str ]:
		"""Get translation-model options.

		Purpose:
			Returns OpenAI models supported by the Audio Translations API.

		Returns:
			List[str]: Supported translation model identifiers.
		"""
		return [
			'whisper-1',
		]

	@property
	def mime_options( self ) -> List[ str ]:
		"""Get supported audio-file extensions.

		Purpose:
			Returns audio formats accepted by the OpenAI Audio Translations API.

		Returns:
			List[str]: Supported audio-file extensions.
		"""
		return [
			'flac',
			'mp3',
			'mp4',
			'mpeg',
			'mpga',
			'm4a',
			'ogg',
			'wav',
			'webm',
		]

	@property
	def format_options( self ) -> List[ str ]:
		"""Get translation-format options.

		Purpose:
			Returns response formats supported by the OpenAI Audio Translations API.

		Returns:
			List[str]: Supported translation response formats.
		"""
		return [
			'json',
			'text',
			'srt',
			'verbose_json',
			'vtt',
		]

	@property
	def language_options( self ) -> List[ str ]:
		"""Get target-language options.

		Purpose:
			Returns the only target language supported by the OpenAI Audio Translations API.

		Returns:
			List[str]: Supported target-language values.
		"""
		return [
			'English',
		]

	def translate( self, path: str, model: str = 'whisper-1',
		prompt: str = '', format: str = 'json',
		temperature: float = 0.0 ) -> str:
		"""Translate audio.

		Purpose:
			Translates a required local audio file into English through the OpenAI Audio
			Translations API using the selected model, optional English prompt, response format,
			and sampling temperature.

		Args:
			path (str): Required local audio-file path.
			model (str): OpenAI audio-translation model.
			prompt (str): Optional English prompt used to guide translation.
			format (str): Translation response format.
			temperature (float): Translation sampling temperature.

		Returns:
			str: English translation extracted from the provider response.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'path', path )
			throw_if( 'model', model )
			throw_if( 'format', format )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.audio_file = path
			self.model = model
			self.prompt = prompt
			self.response_format = format
			self.temperature = temperature
			self.client = OpenAI(
				api_key=self.api_key,
			)
			self.response = None
			self.translation = ''
			self.result = { }
			self.segments = [ ]
			self.duration = 0.0
			self.request = {
				'model': self.model,
				'response_format': self.response_format,
				'temperature': self.temperature,
			}

			if self.prompt:
				self.request[ 'prompt' ] = self.prompt

			with open( self.audio_file, 'rb' ) as source:
				self.response = self.client.audio.translations.create(
					file=source,
					**self.request
				)

			throw_if( 'response', self.response )

			if isinstance( self.response, str ):
				self.translation = self.response
				self.result = {
					'text': self.translation,
					'language': self.language,
					'duration': self.duration,
					'segments': self.segments,
					'raw': self.response,
				}
				return self.translation

			self.translation = getattr(
				self.response,
				'text',
				'',
			)
			self.duration = getattr(
				self.response,
				'duration',
				0.0,
			)
			self.response_segments = getattr(
				self.response,
				'segments',
				[ ],
			) or [ ]

			for segment in self.response_segments:
				if hasattr( segment, 'model_dump' ):
					self.segments.append(
						segment.model_dump( )
					)
				elif isinstance( segment, dict ):
					self.segments.append( segment )
				else:
					self.segments.append(
						{
							'text': str( segment ),
						}
					)

			if not self.translation:
				self.text_parts = [ ]

				for segment in self.segments:
					if not isinstance( segment, dict ):
						continue

					self.segment_text = segment.get(
						'text',
						'',
					)

					if self.segment_text:
						self.text_parts.append(
							self.segment_text
						)

				self.translation = '\n'.join(
					self.text_parts
				).strip( )

			throw_if( 'translation', self.translation )

			if hasattr( self.response, 'model_dump' ):
				self.raw_response = self.response.model_dump( )
			else:
				self.raw_response = str( self.response )

			self.result = {
				'text': self.translation,
				'language': self.language,
				'duration': self.duration,
				'segments': self.segments,
				'raw': self.raw_response,
			}
			return self.translation
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Translation'
			exception.method = 'translate( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def __dir__( self ) -> List[ str ]:
		"""Return member names.

		Purpose:
			Returns public members exposed by the OpenAI audio-translation wrapper.

		Returns:
			List[str]: Public member names.
		"""
		return [
			'api_key',
			'client',
			'model',
			'audio_file',
			'prompt',
			'response_format',
			'temperature',
			'response',
			'translation',
			'result',
			'request',
			'segments',
			'language',
			'duration',
			'model_options',
			'mime_options',
			'format_options',
			'language_options',
			'translate',
		]

model_options property

model_options: List[str]

Get translation-model options.

Purpose

Returns OpenAI models supported by the Audio Translations API.

Returns:

Type Description
List[str]

List[str]: Supported translation model identifiers.

mime_options property

mime_options: List[str]

Get supported audio-file extensions.

Purpose

Returns audio formats accepted by the OpenAI Audio Translations API.

Returns:

Type Description
List[str]

List[str]: Supported audio-file extensions.

format_options property

format_options: List[str]

Get translation-format options.

Purpose

Returns response formats supported by the OpenAI Audio Translations API.

Returns:

Type Description
List[str]

List[str]: Supported translation response formats.

language_options property

language_options: List[str]

Get target-language options.

Purpose

Returns the only target language supported by the OpenAI Audio Translations API.

Returns:

Type Description
List[str]

List[str]: Supported target-language values.

__init__

__init__(
    model: str = "whisper-1",
    format: str = "json",
    temperature: float = 0.0,
) -> None

Initialize instance.

Purpose

Initializes OpenAI audio-translation configuration and runtime state without executing a provider request.

Parameters:

Name Type Description Default
model str

Default OpenAI audio-translation model.

'whisper-1'
format str

Default translation response format.

'json'
temperature float

Default translation sampling temperature.

0.0

Returns:

Name Type Description
None None

This method initializes object state.

Source code in gpt.py
def __init__( self, model: str = 'whisper-1',
	format: str = 'json', temperature: float = 0.0 ) -> None:
	"""Initialize instance.

	Purpose:
		Initializes OpenAI audio-translation configuration and runtime state without
		executing a provider request.

	Args:
		model (str): Default OpenAI audio-translation model.
		format (str): Default translation response format.
		temperature (float): Default translation sampling temperature.

	Returns:
		None: This method initializes object state.
	"""
	super( ).__init__( )
	self.api_key = cfg.OPENAI_API_KEY
	self.client = None
	self.model = model
	self.audio_file = ''
	self.prompt = ''
	self.response_format = format
	self.temperature = temperature
	self.response = None
	self.translation = ''
	self.result = { }
	self.request = { }
	self.segments = [ ]
	self.language = 'English'
	self.duration = 0.0

translate

translate(
    path: str,
    model: str = "whisper-1",
    prompt: str = "",
    format: str = "json",
    temperature: float = 0.0,
) -> str

Translate audio.

Purpose

Translates a required local audio file into English through the OpenAI Audio Translations API using the selected model, optional English prompt, response format, and sampling temperature.

Parameters:

Name Type Description Default
path str

Required local audio-file path.

required
model str

OpenAI audio-translation model.

'whisper-1'
prompt str

Optional English prompt used to guide translation.

''
format str

Translation response format.

'json'
temperature float

Translation sampling temperature.

0.0

Returns:

Name Type Description
str str

English translation extracted from the provider response.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def translate( self, path: str, model: str = 'whisper-1',
	prompt: str = '', format: str = 'json',
	temperature: float = 0.0 ) -> str:
	"""Translate audio.

	Purpose:
		Translates a required local audio file into English through the OpenAI Audio
		Translations API using the selected model, optional English prompt, response format,
		and sampling temperature.

	Args:
		path (str): Required local audio-file path.
		model (str): OpenAI audio-translation model.
		prompt (str): Optional English prompt used to guide translation.
		format (str): Translation response format.
		temperature (float): Translation sampling temperature.

	Returns:
		str: English translation extracted from the provider response.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'path', path )
		throw_if( 'model', model )
		throw_if( 'format', format )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.audio_file = path
		self.model = model
		self.prompt = prompt
		self.response_format = format
		self.temperature = temperature
		self.client = OpenAI(
			api_key=self.api_key,
		)
		self.response = None
		self.translation = ''
		self.result = { }
		self.segments = [ ]
		self.duration = 0.0
		self.request = {
			'model': self.model,
			'response_format': self.response_format,
			'temperature': self.temperature,
		}

		if self.prompt:
			self.request[ 'prompt' ] = self.prompt

		with open( self.audio_file, 'rb' ) as source:
			self.response = self.client.audio.translations.create(
				file=source,
				**self.request
			)

		throw_if( 'response', self.response )

		if isinstance( self.response, str ):
			self.translation = self.response
			self.result = {
				'text': self.translation,
				'language': self.language,
				'duration': self.duration,
				'segments': self.segments,
				'raw': self.response,
			}
			return self.translation

		self.translation = getattr(
			self.response,
			'text',
			'',
		)
		self.duration = getattr(
			self.response,
			'duration',
			0.0,
		)
		self.response_segments = getattr(
			self.response,
			'segments',
			[ ],
		) or [ ]

		for segment in self.response_segments:
			if hasattr( segment, 'model_dump' ):
				self.segments.append(
					segment.model_dump( )
				)
			elif isinstance( segment, dict ):
				self.segments.append( segment )
			else:
				self.segments.append(
					{
						'text': str( segment ),
					}
				)

		if not self.translation:
			self.text_parts = [ ]

			for segment in self.segments:
				if not isinstance( segment, dict ):
					continue

				self.segment_text = segment.get(
					'text',
					'',
				)

				if self.segment_text:
					self.text_parts.append(
						self.segment_text
					)

			self.translation = '\n'.join(
				self.text_parts
			).strip( )

		throw_if( 'translation', self.translation )

		if hasattr( self.response, 'model_dump' ):
			self.raw_response = self.response.model_dump( )
		else:
			self.raw_response = str( self.response )

		self.result = {
			'text': self.translation,
			'language': self.language,
			'duration': self.duration,
			'segments': self.segments,
			'raw': self.raw_response,
		}
		return self.translation
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Translation'
		exception.method = 'translate( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

__dir__

__dir__() -> List[str]

Return member names.

Purpose

Returns public members exposed by the OpenAI audio-translation wrapper.

Returns:

Type Description
List[str]

List[str]: Public member names.

Source code in gpt.py
def __dir__( self ) -> List[ str ]:
	"""Return member names.

	Purpose:
		Returns public members exposed by the OpenAI audio-translation wrapper.

	Returns:
		List[str]: Public member names.
	"""
	return [
		'api_key',
		'client',
		'model',
		'audio_file',
		'prompt',
		'response_format',
		'temperature',
		'response',
		'translation',
		'result',
		'request',
		'segments',
		'language',
		'duration',
		'model_options',
		'mime_options',
		'format_options',
		'language_options',
		'translate',
	]

Embeddings

Bases: GPT

Provide Embeddings workflow support.

Purpose

Provides OpenAI embedding generation for text inputs. The class manages embedding model selection, encoding format, optional dimensions, usage metadata, and normalized single or batch embedding output.

Attributes:

Name Type Description
api_key Optional[str]

Api key retained by the provider wrapper.

client Optional[OpenAI]

Client retained by the provider wrapper.

model Optional[str]

Model retained by the provider wrapper.

input Optional[str | List[str]]

Input retained by the provider wrapper.

encoding_format Optional[str]

Encoding format retained by the provider wrapper.

dimensions Optional[int]

Dimensions retained by the provider wrapper.

user Optional[str]

User retained by the provider wrapper.

response Optional[CreateEmbeddingResponse]

Response retained by the provider wrapper.

embedding Optional[List[float] | str]

Embedding retained by the provider wrapper.

embeddings Optional[List[List[float]] | List[str]]

Embeddings retained by the provider wrapper.

usage Optional[Any]

Usage retained by the provider wrapper.

request Optional[Dict[str, Any]]

Request retained by the provider wrapper.

Source code in gpt.py
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
class Embeddings( GPT ):
	"""Provide Embeddings workflow support.

	Purpose:
		Provides OpenAI embedding generation for text inputs. The class manages embedding model
		selection, encoding format, optional dimensions, usage metadata, and normalized single
		or batch embedding output.

	Attributes:
		api_key (Optional[str]): Api key retained by the provider wrapper.
		client (Optional[OpenAI]): Client retained by the provider wrapper.
		model (Optional[str]): Model retained by the provider wrapper.
		input (Optional[str | List[str]]): Input retained by the provider wrapper.
		encoding_format (Optional[str]): Encoding format retained by the provider wrapper.
		dimensions (Optional[int]): Dimensions retained by the provider wrapper.
		user (Optional[str]): User retained by the provider wrapper.
		response (Optional[CreateEmbeddingResponse]): Response retained by the provider wrapper.
		embedding (Optional[List[float] | str]): Embedding retained by the provider wrapper.
		embeddings (Optional[List[List[float]] | List[str]]): Embeddings retained by the provider
			wrapper.
		usage (Optional[Any]): Usage retained by the provider wrapper.
		request (Optional[Dict[str, Any]]): Request retained by the provider wrapper.
	"""
	api_key: Optional[ str ]
	client: Optional[ OpenAI ]
	model: Optional[ str ]
	input: Optional[ str | List[ str ] ]
	encoding_format: Optional[ str ]
	dimensions: Optional[ int ]
	user: Optional[ str ]
	response: Optional[ CreateEmbeddingResponse ]
	embedding: Optional[ List[ float ] | str ]
	embeddings: Optional[ List[ List[ float ] ] | List[ str ] ]
	usage: Optional[ Any ]
	request: Optional[ Dict[ str, Any ] ]

	def __init__( self, text: str | List[ str ] = None, model: str='text-embedding-3-small',
		format: str='float', dimensions: int=None, user: str=None ):
		"""Initialize instance.

		Purpose:
			Initializes the Embeddings object with default configuration, runtime state, provider
			settings, and compatibility fields. This constructor prepares the instance for later
			method calls without performing external work beyond local attribute assignment.

		Args:
			text (str | List[str]): Text value used by the operation.
			model (str): Model value used by the operation.
			format (str): Format value used by the operation.
			dimensions (int): Dimensions value used by the operation.
			user (str): User value used by the operation.
		"""
		super( ).__init__( )
		self.api_key = cfg.OPENAI_API_KEY
		self.client = None
		self.model = model
		self.input = text
		self.encoding_format = format
		self.dimensions = dimensions
		self.user = user
		self.response = None
		self.embedding = None
		self.embeddings = None
		self.usage = None
		self.request = None

	@property
	def model_options( self ) -> List[ str ] | None:
		"""Get model options.

		Purpose:
			Returns the model options exposed by the Embeddings wrapper. The property
			centralizes UI
			option values and keeps application selectors aligned with the provider-specific
			implementation.

		Returns:
			Available option values exposed by the provider wrapper.
		"""
		return [ 'text-embedding-3-small', 'text-embedding-3-large', 'text-embedding-ada-002', ]

	@property
	def encoding_options( self ) -> List[ str ] | None:
		"""Get encoding options.

		Purpose:
			Returns the encoding options exposed by the Embeddings wrapper. The property
			centralizes
			UI option values and keeps application selectors aligned with the provider-specific
			implementation.

		Returns:
			Available option values exposed by the provider wrapper.
		"""
		return [ 'float', 'base64', ]

	@property
	def model_default_dimensions( self ) -> Dict[ str, int ]:
		"""Get model default dimensions.

		Purpose:
			Returns the model default dimensions exposed by the Embeddings wrapper. The property
			centralizes UI option values and keeps application selectors aligned with the
			provider-specific implementation.

		Returns:
			Available option values exposed by the provider wrapper.
		"""
		return { 'text-embedding-3-small': 1536, 'text-embedding-3-large': 3072,
			'text-embedding-ada-002': 1536, }

	@property
	def model_max_dimensions( self ) -> Dict[ str, int ]:
		"""Get model max dimensions.

		Purpose:
			Returns the model max dimensions exposed by the Embeddings wrapper. The property
			centralizes UI option values and keeps application selectors aligned with the
			provider-specific implementation.

		Returns:
			Available option values exposed by the provider wrapper.
		"""
		return { 'text-embedding-3-small': 1536, 'text-embedding-3-large': 3072,
			'text-embedding-ada-002': 1536, }

	@property
	def model_dimension_support( self ) -> Dict[ str, bool ]:
		"""Get model dimension support.

		Purpose:
			Returns the model dimension support exposed by the Embeddings wrapper. The property
			centralizes UI option values and keeps application selectors aligned with the
			provider-specific implementation.

		Returns:
			Available option values exposed by the provider wrapper.
		"""
		return { 'text-embedding-3-small': True, 'text-embedding-3-large': True,
			'text-embedding-ada-002': False, }

	def validate_input( self, text: str | List[ str ] ) -> str | List[ str ]:
		"""Validate input.

		Purpose:
			Validates and normalizes the input value used for the Embeddings workflow. The method
			raises an application error when required input is missing and returns a clean value
			suitable for downstream provider calls.

		Args:
			text (str | List[str]): Text value used by the operation.

		Returns:
			Validated and normalized value for downstream use.

		Raises:
			Error: Re-raised after the exception is wrapped and written to the application logger.
		"""
		try:
			throw_if( 'text', text )

			if isinstance( text, str ):
				value = text.strip( )
				throw_if( 'text', value )
				return value

			if isinstance( text, list ):
				values = [ ]
				for item in text:
					if not isinstance( item, str ):
						continue

					clean = item.strip( )
					if clean:
						values.append( clean )

				throw_if( 'text', values )
				return values

			raise ValueError( 'Embedding input must be a string or list of strings.' )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Embeddings'
			exception.method = 'validate_input( self, text: str | List[ str ] )'
			Logger( ).write( exception )
			raise exception

	def validate_dimensions( self ) -> int | None:
		"""Validate dimensions.

		Purpose:
			Validates and normalizes the dimensions value used for the Embeddings workflow. The
			method raises an application error when required input is missing and returns a clean
			value suitable for downstream provider calls.

		Returns:
			Validated and normalized value for downstream use.

		Raises:
			Error: Re-raised after the exception is wrapped and written to the application logger.
		"""
		try:
			if self.dimensions is None:
				return None

			try:
				value = int( self.dimensions )
			except Exception as e:
				exception = Error( e )
				exception.module = 'gpt'
				exception.cause = 'Embeddings'
				exception.method = 'validate_dimensions( ... )'
				Logger( ).write( exception )
				return None

			if value <= 0:
				return None

			supports_dimensions = self.model_dimension_support.get( self.model, False )
			if not supports_dimensions:
				return None

			max_dimensions = self.get_max_dimensions( self.model )
			if value > max_dimensions:
				return max_dimensions

			return value
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Embeddings'
			exception.method = 'validate_dimensions( self ) -> int | None'
			Logger( ).write( exception )
			raise exception

	def get_default_dimensions( self, model: str ) -> int:
		"""Get default dimensions.

		Purpose:
			Returns the default dimensions value for the active Embeddings request. The method
			inspects current runtime state and provides a safe application-facing result.

		Args:
			model (str): Model value used by the operation.

		Returns:
			Requested value derived from the current runtime state.

		Raises:
			Error: Re-raised after the exception is wrapped and written to the application logger.
		"""
		try:
			throw_if( 'model', model )
			return int( self.model_default_dimensions.get( model, 1536 ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Embeddings'
			exception.method = 'get_default_dimensions( self, model: str ) -> int'
			Logger( ).write( exception )
			raise exception

	def get_max_dimensions( self, model: str ) -> int:
		"""Get max dimensions.

		Purpose:
			Returns the max dimensions value for the active Embeddings request. The method inspects
			current runtime state and provides a safe application-facing result.

		Args:
			model (str): Model value used by the operation.

		Returns:
			Requested value derived from the current runtime state.

		Raises:
			Error: Re-raised after the exception is wrapped and written to the application logger.
		"""
		try:
			throw_if( 'model', model )
			return int( self.model_max_dimensions.get( model, 1536 ) )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Embeddings'
			exception.method = 'get_max_dimensions( self, model: str ) -> int'
			Logger( ).write( exception )
			raise exception

	def build_request( self, text: str | List[ str ], model: str='text-embedding-3-small',
		format: str='float', dimensions: int=None, user: str=None ) -> Dict[ str, Any ]:
		"""Build request.

		Purpose:
			Builds the request payload used for the Embeddings workflow. The method validates
			caller
			input, applies compatibility defaults, and returns a provider-ready structure without
			executing the provider request.

		Args:
			text (str | List[str]): Text value used by the operation.
			model (str): Model value used by the operation.
			format (str): Format value used by the operation.
			dimensions (int): Dimensions value used by the operation.
			user (str): User value used by the operation.

		Returns:
			Provider-ready request structure or omitted optional payload.

		Raises:
			Error: Re-raised after the exception is wrapped and written to the application logger.
		"""
		try:
			throw_if( 'text', text )
			throw_if( 'model', model )
			throw_if( 'format', format )

			self.input = self.validate_input( text )
			self.model = model
			self.encoding_format = format
			self.dimensions = dimensions
			self.dimensions = self.validate_dimensions( )
			self.user = user if isinstance( user, str ) and user.strip( ) else None
			self.request = { 'model': self.model, 'input': self.input,
				'encoding_format': self.encoding_format, }

			if self.dimensions is not None:
				self.request[ 'dimensions' ] = self.dimensions

			if self.user:
				self.request[ 'user' ] = self.user.strip( )

			return self.request
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Embeddings'
			exception.method = 'build_request( self, text: str | List[ str ], **kwargs )'
			Logger( ).write( exception )
			raise exception

	def create( self, text: str | List[ str ], model: str='text-embedding-3-small',
		format: str='float', dimensions: int=None, user: str=None ) -> List[ float ] | List[
		List[ float ] ] | str | List[ str ] | None:
		"""Create.

		Purpose:
			Creates provider resources or generated outputs for the Embeddings workflow using
			validated request state and provider-specific defaults.

		Args:
			text (str | List[str]): Text value used by the operation.
			model (str): Model value used by the operation.
			format (str): Format value used by the operation.
			dimensions (int): Dimensions value used by the operation.
			user (str): User value used by the operation.

		Returns:
			Single embedding, batch embeddings, base64 embedding content, or no value when no
			embeddings are returned.

		Raises:
			Error: Re-raised after the exception is wrapped and written to the application logger.
		"""
		try:
			self.client = OpenAI( api_key=self.api_key )
			self.request = self.build_request( text=text, model=model, format=format,
				dimensions=dimensions, user=user )

			self.response = self.client.embeddings.create( **self.request )
			self.usage = getattr( self.response, 'usage', None )
			self.data = getattr( self.response, 'data', None )
			self.embeddings = [ ]

			if self.data is None or len( self.data ) == 0:
				self.embedding = None
				return None

			for item in self.data:
				value = getattr( item, 'embedding', None )
				if value is not None:
					self.embeddings.append( value )

			if len( self.embeddings ) == 0:
				self.embedding = None
				return None

			self.embedding = self.embeddings[ 0 ]

			if isinstance( self.input, str ):
				return self.embedding

			return self.embeddings
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Embeddings'
			exception.method = 'create( self, text: str | List[ str ], **kwargs )'
			Logger( ).write( exception )
			raise exception

	def __dir__( self ) -> List[ str ] | None:
		"""Return member names.

		Purpose:
			Returns a stable list of public members exposed by the Embeddings object for
			interactive
			inspection, debugging, and application-level compatibility.

		Returns:
			Member names exposed for inspection.
		"""
		return [ 'api_key', 'client', 'model', 'input', 'encoding_format', 'dimensions', 'user',
			'response', 'embedding', 'embeddings', 'usage', 'request', 'model_options',
			'encoding_options', 'model_default_dimensions', 'model_max_dimensions',
			'model_dimension_support', 'validate_input', 'validate_dimensions',
			'get_default_dimensions', 'get_max_dimensions', 'build_request', 'create', ]

model_options property

model_options: List[str] | None

Get model options.

Purpose

Returns the model options exposed by the Embeddings wrapper. The property centralizes UI option values and keeps application selectors aligned with the provider-specific implementation.

Returns:

Type Description
List[str] | None

Available option values exposed by the provider wrapper.

encoding_options property

encoding_options: List[str] | None

Get encoding options.

Purpose

Returns the encoding options exposed by the Embeddings wrapper. The property centralizes UI option values and keeps application selectors aligned with the provider-specific implementation.

Returns:

Type Description
List[str] | None

Available option values exposed by the provider wrapper.

model_default_dimensions property

model_default_dimensions: Dict[str, int]

Get model default dimensions.

Purpose

Returns the model default dimensions exposed by the Embeddings wrapper. The property centralizes UI option values and keeps application selectors aligned with the provider-specific implementation.

Returns:

Type Description
Dict[str, int]

Available option values exposed by the provider wrapper.

model_max_dimensions property

model_max_dimensions: Dict[str, int]

Get model max dimensions.

Purpose

Returns the model max dimensions exposed by the Embeddings wrapper. The property centralizes UI option values and keeps application selectors aligned with the provider-specific implementation.

Returns:

Type Description
Dict[str, int]

Available option values exposed by the provider wrapper.

model_dimension_support property

model_dimension_support: Dict[str, bool]

Get model dimension support.

Purpose

Returns the model dimension support exposed by the Embeddings wrapper. The property centralizes UI option values and keeps application selectors aligned with the provider-specific implementation.

Returns:

Type Description
Dict[str, bool]

Available option values exposed by the provider wrapper.

__init__

__init__(
    text: str | List[str] = None,
    model: str = "text-embedding-3-small",
    format: str = "float",
    dimensions: int = None,
    user: str = None,
)

Initialize instance.

Purpose

Initializes the Embeddings object with default configuration, runtime state, provider settings, and compatibility fields. This constructor prepares the instance for later method calls without performing external work beyond local attribute assignment.

Parameters:

Name Type Description Default
text str | List[str]

Text value used by the operation.

None
model str

Model value used by the operation.

'text-embedding-3-small'
format str

Format value used by the operation.

'float'
dimensions int

Dimensions value used by the operation.

None
user str

User value used by the operation.

None
Source code in gpt.py
def __init__( self, text: str | List[ str ] = None, model: str='text-embedding-3-small',
	format: str='float', dimensions: int=None, user: str=None ):
	"""Initialize instance.

	Purpose:
		Initializes the Embeddings object with default configuration, runtime state, provider
		settings, and compatibility fields. This constructor prepares the instance for later
		method calls without performing external work beyond local attribute assignment.

	Args:
		text (str | List[str]): Text value used by the operation.
		model (str): Model value used by the operation.
		format (str): Format value used by the operation.
		dimensions (int): Dimensions value used by the operation.
		user (str): User value used by the operation.
	"""
	super( ).__init__( )
	self.api_key = cfg.OPENAI_API_KEY
	self.client = None
	self.model = model
	self.input = text
	self.encoding_format = format
	self.dimensions = dimensions
	self.user = user
	self.response = None
	self.embedding = None
	self.embeddings = None
	self.usage = None
	self.request = None

validate_input

validate_input(text: str | List[str]) -> str | List[str]

Validate input.

Purpose

Validates and normalizes the input value used for the Embeddings workflow. The method raises an application error when required input is missing and returns a clean value suitable for downstream provider calls.

Parameters:

Name Type Description Default
text str | List[str]

Text value used by the operation.

required

Returns:

Type Description
str | List[str]

Validated and normalized value for downstream use.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

Source code in gpt.py
def validate_input( self, text: str | List[ str ] ) -> str | List[ str ]:
	"""Validate input.

	Purpose:
		Validates and normalizes the input value used for the Embeddings workflow. The method
		raises an application error when required input is missing and returns a clean value
		suitable for downstream provider calls.

	Args:
		text (str | List[str]): Text value used by the operation.

	Returns:
		Validated and normalized value for downstream use.

	Raises:
		Error: Re-raised after the exception is wrapped and written to the application logger.
	"""
	try:
		throw_if( 'text', text )

		if isinstance( text, str ):
			value = text.strip( )
			throw_if( 'text', value )
			return value

		if isinstance( text, list ):
			values = [ ]
			for item in text:
				if not isinstance( item, str ):
					continue

				clean = item.strip( )
				if clean:
					values.append( clean )

			throw_if( 'text', values )
			return values

		raise ValueError( 'Embedding input must be a string or list of strings.' )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Embeddings'
		exception.method = 'validate_input( self, text: str | List[ str ] )'
		Logger( ).write( exception )
		raise exception

validate_dimensions

validate_dimensions() -> int | None

Validate dimensions.

Purpose

Validates and normalizes the dimensions value used for the Embeddings workflow. The method raises an application error when required input is missing and returns a clean value suitable for downstream provider calls.

Returns:

Type Description
int | None

Validated and normalized value for downstream use.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

Source code in gpt.py
def validate_dimensions( self ) -> int | None:
	"""Validate dimensions.

	Purpose:
		Validates and normalizes the dimensions value used for the Embeddings workflow. The
		method raises an application error when required input is missing and returns a clean
		value suitable for downstream provider calls.

	Returns:
		Validated and normalized value for downstream use.

	Raises:
		Error: Re-raised after the exception is wrapped and written to the application logger.
	"""
	try:
		if self.dimensions is None:
			return None

		try:
			value = int( self.dimensions )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Embeddings'
			exception.method = 'validate_dimensions( ... )'
			Logger( ).write( exception )
			return None

		if value <= 0:
			return None

		supports_dimensions = self.model_dimension_support.get( self.model, False )
		if not supports_dimensions:
			return None

		max_dimensions = self.get_max_dimensions( self.model )
		if value > max_dimensions:
			return max_dimensions

		return value
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Embeddings'
		exception.method = 'validate_dimensions( self ) -> int | None'
		Logger( ).write( exception )
		raise exception

get_default_dimensions

get_default_dimensions(model: str) -> int

Get default dimensions.

Purpose

Returns the default dimensions value for the active Embeddings request. The method inspects current runtime state and provides a safe application-facing result.

Parameters:

Name Type Description Default
model str

Model value used by the operation.

required

Returns:

Type Description
int

Requested value derived from the current runtime state.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

Source code in gpt.py
def get_default_dimensions( self, model: str ) -> int:
	"""Get default dimensions.

	Purpose:
		Returns the default dimensions value for the active Embeddings request. The method
		inspects current runtime state and provides a safe application-facing result.

	Args:
		model (str): Model value used by the operation.

	Returns:
		Requested value derived from the current runtime state.

	Raises:
		Error: Re-raised after the exception is wrapped and written to the application logger.
	"""
	try:
		throw_if( 'model', model )
		return int( self.model_default_dimensions.get( model, 1536 ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Embeddings'
		exception.method = 'get_default_dimensions( self, model: str ) -> int'
		Logger( ).write( exception )
		raise exception

get_max_dimensions

get_max_dimensions(model: str) -> int

Get max dimensions.

Purpose

Returns the max dimensions value for the active Embeddings request. The method inspects current runtime state and provides a safe application-facing result.

Parameters:

Name Type Description Default
model str

Model value used by the operation.

required

Returns:

Type Description
int

Requested value derived from the current runtime state.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

Source code in gpt.py
def get_max_dimensions( self, model: str ) -> int:
	"""Get max dimensions.

	Purpose:
		Returns the max dimensions value for the active Embeddings request. The method inspects
		current runtime state and provides a safe application-facing result.

	Args:
		model (str): Model value used by the operation.

	Returns:
		Requested value derived from the current runtime state.

	Raises:
		Error: Re-raised after the exception is wrapped and written to the application logger.
	"""
	try:
		throw_if( 'model', model )
		return int( self.model_max_dimensions.get( model, 1536 ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Embeddings'
		exception.method = 'get_max_dimensions( self, model: str ) -> int'
		Logger( ).write( exception )
		raise exception

build_request

build_request(
    text: str | List[str],
    model: str = "text-embedding-3-small",
    format: str = "float",
    dimensions: int = None,
    user: str = None,
) -> Dict[str, Any]

Build request.

Purpose

Builds the request payload used for the Embeddings workflow. The method validates caller input, applies compatibility defaults, and returns a provider-ready structure without executing the provider request.

Parameters:

Name Type Description Default
text str | List[str]

Text value used by the operation.

required
model str

Model value used by the operation.

'text-embedding-3-small'
format str

Format value used by the operation.

'float'
dimensions int

Dimensions value used by the operation.

None
user str

User value used by the operation.

None

Returns:

Type Description
Dict[str, Any]

Provider-ready request structure or omitted optional payload.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

Source code in gpt.py
def build_request( self, text: str | List[ str ], model: str='text-embedding-3-small',
	format: str='float', dimensions: int=None, user: str=None ) -> Dict[ str, Any ]:
	"""Build request.

	Purpose:
		Builds the request payload used for the Embeddings workflow. The method validates
		caller
		input, applies compatibility defaults, and returns a provider-ready structure without
		executing the provider request.

	Args:
		text (str | List[str]): Text value used by the operation.
		model (str): Model value used by the operation.
		format (str): Format value used by the operation.
		dimensions (int): Dimensions value used by the operation.
		user (str): User value used by the operation.

	Returns:
		Provider-ready request structure or omitted optional payload.

	Raises:
		Error: Re-raised after the exception is wrapped and written to the application logger.
	"""
	try:
		throw_if( 'text', text )
		throw_if( 'model', model )
		throw_if( 'format', format )

		self.input = self.validate_input( text )
		self.model = model
		self.encoding_format = format
		self.dimensions = dimensions
		self.dimensions = self.validate_dimensions( )
		self.user = user if isinstance( user, str ) and user.strip( ) else None
		self.request = { 'model': self.model, 'input': self.input,
			'encoding_format': self.encoding_format, }

		if self.dimensions is not None:
			self.request[ 'dimensions' ] = self.dimensions

		if self.user:
			self.request[ 'user' ] = self.user.strip( )

		return self.request
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Embeddings'
		exception.method = 'build_request( self, text: str | List[ str ], **kwargs )'
		Logger( ).write( exception )
		raise exception

create

create(
    text: str | List[str],
    model: str = "text-embedding-3-small",
    format: str = "float",
    dimensions: int = None,
    user: str = None,
) -> (
    List[float] | List[List[float]] | str | List[str] | None
)

Create.

Purpose

Creates provider resources or generated outputs for the Embeddings workflow using validated request state and provider-specific defaults.

Parameters:

Name Type Description Default
text str | List[str]

Text value used by the operation.

required
model str

Model value used by the operation.

'text-embedding-3-small'
format str

Format value used by the operation.

'float'
dimensions int

Dimensions value used by the operation.

None
user str

User value used by the operation.

None

Returns:

Type Description
List[float] | List[List[float]] | str | List[str] | None

Single embedding, batch embeddings, base64 embedding content, or no value when no

List[float] | List[List[float]] | str | List[str] | None

embeddings are returned.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

Source code in gpt.py
def create( self, text: str | List[ str ], model: str='text-embedding-3-small',
	format: str='float', dimensions: int=None, user: str=None ) -> List[ float ] | List[
	List[ float ] ] | str | List[ str ] | None:
	"""Create.

	Purpose:
		Creates provider resources or generated outputs for the Embeddings workflow using
		validated request state and provider-specific defaults.

	Args:
		text (str | List[str]): Text value used by the operation.
		model (str): Model value used by the operation.
		format (str): Format value used by the operation.
		dimensions (int): Dimensions value used by the operation.
		user (str): User value used by the operation.

	Returns:
		Single embedding, batch embeddings, base64 embedding content, or no value when no
		embeddings are returned.

	Raises:
		Error: Re-raised after the exception is wrapped and written to the application logger.
	"""
	try:
		self.client = OpenAI( api_key=self.api_key )
		self.request = self.build_request( text=text, model=model, format=format,
			dimensions=dimensions, user=user )

		self.response = self.client.embeddings.create( **self.request )
		self.usage = getattr( self.response, 'usage', None )
		self.data = getattr( self.response, 'data', None )
		self.embeddings = [ ]

		if self.data is None or len( self.data ) == 0:
			self.embedding = None
			return None

		for item in self.data:
			value = getattr( item, 'embedding', None )
			if value is not None:
				self.embeddings.append( value )

		if len( self.embeddings ) == 0:
			self.embedding = None
			return None

		self.embedding = self.embeddings[ 0 ]

		if isinstance( self.input, str ):
			return self.embedding

		return self.embeddings
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Embeddings'
		exception.method = 'create( self, text: str | List[ str ], **kwargs )'
		Logger( ).write( exception )
		raise exception

__dir__

__dir__() -> List[str] | None

Return member names.

Purpose

Returns a stable list of public members exposed by the Embeddings object for interactive inspection, debugging, and application-level compatibility.

Returns:

Type Description
List[str] | None

Member names exposed for inspection.

Source code in gpt.py
def __dir__( self ) -> List[ str ] | None:
	"""Return member names.

	Purpose:
		Returns a stable list of public members exposed by the Embeddings object for
		interactive
		inspection, debugging, and application-level compatibility.

	Returns:
		Member names exposed for inspection.
	"""
	return [ 'api_key', 'client', 'model', 'input', 'encoding_format', 'dimensions', 'user',
		'response', 'embedding', 'embeddings', 'usage', 'request', 'model_options',
		'encoding_options', 'model_default_dimensions', 'model_max_dimensions',
		'model_dimension_support', 'validate_input', 'validate_dimensions',
		'get_default_dimensions', 'get_max_dimensions', 'build_request', 'create', ]

Files

Bases: GPT

Provide OpenAI Files API workflow support.

Purpose

Provides OpenAI file upload, listing, retrieval, content extraction, deletion, summary, search, and survey operations. The class assigns each accepted method argument to an object member before constructing and executing the corresponding provider request.

Attributes:

Name Type Description
api_key str

OpenAI API key used by the wrapper.

client Optional[OpenAI]

OpenAI client used by the wrapper.

file Any

Latest OpenAI file object.

file_id str

File identifier used by the current operation.

filepath str

Local file path used by an upload operation.

filename str

Filename associated with the current file.

purpose str

OpenAI file purpose.

response Any

Latest provider response.

content str | bytes | Dict[str, Any] | None

Retrieved file content.

files List[Dict[str, Any]]

File metadata returned by the latest list operation.

request Dict[str, Any]

Provider-ready request values.

model str

OpenAI model used for file-content analysis.

prompt str

Prompt used for file-content analysis.

output_text str

Text returned by the latest Responses API request.

max_chars int

Maximum file-content characters included in analysis.

Source code in gpt.py
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
class Files( GPT ):
	"""Provide OpenAI Files API workflow support.

	Purpose:
		Provides OpenAI file upload, listing, retrieval, content extraction, deletion, summary,
		search, and survey operations. The class assigns each accepted method argument to an
		object member before constructing and executing the corresponding provider request.

	Attributes:
		api_key (str): OpenAI API key used by the wrapper.
		client (Optional[OpenAI]): OpenAI client used by the wrapper.
		file (Any): Latest OpenAI file object.
		file_id (str): File identifier used by the current operation.
		filepath (str): Local file path used by an upload operation.
		filename (str): Filename associated with the current file.
		purpose (str): OpenAI file purpose.
		response (Any): Latest provider response.
		content (str | bytes | Dict[str, Any] | None): Retrieved file content.
		files (List[Dict[str, Any]]): File metadata returned by the latest list operation.
		request (Dict[str, Any]): Provider-ready request values.
		model (str): OpenAI model used for file-content analysis.
		prompt (str): Prompt used for file-content analysis.
		output_text (str): Text returned by the latest Responses API request.
		max_chars (int): Maximum file-content characters included in analysis.
	"""
	api_key: str
	client: Optional[ OpenAI ]
	file: Any
	file_id: str
	filepath: str
	filename: str
	purpose: str
	response: Any
	content: str | bytes | Dict[ str, Any ] | None
	files: List[ Dict[ str, Any ] ]
	request: Dict[ str, Any ]
	model: str
	prompt: str
	output_text: str
	max_chars: int

	def __init__( self, id: str = '', filepath: str = '', purpose: str = 'user_data',
		model: str = 'gpt-4o-mini', prompt: str = '' ) -> None:
		"""Initialize instance.

		Purpose:
			Initializes OpenAI Files API configuration and runtime state without executing a
			provider request.

		Args:
			id (str): Optional initial OpenAI file identifier.
			filepath (str): Optional initial local file path.
			purpose (str): Default OpenAI upload purpose.
			model (str): Default model used for file-content analysis.
			prompt (str): Optional initial file-analysis prompt.

		Returns:
			None: This method initializes object state.
		"""
		super( ).__init__( )
		self.api_key = cfg.OPENAI_API_KEY
		self.client = None
		self.file = None
		self.file_id = id
		self.filepath = filepath
		self.filename = ''
		self.purpose = purpose
		self.response = None
		self.content = None
		self.files = [ ]
		self.request = { }
		self.model = model
		self.prompt = prompt
		self.output_text = ''
		self.max_chars = 0
		self.metadata = { }
		self.preview = ''
		self.file_data = [ ]
		self.source = { }
		self.content_text = ''
		self.input = [ ]

	@property
	def upload_purpose_options( self ) -> List[ str ]:
		"""Get upload-purpose options.

		Purpose:
			Returns purposes accepted when uploading files through the OpenAI Files API.

		Returns:
			List[str]: Supported upload-purpose values.
		"""
		return [ 'assistants', 'batch', 'fine-tune', 'vision', 'user_data', 'evals', ]

	@property
	def file_purpose_options( self ) -> List[ str ]:
		"""Get file-purpose options.

		Purpose:
			Returns file-purpose values that may appear in OpenAI file metadata.

		Returns:
			List[str]: Supported file-purpose metadata values.
		"""
		return [ 'assistants', 'assistants_output', 'batch', 'batch_output', 'fine-tune',
			'fine-tune-results', 'vision', 'user_data', 'evals', ]

	@property
	def purpose_options( self ) -> List[ str ]:
		"""Get purpose options.

		Purpose:
			Returns upload-purpose values exposed to the application.

		Returns:
			List[str]: Supported upload-purpose values.
		"""
		return self.upload_purpose_options

	@property
	def model_options( self ) -> List[ str ]:
		"""Get file-analysis model options.

		Purpose:
			Returns OpenAI models exposed for file-content summary and search operations.

		Returns:
			List[str]: Supported model identifiers.
		"""
		return [ 'gpt-5-mini', 'gpt-5-nano', 'gpt-4.1-mini', 'gpt-4.1-nano', 'gpt-4o-mini', ]

	def get_file_metadata( self, file: Any ) -> Dict[ str, Any ]:
		"""Get file metadata.

		Purpose:
			Extracts application-facing metadata from a required OpenAI file object.

		Args:
			file (Any): Required OpenAI file object or file metadata dictionary.

		Returns:
			Dict[str, Any]: Application-facing file metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'file', file )
			self.file = file

			if isinstance( self.file, dict ):
				self.source = self.file
			elif hasattr( self.file, 'model_dump' ):
				self.source = self.file.model_dump( )
			else:
				self.source = { 'id': getattr( self.file, 'id', '' ),
					'bytes': getattr( self.file, 'bytes', 0 ),
					'created_at': getattr( self.file, 'created_at', 0 ),
					'expires_at': getattr( self.file, 'expires_at', 0 ),
					'filename': getattr( self.file, 'filename', '' ),
					'object': getattr( self.file, 'object', '' ),
					'purpose': getattr( self.file, 'purpose', '' ),
					'status': getattr( self.file, 'status', '' ),
					'status_details': getattr( self.file, 'status_details', None, ), }

			self.metadata = { 'id': self.source.get( 'id', '' ),
				'filename': self.source.get( 'filename', '' ),
				'purpose': self.source.get( 'purpose', '' ), 'bytes': self.source.get( 'bytes',
					0 ),
				'created_at': self.source.get( 'created_at', 0 ),
				'expires_at': self.source.get( 'expires_at', 0 ),
				'object': self.source.get( 'object', '' ),
				'status': self.source.get( 'status', '' ),
				'status_details': self.source.get( 'status_details', None, ), }
			return self.metadata
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = ('get_file_metadata( self, file: Any ) -> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def get_file_content( self, response: Any ) -> str | bytes | Dict[ str, Any ]:
		"""Get file content.

		Purpose:
			Extracts text, bytes, or structured content from a required OpenAI file-content
			response.

		Args:
			response (Any): Required OpenAI file-content response.

		Returns:
			str | bytes | Dict[str, Any]: Extracted file content.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'response', response )
			self.response = response

			if isinstance( self.response, bytes ):
				self.content = self.response
				return self.content

			if isinstance( self.response, str ):
				self.content = self.response
				return self.content

			if isinstance( self.response, dict ):
				self.content = self.response
				return self.content

			if hasattr( self.response, 'text' ):
				self.response_text = self.response.text

				if callable( self.response_text ):
					self.content = self.response_text( )
				else:
					self.content = self.response_text

				if self.content is not None:
					return self.content

			if hasattr( self.response, 'content' ):
				self.response_content = self.response.content

				if callable( self.response_content ):
					self.content = self.response_content( )
				else:
					self.content = self.response_content

				if self.content is not None:
					return self.content

			if hasattr( self.response, 'read' ):
				self.content = self.response.read( )
				return self.content

			if hasattr( self.response, 'model_dump' ):
				self.content = self.response.model_dump( )
				return self.content

			self.content = str( self.response )
			return self.content
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = ('get_file_content( self, response: Any ) -> '
			                    'str | bytes | Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def get_content_text( self, content: str | bytes | Dict[ str, Any ] ) -> str:
		"""Get content text.

		Purpose:
			Converts retrieved file content into text suitable for a Responses API request.

		Args:
			content (str | bytes | Dict[str, Any]): Required retrieved file content.

		Returns:
			str: File content represented as text.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'content', content )
			self.content = content
			self.content_text = ''

			if isinstance( self.content, str ):
				self.content_text = self.content
			elif isinstance( self.content, bytes ):
				self.content_text = self.content.decode( 'utf-8', errors='replace', )
			elif isinstance( self.content, dict ):
				self.content_text = json.dumps( self.content, ensure_ascii=False, indent=2,
					default=str, )
			else:
				self.content_text = str( self.content )

			throw_if( 'content_text', self.content_text )
			return self.content_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = ('get_content_text( self, content: str | bytes | '
			                    'Dict[ str, Any ] ) -> str')
			Logger( ).write( exception )
			raise exception

	def upload( self, path: str, purpose: str = 'user_data' ) -> Dict[ str, Any ]:
		"""Upload a file.

		Purpose:
			Uploads a required local file to the OpenAI Files API using the selected purpose.

		Args:
			path (str): Required local file path.
			purpose (str): OpenAI upload purpose.

		Returns:
			Dict[str, Any]: Metadata for the uploaded file.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'path', path )
			throw_if( 'purpose', purpose )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.filepath = path
			self.purpose = purpose
			self.filename = Path( self.filepath ).name
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'purpose': self.purpose, }

			with open( self.filepath, 'rb' ) as source:
				self.file = source
				self.response = self.client.files.create( file=self.file,
					purpose=self.request[ 'purpose' ], )

			self.file = self.response
			self.metadata = self.get_file_metadata( self.file )
			self.file_id = self.metadata.get( 'id', '', )
			self.filename = self.metadata.get( 'filename', self.filename, )
			return self.metadata
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = 'upload( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def list( self, purpose: str = '' ) -> List[ Dict[ str, Any ] ]:
		"""List files.

		Purpose:
			Lists files available through the OpenAI Files API and optionally limits the result
			to a selected file purpose.

		Args:
			purpose (str): Optional file-purpose filter.

		Returns:
			List[Dict[str, Any]]: Application-facing file metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.purpose = purpose
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { }
			self.response = self.client.files.list( )
			self.file_data = getattr( self.response, 'data', [ ], ) or [ ]
			self.files = [ ]

			for item in self.file_data:
				self.metadata = self.get_file_metadata( item )

				if self.purpose:
					if self.metadata.get( 'purpose', '' ) != self.purpose:
						continue

				self.files.append( self.metadata )

			return self.files
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = ('list( self, purpose: str = "" ) -> '
			                    'List[ Dict[ str, Any ] ]')
			Logger( ).write( exception )
			raise exception

	def retrieve( self, id: str ) -> Dict[ str, Any ]:
		"""Retrieve file metadata.

		Purpose:
			Retrieves metadata for a required OpenAI file identifier.

		Args:
			id (str): Required OpenAI file identifier.

		Returns:
			Dict[str, Any]: Application-facing file metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'id', id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.file_id = id
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'file_id': self.file_id, }
			self.response = self.client.files.retrieve( file_id=self.request[ 'file_id' ], )
			self.file = self.response
			self.metadata = self.get_file_metadata( self.file )
			self.filename = self.metadata.get( 'filename', '', )
			return self.metadata
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = ('retrieve( self, id: str ) -> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def extract( self, id: str ) -> str | bytes | Dict[ str, Any ]:
		"""Extract file content.

		Purpose:
			Retrieves content for a required OpenAI file identifier.

		Args:
			id (str): Required OpenAI file identifier.

		Returns:
			str | bytes | Dict[str, Any]: Retrieved file content.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'id', id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.file_id = id
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'file_id': self.file_id, }
			self.response = self.client.files.content( file_id=self.request[ 'file_id' ], )
			self.content = self.get_file_content( self.response )
			return self.content
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = ('extract( self, id: str ) -> '
			                    'str | bytes | Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def delete( self, id: str ) -> Dict[ str, Any ]:
		"""Delete a file.

		Purpose:
			Deletes a required OpenAI file identifier and returns the provider deletion result.

		Args:
			id (str): Required OpenAI file identifier.

		Returns:
			Dict[str, Any]: File deletion result.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'id', id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.file_id = id
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'file_id': self.file_id, }
			self.response = self.client.files.delete( file_id=self.request[ 'file_id' ], )

			if isinstance( self.response, dict ):
				self.metadata = self.response
			elif hasattr( self.response, 'model_dump' ):
				self.metadata = self.response.model_dump( )
			else:
				self.metadata = { 'id': getattr( self.response, 'id', self.file_id, ),
					'deleted': getattr( self.response, 'deleted', False, ),
					'object': getattr( self.response, 'object', 'file', ), }

			return self.metadata
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = ('delete( self, id: str ) -> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def summarize( self, id: str, prompt: str = 'Summarize the selected file content.',
		model: str = 'gpt-4o-mini', max_chars: int = 120000 ) -> str:
		"""Summarize file content.

		Purpose:
			Retrieves a required file and summarizes or analyzes its content through the OpenAI
			Responses API.

		Args:
			id (str): Required OpenAI file identifier.
			prompt (str): File-summary or analysis instruction.
			model (str): OpenAI model used for analysis.
			max_chars (int): Maximum content characters included in the request.

		Returns:
			str: Generated file-content analysis.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'id', id )
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.file_id = id
			self.prompt = prompt
			self.model = model
			self.max_chars = max_chars
			self.content = self.extract( self.file_id )
			self.content_text = self.get_content_text( self.content )

			if self.max_chars > 0:
				self.content_text = self.content_text[ :self.max_chars ]

			self.input = [
			{ 'role': 'user',
				'content': [ { 'type': 'input_text', 'text': (f'{self.prompt}\n\nFile ID: {self.file_id}\n\n{self.content_text}'), }, ], }, ]
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'model': self.model, 'input': self.input, }
			self.response = self.client.responses.create( **self.request )
			self.output_text = getattr( self.response, 'output_text', '', )

			if self.output_text:
				return self.output_text

			self.output_text = str( self.response )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = 'summarize( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def search( self, id: str, query: str, model: str = 'gpt-4o-mini',
		max_chars: int = 120000 ) -> str:
		"""Search file content.

		Purpose:
			Answers a required question using content retrieved from a required OpenAI file.

		Args:
			id (str): Required OpenAI file identifier.
			query (str): Required question about the selected file.
			model (str): OpenAI model used for analysis.
			max_chars (int): Maximum content characters included in the request.

		Returns:
			str: Generated answer based on the selected file.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'id', id )
			throw_if( 'query', query )
			throw_if( 'model', model )
			self.file_id = id
			self.query = query
			self.model = model
			self.max_chars = max_chars
			self.prompt = ('Answer the user question using the selected file content. '
			               f'Question: {self.query}')
			self.output_text = self.summarize( self.file_id, self.prompt, self.model,
				self.max_chars, )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = 'search( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def survey( self, id: str, max_chars: int = 4000 ) -> Dict[ str, Any ]:
		"""Survey a file.

		Purpose:
			Retrieves file metadata and a bounded content preview for a required OpenAI file.

		Args:
			id (str): Required OpenAI file identifier.
			max_chars (int): Maximum preview characters returned.

		Returns:
			Dict[str, Any]: File metadata, content preview, and file identifier.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'id', id )
			self.file_id = id
			self.max_chars = max_chars
			self.metadata = self.retrieve( self.file_id )
			self.content = self.extract( self.file_id )
			self.content_text = self.get_content_text( self.content )
			self.preview = self.content_text

			if self.max_chars > 0:
				self.preview = self.content_text[ :self.max_chars ]

			self.result = { 'metadata': self.metadata, 'preview': self.preview,
				'file_id': self.file_id, }
			return self.result
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'Files'
			exception.method = 'survey( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def __dir__( self ) -> List[ str ]:
		"""Return member names.

		Purpose:
			Returns public members exposed by the OpenAI Files wrapper.

		Returns:
			List[str]: Public member names.
		"""
		return [ 'api_key', 'client', 'file', 'file_id', 'filepath', 'filename', 'purpose',
			'response', 'content', 'files', 'request', 'model', 'prompt', 'output_text',
			'max_chars', 'metadata', 'preview', 'upload_purpose_options', 'file_purpose_options',
			'purpose_options', 'model_options', 'get_file_metadata', 'get_file_content',
			'get_content_text', 'upload', 'list', 'retrieve', 'extract', 'delete', 'summarize',
			'search', 'survey', ]

upload_purpose_options property

upload_purpose_options: List[str]

Get upload-purpose options.

Purpose

Returns purposes accepted when uploading files through the OpenAI Files API.

Returns:

Type Description
List[str]

List[str]: Supported upload-purpose values.

file_purpose_options property

file_purpose_options: List[str]

Get file-purpose options.

Purpose

Returns file-purpose values that may appear in OpenAI file metadata.

Returns:

Type Description
List[str]

List[str]: Supported file-purpose metadata values.

purpose_options property

purpose_options: List[str]

Get purpose options.

Purpose

Returns upload-purpose values exposed to the application.

Returns:

Type Description
List[str]

List[str]: Supported upload-purpose values.

model_options property

model_options: List[str]

Get file-analysis model options.

Purpose

Returns OpenAI models exposed for file-content summary and search operations.

Returns:

Type Description
List[str]

List[str]: Supported model identifiers.

__init__

__init__(
    id: str = "",
    filepath: str = "",
    purpose: str = "user_data",
    model: str = "gpt-4o-mini",
    prompt: str = "",
) -> None

Initialize instance.

Purpose

Initializes OpenAI Files API configuration and runtime state without executing a provider request.

Parameters:

Name Type Description Default
id str

Optional initial OpenAI file identifier.

''
filepath str

Optional initial local file path.

''
purpose str

Default OpenAI upload purpose.

'user_data'
model str

Default model used for file-content analysis.

'gpt-4o-mini'
prompt str

Optional initial file-analysis prompt.

''

Returns:

Name Type Description
None None

This method initializes object state.

Source code in gpt.py
def __init__( self, id: str = '', filepath: str = '', purpose: str = 'user_data',
	model: str = 'gpt-4o-mini', prompt: str = '' ) -> None:
	"""Initialize instance.

	Purpose:
		Initializes OpenAI Files API configuration and runtime state without executing a
		provider request.

	Args:
		id (str): Optional initial OpenAI file identifier.
		filepath (str): Optional initial local file path.
		purpose (str): Default OpenAI upload purpose.
		model (str): Default model used for file-content analysis.
		prompt (str): Optional initial file-analysis prompt.

	Returns:
		None: This method initializes object state.
	"""
	super( ).__init__( )
	self.api_key = cfg.OPENAI_API_KEY
	self.client = None
	self.file = None
	self.file_id = id
	self.filepath = filepath
	self.filename = ''
	self.purpose = purpose
	self.response = None
	self.content = None
	self.files = [ ]
	self.request = { }
	self.model = model
	self.prompt = prompt
	self.output_text = ''
	self.max_chars = 0
	self.metadata = { }
	self.preview = ''
	self.file_data = [ ]
	self.source = { }
	self.content_text = ''
	self.input = [ ]

get_file_metadata

get_file_metadata(file: Any) -> Dict[str, Any]

Get file metadata.

Purpose

Extracts application-facing metadata from a required OpenAI file object.

Parameters:

Name Type Description Default
file Any

Required OpenAI file object or file metadata dictionary.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_file_metadata( self, file: Any ) -> Dict[ str, Any ]:
	"""Get file metadata.

	Purpose:
		Extracts application-facing metadata from a required OpenAI file object.

	Args:
		file (Any): Required OpenAI file object or file metadata dictionary.

	Returns:
		Dict[str, Any]: Application-facing file metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'file', file )
		self.file = file

		if isinstance( self.file, dict ):
			self.source = self.file
		elif hasattr( self.file, 'model_dump' ):
			self.source = self.file.model_dump( )
		else:
			self.source = { 'id': getattr( self.file, 'id', '' ),
				'bytes': getattr( self.file, 'bytes', 0 ),
				'created_at': getattr( self.file, 'created_at', 0 ),
				'expires_at': getattr( self.file, 'expires_at', 0 ),
				'filename': getattr( self.file, 'filename', '' ),
				'object': getattr( self.file, 'object', '' ),
				'purpose': getattr( self.file, 'purpose', '' ),
				'status': getattr( self.file, 'status', '' ),
				'status_details': getattr( self.file, 'status_details', None, ), }

		self.metadata = { 'id': self.source.get( 'id', '' ),
			'filename': self.source.get( 'filename', '' ),
			'purpose': self.source.get( 'purpose', '' ), 'bytes': self.source.get( 'bytes',
				0 ),
			'created_at': self.source.get( 'created_at', 0 ),
			'expires_at': self.source.get( 'expires_at', 0 ),
			'object': self.source.get( 'object', '' ),
			'status': self.source.get( 'status', '' ),
			'status_details': self.source.get( 'status_details', None, ), }
		return self.metadata
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = ('get_file_metadata( self, file: Any ) -> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

get_file_content

get_file_content(
    response: Any,
) -> str | bytes | Dict[str, Any]

Get file content.

Purpose

Extracts text, bytes, or structured content from a required OpenAI file-content response.

Parameters:

Name Type Description Default
response Any

Required OpenAI file-content response.

required

Returns:

Type Description
str | bytes | Dict[str, Any]

str | bytes | Dict[str, Any]: Extracted file content.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_file_content( self, response: Any ) -> str | bytes | Dict[ str, Any ]:
	"""Get file content.

	Purpose:
		Extracts text, bytes, or structured content from a required OpenAI file-content
		response.

	Args:
		response (Any): Required OpenAI file-content response.

	Returns:
		str | bytes | Dict[str, Any]: Extracted file content.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'response', response )
		self.response = response

		if isinstance( self.response, bytes ):
			self.content = self.response
			return self.content

		if isinstance( self.response, str ):
			self.content = self.response
			return self.content

		if isinstance( self.response, dict ):
			self.content = self.response
			return self.content

		if hasattr( self.response, 'text' ):
			self.response_text = self.response.text

			if callable( self.response_text ):
				self.content = self.response_text( )
			else:
				self.content = self.response_text

			if self.content is not None:
				return self.content

		if hasattr( self.response, 'content' ):
			self.response_content = self.response.content

			if callable( self.response_content ):
				self.content = self.response_content( )
			else:
				self.content = self.response_content

			if self.content is not None:
				return self.content

		if hasattr( self.response, 'read' ):
			self.content = self.response.read( )
			return self.content

		if hasattr( self.response, 'model_dump' ):
			self.content = self.response.model_dump( )
			return self.content

		self.content = str( self.response )
		return self.content
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = ('get_file_content( self, response: Any ) -> '
		                    'str | bytes | Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

get_content_text

get_content_text(
    content: str | bytes | Dict[str, Any],
) -> str

Get content text.

Purpose

Converts retrieved file content into text suitable for a Responses API request.

Parameters:

Name Type Description Default
content str | bytes | Dict[str, Any]

Required retrieved file content.

required

Returns:

Name Type Description
str str

File content represented as text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_content_text( self, content: str | bytes | Dict[ str, Any ] ) -> str:
	"""Get content text.

	Purpose:
		Converts retrieved file content into text suitable for a Responses API request.

	Args:
		content (str | bytes | Dict[str, Any]): Required retrieved file content.

	Returns:
		str: File content represented as text.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'content', content )
		self.content = content
		self.content_text = ''

		if isinstance( self.content, str ):
			self.content_text = self.content
		elif isinstance( self.content, bytes ):
			self.content_text = self.content.decode( 'utf-8', errors='replace', )
		elif isinstance( self.content, dict ):
			self.content_text = json.dumps( self.content, ensure_ascii=False, indent=2,
				default=str, )
		else:
			self.content_text = str( self.content )

		throw_if( 'content_text', self.content_text )
		return self.content_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = ('get_content_text( self, content: str | bytes | '
		                    'Dict[ str, Any ] ) -> str')
		Logger( ).write( exception )
		raise exception

upload

upload(
    path: str, purpose: str = "user_data"
) -> Dict[str, Any]

Upload a file.

Purpose

Uploads a required local file to the OpenAI Files API using the selected purpose.

Parameters:

Name Type Description Default
path str

Required local file path.

required
purpose str

OpenAI upload purpose.

'user_data'

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Metadata for the uploaded file.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def upload( self, path: str, purpose: str = 'user_data' ) -> Dict[ str, Any ]:
	"""Upload a file.

	Purpose:
		Uploads a required local file to the OpenAI Files API using the selected purpose.

	Args:
		path (str): Required local file path.
		purpose (str): OpenAI upload purpose.

	Returns:
		Dict[str, Any]: Metadata for the uploaded file.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'path', path )
		throw_if( 'purpose', purpose )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.filepath = path
		self.purpose = purpose
		self.filename = Path( self.filepath ).name
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'purpose': self.purpose, }

		with open( self.filepath, 'rb' ) as source:
			self.file = source
			self.response = self.client.files.create( file=self.file,
				purpose=self.request[ 'purpose' ], )

		self.file = self.response
		self.metadata = self.get_file_metadata( self.file )
		self.file_id = self.metadata.get( 'id', '', )
		self.filename = self.metadata.get( 'filename', self.filename, )
		return self.metadata
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = 'upload( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

list

list(purpose: str = '') -> List[Dict[str, Any]]

List files.

Purpose

Lists files available through the OpenAI Files API and optionally limits the result to a selected file purpose.

Parameters:

Name Type Description Default
purpose str

Optional file-purpose filter.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Application-facing file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def list( self, purpose: str = '' ) -> List[ Dict[ str, Any ] ]:
	"""List files.

	Purpose:
		Lists files available through the OpenAI Files API and optionally limits the result
		to a selected file purpose.

	Args:
		purpose (str): Optional file-purpose filter.

	Returns:
		List[Dict[str, Any]]: Application-facing file metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.purpose = purpose
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { }
		self.response = self.client.files.list( )
		self.file_data = getattr( self.response, 'data', [ ], ) or [ ]
		self.files = [ ]

		for item in self.file_data:
			self.metadata = self.get_file_metadata( item )

			if self.purpose:
				if self.metadata.get( 'purpose', '' ) != self.purpose:
					continue

			self.files.append( self.metadata )

		return self.files
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = ('list( self, purpose: str = "" ) -> '
		                    'List[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

retrieve

retrieve(id: str) -> Dict[str, Any]

Retrieve file metadata.

Purpose

Retrieves metadata for a required OpenAI file identifier.

Parameters:

Name Type Description Default
id str

Required OpenAI file identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def retrieve( self, id: str ) -> Dict[ str, Any ]:
	"""Retrieve file metadata.

	Purpose:
		Retrieves metadata for a required OpenAI file identifier.

	Args:
		id (str): Required OpenAI file identifier.

	Returns:
		Dict[str, Any]: Application-facing file metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'id', id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.file_id = id
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'file_id': self.file_id, }
		self.response = self.client.files.retrieve( file_id=self.request[ 'file_id' ], )
		self.file = self.response
		self.metadata = self.get_file_metadata( self.file )
		self.filename = self.metadata.get( 'filename', '', )
		return self.metadata
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = ('retrieve( self, id: str ) -> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

extract

extract(id: str) -> str | bytes | Dict[str, Any]

Extract file content.

Purpose

Retrieves content for a required OpenAI file identifier.

Parameters:

Name Type Description Default
id str

Required OpenAI file identifier.

required

Returns:

Type Description
str | bytes | Dict[str, Any]

str | bytes | Dict[str, Any]: Retrieved file content.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def extract( self, id: str ) -> str | bytes | Dict[ str, Any ]:
	"""Extract file content.

	Purpose:
		Retrieves content for a required OpenAI file identifier.

	Args:
		id (str): Required OpenAI file identifier.

	Returns:
		str | bytes | Dict[str, Any]: Retrieved file content.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'id', id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.file_id = id
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'file_id': self.file_id, }
		self.response = self.client.files.content( file_id=self.request[ 'file_id' ], )
		self.content = self.get_file_content( self.response )
		return self.content
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = ('extract( self, id: str ) -> '
		                    'str | bytes | Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

delete

delete(id: str) -> Dict[str, Any]

Delete a file.

Purpose

Deletes a required OpenAI file identifier and returns the provider deletion result.

Parameters:

Name Type Description Default
id str

Required OpenAI file identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: File deletion result.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def delete( self, id: str ) -> Dict[ str, Any ]:
	"""Delete a file.

	Purpose:
		Deletes a required OpenAI file identifier and returns the provider deletion result.

	Args:
		id (str): Required OpenAI file identifier.

	Returns:
		Dict[str, Any]: File deletion result.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'id', id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.file_id = id
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'file_id': self.file_id, }
		self.response = self.client.files.delete( file_id=self.request[ 'file_id' ], )

		if isinstance( self.response, dict ):
			self.metadata = self.response
		elif hasattr( self.response, 'model_dump' ):
			self.metadata = self.response.model_dump( )
		else:
			self.metadata = { 'id': getattr( self.response, 'id', self.file_id, ),
				'deleted': getattr( self.response, 'deleted', False, ),
				'object': getattr( self.response, 'object', 'file', ), }

		return self.metadata
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = ('delete( self, id: str ) -> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

summarize

summarize(
    id: str,
    prompt: str = "Summarize the selected file content.",
    model: str = "gpt-4o-mini",
    max_chars: int = 120000,
) -> str

Summarize file content.

Purpose

Retrieves a required file and summarizes or analyzes its content through the OpenAI Responses API.

Parameters:

Name Type Description Default
id str

Required OpenAI file identifier.

required
prompt str

File-summary or analysis instruction.

'Summarize the selected file content.'
model str

OpenAI model used for analysis.

'gpt-4o-mini'
max_chars int

Maximum content characters included in the request.

120000

Returns:

Name Type Description
str str

Generated file-content analysis.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def summarize( self, id: str, prompt: str = 'Summarize the selected file content.',
	model: str = 'gpt-4o-mini', max_chars: int = 120000 ) -> str:
	"""Summarize file content.

	Purpose:
		Retrieves a required file and summarizes or analyzes its content through the OpenAI
		Responses API.

	Args:
		id (str): Required OpenAI file identifier.
		prompt (str): File-summary or analysis instruction.
		model (str): OpenAI model used for analysis.
		max_chars (int): Maximum content characters included in the request.

	Returns:
		str: Generated file-content analysis.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'id', id )
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.file_id = id
		self.prompt = prompt
		self.model = model
		self.max_chars = max_chars
		self.content = self.extract( self.file_id )
		self.content_text = self.get_content_text( self.content )

		if self.max_chars > 0:
			self.content_text = self.content_text[ :self.max_chars ]

		self.input = [
		{ 'role': 'user',
			'content': [ { 'type': 'input_text', 'text': (f'{self.prompt}\n\nFile ID: {self.file_id}\n\n{self.content_text}'), }, ], }, ]
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'model': self.model, 'input': self.input, }
		self.response = self.client.responses.create( **self.request )
		self.output_text = getattr( self.response, 'output_text', '', )

		if self.output_text:
			return self.output_text

		self.output_text = str( self.response )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = 'summarize( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

search

search(
    id: str,
    query: str,
    model: str = "gpt-4o-mini",
    max_chars: int = 120000,
) -> str

Search file content.

Purpose

Answers a required question using content retrieved from a required OpenAI file.

Parameters:

Name Type Description Default
id str

Required OpenAI file identifier.

required
query str

Required question about the selected file.

required
model str

OpenAI model used for analysis.

'gpt-4o-mini'
max_chars int

Maximum content characters included in the request.

120000

Returns:

Name Type Description
str str

Generated answer based on the selected file.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def search( self, id: str, query: str, model: str = 'gpt-4o-mini',
	max_chars: int = 120000 ) -> str:
	"""Search file content.

	Purpose:
		Answers a required question using content retrieved from a required OpenAI file.

	Args:
		id (str): Required OpenAI file identifier.
		query (str): Required question about the selected file.
		model (str): OpenAI model used for analysis.
		max_chars (int): Maximum content characters included in the request.

	Returns:
		str: Generated answer based on the selected file.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'id', id )
		throw_if( 'query', query )
		throw_if( 'model', model )
		self.file_id = id
		self.query = query
		self.model = model
		self.max_chars = max_chars
		self.prompt = ('Answer the user question using the selected file content. '
		               f'Question: {self.query}')
		self.output_text = self.summarize( self.file_id, self.prompt, self.model,
			self.max_chars, )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = 'search( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

survey

survey(id: str, max_chars: int = 4000) -> Dict[str, Any]

Survey a file.

Purpose

Retrieves file metadata and a bounded content preview for a required OpenAI file.

Parameters:

Name Type Description Default
id str

Required OpenAI file identifier.

required
max_chars int

Maximum preview characters returned.

4000

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: File metadata, content preview, and file identifier.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def survey( self, id: str, max_chars: int = 4000 ) -> Dict[ str, Any ]:
	"""Survey a file.

	Purpose:
		Retrieves file metadata and a bounded content preview for a required OpenAI file.

	Args:
		id (str): Required OpenAI file identifier.
		max_chars (int): Maximum preview characters returned.

	Returns:
		Dict[str, Any]: File metadata, content preview, and file identifier.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'id', id )
		self.file_id = id
		self.max_chars = max_chars
		self.metadata = self.retrieve( self.file_id )
		self.content = self.extract( self.file_id )
		self.content_text = self.get_content_text( self.content )
		self.preview = self.content_text

		if self.max_chars > 0:
			self.preview = self.content_text[ :self.max_chars ]

		self.result = { 'metadata': self.metadata, 'preview': self.preview,
			'file_id': self.file_id, }
		return self.result
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'Files'
		exception.method = 'survey( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

__dir__

__dir__() -> List[str]

Return member names.

Purpose

Returns public members exposed by the OpenAI Files wrapper.

Returns:

Type Description
List[str]

List[str]: Public member names.

Source code in gpt.py
def __dir__( self ) -> List[ str ]:
	"""Return member names.

	Purpose:
		Returns public members exposed by the OpenAI Files wrapper.

	Returns:
		List[str]: Public member names.
	"""
	return [ 'api_key', 'client', 'file', 'file_id', 'filepath', 'filename', 'purpose',
		'response', 'content', 'files', 'request', 'model', 'prompt', 'output_text',
		'max_chars', 'metadata', 'preview', 'upload_purpose_options', 'file_purpose_options',
		'purpose_options', 'model_options', 'get_file_metadata', 'get_file_content',
		'get_content_text', 'upload', 'list', 'retrieve', 'extract', 'delete', 'summarize',
		'search', 'survey', ]

VectorStores

Bases: GPT

Provide OpenAI Vector Stores API workflow support.

Purpose

Provides vector-store management, attached-file management, file-batch operations, native vector-store search, and Responses API file-search workflows. Each public wrapper method checks required input with throw_if, assigns accepted arguments to object members, constructs provider requests from those members, and returns application-facing metadata or generated text.

Attributes:

Name Type Description
api_key str

OpenAI API key used by the wrapper.

client Optional[OpenAI]

OpenAI client used by the wrapper.

name str

Vector-store name used by the current operation.

description str

Vector-store description used by the current operation.

store_id str

Vector-store identifier used by the current operation.

file_id str

File identifier used by the current operation.

file_ids List[str]

File identifiers used by the current operation.

batch_id str

File-batch identifier used by the current operation.

model str

OpenAI model used by file-search answer workflows.

query str

Native vector-store search query.

prompt str

Responses API file-search prompt.

instructions str

Optional Responses API instructions.

max_search_results int

Maximum number of search results requested.

response Any

Latest provider response.

vector_store Dict[str, Any]

Latest vector-store metadata.

vector_stores List[Dict[str, Any]]

Latest vector-store collection.

vector_file Dict[str, Any]

Latest attached-file metadata.

vector_files List[Dict[str, Any]]

Latest attached-file collection.

file_batch Dict[str, Any]

Latest file-batch metadata.

search_results List[Dict[str, Any]]

Latest native search results.

output_text str

Latest Responses API file-search answer.

request Dict[str, Any]

Provider-ready request.

Source code in gpt.py
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
class VectorStores( GPT ):
	"""Provide OpenAI Vector Stores API workflow support.

	Purpose:
		Provides vector-store management, attached-file management, file-batch operations,
		native vector-store search, and Responses API file-search workflows. Each public
		wrapper method checks required input with throw_if, assigns accepted arguments to
		object members, constructs provider requests from those members, and returns
		application-facing metadata or generated text.

	Attributes:
		api_key (str): OpenAI API key used by the wrapper.
		client (Optional[OpenAI]): OpenAI client used by the wrapper.
		name (str): Vector-store name used by the current operation.
		description (str): Vector-store description used by the current operation.
		store_id (str): Vector-store identifier used by the current operation.
		file_id (str): File identifier used by the current operation.
		file_ids (List[str]): File identifiers used by the current operation.
		batch_id (str): File-batch identifier used by the current operation.
		model (str): OpenAI model used by file-search answer workflows.
		query (str): Native vector-store search query.
		prompt (str): Responses API file-search prompt.
		instructions (str): Optional Responses API instructions.
		max_search_results (int): Maximum number of search results requested.
		response (Any): Latest provider response.
		vector_store (Dict[str, Any]): Latest vector-store metadata.
		vector_stores (List[Dict[str, Any]]): Latest vector-store collection.
		vector_file (Dict[str, Any]): Latest attached-file metadata.
		vector_files (List[Dict[str, Any]]): Latest attached-file collection.
		file_batch (Dict[str, Any]): Latest file-batch metadata.
		search_results (List[Dict[str, Any]]): Latest native search results.
		output_text (str): Latest Responses API file-search answer.
		request (Dict[str, Any]): Provider-ready request.
	"""
	api_key: str
	client: Optional[ OpenAI ]
	name: str
	description: str
	store_id: str
	file_id: str
	file_ids: List[ str ]
	batch_id: str
	model: str
	query: str
	prompt: str
	instructions: str
	max_search_results: int
	response: Any
	vector_store: Dict[ str, Any ]
	vector_stores: List[ Dict[ str, Any ] ]
	vector_file: Dict[ str, Any ]
	vector_files: List[ Dict[ str, Any ] ]
	file_batch: Dict[ str, Any ]
	search_results: List[ Dict[ str, Any ] ]
	output_text: str
	request: Dict[ str, Any ]

	def __init__( self, name: str = '', store_id: str = '', file_id: str = '',
		model: str = 'gpt-4o-mini', max_search_results: int = 10 ) -> None:
		"""Initialize instance.

		Purpose:
			Initializes OpenAI vector-store configuration and runtime state without executing a
			provider request.

		Args:
			name (str): Optional initial vector-store name.
			store_id (str): Optional initial vector-store identifier.
			file_id (str): Optional initial file identifier.
			model (str): Default model used by file-search answer workflows.
			max_search_results (int): Default maximum number of search results.

		Returns:
			None: This method initializes object state.
		"""
		super( ).__init__( )
		self.api_key = cfg.OPENAI_API_KEY
		self.client = None
		self.name = name
		self.description = ''
		self.store_id = store_id
		self.file_id = file_id
		self.file_ids = [ ]
		self.batch_id = ''
		self.model = model
		self.query = ''
		self.prompt = ''
		self.instructions = ''
		self.max_search_results = max_search_results
		self.metadata = { }
		self.attributes = { }
		self.filters = { }
		self.ranking_options = { }
		self.expires_after = { }
		self.chunking_strategy = { }
		self.response = None
		self.vector_store = { }
		self.vector_stores = [ ]
		self.vector_file = { }
		self.vector_files = [ ]
		self.file_batch = { }
		self.search_results = [ ]
		self.output_text = ''
		self.request = { }
		self.input = [ ]
		self.limit = 100
		self.order = 'desc'
		self.after = ''
		self.before = ''
		self.rewrite_query = False
		self.collections = { 'Governance': 'vs_6a1850a9bdc08191912353eedf59aede',
			'Public Laws': 'vs_699506f7d5348191990e0557c717fa9d',
			'Explanatory Statements': 'vs_699505df9ac48191a525c0ecb86fef66',
			'Army Techniques Publications': 'vs_699356ef052c81918da14c4ed3bcea17',
			'Army Field Manuals': 'vs_69935542863481918d150c1e89c38633',
			'Army Regulations': 'vs_6993550488408191919cd70968ba8be8',
			'DoD Armory': 'vs_697f86ad98888191b967685ae558bfc0',
			'Army Style Guides': 'vs_68f4efd7d4c4819191458dd6cde6f2cc',
			'Apportionments': 'vs_68a34aaff93481918c3b3fef8c4e8fea',
			'Financial Regulations': 'vs_712r5W5833G6aLxIYIbuvVcK', }

	@property
	def model_options( self ) -> List[ str ]:
		"""Get model options.

		Purpose:
			Returns OpenAI models exposed for Responses API file-search answer workflows.

		Returns:
			List[str]: Supported model identifiers.
		"""
		return [ 'gpt-5-mini', 'gpt-5-nano', 'gpt-4.1-mini', 'gpt-4.1-nano', 'gpt-4o-mini', ]

	@property
	def ranker_options( self ) -> List[ str ]:
		"""Get ranker options.

		Purpose:
			Returns ranking algorithms exposed for native vector-store search.

		Returns:
			List[str]: Supported ranker values.
		"""
		return [ 'auto', 'default-2024-11-15', ]

	@property
	def chunking_strategy_options( self ) -> List[ str ]:
		"""Get chunking-strategy options.

		Purpose:
			Returns chunking strategies supported by vector-store file operations.

		Returns:
			List[str]: Supported chunking-strategy values.
		"""
		return [ 'auto', 'static', ]

	def get_vector_store( self, response: Any ) -> Dict[ str, Any ]:
		"""Get vector-store metadata.

		Purpose:
			Extracts application-facing metadata from a required vector-store response.

		Args:
			response (Any): Required provider vector-store response.

		Returns:
			Dict[str, Any]: Application-facing vector-store metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'response', response )
			self.response = response

			if isinstance( self.response, dict ):
				self.source = self.response
			elif hasattr( self.response, 'model_dump' ):
				self.source = self.response.model_dump( )
			else:
				self.source = { 'id': getattr( self.response, 'id', '' ),
					'name': getattr( self.response, 'name', '' ),
					'description': getattr( self.response, 'description', '' ),
					'created_at': getattr( self.response, 'created_at', 0 ),
					'object': getattr( self.response, 'object', '' ),
					'usage_bytes': getattr( self.response, 'usage_bytes', 0 ),
					'file_counts': getattr( self.response, 'file_counts', None ),
					'status': getattr( self.response, 'status', '' ),
					'expires_after': getattr( self.response, 'expires_after', None ),
					'expires_at': getattr( self.response, 'expires_at', 0 ),
					'last_active_at': getattr( self.response, 'last_active_at', 0 ),
					'metadata': getattr( self.response, 'metadata', None ), }

			self.vector_store = { 'id': self.source.get( 'id', '' ),
				'name': self.source.get( 'name', '' ),
				'description': self.source.get( 'description', '' ),
				'created_at': self.source.get( 'created_at', 0 ),
				'object': self.source.get( 'object', '' ),
				'usage_bytes': self.source.get( 'usage_bytes', 0 ),
				'file_counts': self.source.get( 'file_counts', None ),
				'status': self.source.get( 'status', '' ),
				'expires_after': self.source.get( 'expires_after', None ),
				'expires_at': self.source.get( 'expires_at', 0 ),
				'last_active_at': self.source.get( 'last_active_at', 0 ),
				'metadata': self.source.get( 'metadata', None ), }
			return self.vector_store
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'get_vector_store( self, response: Any )'
			Logger( ).write( exception )
			raise exception

	def get_vector_file( self, response: Any ) -> Dict[ str, Any ]:
		"""Get vector-store file metadata.

		Purpose:
			Extracts application-facing metadata from a required vector-store file response.

		Args:
			response (Any): Required provider vector-store file response.

		Returns:
			Dict[str, Any]: Application-facing attached-file metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'response', response )
			self.response = response

			if isinstance( self.response, dict ):
				self.source = self.response
			elif hasattr( self.response, 'model_dump' ):
				self.source = self.response.model_dump( )
			else:
				self.source = { 'id': getattr( self.response, 'id', '' ),
					'object': getattr( self.response, 'object', '' ),
					'created_at': getattr( self.response, 'created_at', 0 ),
					'vector_store_id': getattr( self.response, 'vector_store_id', '', ),
					'status': getattr( self.response, 'status', '' ),
					'last_error': getattr( self.response, 'last_error', None ),
					'chunking_strategy': getattr( self.response, 'chunking_strategy', None, ),
					'attributes': getattr( self.response, 'attributes', None ),
					'usage_bytes': getattr( self.response, 'usage_bytes', 0 ), }

			self.vector_file = { 'id': self.source.get( 'id', '' ),
				'object': self.source.get( 'object', '' ),
				'created_at': self.source.get( 'created_at', 0 ),
				'vector_store_id': self.source.get( 'vector_store_id', '' ),
				'status': self.source.get( 'status', '' ),
				'last_error': self.source.get( 'last_error', None ),
				'chunking_strategy': self.source.get( 'chunking_strategy', None ),
				'attributes': self.source.get( 'attributes', None ),
				'usage_bytes': self.source.get( 'usage_bytes', 0 ), }
			return self.vector_file
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'get_vector_file( self, response: Any )'
			Logger( ).write( exception )
			raise exception

	def get_file_batch( self, response: Any ) -> Dict[ str, Any ]:
		"""Get file-batch metadata.

		Purpose:
			Extracts application-facing metadata from a required file-batch response.

		Args:
			response (Any): Required provider file-batch response.

		Returns:
			Dict[str, Any]: Application-facing file-batch metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'response', response )
			self.response = response

			if isinstance( self.response, dict ):
				self.source = self.response
			elif hasattr( self.response, 'model_dump' ):
				self.source = self.response.model_dump( )
			else:
				self.source = { 'id': getattr( self.response, 'id', '' ),
					'object': getattr( self.response, 'object', '' ),
					'created_at': getattr( self.response, 'created_at', 0 ),
					'vector_store_id': getattr( self.response, 'vector_store_id', '', ),
					'status': getattr( self.response, 'status', '' ),
					'file_counts': getattr( self.response, 'file_counts', None, ), }

			self.file_batch = { 'id': self.source.get( 'id', '' ),
				'object': self.source.get( 'object', '' ),
				'created_at': self.source.get( 'created_at', 0 ),
				'vector_store_id': self.source.get( 'vector_store_id', '' ),
				'status': self.source.get( 'status', '' ),
				'file_counts': self.source.get( 'file_counts', None ), }
			return self.file_batch
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'get_file_batch( self, response: Any )'
			Logger( ).write( exception )
			raise exception

	def get_search_results( self, response: Any ) -> List[ Dict[ str, Any ] ]:
		"""Get vector-store search results.

		Purpose:
			Extracts native vector-store search results from a required provider response.

		Args:
			response (Any): Required provider vector-store search response.

		Returns:
			List[Dict[str, Any]]: Application-facing search results.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'response', response )
			self.response = response
			self.items = getattr( self.response, 'data', [ ], ) or [ ]
			self.search_results = [ ]

			for item in self.items:
				if isinstance( item, dict ):
					self.source = item
				elif hasattr( item, 'model_dump' ):
					self.source = item.model_dump( )
				else:
					self.source = { 'file_id': getattr( item, 'file_id', '' ),
						'filename': getattr( item, 'filename', '' ),
						'score': getattr( item, 'score', 0.0 ),
						'attributes': getattr( item, 'attributes', None ),
						'content': getattr( item, 'content', [ ] ), }

				self.search_results.append( { 'file_id': self.source.get( 'file_id', '' ),
					'filename': self.source.get( 'filename', '' ),
					'score': self.source.get( 'score', 0.0 ),
					'attributes': self.source.get( 'attributes', None ),
					'content': self.source.get( 'content', [ ] ), } )

			return self.search_results
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'get_search_results( self, response: Any )'
			Logger( ).write( exception )
			raise exception

	def create( self, name: str, description: str = '',
		metadata: Optional[ Dict[ str, Any ] ] = None,
		expires_after: Optional[ Dict[ str, Any ] ] = None,
		file_ids: Optional[ List[ str ] ] = None,
		chunking_strategy: Optional[ Dict[ str, Any ] ] = None ) -> Dict[ str, Any ]:
		"""Create a vector store.

		Purpose:
			Creates a vector store with a required name and optional description, metadata,
			expiration policy, files, and chunking strategy.

		Args:
			name (str): Required vector-store name.
			description (str): Optional vector-store description.
			metadata (Optional[Dict[str, Any]]): Optional vector-store metadata.
			expires_after (Optional[Dict[str, Any]]): Optional expiration policy.
			file_ids (Optional[List[str]]): Optional files attached during creation.
			chunking_strategy (Optional[Dict[str, Any]]): Optional chunking strategy.

		Returns:
			Dict[str, Any]: Created vector-store metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'name', name )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.name = name
			self.description = description
			self.metadata = metadata if metadata is not None else { }
			self.expires_after = (expires_after if expires_after is not None else { })
			self.file_ids = file_ids if file_ids is not None else [ ]
			self.chunking_strategy = (chunking_strategy if chunking_strategy is not None else { })
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'name': self.name, }

			if self.description:
				self.request[ 'description' ] = self.description

			if self.metadata:
				self.request[ 'metadata' ] = self.metadata

			if self.expires_after:
				self.request[ 'expires_after' ] = self.expires_after

			if self.file_ids:
				self.request[ 'file_ids' ] = self.file_ids

			if self.chunking_strategy:
				self.request[ 'chunking_strategy' ] = self.chunking_strategy

			self.response = self.client.vector_stores.create( **self.request )
			self.vector_store = self.get_vector_store( self.response )
			self.store_id = self.vector_store.get( 'id', '', )
			return self.vector_store
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'create( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def list_stores( self, limit: int = 100, order: str = 'desc', after: str = '',
		before: str = '' ) -> List[ Dict[ str, Any ] ]:
		"""List vector stores.

		Purpose:
			Lists vector stores using the selected result limit, order, and cursor values.

		Args:
			limit (int): Maximum number of vector stores returned.
			order (str): Result order.
			after (str): Optional cursor identifying the first result boundary.
			before (str): Optional cursor identifying the last result boundary.

		Returns:
			List[Dict[str, Any]]: Vector-store metadata rows.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.limit = limit
			self.order = order
			self.after = after
			self.before = before
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'limit': self.limit, 'order': self.order, }

			if self.after:
				self.request[ 'after' ] = self.after

			if self.before:
				self.request[ 'before' ] = self.before

			self.response = self.client.vector_stores.list( **self.request )
			self.items = getattr( self.response, 'data', [ ], ) or [ ]
			self.vector_stores = [ self.get_vector_store( item ) for item in self.items ]
			return self.vector_stores
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'list_stores( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def list( self, limit: int=100, order: str='desc', after: str='',
		before: str='' ) -> List[ Dict[ str, Any ] ]:
		"""List vector stores.

		Purpose:
			Provides the application-compatible list alias for vector-store listing.

		Args:
			limit (int): Maximum number of vector stores returned.
			order (str): Result order.
			after (str): Optional after cursor.
			before (str): Optional before cursor.

		Returns:
			List[Dict[str, Any]]: Vector-store metadata rows.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.limit = limit
			self.order = order
			self.after = after
			self.before = before
			return self.list_stores( self.limit, self.order, self.after, self.before, )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'list( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def retrieve( self, store_id: str ) -> Dict[ str, Any ]:
		"""Retrieve a vector store.

		Purpose:
			Retrieves metadata for a required vector-store identifier.

		Args:
			store_id (str): Required vector-store identifier.

		Returns:
			Dict[str, Any]: Retrieved vector-store metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.client = OpenAI( api_key=self.api_key, )
			self.response = self.client.vector_stores.retrieve( self.store_id )
			self.vector_store = self.get_vector_store( self.response )
			return self.vector_store
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = ('retrieve( self, store_id: str ) -> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def update( self, store_id: str, name: str = '', description: str = '',
		metadata: Optional[ Dict[ str, Any ] ] = None,
		expires_after: Optional[ Dict[ str, Any ] ] = None ) -> Dict[ str, Any ]:
		"""Update a vector store.

		Purpose:
			Updates a required vector store using supplied name, description, metadata, or
			expiration-policy values.

		Args:
			store_id (str): Required vector-store identifier.
			name (str): Optional updated vector-store name.
			description (str): Optional updated description.
			metadata (Optional[Dict[str, Any]]): Optional updated metadata.
			expires_after (Optional[Dict[str, Any]]): Optional updated expiration policy.

		Returns:
			Dict[str, Any]: Updated vector-store metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.name = name
			self.description = description
			self.metadata = metadata if metadata is not None else { }
			self.expires_after = (expires_after if expires_after is not None else { })
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { }

			if self.name:
				self.request[ 'name' ] = self.name

			if self.description:
				self.request[ 'description' ] = self.description

			if metadata is not None:
				self.request[ 'metadata' ] = self.metadata

			if self.expires_after:
				self.request[ 'expires_after' ] = self.expires_after

			if not self.request:
				return self.retrieve( self.store_id )

			self.response = self.client.vector_stores.update( self.store_id, **self.request )
			self.vector_store = self.get_vector_store( self.response )
			return self.vector_store
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'update( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def delete( self, store_id: str ) -> Dict[ str, Any ]:
		"""Delete a vector store.

		Purpose:
			Deletes a required vector-store identifier.

		Args:
			store_id (str): Required vector-store identifier.

		Returns:
			Dict[str, Any]: Provider deletion result.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.client = OpenAI( api_key=self.api_key, )
			self.response = self.client.vector_stores.delete( self.store_id )

			if isinstance( self.response, dict ):
				return self.response

			if hasattr( self.response, 'model_dump' ):
				return self.response.model_dump( )

			return { 'id': getattr( self.response, 'id', self.store_id ),
				'deleted': getattr( self.response, 'deleted', False ),
				'object': getattr( self.response, 'object', '' ), }
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = ('delete( self, store_id: str ) -> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def attach_file( self, store_id: str, file_id: str,
		attributes: Optional[ Dict[ str, Any ] ] = None,
		chunking_strategy: Optional[ Dict[ str, Any ] ] = None ) -> Dict[ str, Any ]:
		"""Attach a file.

		Purpose:
			Attaches a required OpenAI file to a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			file_id (str): Required OpenAI file identifier.
			attributes (Optional[Dict[str, Any]]): Optional attached-file attributes.
			chunking_strategy (Optional[Dict[str, Any]]): Optional chunking strategy.

		Returns:
			Dict[str, Any]: Attached-file metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'file_id', file_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.file_id = file_id
			self.attributes = attributes if attributes is not None else { }
			self.chunking_strategy = (chunking_strategy if chunking_strategy is not None else { })
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'file_id': self.file_id, }

			if self.attributes:
				self.request[ 'attributes' ] = self.attributes

			if self.chunking_strategy:
				self.request[ 'chunking_strategy' ] = self.chunking_strategy

			self.response = self.client.vector_stores.files.create( self.store_id, **self.request )
			self.vector_file = self.get_vector_file( self.response )
			return self.vector_file
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'attach_file( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def list_files( self, store_id: str, limit: int = 100, order: str = 'desc', after: str = '',
		before: str = '', filter: str = '' ) -> List[ Dict[ str, Any ] ]:
		"""List attached files.

		Purpose:
			Lists files attached to a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			limit (int): Maximum number of files returned.
			order (str): Result order.
			after (str): Optional after cursor.
			before (str): Optional before cursor.
			filter (str): Optional attached-file status filter.

		Returns:
			List[Dict[str, Any]]: Attached-file metadata rows.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.limit = limit
			self.order = order
			self.after = after
			self.before = before
			self.filter = filter
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'limit': self.limit, 'order': self.order, }
			if self.after:
				self.request[ 'after' ] = self.after

			if self.before:
				self.request[ 'before' ] = self.before

			if self.filter:
				self.request[ 'filter' ] = self.filter

			self.response = self.client.vector_stores.files.list( self.store_id, **self.request )
			self.items = getattr( self.response, 'data', [ ], ) or [ ]
			self.vector_files = [ self.get_vector_file( item ) for item in self.items ]
			return self.vector_files
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'list_files( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def retrieve_file( self, store_id: str, file_id: str ) -> Dict[ str, Any ]:
		"""Retrieve an attached file.

		Purpose:
			Retrieves metadata for a required file attached to a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			file_id (str): Required attached-file identifier.

		Returns:
			Dict[str, Any]: Attached-file metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'file_id', file_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.file_id = file_id
			self.client = OpenAI( api_key=self.api_key, )
			self.response = self.client.vector_stores.files.retrieve( self.file_id,
				vector_store_id=self.store_id, )
			self.vector_file = self.get_vector_file( self.response )
			return self.vector_file
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'retrieve_file( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def update_file( self, store_id: str, file_id: str,
		attributes: Dict[ str, Any ] ) -> Dict[ str, Any ]:
		"""Update an attached file.

		Purpose:
			Updates attributes for a required file attached to a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			file_id (str): Required attached-file identifier.
			attributes (Dict[str, Any]): Required updated file attributes.

		Returns:
			Dict[str, Any]: Updated attached-file metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'file_id', file_id )
			throw_if( 'attributes', attributes )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.file_id = file_id
			self.attributes = attributes
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'attributes': self.attributes, }
			self.response = self.client.vector_stores.files.update( self.file_id,
				vector_store_id=self.store_id, **self.request )
			self.vector_file = self.get_vector_file( self.response )
			return self.vector_file
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'update_file( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def delete_file( self, store_id: str, file_id: str ) -> Dict[ str, Any ]:
		"""Delete an attached file.

		Purpose:
			Removes a required file from a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			file_id (str): Required attached-file identifier.

		Returns:
			Dict[str, Any]: Provider deletion result.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'file_id', file_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.file_id = file_id
			self.client = OpenAI( api_key=self.api_key, )
			self.response = self.client.vector_stores.files.delete( self.file_id,
				vector_store_id=self.store_id, )

			if isinstance( self.response, dict ):
				return self.response

			if hasattr( self.response, 'model_dump' ):
				return self.response.model_dump( )

			return { 'id': getattr( self.response, 'id', self.file_id ),
				'deleted': getattr( self.response, 'deleted', False ),
				'object': getattr( self.response, 'object', '' ), }
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'delete_file( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def retrieve_file_content( self, store_id: str, file_id: str ) -> Any:
		"""Retrieve attached-file content.

		Purpose:
			Retrieves parsed content for a required file attached to a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			file_id (str): Required attached-file identifier.

		Returns:
			Any: Provider file-content response.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'file_id', file_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.file_id = file_id
			self.client = OpenAI( api_key=self.api_key, )
			self.response = self.client.vector_stores.files.content( self.file_id,
				vector_store_id=self.store_id, )
			return self.response
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'retrieve_file_content( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def create_file_batch( self, store_id: str, file_ids: List[ str ],
		attributes: Optional[ Dict[ str, Any ] ] = None,
		chunking_strategy: Optional[ Dict[ str, Any ] ] = None ) -> Dict[ str, Any ]:
		"""Create a file batch.

		Purpose:
			Creates a file batch for required files in a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			file_ids (List[str]): Required OpenAI file identifiers.
			attributes (Optional[Dict[str, Any]]): Optional common file attributes.
			chunking_strategy (Optional[Dict[str, Any]]): Optional chunking strategy.

		Returns:
			Dict[str, Any]: Created file-batch metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'file_ids', file_ids )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.file_ids = file_ids
			self.attributes = attributes if attributes is not None else { }
			self.chunking_strategy = (chunking_strategy if chunking_strategy is not None else { })
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'file_ids': self.file_ids, }

			if self.attributes:
				self.request[ 'attributes' ] = self.attributes

			if self.chunking_strategy:
				self.request[ 'chunking_strategy' ] = self.chunking_strategy

			self.response = self.client.vector_stores.file_batches.create( self.store_id,
				**self.request )
			self.file_batch = self.get_file_batch( self.response )
			self.batch_id = self.file_batch.get( 'id', '', )
			return self.file_batch
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'create_file_batch( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def retrieve_file_batch( self, store_id: str, batch_id: str ) -> Dict[ str, Any ]:
		"""Retrieve a file batch.

		Purpose:
			Retrieves metadata for a required file batch in a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			batch_id (str): Required file-batch identifier.

		Returns:
			Dict[str, Any]: File-batch metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'batch_id', batch_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.batch_id = batch_id
			self.client = OpenAI( api_key=self.api_key, )
			self.response = self.client.vector_stores.file_batches.retrieve( self.batch_id,
				vector_store_id=self.store_id, )
			self.file_batch = self.get_file_batch( self.response )
			return self.file_batch
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'retrieve_file_batch( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def list_file_batch_files( self, store_id: str, batch_id: str, limit: int = 100,
		order: str = 'desc', after: str = '', before: str = '', filter: str = '' ) -> List[
		Dict[ str, Any ] ]:
		"""List file-batch files.

		Purpose:
			Lists files associated with a required file batch and vector store.

		Args:
			store_id (str): Required vector-store identifier.
			batch_id (str): Required file-batch identifier.
			limit (int): Maximum number of files returned.
			order (str): Result order.
			after (str): Optional after cursor.
			before (str): Optional before cursor.
			filter (str): Optional file-status filter.

		Returns:
			List[Dict[str, Any]]: File-batch attached-file metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'batch_id', batch_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.batch_id = batch_id
			self.limit = limit
			self.order = order
			self.after = after
			self.before = before
			self.filter = filter
			self.client = OpenAI( api_key=self.api_key, )
			self.request = { 'limit': self.limit, 'order': self.order, }

			if self.after:
				self.request[ 'after' ] = self.after

			if self.before:
				self.request[ 'before' ] = self.before

			if self.filter:
				self.request[ 'filter' ] = self.filter

			self.response = self.client.vector_stores.file_batches.list_files( self.batch_id,
				vector_store_id=self.store_id, **self.request )
			self.items = getattr( self.response, 'data', [ ], ) or [ ]
			self.vector_files = [ self.get_vector_file( item ) for item in self.items ]
			return self.vector_files
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'list_file_batch_files( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def cancel_file_batch( self, store_id: str, batch_id: str ) -> Dict[ str, Any ]:
		"""Cancel a file batch.

		Purpose:
			Cancels a required file batch in a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			batch_id (str): Required file-batch identifier.

		Returns:
			Dict[str, Any]: Updated file-batch metadata.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'batch_id', batch_id )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.batch_id = batch_id
			self.client = OpenAI( api_key=self.api_key, )
			self.response = self.client.vector_stores.file_batches.cancel( self.batch_id,
				vector_store_id=self.store_id, )
			self.file_batch = self.get_file_batch( self.response )
			return self.file_batch
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'cancel_file_batch( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def search( self, store_id: str, query: str, max_num_results: int = 10,
		filters: Optional[ Dict[ str, Any ] ] = None,
		ranking_options: Optional[ Dict[ str, Any ] ] = None, rewrite_query: bool = False ) -> (
			List)[
		Dict[ str, Any ] ]:
		"""Search a vector store.

		Purpose:
			Provides the application-compatible alias for native vector-store search.

		Args:
			store_id (str): Required vector-store identifier.
			query (str): Required semantic-search query.
			max_num_results (int): Maximum number of results.
			filters (Optional[Dict[str, Any]]): Optional attribute filters.
			ranking_options (Optional[Dict[str, Any]]): Optional ranking configuration.
			rewrite_query (bool): Indicates whether the provider may rewrite the query.

		Returns:
			List[Dict[str, Any]]: Native vector-store search results.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			self.store_id = store_id
			self.query = query
			self.max_search_results = max_num_results
			self.filters = filters if filters is not None else { }
			self.ranking_options = (ranking_options if ranking_options is not None else { })
			self.rewrite_query = rewrite_query
			return self.search_store( self.store_id, self.query, self.max_search_results,
				self.filters, self.ranking_options, self.rewrite_query, )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'search( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def search_store( self, store_id: str, query: str, max_num_results: int = 10,
		filters: Optional[ Dict[ str, Any ] ] = None,
		ranking_options: Optional[ Dict[ str, Any ] ] = None, rewrite_query: bool = False ) -> (
			List)[
		Dict[ str, Any ] ]:
		"""Search a vector store.

		Purpose:
			Executes native semantic search against a required vector store.

		Args:
			store_id (str): Required vector-store identifier.
			query (str): Required semantic-search query.
			max_num_results (int): Maximum number of results.
			filters (Optional[Dict[str, Any]]): Optional attribute filters.
			ranking_options (Optional[Dict[str, Any]]): Optional ranking configuration.
			rewrite_query (bool): Indicates whether the provider may rewrite the query.

		Returns:
			List[Dict[str, Any]]: Native vector-store search results.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_id', store_id )
			throw_if( 'query', query )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_id = store_id
			self.query = query
			self.max_search_results = max_num_results
			self.filters = filters if filters is not None else { }
			self.ranking_options = (ranking_options if ranking_options is not None else { })
			self.rewrite_query = rewrite_query
			self.client = OpenAI( api_key=self.api_key, )

			if self.max_search_results < 1:
				self.max_search_results = 1

			if self.max_search_results > 50:
				self.max_search_results = 50

			self.request = { 'query': self.query, 'max_num_results': self.max_search_results,
				'rewrite_query': self.rewrite_query, }

			if self.filters:
				self.request[ 'filters' ] = self.filters

			if self.ranking_options:
				self.request[ 'ranking_options' ] = self.ranking_options

			self.response = self.client.vector_stores.search( self.store_id, **self.request )
			self.search_results = self.get_search_results( self.response )
			return self.search_results
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'search_store( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def answer_with_file_search( self, store_ids: List[ str ], prompt: str,
		model: str = 'gpt-4o-mini', max_num_results: int = 10, instructions: str = '' ) -> str:
		"""Answer with file search.

		Purpose:
			Answers a required prompt using the Responses API file-search tool across required
			vector stores.

		Args:
			store_ids (List[str]): Required vector-store identifiers.
			prompt (str): Required user prompt.
			model (str): OpenAI model used to generate the answer.
			max_num_results (int): Maximum number of retrieved results.
			instructions (str): Optional system or developer instructions.

		Returns:
			str: Generated answer text.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_ids', store_ids )
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			throw_if( 'OPENAI_API_KEY', self.api_key )
			self.store_ids = store_ids
			self.prompt = prompt
			self.model = model
			self.max_search_results = max_num_results
			self.instructions = instructions
			self.client = OpenAI( api_key=self.api_key, )

			if self.max_search_results < 1:
				self.max_search_results = 1

			if self.max_search_results > 50:
				self.max_search_results = 50

			self.input = [ { 'role': 'user',
				'content': [ { 'type': 'input_text', 'text': self.prompt, }, ], }, ]
			self.request = { 'model': self.model, 'input': self.input, 'tools': [
				{ 'type': 'file_search', 'vector_store_ids': self.store_ids,
					'max_num_results': self.max_search_results, }, ], }

			if self.instructions:
				self.request[ 'instructions' ] = self.instructions

			self.response = self.client.responses.create( **self.request )
			self.output_text = getattr( self.response, 'output_text', '', )

			if self.output_text:
				return self.output_text

			self.output_text = str( self.response )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'answer_with_file_search( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def survey( self, store_ids: List[ str ],
		prompt: str = ('Summarize the most relevant information available in the '
		               'selected vector stores.'), model: str = 'gpt-4o-mini',
		max_num_results: int = 10, instructions: str = '' ) -> str:
		"""Survey vector stores.

		Purpose:
			Generates a summary across required vector stores through the Responses API
			file-search tool.

		Args:
			store_ids (List[str]): Required vector-store identifiers.
			prompt (str): Summary prompt.
			model (str): OpenAI model used to generate the summary.
			max_num_results (int): Maximum number of retrieved results.
			instructions (str): Optional system or developer instructions.

		Returns:
			str: Generated vector-store summary.

		Raises:
			Error: Re-raised after the exception is logged.
		"""
		try:
			throw_if( 'store_ids', store_ids )
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.store_ids = store_ids
			self.prompt = prompt
			self.model = model
			self.max_search_results = max_num_results
			self.instructions = instructions
			self.output_text = self.answer_with_file_search( self.store_ids, self.prompt,
				self.model, self.max_search_results, self.instructions, )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gpt'
			exception.cause = 'VectorStores'
			exception.method = 'survey( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

	def __dir__( self ) -> List[ str ]:
		"""Return member names.

		Purpose:
			Returns public members exposed by the OpenAI VectorStores wrapper.

		Returns:
			List[str]: Public member names.
		"""
		return [ 'api_key', 'client', 'name', 'description', 'store_id', 'file_id', 'file_ids',
			'batch_id', 'model', 'query', 'prompt', 'instructions', 'max_search_results',
			'response', 'vector_store', 'vector_stores', 'vector_file', 'vector_files',
			'file_batch', 'search_results', 'output_text', 'request', 'collections',
			'model_options', 'ranker_options', 'chunking_strategy_options', 'get_vector_store',
			'get_vector_file', 'get_file_batch', 'get_search_results', 'create', 'list_stores',
			'list', 'retrieve', 'update', 'delete', 'attach_file', 'list_files', 'retrieve_file',
			'update_file', 'delete_file', 'retrieve_file_content', 'create_file_batch',
			'retrieve_file_batch', 'list_file_batch_files', 'cancel_file_batch', 'search',
			'search_store', 'answer_with_file_search', 'survey', ]

model_options property

model_options: List[str]

Get model options.

Purpose

Returns OpenAI models exposed for Responses API file-search answer workflows.

Returns:

Type Description
List[str]

List[str]: Supported model identifiers.

ranker_options property

ranker_options: List[str]

Get ranker options.

Purpose

Returns ranking algorithms exposed for native vector-store search.

Returns:

Type Description
List[str]

List[str]: Supported ranker values.

chunking_strategy_options property

chunking_strategy_options: List[str]

Get chunking-strategy options.

Purpose

Returns chunking strategies supported by vector-store file operations.

Returns:

Type Description
List[str]

List[str]: Supported chunking-strategy values.

__init__

__init__(
    name: str = "",
    store_id: str = "",
    file_id: str = "",
    model: str = "gpt-4o-mini",
    max_search_results: int = 10,
) -> None

Initialize instance.

Purpose

Initializes OpenAI vector-store configuration and runtime state without executing a provider request.

Parameters:

Name Type Description Default
name str

Optional initial vector-store name.

''
store_id str

Optional initial vector-store identifier.

''
file_id str

Optional initial file identifier.

''
model str

Default model used by file-search answer workflows.

'gpt-4o-mini'
max_search_results int

Default maximum number of search results.

10

Returns:

Name Type Description
None None

This method initializes object state.

Source code in gpt.py
def __init__( self, name: str = '', store_id: str = '', file_id: str = '',
	model: str = 'gpt-4o-mini', max_search_results: int = 10 ) -> None:
	"""Initialize instance.

	Purpose:
		Initializes OpenAI vector-store configuration and runtime state without executing a
		provider request.

	Args:
		name (str): Optional initial vector-store name.
		store_id (str): Optional initial vector-store identifier.
		file_id (str): Optional initial file identifier.
		model (str): Default model used by file-search answer workflows.
		max_search_results (int): Default maximum number of search results.

	Returns:
		None: This method initializes object state.
	"""
	super( ).__init__( )
	self.api_key = cfg.OPENAI_API_KEY
	self.client = None
	self.name = name
	self.description = ''
	self.store_id = store_id
	self.file_id = file_id
	self.file_ids = [ ]
	self.batch_id = ''
	self.model = model
	self.query = ''
	self.prompt = ''
	self.instructions = ''
	self.max_search_results = max_search_results
	self.metadata = { }
	self.attributes = { }
	self.filters = { }
	self.ranking_options = { }
	self.expires_after = { }
	self.chunking_strategy = { }
	self.response = None
	self.vector_store = { }
	self.vector_stores = [ ]
	self.vector_file = { }
	self.vector_files = [ ]
	self.file_batch = { }
	self.search_results = [ ]
	self.output_text = ''
	self.request = { }
	self.input = [ ]
	self.limit = 100
	self.order = 'desc'
	self.after = ''
	self.before = ''
	self.rewrite_query = False
	self.collections = { 'Governance': 'vs_6a1850a9bdc08191912353eedf59aede',
		'Public Laws': 'vs_699506f7d5348191990e0557c717fa9d',
		'Explanatory Statements': 'vs_699505df9ac48191a525c0ecb86fef66',
		'Army Techniques Publications': 'vs_699356ef052c81918da14c4ed3bcea17',
		'Army Field Manuals': 'vs_69935542863481918d150c1e89c38633',
		'Army Regulations': 'vs_6993550488408191919cd70968ba8be8',
		'DoD Armory': 'vs_697f86ad98888191b967685ae558bfc0',
		'Army Style Guides': 'vs_68f4efd7d4c4819191458dd6cde6f2cc',
		'Apportionments': 'vs_68a34aaff93481918c3b3fef8c4e8fea',
		'Financial Regulations': 'vs_712r5W5833G6aLxIYIbuvVcK', }

get_vector_store

get_vector_store(response: Any) -> Dict[str, Any]

Get vector-store metadata.

Purpose

Extracts application-facing metadata from a required vector-store response.

Parameters:

Name Type Description Default
response Any

Required provider vector-store response.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing vector-store metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_vector_store( self, response: Any ) -> Dict[ str, Any ]:
	"""Get vector-store metadata.

	Purpose:
		Extracts application-facing metadata from a required vector-store response.

	Args:
		response (Any): Required provider vector-store response.

	Returns:
		Dict[str, Any]: Application-facing vector-store metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'response', response )
		self.response = response

		if isinstance( self.response, dict ):
			self.source = self.response
		elif hasattr( self.response, 'model_dump' ):
			self.source = self.response.model_dump( )
		else:
			self.source = { 'id': getattr( self.response, 'id', '' ),
				'name': getattr( self.response, 'name', '' ),
				'description': getattr( self.response, 'description', '' ),
				'created_at': getattr( self.response, 'created_at', 0 ),
				'object': getattr( self.response, 'object', '' ),
				'usage_bytes': getattr( self.response, 'usage_bytes', 0 ),
				'file_counts': getattr( self.response, 'file_counts', None ),
				'status': getattr( self.response, 'status', '' ),
				'expires_after': getattr( self.response, 'expires_after', None ),
				'expires_at': getattr( self.response, 'expires_at', 0 ),
				'last_active_at': getattr( self.response, 'last_active_at', 0 ),
				'metadata': getattr( self.response, 'metadata', None ), }

		self.vector_store = { 'id': self.source.get( 'id', '' ),
			'name': self.source.get( 'name', '' ),
			'description': self.source.get( 'description', '' ),
			'created_at': self.source.get( 'created_at', 0 ),
			'object': self.source.get( 'object', '' ),
			'usage_bytes': self.source.get( 'usage_bytes', 0 ),
			'file_counts': self.source.get( 'file_counts', None ),
			'status': self.source.get( 'status', '' ),
			'expires_after': self.source.get( 'expires_after', None ),
			'expires_at': self.source.get( 'expires_at', 0 ),
			'last_active_at': self.source.get( 'last_active_at', 0 ),
			'metadata': self.source.get( 'metadata', None ), }
		return self.vector_store
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'get_vector_store( self, response: Any )'
		Logger( ).write( exception )
		raise exception

get_vector_file

get_vector_file(response: Any) -> Dict[str, Any]

Get vector-store file metadata.

Purpose

Extracts application-facing metadata from a required vector-store file response.

Parameters:

Name Type Description Default
response Any

Required provider vector-store file response.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing attached-file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_vector_file( self, response: Any ) -> Dict[ str, Any ]:
	"""Get vector-store file metadata.

	Purpose:
		Extracts application-facing metadata from a required vector-store file response.

	Args:
		response (Any): Required provider vector-store file response.

	Returns:
		Dict[str, Any]: Application-facing attached-file metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'response', response )
		self.response = response

		if isinstance( self.response, dict ):
			self.source = self.response
		elif hasattr( self.response, 'model_dump' ):
			self.source = self.response.model_dump( )
		else:
			self.source = { 'id': getattr( self.response, 'id', '' ),
				'object': getattr( self.response, 'object', '' ),
				'created_at': getattr( self.response, 'created_at', 0 ),
				'vector_store_id': getattr( self.response, 'vector_store_id', '', ),
				'status': getattr( self.response, 'status', '' ),
				'last_error': getattr( self.response, 'last_error', None ),
				'chunking_strategy': getattr( self.response, 'chunking_strategy', None, ),
				'attributes': getattr( self.response, 'attributes', None ),
				'usage_bytes': getattr( self.response, 'usage_bytes', 0 ), }

		self.vector_file = { 'id': self.source.get( 'id', '' ),
			'object': self.source.get( 'object', '' ),
			'created_at': self.source.get( 'created_at', 0 ),
			'vector_store_id': self.source.get( 'vector_store_id', '' ),
			'status': self.source.get( 'status', '' ),
			'last_error': self.source.get( 'last_error', None ),
			'chunking_strategy': self.source.get( 'chunking_strategy', None ),
			'attributes': self.source.get( 'attributes', None ),
			'usage_bytes': self.source.get( 'usage_bytes', 0 ), }
		return self.vector_file
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'get_vector_file( self, response: Any )'
		Logger( ).write( exception )
		raise exception

get_file_batch

get_file_batch(response: Any) -> Dict[str, Any]

Get file-batch metadata.

Purpose

Extracts application-facing metadata from a required file-batch response.

Parameters:

Name Type Description Default
response Any

Required provider file-batch response.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing file-batch metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_file_batch( self, response: Any ) -> Dict[ str, Any ]:
	"""Get file-batch metadata.

	Purpose:
		Extracts application-facing metadata from a required file-batch response.

	Args:
		response (Any): Required provider file-batch response.

	Returns:
		Dict[str, Any]: Application-facing file-batch metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'response', response )
		self.response = response

		if isinstance( self.response, dict ):
			self.source = self.response
		elif hasattr( self.response, 'model_dump' ):
			self.source = self.response.model_dump( )
		else:
			self.source = { 'id': getattr( self.response, 'id', '' ),
				'object': getattr( self.response, 'object', '' ),
				'created_at': getattr( self.response, 'created_at', 0 ),
				'vector_store_id': getattr( self.response, 'vector_store_id', '', ),
				'status': getattr( self.response, 'status', '' ),
				'file_counts': getattr( self.response, 'file_counts', None, ), }

		self.file_batch = { 'id': self.source.get( 'id', '' ),
			'object': self.source.get( 'object', '' ),
			'created_at': self.source.get( 'created_at', 0 ),
			'vector_store_id': self.source.get( 'vector_store_id', '' ),
			'status': self.source.get( 'status', '' ),
			'file_counts': self.source.get( 'file_counts', None ), }
		return self.file_batch
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'get_file_batch( self, response: Any )'
		Logger( ).write( exception )
		raise exception

get_search_results

get_search_results(response: Any) -> List[Dict[str, Any]]

Get vector-store search results.

Purpose

Extracts native vector-store search results from a required provider response.

Parameters:

Name Type Description Default
response Any

Required provider vector-store search response.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Application-facing search results.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def get_search_results( self, response: Any ) -> List[ Dict[ str, Any ] ]:
	"""Get vector-store search results.

	Purpose:
		Extracts native vector-store search results from a required provider response.

	Args:
		response (Any): Required provider vector-store search response.

	Returns:
		List[Dict[str, Any]]: Application-facing search results.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'response', response )
		self.response = response
		self.items = getattr( self.response, 'data', [ ], ) or [ ]
		self.search_results = [ ]

		for item in self.items:
			if isinstance( item, dict ):
				self.source = item
			elif hasattr( item, 'model_dump' ):
				self.source = item.model_dump( )
			else:
				self.source = { 'file_id': getattr( item, 'file_id', '' ),
					'filename': getattr( item, 'filename', '' ),
					'score': getattr( item, 'score', 0.0 ),
					'attributes': getattr( item, 'attributes', None ),
					'content': getattr( item, 'content', [ ] ), }

			self.search_results.append( { 'file_id': self.source.get( 'file_id', '' ),
				'filename': self.source.get( 'filename', '' ),
				'score': self.source.get( 'score', 0.0 ),
				'attributes': self.source.get( 'attributes', None ),
				'content': self.source.get( 'content', [ ] ), } )

		return self.search_results
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'get_search_results( self, response: Any )'
		Logger( ).write( exception )
		raise exception

create

create(
    name: str,
    description: str = "",
    metadata: Optional[Dict[str, Any]] = None,
    expires_after: Optional[Dict[str, Any]] = None,
    file_ids: Optional[List[str]] = None,
    chunking_strategy: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]

Create a vector store.

Purpose

Creates a vector store with a required name and optional description, metadata, expiration policy, files, and chunking strategy.

Parameters:

Name Type Description Default
name str

Required vector-store name.

required
description str

Optional vector-store description.

''
metadata Optional[Dict[str, Any]]

Optional vector-store metadata.

None
expires_after Optional[Dict[str, Any]]

Optional expiration policy.

None
file_ids Optional[List[str]]

Optional files attached during creation.

None
chunking_strategy Optional[Dict[str, Any]]

Optional chunking strategy.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Created vector-store metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def create( self, name: str, description: str = '',
	metadata: Optional[ Dict[ str, Any ] ] = None,
	expires_after: Optional[ Dict[ str, Any ] ] = None,
	file_ids: Optional[ List[ str ] ] = None,
	chunking_strategy: Optional[ Dict[ str, Any ] ] = None ) -> Dict[ str, Any ]:
	"""Create a vector store.

	Purpose:
		Creates a vector store with a required name and optional description, metadata,
		expiration policy, files, and chunking strategy.

	Args:
		name (str): Required vector-store name.
		description (str): Optional vector-store description.
		metadata (Optional[Dict[str, Any]]): Optional vector-store metadata.
		expires_after (Optional[Dict[str, Any]]): Optional expiration policy.
		file_ids (Optional[List[str]]): Optional files attached during creation.
		chunking_strategy (Optional[Dict[str, Any]]): Optional chunking strategy.

	Returns:
		Dict[str, Any]: Created vector-store metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'name', name )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.name = name
		self.description = description
		self.metadata = metadata if metadata is not None else { }
		self.expires_after = (expires_after if expires_after is not None else { })
		self.file_ids = file_ids if file_ids is not None else [ ]
		self.chunking_strategy = (chunking_strategy if chunking_strategy is not None else { })
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'name': self.name, }

		if self.description:
			self.request[ 'description' ] = self.description

		if self.metadata:
			self.request[ 'metadata' ] = self.metadata

		if self.expires_after:
			self.request[ 'expires_after' ] = self.expires_after

		if self.file_ids:
			self.request[ 'file_ids' ] = self.file_ids

		if self.chunking_strategy:
			self.request[ 'chunking_strategy' ] = self.chunking_strategy

		self.response = self.client.vector_stores.create( **self.request )
		self.vector_store = self.get_vector_store( self.response )
		self.store_id = self.vector_store.get( 'id', '', )
		return self.vector_store
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'create( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

list_stores

list_stores(
    limit: int = 100,
    order: str = "desc",
    after: str = "",
    before: str = "",
) -> List[Dict[str, Any]]

List vector stores.

Purpose

Lists vector stores using the selected result limit, order, and cursor values.

Parameters:

Name Type Description Default
limit int

Maximum number of vector stores returned.

100
order str

Result order.

'desc'
after str

Optional cursor identifying the first result boundary.

''
before str

Optional cursor identifying the last result boundary.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Vector-store metadata rows.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def list_stores( self, limit: int = 100, order: str = 'desc', after: str = '',
	before: str = '' ) -> List[ Dict[ str, Any ] ]:
	"""List vector stores.

	Purpose:
		Lists vector stores using the selected result limit, order, and cursor values.

	Args:
		limit (int): Maximum number of vector stores returned.
		order (str): Result order.
		after (str): Optional cursor identifying the first result boundary.
		before (str): Optional cursor identifying the last result boundary.

	Returns:
		List[Dict[str, Any]]: Vector-store metadata rows.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.limit = limit
		self.order = order
		self.after = after
		self.before = before
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'limit': self.limit, 'order': self.order, }

		if self.after:
			self.request[ 'after' ] = self.after

		if self.before:
			self.request[ 'before' ] = self.before

		self.response = self.client.vector_stores.list( **self.request )
		self.items = getattr( self.response, 'data', [ ], ) or [ ]
		self.vector_stores = [ self.get_vector_store( item ) for item in self.items ]
		return self.vector_stores
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'list_stores( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

list

list(
    limit: int = 100,
    order: str = "desc",
    after: str = "",
    before: str = "",
) -> List[Dict[str, Any]]

List vector stores.

Purpose

Provides the application-compatible list alias for vector-store listing.

Parameters:

Name Type Description Default
limit int

Maximum number of vector stores returned.

100
order str

Result order.

'desc'
after str

Optional after cursor.

''
before str

Optional before cursor.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Vector-store metadata rows.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def list( self, limit: int=100, order: str='desc', after: str='',
	before: str='' ) -> List[ Dict[ str, Any ] ]:
	"""List vector stores.

	Purpose:
		Provides the application-compatible list alias for vector-store listing.

	Args:
		limit (int): Maximum number of vector stores returned.
		order (str): Result order.
		after (str): Optional after cursor.
		before (str): Optional before cursor.

	Returns:
		List[Dict[str, Any]]: Vector-store metadata rows.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.limit = limit
		self.order = order
		self.after = after
		self.before = before
		return self.list_stores( self.limit, self.order, self.after, self.before, )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'list( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

retrieve

retrieve(store_id: str) -> Dict[str, Any]

Retrieve a vector store.

Purpose

Retrieves metadata for a required vector-store identifier.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Retrieved vector-store metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def retrieve( self, store_id: str ) -> Dict[ str, Any ]:
	"""Retrieve a vector store.

	Purpose:
		Retrieves metadata for a required vector-store identifier.

	Args:
		store_id (str): Required vector-store identifier.

	Returns:
		Dict[str, Any]: Retrieved vector-store metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.client = OpenAI( api_key=self.api_key, )
		self.response = self.client.vector_stores.retrieve( self.store_id )
		self.vector_store = self.get_vector_store( self.response )
		return self.vector_store
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = ('retrieve( self, store_id: str ) -> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

update

update(
    store_id: str,
    name: str = "",
    description: str = "",
    metadata: Optional[Dict[str, Any]] = None,
    expires_after: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]

Update a vector store.

Purpose

Updates a required vector store using supplied name, description, metadata, or expiration-policy values.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
name str

Optional updated vector-store name.

''
description str

Optional updated description.

''
metadata Optional[Dict[str, Any]]

Optional updated metadata.

None
expires_after Optional[Dict[str, Any]]

Optional updated expiration policy.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Updated vector-store metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def update( self, store_id: str, name: str = '', description: str = '',
	metadata: Optional[ Dict[ str, Any ] ] = None,
	expires_after: Optional[ Dict[ str, Any ] ] = None ) -> Dict[ str, Any ]:
	"""Update a vector store.

	Purpose:
		Updates a required vector store using supplied name, description, metadata, or
		expiration-policy values.

	Args:
		store_id (str): Required vector-store identifier.
		name (str): Optional updated vector-store name.
		description (str): Optional updated description.
		metadata (Optional[Dict[str, Any]]): Optional updated metadata.
		expires_after (Optional[Dict[str, Any]]): Optional updated expiration policy.

	Returns:
		Dict[str, Any]: Updated vector-store metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.name = name
		self.description = description
		self.metadata = metadata if metadata is not None else { }
		self.expires_after = (expires_after if expires_after is not None else { })
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { }

		if self.name:
			self.request[ 'name' ] = self.name

		if self.description:
			self.request[ 'description' ] = self.description

		if metadata is not None:
			self.request[ 'metadata' ] = self.metadata

		if self.expires_after:
			self.request[ 'expires_after' ] = self.expires_after

		if not self.request:
			return self.retrieve( self.store_id )

		self.response = self.client.vector_stores.update( self.store_id, **self.request )
		self.vector_store = self.get_vector_store( self.response )
		return self.vector_store
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'update( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

delete

delete(store_id: str) -> Dict[str, Any]

Delete a vector store.

Purpose

Deletes a required vector-store identifier.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Provider deletion result.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def delete( self, store_id: str ) -> Dict[ str, Any ]:
	"""Delete a vector store.

	Purpose:
		Deletes a required vector-store identifier.

	Args:
		store_id (str): Required vector-store identifier.

	Returns:
		Dict[str, Any]: Provider deletion result.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.client = OpenAI( api_key=self.api_key, )
		self.response = self.client.vector_stores.delete( self.store_id )

		if isinstance( self.response, dict ):
			return self.response

		if hasattr( self.response, 'model_dump' ):
			return self.response.model_dump( )

		return { 'id': getattr( self.response, 'id', self.store_id ),
			'deleted': getattr( self.response, 'deleted', False ),
			'object': getattr( self.response, 'object', '' ), }
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = ('delete( self, store_id: str ) -> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

attach_file

attach_file(
    store_id: str,
    file_id: str,
    attributes: Optional[Dict[str, Any]] = None,
    chunking_strategy: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]

Attach a file.

Purpose

Attaches a required OpenAI file to a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
file_id str

Required OpenAI file identifier.

required
attributes Optional[Dict[str, Any]]

Optional attached-file attributes.

None
chunking_strategy Optional[Dict[str, Any]]

Optional chunking strategy.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Attached-file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def attach_file( self, store_id: str, file_id: str,
	attributes: Optional[ Dict[ str, Any ] ] = None,
	chunking_strategy: Optional[ Dict[ str, Any ] ] = None ) -> Dict[ str, Any ]:
	"""Attach a file.

	Purpose:
		Attaches a required OpenAI file to a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		file_id (str): Required OpenAI file identifier.
		attributes (Optional[Dict[str, Any]]): Optional attached-file attributes.
		chunking_strategy (Optional[Dict[str, Any]]): Optional chunking strategy.

	Returns:
		Dict[str, Any]: Attached-file metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'file_id', file_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.file_id = file_id
		self.attributes = attributes if attributes is not None else { }
		self.chunking_strategy = (chunking_strategy if chunking_strategy is not None else { })
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'file_id': self.file_id, }

		if self.attributes:
			self.request[ 'attributes' ] = self.attributes

		if self.chunking_strategy:
			self.request[ 'chunking_strategy' ] = self.chunking_strategy

		self.response = self.client.vector_stores.files.create( self.store_id, **self.request )
		self.vector_file = self.get_vector_file( self.response )
		return self.vector_file
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'attach_file( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

list_files

list_files(
    store_id: str,
    limit: int = 100,
    order: str = "desc",
    after: str = "",
    before: str = "",
    filter: str = "",
) -> List[Dict[str, Any]]

List attached files.

Purpose

Lists files attached to a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
limit int

Maximum number of files returned.

100
order str

Result order.

'desc'
after str

Optional after cursor.

''
before str

Optional before cursor.

''
filter str

Optional attached-file status filter.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Attached-file metadata rows.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def list_files( self, store_id: str, limit: int = 100, order: str = 'desc', after: str = '',
	before: str = '', filter: str = '' ) -> List[ Dict[ str, Any ] ]:
	"""List attached files.

	Purpose:
		Lists files attached to a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		limit (int): Maximum number of files returned.
		order (str): Result order.
		after (str): Optional after cursor.
		before (str): Optional before cursor.
		filter (str): Optional attached-file status filter.

	Returns:
		List[Dict[str, Any]]: Attached-file metadata rows.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.limit = limit
		self.order = order
		self.after = after
		self.before = before
		self.filter = filter
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'limit': self.limit, 'order': self.order, }
		if self.after:
			self.request[ 'after' ] = self.after

		if self.before:
			self.request[ 'before' ] = self.before

		if self.filter:
			self.request[ 'filter' ] = self.filter

		self.response = self.client.vector_stores.files.list( self.store_id, **self.request )
		self.items = getattr( self.response, 'data', [ ], ) or [ ]
		self.vector_files = [ self.get_vector_file( item ) for item in self.items ]
		return self.vector_files
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'list_files( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

retrieve_file

retrieve_file(
    store_id: str, file_id: str
) -> Dict[str, Any]

Retrieve an attached file.

Purpose

Retrieves metadata for a required file attached to a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
file_id str

Required attached-file identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Attached-file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def retrieve_file( self, store_id: str, file_id: str ) -> Dict[ str, Any ]:
	"""Retrieve an attached file.

	Purpose:
		Retrieves metadata for a required file attached to a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		file_id (str): Required attached-file identifier.

	Returns:
		Dict[str, Any]: Attached-file metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'file_id', file_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.file_id = file_id
		self.client = OpenAI( api_key=self.api_key, )
		self.response = self.client.vector_stores.files.retrieve( self.file_id,
			vector_store_id=self.store_id, )
		self.vector_file = self.get_vector_file( self.response )
		return self.vector_file
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'retrieve_file( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

update_file

update_file(
    store_id: str, file_id: str, attributes: Dict[str, Any]
) -> Dict[str, Any]

Update an attached file.

Purpose

Updates attributes for a required file attached to a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
file_id str

Required attached-file identifier.

required
attributes Dict[str, Any]

Required updated file attributes.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Updated attached-file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def update_file( self, store_id: str, file_id: str,
	attributes: Dict[ str, Any ] ) -> Dict[ str, Any ]:
	"""Update an attached file.

	Purpose:
		Updates attributes for a required file attached to a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		file_id (str): Required attached-file identifier.
		attributes (Dict[str, Any]): Required updated file attributes.

	Returns:
		Dict[str, Any]: Updated attached-file metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'file_id', file_id )
		throw_if( 'attributes', attributes )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.file_id = file_id
		self.attributes = attributes
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'attributes': self.attributes, }
		self.response = self.client.vector_stores.files.update( self.file_id,
			vector_store_id=self.store_id, **self.request )
		self.vector_file = self.get_vector_file( self.response )
		return self.vector_file
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'update_file( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

delete_file

delete_file(store_id: str, file_id: str) -> Dict[str, Any]

Delete an attached file.

Purpose

Removes a required file from a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
file_id str

Required attached-file identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Provider deletion result.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def delete_file( self, store_id: str, file_id: str ) -> Dict[ str, Any ]:
	"""Delete an attached file.

	Purpose:
		Removes a required file from a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		file_id (str): Required attached-file identifier.

	Returns:
		Dict[str, Any]: Provider deletion result.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'file_id', file_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.file_id = file_id
		self.client = OpenAI( api_key=self.api_key, )
		self.response = self.client.vector_stores.files.delete( self.file_id,
			vector_store_id=self.store_id, )

		if isinstance( self.response, dict ):
			return self.response

		if hasattr( self.response, 'model_dump' ):
			return self.response.model_dump( )

		return { 'id': getattr( self.response, 'id', self.file_id ),
			'deleted': getattr( self.response, 'deleted', False ),
			'object': getattr( self.response, 'object', '' ), }
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'delete_file( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

retrieve_file_content

retrieve_file_content(store_id: str, file_id: str) -> Any

Retrieve attached-file content.

Purpose

Retrieves parsed content for a required file attached to a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
file_id str

Required attached-file identifier.

required

Returns:

Name Type Description
Any Any

Provider file-content response.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def retrieve_file_content( self, store_id: str, file_id: str ) -> Any:
	"""Retrieve attached-file content.

	Purpose:
		Retrieves parsed content for a required file attached to a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		file_id (str): Required attached-file identifier.

	Returns:
		Any: Provider file-content response.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'file_id', file_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.file_id = file_id
		self.client = OpenAI( api_key=self.api_key, )
		self.response = self.client.vector_stores.files.content( self.file_id,
			vector_store_id=self.store_id, )
		return self.response
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'retrieve_file_content( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

create_file_batch

create_file_batch(
    store_id: str,
    file_ids: List[str],
    attributes: Optional[Dict[str, Any]] = None,
    chunking_strategy: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]

Create a file batch.

Purpose

Creates a file batch for required files in a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
file_ids List[str]

Required OpenAI file identifiers.

required
attributes Optional[Dict[str, Any]]

Optional common file attributes.

None
chunking_strategy Optional[Dict[str, Any]]

Optional chunking strategy.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Created file-batch metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def create_file_batch( self, store_id: str, file_ids: List[ str ],
	attributes: Optional[ Dict[ str, Any ] ] = None,
	chunking_strategy: Optional[ Dict[ str, Any ] ] = None ) -> Dict[ str, Any ]:
	"""Create a file batch.

	Purpose:
		Creates a file batch for required files in a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		file_ids (List[str]): Required OpenAI file identifiers.
		attributes (Optional[Dict[str, Any]]): Optional common file attributes.
		chunking_strategy (Optional[Dict[str, Any]]): Optional chunking strategy.

	Returns:
		Dict[str, Any]: Created file-batch metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'file_ids', file_ids )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.file_ids = file_ids
		self.attributes = attributes if attributes is not None else { }
		self.chunking_strategy = (chunking_strategy if chunking_strategy is not None else { })
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'file_ids': self.file_ids, }

		if self.attributes:
			self.request[ 'attributes' ] = self.attributes

		if self.chunking_strategy:
			self.request[ 'chunking_strategy' ] = self.chunking_strategy

		self.response = self.client.vector_stores.file_batches.create( self.store_id,
			**self.request )
		self.file_batch = self.get_file_batch( self.response )
		self.batch_id = self.file_batch.get( 'id', '', )
		return self.file_batch
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'create_file_batch( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

retrieve_file_batch

retrieve_file_batch(
    store_id: str, batch_id: str
) -> Dict[str, Any]

Retrieve a file batch.

Purpose

Retrieves metadata for a required file batch in a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
batch_id str

Required file-batch identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: File-batch metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def retrieve_file_batch( self, store_id: str, batch_id: str ) -> Dict[ str, Any ]:
	"""Retrieve a file batch.

	Purpose:
		Retrieves metadata for a required file batch in a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		batch_id (str): Required file-batch identifier.

	Returns:
		Dict[str, Any]: File-batch metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'batch_id', batch_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.batch_id = batch_id
		self.client = OpenAI( api_key=self.api_key, )
		self.response = self.client.vector_stores.file_batches.retrieve( self.batch_id,
			vector_store_id=self.store_id, )
		self.file_batch = self.get_file_batch( self.response )
		return self.file_batch
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'retrieve_file_batch( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

list_file_batch_files

list_file_batch_files(
    store_id: str,
    batch_id: str,
    limit: int = 100,
    order: str = "desc",
    after: str = "",
    before: str = "",
    filter: str = "",
) -> List[Dict[str, Any]]

List file-batch files.

Purpose

Lists files associated with a required file batch and vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
batch_id str

Required file-batch identifier.

required
limit int

Maximum number of files returned.

100
order str

Result order.

'desc'
after str

Optional after cursor.

''
before str

Optional before cursor.

''
filter str

Optional file-status filter.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: File-batch attached-file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def list_file_batch_files( self, store_id: str, batch_id: str, limit: int = 100,
	order: str = 'desc', after: str = '', before: str = '', filter: str = '' ) -> List[
	Dict[ str, Any ] ]:
	"""List file-batch files.

	Purpose:
		Lists files associated with a required file batch and vector store.

	Args:
		store_id (str): Required vector-store identifier.
		batch_id (str): Required file-batch identifier.
		limit (int): Maximum number of files returned.
		order (str): Result order.
		after (str): Optional after cursor.
		before (str): Optional before cursor.
		filter (str): Optional file-status filter.

	Returns:
		List[Dict[str, Any]]: File-batch attached-file metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'batch_id', batch_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.batch_id = batch_id
		self.limit = limit
		self.order = order
		self.after = after
		self.before = before
		self.filter = filter
		self.client = OpenAI( api_key=self.api_key, )
		self.request = { 'limit': self.limit, 'order': self.order, }

		if self.after:
			self.request[ 'after' ] = self.after

		if self.before:
			self.request[ 'before' ] = self.before

		if self.filter:
			self.request[ 'filter' ] = self.filter

		self.response = self.client.vector_stores.file_batches.list_files( self.batch_id,
			vector_store_id=self.store_id, **self.request )
		self.items = getattr( self.response, 'data', [ ], ) or [ ]
		self.vector_files = [ self.get_vector_file( item ) for item in self.items ]
		return self.vector_files
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'list_file_batch_files( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

cancel_file_batch

cancel_file_batch(
    store_id: str, batch_id: str
) -> Dict[str, Any]

Cancel a file batch.

Purpose

Cancels a required file batch in a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
batch_id str

Required file-batch identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Updated file-batch metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def cancel_file_batch( self, store_id: str, batch_id: str ) -> Dict[ str, Any ]:
	"""Cancel a file batch.

	Purpose:
		Cancels a required file batch in a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		batch_id (str): Required file-batch identifier.

	Returns:
		Dict[str, Any]: Updated file-batch metadata.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'batch_id', batch_id )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.batch_id = batch_id
		self.client = OpenAI( api_key=self.api_key, )
		self.response = self.client.vector_stores.file_batches.cancel( self.batch_id,
			vector_store_id=self.store_id, )
		self.file_batch = self.get_file_batch( self.response )
		return self.file_batch
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'cancel_file_batch( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

search

search(
    store_id: str,
    query: str,
    max_num_results: int = 10,
    filters: Optional[Dict[str, Any]] = None,
    ranking_options: Optional[Dict[str, Any]] = None,
    rewrite_query: bool = False,
) -> List[Dict[str, Any]]

Search a vector store.

Purpose

Provides the application-compatible alias for native vector-store search.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
query str

Required semantic-search query.

required
max_num_results int

Maximum number of results.

10
filters Optional[Dict[str, Any]]

Optional attribute filters.

None
ranking_options Optional[Dict[str, Any]]

Optional ranking configuration.

None
rewrite_query bool

Indicates whether the provider may rewrite the query.

False

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Native vector-store search results.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def search( self, store_id: str, query: str, max_num_results: int = 10,
	filters: Optional[ Dict[ str, Any ] ] = None,
	ranking_options: Optional[ Dict[ str, Any ] ] = None, rewrite_query: bool = False ) -> (
		List)[
	Dict[ str, Any ] ]:
	"""Search a vector store.

	Purpose:
		Provides the application-compatible alias for native vector-store search.

	Args:
		store_id (str): Required vector-store identifier.
		query (str): Required semantic-search query.
		max_num_results (int): Maximum number of results.
		filters (Optional[Dict[str, Any]]): Optional attribute filters.
		ranking_options (Optional[Dict[str, Any]]): Optional ranking configuration.
		rewrite_query (bool): Indicates whether the provider may rewrite the query.

	Returns:
		List[Dict[str, Any]]: Native vector-store search results.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		self.store_id = store_id
		self.query = query
		self.max_search_results = max_num_results
		self.filters = filters if filters is not None else { }
		self.ranking_options = (ranking_options if ranking_options is not None else { })
		self.rewrite_query = rewrite_query
		return self.search_store( self.store_id, self.query, self.max_search_results,
			self.filters, self.ranking_options, self.rewrite_query, )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'search( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

search_store

search_store(
    store_id: str,
    query: str,
    max_num_results: int = 10,
    filters: Optional[Dict[str, Any]] = None,
    ranking_options: Optional[Dict[str, Any]] = None,
    rewrite_query: bool = False,
) -> List[Dict[str, Any]]

Search a vector store.

Purpose

Executes native semantic search against a required vector store.

Parameters:

Name Type Description Default
store_id str

Required vector-store identifier.

required
query str

Required semantic-search query.

required
max_num_results int

Maximum number of results.

10
filters Optional[Dict[str, Any]]

Optional attribute filters.

None
ranking_options Optional[Dict[str, Any]]

Optional ranking configuration.

None
rewrite_query bool

Indicates whether the provider may rewrite the query.

False

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Native vector-store search results.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def search_store( self, store_id: str, query: str, max_num_results: int = 10,
	filters: Optional[ Dict[ str, Any ] ] = None,
	ranking_options: Optional[ Dict[ str, Any ] ] = None, rewrite_query: bool = False ) -> (
		List)[
	Dict[ str, Any ] ]:
	"""Search a vector store.

	Purpose:
		Executes native semantic search against a required vector store.

	Args:
		store_id (str): Required vector-store identifier.
		query (str): Required semantic-search query.
		max_num_results (int): Maximum number of results.
		filters (Optional[Dict[str, Any]]): Optional attribute filters.
		ranking_options (Optional[Dict[str, Any]]): Optional ranking configuration.
		rewrite_query (bool): Indicates whether the provider may rewrite the query.

	Returns:
		List[Dict[str, Any]]: Native vector-store search results.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_id', store_id )
		throw_if( 'query', query )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_id = store_id
		self.query = query
		self.max_search_results = max_num_results
		self.filters = filters if filters is not None else { }
		self.ranking_options = (ranking_options if ranking_options is not None else { })
		self.rewrite_query = rewrite_query
		self.client = OpenAI( api_key=self.api_key, )

		if self.max_search_results < 1:
			self.max_search_results = 1

		if self.max_search_results > 50:
			self.max_search_results = 50

		self.request = { 'query': self.query, 'max_num_results': self.max_search_results,
			'rewrite_query': self.rewrite_query, }

		if self.filters:
			self.request[ 'filters' ] = self.filters

		if self.ranking_options:
			self.request[ 'ranking_options' ] = self.ranking_options

		self.response = self.client.vector_stores.search( self.store_id, **self.request )
		self.search_results = self.get_search_results( self.response )
		return self.search_results
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'search_store( self, **kwargs )'
		Logger( ).write( exception )
		raise exception
answer_with_file_search(
    store_ids: List[str],
    prompt: str,
    model: str = "gpt-4o-mini",
    max_num_results: int = 10,
    instructions: str = "",
) -> str

Answer with file search.

Purpose

Answers a required prompt using the Responses API file-search tool across required vector stores.

Parameters:

Name Type Description Default
store_ids List[str]

Required vector-store identifiers.

required
prompt str

Required user prompt.

required
model str

OpenAI model used to generate the answer.

'gpt-4o-mini'
max_num_results int

Maximum number of retrieved results.

10
instructions str

Optional system or developer instructions.

''

Returns:

Name Type Description
str str

Generated answer text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def answer_with_file_search( self, store_ids: List[ str ], prompt: str,
	model: str = 'gpt-4o-mini', max_num_results: int = 10, instructions: str = '' ) -> str:
	"""Answer with file search.

	Purpose:
		Answers a required prompt using the Responses API file-search tool across required
		vector stores.

	Args:
		store_ids (List[str]): Required vector-store identifiers.
		prompt (str): Required user prompt.
		model (str): OpenAI model used to generate the answer.
		max_num_results (int): Maximum number of retrieved results.
		instructions (str): Optional system or developer instructions.

	Returns:
		str: Generated answer text.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_ids', store_ids )
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		throw_if( 'OPENAI_API_KEY', self.api_key )
		self.store_ids = store_ids
		self.prompt = prompt
		self.model = model
		self.max_search_results = max_num_results
		self.instructions = instructions
		self.client = OpenAI( api_key=self.api_key, )

		if self.max_search_results < 1:
			self.max_search_results = 1

		if self.max_search_results > 50:
			self.max_search_results = 50

		self.input = [ { 'role': 'user',
			'content': [ { 'type': 'input_text', 'text': self.prompt, }, ], }, ]
		self.request = { 'model': self.model, 'input': self.input, 'tools': [
			{ 'type': 'file_search', 'vector_store_ids': self.store_ids,
				'max_num_results': self.max_search_results, }, ], }

		if self.instructions:
			self.request[ 'instructions' ] = self.instructions

		self.response = self.client.responses.create( **self.request )
		self.output_text = getattr( self.response, 'output_text', '', )

		if self.output_text:
			return self.output_text

		self.output_text = str( self.response )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'answer_with_file_search( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

survey

survey(
    store_ids: List[str],
    prompt: str = "Summarize the most relevant information available in the selected vector stores.",
    model: str = "gpt-4o-mini",
    max_num_results: int = 10,
    instructions: str = "",
) -> str

Survey vector stores.

Purpose

Generates a summary across required vector stores through the Responses API file-search tool.

Parameters:

Name Type Description Default
store_ids List[str]

Required vector-store identifiers.

required
prompt str

Summary prompt.

'Summarize the most relevant information available in the selected vector stores.'
model str

OpenAI model used to generate the summary.

'gpt-4o-mini'
max_num_results int

Maximum number of retrieved results.

10
instructions str

Optional system or developer instructions.

''

Returns:

Name Type Description
str str

Generated vector-store summary.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in gpt.py
def survey( self, store_ids: List[ str ],
	prompt: str = ('Summarize the most relevant information available in the '
	               'selected vector stores.'), model: str = 'gpt-4o-mini',
	max_num_results: int = 10, instructions: str = '' ) -> str:
	"""Survey vector stores.

	Purpose:
		Generates a summary across required vector stores through the Responses API
		file-search tool.

	Args:
		store_ids (List[str]): Required vector-store identifiers.
		prompt (str): Summary prompt.
		model (str): OpenAI model used to generate the summary.
		max_num_results (int): Maximum number of retrieved results.
		instructions (str): Optional system or developer instructions.

	Returns:
		str: Generated vector-store summary.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'store_ids', store_ids )
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.store_ids = store_ids
		self.prompt = prompt
		self.model = model
		self.max_search_results = max_num_results
		self.instructions = instructions
		self.output_text = self.answer_with_file_search( self.store_ids, self.prompt,
			self.model, self.max_search_results, self.instructions, )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gpt'
		exception.cause = 'VectorStores'
		exception.method = 'survey( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

__dir__

__dir__() -> List[str]

Return member names.

Purpose

Returns public members exposed by the OpenAI VectorStores wrapper.

Returns:

Type Description
List[str]

List[str]: Public member names.

Source code in gpt.py
def __dir__( self ) -> List[ str ]:
	"""Return member names.

	Purpose:
		Returns public members exposed by the OpenAI VectorStores wrapper.

	Returns:
		List[str]: Public member names.
	"""
	return [ 'api_key', 'client', 'name', 'description', 'store_id', 'file_id', 'file_ids',
		'batch_id', 'model', 'query', 'prompt', 'instructions', 'max_search_results',
		'response', 'vector_store', 'vector_stores', 'vector_file', 'vector_files',
		'file_batch', 'search_results', 'output_text', 'request', 'collections',
		'model_options', 'ranker_options', 'chunking_strategy_options', 'get_vector_store',
		'get_vector_file', 'get_file_batch', 'get_search_results', 'create', 'list_stores',
		'list', 'retrieve', 'update', 'delete', 'attach_file', 'list_files', 'retrieve_file',
		'update_file', 'delete_file', 'retrieve_file_content', 'create_file_batch',
		'retrieve_file_batch', 'list_file_batch_files', 'cancel_file_batch', 'search',
		'search_store', 'answer_with_file_search', 'survey', ]

throw_if

throw_if(name: str, value: object) -> None

Throw if.

Purpose

Validates that a required argument contains a usable value so failures occur before provider, filesystem, or parsing work begins.

Parameters:

Name Type Description Default
name str

Argument name included in validation error messages.

required
value object

Candidate value to validate or normalize.

required

Returns:

Name Type Description
None None

This method updates instance state or validates input and does not return a value.

Raises:

Type Description
ValueError

Raised when the method cannot satisfy its documented value requirement.

Source code in gpt.py
def throw_if( name: str, value: object ) -> None:
	"""Throw if.

	Purpose:
	    Validates that a required argument contains a usable value so failures occur before provider, filesystem, or parsing work begins.

	Args:
	    name (str): Argument name included in validation error messages.
	    value (object): Candidate value to validate or normalize.

	Returns:
	    None: This method updates instance state or validates input and does not return a value.

	Raises:
	    ValueError: Raised when the method cannot satisfy its documented value requirement.
	"""
	if value is None:
		raise ValueError( f'Argument "{name}" cannot be empty!' )

	if isinstance( value, str ) and (not value.strip( )):
		raise ValueError( f'Argument "{name}" cannot be empty!' )

	if isinstance( value, (list, tuple, dict, set) ) and len( value ) == 0:
		raise ValueError( f'Argument "{name}" cannot be empty!' )

encode_image

encode_image(image_path: str) -> str

Encode image.

Purpose

Reads a local image file and converts its bytes into a base64-encoded string. The encoded value is used by image and vision workflows that require inline image content.

Parameters:

Name Type Description Default
image_path str

Image path value used by the operation.

required

Returns:

Type Description
str

Base64-encoded image content.

Source code in gpt.py
def encode_image( image_path: str ) -> str:
	"""Encode image.

	Purpose:
		Reads a local image file and converts its bytes into a base64-encoded string. The
		encoded value is used by image and vision workflows that require inline image content.

	Args:
		image_path (str): Image path value used by the operation.

	Returns:
		Base64-encoded image content.
	"""
	with open( image_path, "rb" ) as image_file:
		return base64.b64encode( image_file.read( ) ).decode( 'utf-8' )