Skip to content

Gemini API

Gemini isolates Google-specific SDK calls from the Streamlit application shell. It should provide documented methods for Gemini text, multimodal, file, and grounded-generation workflows while keeping Google SDK details outside the UI layer.

Provider Scope

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

Workflow Description
Chat/Text Sends prompts to Gemini text-capable models.
Multimodal Generation Sends text plus images or files to Gemini multimodal models.
Image Workflows Handles image-related workflows where supported by the configured Gemini model.
Files Uploads, retrieves, lists, or deletes Gemini-managed files.
Grounded Generation Uses Google-supported grounding or search features where configured.
File Search Stores Manages provider-side file-search or document-search resources where implemented.

Design Contract

The wrapper should follow these conventions:

Contract Expected Pattern
Configuration Assign Gemini API keys and reusable model names from config.py or environment-derived config.
Validation Validate mandatory method arguments before provider calls.
Client lifecycle Create Gemini clients inside the method that uses them, not at import time.
File handling Keep file upload, polling, and cleanup logic inside the wrapper.
Error handling Capture exceptions using the project Error and Logger pattern.
Documentation Use Google-style docstrings for every public class and method.

Common Configuration Values

Value Purpose
GEMINI_API_KEY Primary Gemini credential.
GOOGLE_API_KEY Related Google API credential where used.
Gemini model constants Default text or multimodal model names.
File or store constants Default Gemini file-search store names or identifiers where implemented.

Usage Pattern

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

wrapper = Gemini()
response = wrapper.generate_content( text=prompt_text, model=model_name )

The exact class and method names should match the source code. The important architectural rule is that app.py should not directly embed Google SDK request construction.

File Workflow Notes

Gemini file workflows often require additional steps beyond a simple prompt call:

  1. upload the local file;
  2. wait until the provider marks the file usable;
  3. include the file reference in a model request;
  4. optionally clean up provider-side files.

Those steps should remain encapsulated in gemini.py so the UI can remain simple.

Documentation Guidance

Every public method should document:

  • whether it accepts raw text, local file paths, uploaded file objects, or provider file IDs;
  • whether it creates provider-managed resources;
  • whether polling or waiting is performed;
  • what response object or normalized payload is returned;
  • what errors are logged or surfaced to the caller.

API Reference

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

gemini

AI wrapping the gemini API for the Boo Streamlit application.

Purpose

Provides classes for Gemini text generation, image generation and analysis, embeddings, transcription, translation, text-to-speech, Gemini file operations, file-search stores, and Google Cloud Storage bucket workflows.

The module centralizes provider request construction, option lists, response extraction, and error logging so the application can call stable Python interfaces instead of provider-specific SDK objects directly.

Classes:

Name Description
Gemini

Shared base class for Gemini wrapper configuration and runtime state.

Chat

Text-generation wrapper for Gemini chat and grounding workflows.

Images

Image generation, analysis, and editing wrapper.

Embeddings

Text embedding wrapper.

TTS

Text-to-speech wrapper.

Transcription

Audio transcription wrapper.

Translation

Audio translation wrapper.

Files

Gemini file and document workflow wrapper.

FileSearch

Gemini file-search store wrapper.

CloudBuckets

Google Cloud Storage bucket wrapper.

License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, subject to inclusion of the copyright notice and permission notice in substantial portions of the software.

Contact

Terry Eppler, terryeppler@gmail.com or eppler.terry@epa.gov.

Gemini

Shared configuration state for Gemini provider wrappers.

Purpose

Initializes the API credentials, model parameters, generation settings, response configuration, and tool selections shared by the specialized Gemini wrapper classes. The base class performs no provider requests and contains no workflow-specific processing.

Attributes:

Name Type Description
google_api_key Optional[str]

Google API key loaded from application configuration.

gemini_api_key Optional[str]

Gemini API key loaded from application configuration.

model Optional[str]

Active Gemini model identifier.

api_version Optional[str]

API version selected by a specialized wrapper.

temperature Optional[float]

Sampling temperature.

top_p Optional[float]

Top-p sampling value.

top_k Optional[int]

Top-k sampling value.

candidate_count Optional[int]

Requested candidate count.

frequency_penalty Optional[float]

Frequency-penalty value.

presence_penalty Optional[float]

Presence-penalty value.

max_tokens Optional[int]

Maximum output-token count.

instructions Optional[str]

System instruction text.

prompt Optional[str]

Active user prompt.

response_format Optional[str]

Requested response format.

number Optional[int]

Requested number of generated results.

response_modalities List[str]

Requested response modalities.

stops List[str]

Stop sequences.

domains List[str]

Domain restrictions used by supported search workflows.

tools List[str]

Selected provider tools.

tool_choice Optional[str]

Tool-selection behavior.

content_response Optional[GenerateContentResponse]

Latest content response.

image_response Optional[GenerateImagesResponse]

Latest image-generation response.

content_config Optional[GenerateContentConfig]

Content-generation configuration.

function_config Optional[FunctionCallingConfig]

Function-calling configuration.

thought_config Optional[ThinkingConfig]

Thinking configuration.

genimg_config Optional[GenerateImagesConfig]

Image-generation configuration.

image_config Optional[ImageConfig]

Image-output configuration.

tool_config Optional[List[Tool]]

Provider tool configuration.

Source code in gemini.py
class Gemini( ):
	"""Shared configuration state for Gemini provider wrappers.

	Purpose:
		Initializes the API credentials, model parameters, generation settings, response
		configuration, and tool selections shared by the specialized Gemini wrapper classes.
		The base class performs no provider requests and contains no workflow-specific processing.

	Attributes:
		google_api_key (Optional[str]): Google API key loaded from application configuration.
		gemini_api_key (Optional[str]): Gemini API key loaded from application configuration.
		model (Optional[str]): Active Gemini model identifier.
		api_version (Optional[str]): API version selected by a specialized wrapper.
		temperature (Optional[float]): Sampling temperature.
		top_p (Optional[float]): Top-p sampling value.
		top_k (Optional[int]): Top-k sampling value.
		candidate_count (Optional[int]): Requested candidate count.
		frequency_penalty (Optional[float]): Frequency-penalty value.
		presence_penalty (Optional[float]): Presence-penalty value.
		max_tokens (Optional[int]): Maximum output-token count.
		instructions (Optional[str]): System instruction text.
		prompt (Optional[str]): Active user prompt.
		response_format (Optional[str]): Requested response format.
		number (Optional[int]): Requested number of generated results.
		response_modalities (List[str]): Requested response modalities.
		stops (List[str]): Stop sequences.
		domains (List[str]): Domain restrictions used by supported search workflows.
		tools (List[str]): Selected provider tools.
		tool_choice (Optional[str]): Tool-selection behavior.
		content_response (Optional[GenerateContentResponse]): Latest content response.
		image_response (Optional[GenerateImagesResponse]): Latest image-generation response.
		content_config (Optional[GenerateContentConfig]): Content-generation configuration.
		function_config (Optional[FunctionCallingConfig]): Function-calling configuration.
		thought_config (Optional[ThinkingConfig]): Thinking configuration.
		genimg_config (Optional[GenerateImagesConfig]): Image-generation configuration.
		image_config (Optional[ImageConfig]): Image-output configuration.
		tool_config (Optional[List[types.Tool]]): Provider tool configuration.
	"""

	google_api_key: Optional[ str ]
	gemini_api_key: Optional[ str ]
	model: Optional[ str ]
	api_version: Optional[ str ]
	temperature: Optional[ float ]
	top_p: Optional[ float ]
	top_k: Optional[ int ]
	candidate_count: Optional[ int ]
	frequency_penalty: Optional[ float ]
	presence_penalty: Optional[ float ]
	max_tokens: Optional[ int ]
	instructions: Optional[ str ]
	prompt: Optional[ str ]
	response_format: Optional[ str ]
	number: Optional[ int ]
	response_modalities: List[ str ]
	stops: List[ str ]
	domains: List[ str ]
	tools: List[ str ]
	tool_choice: Optional[ str ]
	content_response: Optional[ GenerateContentResponse ]
	image_response: Optional[ GenerateImagesResponse ]
	content_config: Optional[ GenerateContentConfig ]
	function_config: Optional[ FunctionCallingConfig ]
	thought_config: Optional[ ThinkingConfig ]
	genimg_config: Optional[ GenerateImagesConfig ]
	image_config: Optional[ ImageConfig ]
	tool_config: Optional[ List[ types.Tool ] ]

	def __init__( self ) -> None:
		"""Initialize shared Gemini wrapper state.

		Purpose:
			Initializes common credentials, model parameters, request configuration, tool
			selections, and response placeholders used by the specialized Gemini wrappers. The
			constructor performs local state assignment only.

		Returns:
			None: This method initializes object state through side effects.
		"""
		self.google_api_key = cfg.GOOGLE_API_KEY
		self.gemini_api_key = cfg.GEMINI_API_KEY
		self.model = None
		self.api_version = None
		self.temperature = None
		self.top_p = None
		self.top_k = None
		self.candidate_count = None
		self.frequency_penalty = None
		self.presence_penalty = None
		self.max_tokens = None
		self.instructions = None
		self.prompt = None
		self.response_format = None
		self.number = None
		self.response_modalities = [ ]
		self.stops = [ ]
		self.domains = [ ]
		self.tools = [ ]
		self.tool_choice = None
		self.content_response = None
		self.image_response = None
		self.content_config = None
		self.function_config = None
		self.thought_config = None
		self.genimg_config = None
		self.image_config = None
		self.tool_config = None

__init__

__init__() -> None

Initialize shared Gemini wrapper state.

Purpose

Initializes common credentials, model parameters, request configuration, tool selections, and response placeholders used by the specialized Gemini wrappers. The constructor performs local state assignment only.

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self ) -> None:
	"""Initialize shared Gemini wrapper state.

	Purpose:
		Initializes common credentials, model parameters, request configuration, tool
		selections, and response placeholders used by the specialized Gemini wrappers. The
		constructor performs local state assignment only.

	Returns:
		None: This method initializes object state through side effects.
	"""
	self.google_api_key = cfg.GOOGLE_API_KEY
	self.gemini_api_key = cfg.GEMINI_API_KEY
	self.model = None
	self.api_version = None
	self.temperature = None
	self.top_p = None
	self.top_k = None
	self.candidate_count = None
	self.frequency_penalty = None
	self.presence_penalty = None
	self.max_tokens = None
	self.instructions = None
	self.prompt = None
	self.response_format = None
	self.number = None
	self.response_modalities = [ ]
	self.stops = [ ]
	self.domains = [ ]
	self.tools = [ ]
	self.tool_choice = None
	self.content_response = None
	self.image_response = None
	self.content_config = None
	self.function_config = None
	self.thought_config = None
	self.genimg_config = None
	self.image_config = None
	self.tool_config = None

Chat

Bases: Gemini

Gemini text-generation wrapper.

Purpose

Executes text-generation, grounding, structured-output, streaming, URL Context, File Search, Google Search, Google Maps, and Code Execution workflows through the Gemini Interactions API. The class preserves the application-facing contract used by Jeni while maintaining conversation history through the existing client-managed application state.

Attributes:

Name Type Description
use_vertex bool

Whether Vertex AI configuration is enabled.

http_options HttpOptions

Gemini client HTTP configuration.

client Optional[Client]

Gemini SDK client.

storage_client Optional[Client]

Optional Google Cloud Storage client.

contents Optional[List[Dict[str, Any]]]

Complete Interactions input timeline.

input_steps List[Dict[str, Any]]

Interactions input steps submitted to Gemini.

image_uri Optional[str]

Optional image URI retained for interface compatibility.

audio_uri Optional[str]

Optional audio URI retained for interface compatibility.

file_path Optional[str]

Optional local file path retained for compatibility.

files List[str]

File identifiers retained for interface compatibility.

content_block str

Additional content prepended to the active prompt.

context List[Dict[str, Any]]

Existing application-managed conversation history.

urls List[str]

URL-context values.

max_urls int

Maximum URL values included in the prompt.

response_schema Optional[Dict[str, Any]]

Parsed structured-output schema.

safety_profile str

Safety-profile value retained for UI compatibility.

safety_settings Optional[List[SafetySetting]]

Optional Gemini safety settings.

file_search_store_names List[str]

File Search Store resource names.

interaction Optional[Any]

Most recent Gemini Interaction.

interaction_id Optional[str]

Identifier of the most recent Interaction.

steps List[Any]

Steps returned by the most recent Interaction.

response Optional[Any]

Raw response used by application token accounting.

output_text str

Generated response text.

grounding_sources List[Dict[str, Any]]

Normalized grounding citations.

generation_config Dict[str, Any]

Interactions generation configuration.

interaction_response_format Optional[Any]

Interactions response-format value.

tool_objects List[Dict[str, Any]]

Interactions server-side tool definitions.

stream bool

Whether streaming is enabled.

stream_handler Optional[Callable[[str], None]]

Text-delta callback.

Source code in gemini.py
 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
1036
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
class Chat( Gemini ):
	"""Gemini text-generation wrapper.

	Purpose:
		Executes text-generation, grounding, structured-output, streaming, URL Context,
		File Search, Google Search, Google Maps, and Code Execution workflows through the
		Gemini Interactions API. The class preserves the application-facing contract used by
		Jeni while maintaining conversation history through the existing client-managed
		application state.

	Attributes:
		use_vertex (bool): Whether Vertex AI configuration is enabled.
		http_options (HttpOptions): Gemini client HTTP configuration.
		client (Optional[genai.Client]): Gemini SDK client.
		storage_client (Optional[storage.Client]): Optional Google Cloud Storage client.
		contents (Optional[List[Dict[str, Any]]]): Complete Interactions input timeline.
		input_steps (List[Dict[str, Any]]): Interactions input steps submitted to Gemini.
		image_uri (Optional[str]): Optional image URI retained for interface compatibility.
		audio_uri (Optional[str]): Optional audio URI retained for interface compatibility.
		file_path (Optional[str]): Optional local file path retained for compatibility.
		files (List[str]): File identifiers retained for interface compatibility.
		content_block (str): Additional content prepended to the active prompt.
		context (List[Dict[str, Any]]): Existing application-managed conversation history.
		urls (List[str]): URL-context values.
		max_urls (int): Maximum URL values included in the prompt.
		response_schema (Optional[Dict[str, Any]]): Parsed structured-output schema.
		safety_profile (str): Safety-profile value retained for UI compatibility.
		safety_settings (Optional[List[SafetySetting]]): Optional Gemini safety settings.
		file_search_store_names (List[str]): File Search Store resource names.
		interaction (Optional[Any]): Most recent Gemini Interaction.
		interaction_id (Optional[str]): Identifier of the most recent Interaction.
		steps (List[Any]): Steps returned by the most recent Interaction.
		response (Optional[Any]): Raw response used by application token accounting.
		output_text (str): Generated response text.
		grounding_sources (List[Dict[str, Any]]): Normalized grounding citations.
		generation_config (Dict[str, Any]): Interactions generation configuration.
		interaction_response_format (Optional[Any]): Interactions response-format value.
		tool_objects (List[Dict[str, Any]]): Interactions server-side tool definitions.
		stream (bool): Whether streaming is enabled.
		stream_handler (Optional[Callable[[str], None]]): Text-delta callback.
	"""

	use_vertex: bool
	http_options: HttpOptions
	client: Optional[ genai.Client ]
	storage_client: Optional[ storage.Client ]
	contents: Optional[ List[ Dict[ str, Any ] ] ]
	input_steps: List[ Dict[ str, Any ] ]
	image_uri: Optional[ str ]
	audio_uri: Optional[ str ]
	file_path: Optional[ str ]
	files: List[ str ]
	content_block: str
	context: List[ Dict[ str, Any ] ]
	urls: List[ str ]
	max_urls: int
	response_schema: Optional[ Dict[ str, Any ] ]
	safety_profile: str
	safety_settings: Optional[ List[ SafetySetting ] ]
	file_search_store_names: List[ str ]
	interaction: Optional[ Any ]
	interaction_id: Optional[ str ]
	steps: List[ Any ]
	response: Optional[ Any ]
	output_text: str
	grounding_sources: List[ Dict[ str, Any ] ]
	generation_config: Dict[ str, Any ]
	interaction_response_format: Optional[ Any ]
	tool_objects: List[ Dict[ str, Any ] ]
	stream: bool
	stream_handler: Optional[ Callable[ [ str ], None ] ]

	def __init__( self, model: str='gemini-2.5-flash-lite' ) -> None:
		"""Initialize the Chat wrapper.

		Purpose:
			Initializes text-generation configuration, Interactions request state, grounding
			state, conversation-history state, and response placeholders. The constructor
			performs local state assignment only.

		Args:
			model (str): Default Gemini text-generation model.

		Returns:
			None: This method initializes object state through side effects.
		"""
		super( ).__init__( )
		self.gemini_api_key = cfg.GEMINI_API_KEY
		self.google_api_key = cfg.GOOGLE_API_KEY
		self.api_version = 'v1beta'
		self.http_options = types.HttpOptions( api_version=self.api_version )
		self.use_vertex = False
		self.client = None
		self.storage_client = None
		self.model = model
		self.prompt = None
		self.instructions = None
		self.number = 1
		self.candidate_count = 1
		self.temperature = 0.0
		self.top_p = 0.0
		self.top_k = 0
		self.frequency_penalty = 0.0
		self.presence_penalty = 0.0
		self.max_tokens = 0
		self.stops = [ ]
		self.response_format = None
		self.response_schema = None
		self.response_modalities = [ ]
		self.media_resolution = None
		self.tool_choice = None
		self.tools = [ ]
		self.tool_objects = [ ]
		self.generation_config = { }
		self.interaction_response_format = None
		self.safety_profile = ''
		self.safety_settings = None
		self.contents = None
		self.input_steps = [ ]
		self.content_block = ''
		self.context = [ ]
		self.urls = [ ]
		self.max_urls = 0
		self.files = [ ]
		self.file_search_store_names = [ ]
		self.image_uri = None
		self.audio_uri = None
		self.file_path = None
		self.interaction = None
		self.interaction_id = None
		self.steps = [ ]
		self.response = None
		self.content_response = None
		self.output_text = ''
		self.grounding_metadata = None
		self.grounding_sources = [ ]
		self.stream = False
		self.stream_handler = None

	@property
	def model_options( self ) -> List[ str ]:
		"""Return supported Gemini text-generation models.

		Purpose:
			Provides the text-generation model identifiers exposed by the Jeni Text,
			Document Q&A, File Search Stores, and Google Cloud Buckets interfaces.

		Returns:
			List[str]: Supported Gemini text-generation model identifiers.
		"""
		return [ 'gemini-2.5-flash', 'gemini-2.5-flash-lite', 'gemini-2.5-pro',
			'gemini-3.1-flash-lite', 'gemini-3.1-pro-preview', 'gemini-3.5-flash',
			'gemini-3.6-flash', ]

	@property
	def tool_options( self ) -> List[ str ]:
		"""Return supported Interactions server-side tools.

		Purpose:
			Provides the server-side tools exposed by the Jeni Text interface.

		Returns:
			List[str]: Supported Interactions tool identifiers.
		"""
		return [ 'google_search', 'google_maps', 'url_context', 'file_search', 'code_execution', ]

	@property
	def reasoning_options( self ) -> List[ str ]:
		"""Return supported thinking levels.

		Purpose:
			Provides the thinking-level values exposed by the Jeni model controls.

		Returns:
			List[str]: Supported thinking-level values.
		"""
		return [ 'THINKING_LEVEL_UNSPECIFIED', 'MINIMAL', 'LOW', 'MEDIUM', 'HIGH', ]

	@property
	def media_options( self ) -> List[ str ]:
		"""Return supported media-resolution values.

		Purpose:
			Preserves the media-resolution option contract used by the Jeni interface.

		Returns:
			List[str]: Supported media-resolution values.
		"""
		return [ 'media_resolution_high', 'media_resolution_medium', 'media_resolution_low', ]

	@property
	def choice_options( self ) -> List[ str ]:
		"""Return supported tool-choice values.

		Purpose:
			Provides the tool-selection values accepted by the Interactions API.

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

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

		Purpose:
			Preserves the option values consumed by existing Jeni controls while citations
			and tool execution are retrieved from typed Interaction steps.

		Returns:
			List[str]: Existing Jeni include-option values.
		"""
		return [ 'file_search_call.results', 'message.input_image.image_url',
			'message.output_text.logprobs', 'reasoning.encrypted_content', ]

	@property
	def modality_options( self ) -> List[ str ]:
		"""Return supported response modalities.

		Purpose:
			Provides response-modality values used by the Jeni Text interface.

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

	@property
	def format_options( self ) -> List[ str ]:
		"""Return supported text response MIME types.

		Purpose:
			Provides text and structured-output MIME types used by the Text interface.

		Returns:
			List[str]: Supported response MIME types.
		"""
		return [ 'text/plain', 'application/json', 'text/x.enum', ]

	def get_supported_tools( self, model: str ) -> List[ str ]:
		"""Return tools supported by the selected model.

		Purpose:
			Builds the tool list consumed by the Jeni Text controls and conditionally includes
			Google Maps for models that expose that capability.

		Args:
			model (str): Gemini model identifier.

		Returns:
			List[str]: Tool identifiers supported by the selected model.

		Raises:
			Error: Raised when validation or tool-list construction fails.
			ValueError: Raised when ``model`` is missing.
		"""
		try:
			throw_if( 'model', model )
			self.model = model
			self.options = [ 'google_search', 'url_context', 'file_search', 'code_execution', ]

			if self.supports_google_maps( self.model ):
				self.options.append( 'google_maps' )

			return self.options
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = 'get_supported_tools( self, model: str ) -> List[ str ]'
			Logger( ).write( exception )
			raise exception

	def supports_google_maps( self, model: str ) -> bool:
		"""Return whether a model supports Google Maps grounding.

		Purpose:
			Centralizes Google Maps feature gating for the Jeni Text controls.

		Args:
			model (str): Gemini model identifier.

		Returns:
			bool: True when Google Maps may be exposed; otherwise False.

		Raises:
			Error: Raised when validation or model comparison fails.
			ValueError: Raised when ``model`` is missing.
		"""
		try:
			throw_if( 'model', model )
			self.model = model
			self.model_name = self.model.strip( ).lower( )
			self.maps_models = { 'gemini-3.5-flash', 'gemini-3.6-flash', }
			return self.model_name in self.maps_models
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = 'supports_google_maps( self, model: str ) -> bool'
			Logger( ).write( exception )
			raise exception

	def normalize_value( self, value: Any ) -> Any:
		"""Convert an SDK value into standard Python data.

		Purpose:
			Recursively converts SDK response models, dictionaries, and sequences into
			ordinary Python values used by history and citation processing.

		Args:
			value (Any): SDK or Python value to normalize.

		Returns:
			Any: Equivalent standard Python value.

		Raises:
			Error: Raised when value normalization fails.
		"""
		try:
			self.value = value

			if self.value is None or isinstance( self.value, (str, int, float, bool) ):
				return self.value

			if isinstance( self.value, dict ):
				return { key: self.normalize_value( item ) for key, item in self.value.items( ) }

			if isinstance( self.value, (list, tuple, set) ):
				return [ self.normalize_value( item ) for item in self.value ]

			if hasattr( self.value, 'model_dump' ):
				self.value_data = self.value.model_dump( exclude_none=True )
				return self.normalize_value( self.value_data )

			if hasattr( self.value, 'to_dict' ):
				self.value_data = self.value.to_dict( )
				return self.normalize_value( self.value_data )

			return str( self.value )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = 'normalize_value( self, value: Any ) -> Any'
			Logger( ).write( exception )
			raise exception

	def normalize_context( self,
		context: Optional[ List[ Dict[ str, Any ] ] ] = None ) -> List[ Dict[ str, Any ] ]:
		"""Convert application history into Interactions steps.

		Purpose:
			Preserves existing Interactions steps and converts Jeni role/content dictionaries
			into ``user_input`` and ``model_output`` steps for stateless conversation history.

		Args:
			context (Optional[List[Dict[str, Any]]]): Existing conversation history.

		Returns:
			List[Dict[str, Any]]: Interactions-compatible history steps.

		Raises:
			Error: Raised when conversation history cannot be normalized.
		"""
		try:
			self.context = context if isinstance( context, list ) else [ ]
			self.history_steps: List[ Dict[ str, Any ] ] = [ ]
			for message in self.context:
				if not isinstance( message, dict ):
					continue

				self.context_type = str( message.get( 'type', '' ) or '' ).strip( )
				if self.context_type:
					self.context_step = self.normalize_value( message )
					if isinstance( self.context_step, dict ) and self.context_step:
						self.history_steps.append( self.context_step )

					continue

				self.message_role = str( message.get( 'role', '' ) or '' ).strip( ).lower( )
				self.message_content = message.get( 'content', '' )

				if isinstance( self.message_content, list ):
					self.message_text = '\n'.join(
						str( item ).strip( ) for item in self.message_content if
							item is not None and str( item ).strip( ) )
				else:
					self.message_text = str( self.message_content or '' ).strip( )

				if not self.message_text:
					continue

				if self.message_role in ('assistant', 'model'):
					self.step_type = 'model_output'
				else:
					self.step_type = 'user_input'

				self.history_steps.append( { 'type': self.step_type,
					'content': [ { 'type': 'text', 'text': self.message_text, }, ], } )

			self.context = self.history_steps
			return self.context
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = (
				'normalize_context( self, context: Optional[ List[ Dict[ str, Any ] ] ] ) '
				'-> List[ Dict[ str, Any ] ]')
			Logger( ).write( exception )
			raise exception

	def build_urls( self, urls: Optional[ List[ str ] ]=None, max_urls: int=0 ) -> List[ str ]:
		"""Build the normalized URL list.

		Purpose:
			Removes blank and duplicate URL values while preserving order and applies the
			configured maximum before URL values are supplied to the active request.

		Args:
			urls (Optional[List[str]]): Candidate URL values.
			max_urls (int): Maximum URLs to retain; zero retains all values.

		Returns:
			List[str]: Normalized URL values.

		Raises:
			Error: Raised when URL normalization fails.
		"""
		try:
			self.urls = urls if isinstance( urls, list ) else [ ]
			self.max_urls = max_urls
			self.normalized_urls: List[ str ] = [ ]

			for url in self.urls:
				if url is None:
					continue

				self.url = str( url ).strip( )
				if not self.url:
					continue

				if self.url not in self.normalized_urls:
					self.normalized_urls.append( self.url )

			if self.max_urls > 0:
				self.normalized_urls = self.normalized_urls[ :self.max_urls ]

			self.urls = self.normalized_urls
			return self.urls
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('build_urls( self, **kwargs ) -> List[ str ]')
			Logger( ).write( exception )
			raise exception

	def build_input( self, prompt: str, content: str='',
		context: Optional[ List[ Dict[ str, Any ] ] ]=None, urls: Optional[ List[ str ] ]=None,
		max_urls: int=0 ) -> List[ Dict[ str, Any ] ]:
		"""Build the complete Interactions input timeline.

		Purpose:
			Combines existing client-managed conversation history with optional content,
			reference URLs, and the current user prompt.

		Args:
			prompt (str): Current user prompt.
			content (str): Optional content prepended to the prompt.
			context (Optional[List[Dict[str, Any]]]): Existing conversation history.
			urls (Optional[List[str]]): URL-context values.
			max_urls (int): Maximum number of URLs.

		Returns:
			List[Dict[str, Any]]: Complete Interactions input timeline.

		Raises:
			Error: Raised when validation or input construction fails.
			ValueError: Raised when ``prompt`` is missing.
		"""
		try:
			throw_if( 'prompt', prompt )
			self.prompt = prompt
			self.content_block = content
			self.context = context if isinstance( context, list ) else [ ]
			self.urls = urls if isinstance( urls, list ) else [ ]
			self.max_urls = max_urls
			self.input_steps = self.normalize_context( self.context )
			self.urls = self.build_urls( self.urls, self.max_urls )
			self.current_parts: List[ str ] = [ ]
			if self.content_block and self.content_block.strip( ):
				self.current_parts.append( self.content_block.strip( ) )

			if self.urls:
				self.current_parts.append(
					'Reference URLs:\n' + '\n'.join( f'- {url}' for url in self.urls ) )

			self.current_parts.append( self.prompt.strip( ) )
			self.current_text = '\n\n'.join( part for part in self.current_parts if part ).strip( )

			self.input_steps.append( { 'type': 'user_input',
				'content': [ { 'type': 'text', 'text': self.current_text, }, ], } )

			self.contents = self.input_steps
			return self.input_steps
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('build_input( self, **kwargs ) -> List[ Dict[ str, Any ] ]')
			Logger( ).write( exception )
			raise exception

	def build_generation_config( self, temperature: float=0.0, top_p: float=0.0, top_k: int=0,
		max_tokens: int=0, stops: Optional[ List[ str ] ]=None, reasoning: str='',
		tool_choice: Optional[ str ]=None ) -> Dict[ str, Any ]:
		"""Build the Interactions generation configuration.

		Purpose:
			Converts supported Jeni inference controls into the Interactions generation
			configuration without submitting blank or zero-valued optional controls.

		Args:
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			top_k (int): Top-k sampling value.
			max_tokens (int): Maximum output-token count.
			stops (Optional[List[str]]): Stop sequences.
			reasoning (str): Thinking-level value.
			tool_choice (Optional[str]): Tool-selection behavior.

		Returns:
			Dict[str, Any]: Interactions generation configuration.

		Raises:
			Error: Raised when generation configuration construction fails.
		"""
		try:
			self.temperature = temperature
			self.top_p = top_p
			self.top_k = top_k
			self.max_tokens = max_tokens
			self.stops = stops if isinstance( stops, list ) else [ ]
			self.reasoning = reasoning
			self.tool_choice = tool_choice
			self.generation_config = { }
			if self.temperature > 0.0:
				self.generation_config[ 'temperature' ] = self.temperature

			if self.top_p > 0.0:
				self.generation_config[ 'top_p' ] = self.top_p

			if self.top_k > 0:
				self.generation_config[ 'top_k' ] = self.top_k

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

			self.stop_sequences = [ str( value ).strip( ) for value in self.stops if
				value is not None and str( value ).strip( ) ]

			if self.stop_sequences:
				self.generation_config[ 'stop_sequences' ] = self.stop_sequences

			self.thinking_level = str( self.reasoning or '' ).strip( ).lower( )

			if self.thinking_level not in ('', 'thinking_level_unspecified', 'unspecified',):
				self.generation_config[ 'thinking_level' ] = self.thinking_level

			self.tool_choice_value = str( self.tool_choice or '' ).strip( ).lower( )

			if self.tool_choice_value:
				self.generation_config[ 'tool_choice' ] = self.tool_choice_value

			return self.generation_config
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('build_generation_config( self, **kwargs -> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def parse_response_schema( self, response_schema: Any = None ) -> Optional[ Dict[ str, Any ] ]:
		"""Parse an optional structured-output schema.

		Purpose:
			Accepts a dictionary or JSON string and converts it into the JSON Schema mapping
			required by the Interactions API.

		Args:
			response_schema (Any): Optional JSON Schema dictionary or JSON string.

		Returns:
			Optional[Dict[str, Any]]: Parsed JSON Schema, or None when absent.

		Raises:
			Error: Raised when a nonblank schema cannot be parsed.
		"""
		try:
			self.response_schema = response_schema
			if self.response_schema is None:
				return None

			if isinstance( self.response_schema, dict ):
				return self.response_schema

			self.schema_text = str( self.response_schema ).strip( )
			if not self.schema_text:
				self.response_schema = None
				return None

			self.schema_value = json.loads( self.schema_text )
			if not isinstance( self.schema_value, dict ):
				raise ValueError( 'The response schema must contain a JSON object.' )

			self.response_schema = self.schema_value
			return self.response_schema
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('parse_response_schema( self, response_schema: Any ) '
			                    '-> Optional[ Dict[ str, Any ] ]')
			Logger( ).write( exception )
			raise exception

	def build_response_format( self, response_format: str='', response_schema: Any = None,
		modalities: Optional[ List[ str ] ] = None ) -> Optional[ Any ]:
		"""Build the Interactions response format.

		Purpose:
			Converts the Jeni MIME type, response modalities, and optional JSON Schema into
			the polymorphic response-format structure used by the current Interactions API.

		Args:
			response_format (str): Requested text MIME type.
			response_schema (Any): Optional JSON Schema mapping or JSON string.
			modalities (Optional[List[str]]): Requested response modalities.

		Returns:
			Optional[Any]: Interactions response-format value.

		Raises:
			Error: Raised when response-format construction fails.
		"""
		try:
			self.response_format = response_format
			self.response_schema = response_schema
			self.response_modalities = (modalities if isinstance( modalities, list ) else [ ])
			self.response_schema = self.parse_response_schema( self.response_schema )
			self.response_mime_type = str( self.response_format or '' ).strip( )
			self.normalized_modalities = [ str( value ).strip( ).lower( ) for value in
				self.response_modalities if value is not None and str( value ).strip( ) ]

			if self.normalized_modalities and 'text' not in self.normalized_modalities:
				self.interaction_response_format = None
				return None

			if self.response_schema is not None:
				self.interaction_response_format = [
					{ 'type': 'text', 'mime_type': 'application/json',
						'schema': self.response_schema, }, ]
				return self.interaction_response_format

			if self.response_mime_type in ('application/json', 'text/x.enum'):
				self.interaction_response_format = [
					{ 'type': 'text', 'mime_type': self.response_mime_type, }, ]
				return self.interaction_response_format

			self.interaction_response_format = None
			return None
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('build_response_format( self, **kwargs ) -> Optional[ Any ]')
			Logger( ).write( exception )
			raise exception

	def build_tools( self, tools: Optional[ List[ str ] ] = None,
		urls: Optional[ List[ str ] ] = None,
		file_search_store_names: Optional[ List[ str ] ] = None ) -> List[ Dict[ str, Any ] ]:
		"""Build Interactions server-side tools.

		Purpose:
			Translates Jeni tool identifiers into Interactions tool declarations. URL Context
			is enabled when selected or when URLs are supplied. File Search is enabled when
			File Search Store resource names are supplied.

		Args:
			tools (Optional[List[str]]): Selected tool identifiers.
			urls (Optional[List[str]]): Normalized URL-context values.
			file_search_store_names (Optional[List[str]]): File Search Store names.

		Returns:
			List[Dict[str, Any]]: Interactions server-side tool declarations.

		Raises:
			Error: Raised when tool construction fails.
		"""
		try:
			self.tools = tools if isinstance( tools, list ) else [ ]
			self.urls = urls if isinstance( urls, list ) else [ ]
			self.file_search_store_names = (
				file_search_store_names if isinstance( file_search_store_names, list ) else [ ])
			self.selected_tools = [ str( value ).strip( ).lower( ) for value in self.tools if
				value is not None and str( value ).strip( ) ]
			self.file_search_store_names = [ str( value ).strip( ) for value in
				self.file_search_store_names if value is not None and str( value ).strip( ) ]
			self.tool_objects = [ ]
			if 'google_search' in self.selected_tools:
				self.tool_objects.append( { 'type': 'google_search', } )

			if ('google_maps' in self.selected_tools and self.supports_google_maps( self.model )):
				self.tool_objects.append( { 'type': 'google_maps', } )

			if 'url_context' in self.selected_tools or self.urls:
				self.tool_objects.append( { 'type': 'url_context', } )

			if 'code_execution' in self.selected_tools:
				self.tool_objects.append( { 'type': 'code_execution', } )

			if self.file_search_store_names:
				self.tool_objects.append( { 'type': 'file_search',
					'file_search_store_names': self.file_search_store_names, } )

			return self.tool_objects
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('build_tools( self, **kwargs ) -> List[ Dict[ str, Any ] ]')
			Logger( ).write( exception )
			raise exception

	def append_source( self, source: Dict[ str, Any ], default_type: str ) -> None:
		"""Append one normalized grounding source.

		Purpose:
			Converts provider citation and tool-result fields into the stable source shape
			consumed by Jeni and prevents duplicate records.

		Args:
			source (Dict[str, Any]): Provider citation or result mapping.
			default_type (str): Source type used when omitted by the mapping.

		Returns:
			None: This method updates source state through side effects.

		Raises:
			Error: Raised when validation or source normalization fails.
			ValueError: Raised when a required argument is missing.
		"""
		try:
			throw_if( 'source', source )
			throw_if( 'default_type', default_type )
			self.source = source
			self.default_type = default_type
			self.source_type = str(
				self.source.get( 'type', self.default_type ) or self.default_type ).strip( )
			self.source_title = str(
				self.source.get( 'title' ) or self.source.get( 'display_name' ) or self.source.get(
					'file_name' ) or self.source.get( 'name' ) or '' ).strip( )
			self.source_url = str(
				self.source.get( 'uri' ) or self.source.get( 'url' ) or self.source.get(
					'source_url' ) or '' ).strip( )
			self.source_text = str(
				self.source.get( 'text' ) or self.source.get( 'snippet' ) or self.source.get(
					'quote' ) or self.source.get( 'search_suggestions' ) or '' ).strip( )
			self.source_file_id = str(
				self.source.get( 'file_id' ) or self.source.get( 'file_name' ) or self.source.get(
					'document_name' ) or '' ).strip( )

			if not any( [ self.source_title, self.source_url, self.source_text,
				self.source_file_id, ] ):
				return

			self.source_key = (self.source_type, self.source_url or self.source_file_id,
				self.source_text,)

			if self.source_key in self.source_keys:
				return

			self.source_keys.add( self.source_key )
			self.source_values.append( { 'type': self.source_type, 'title': self.source_title or None,
					'snippet': self.source_text or None, 'url': self.source_url or None,
					'files_id': self.source_file_id or None, 'metadata': self.source, } )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('append_source( self, *kwargs ) -> None')
			Logger( ).write( exception )
			raise exception

	def extract_grounding_sources( self, interaction: Any ) -> List[ Dict[ str, Any ] ]:
		"""Extract grounding citations from an Interaction.

		Purpose:
			Collects model-output annotations and supported server-side tool-result data
			from the current Interaction steps.

		Args:
			interaction (Any): Completed Gemini Interaction.

		Returns:
			List[Dict[str, Any]]: Normalized grounding-source records.

		Raises:
			Error: Raised when validation or citation extraction fails.
			ValueError: Raised when ``interaction`` is missing.
		"""
		try:
			throw_if( 'interaction', interaction )
			self.source_interaction = interaction
			self.source_values: List[ Dict[ str, Any ] ] = [ ]
			self.source_keys: Set[ Tuple[ str, str, str ] ] = set( )
			self.source_steps = getattr( self.source_interaction, 'steps', None ) or [ ]
			for step in self.source_steps:
				self.source_step_type = str( getattr( step, 'type', '' ) or '' ).strip( )
				if self.source_step_type == 'model_output':
					self.source_content = getattr( step, 'content', None ) or [ ]
					for block in self.source_content:
						self.annotations = getattr( block, 'annotations', None ) or [ ]

						for annotation in self.annotations:
							self.annotation_value = self.normalize_value( annotation )

							if not isinstance( self.annotation_value, dict ):
								continue

							self.append_source( self.annotation_value, str(
								self.annotation_value.get( 'type', 'citation' ) or 'citation' ) )

				elif self.source_step_type in ('google_search_result', 'file_search_result',
					'url_context_result', 'google_maps_result', 'code_execution_result',):
					self.result_value = self.normalize_value( getattr( step, 'result', None ) )
					if isinstance( self.result_value, list ):
						for result in self.result_value:
							if isinstance( result, dict ) and result:
								self.append_source( result, self.source_step_type )

					elif isinstance( self.result_value, dict ) and self.result_value:
						self.append_source( self.result_value, self.source_step_type )

			return self.source_values
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('extract_grounding_sources( self, **kwargs) -> List[Dict[str, Any]]')
			Logger( ).write( exception )
			raise exception

	def capture_interaction( self, interaction: Any ) -> None:
		"""Capture a completed Gemini Interaction.

		Purpose:
			Stores the raw response, identifier, output steps, generated text, and grounding
			sources on the members consumed by the Jeni application.

		Args:
			interaction (Any): Completed Gemini Interaction.

		Returns:
			None: This method updates response state through side effects.

		Raises:
			Error: Raised when validation or response extraction fails.
			ValueError: Raised when ``interaction`` is missing.
		"""
		try:
			throw_if( 'interaction', interaction )
			self.interaction = interaction
			self.response = self.interaction
			self.content_response = self.interaction
			self.interaction_id = getattr( self.interaction, 'id', None )
			self.steps = list( getattr( self.interaction, 'steps', None ) or [ ] )
			self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
			self.grounding_sources = self.extract_grounding_sources( self.interaction )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('capture_interaction( self, interaction: Any ) -> None')
			Logger( ).write( exception )
			raise exception

	def get_grounding_sources( self ) -> List[ Dict[ str, Any ] ]:
		"""Return sources from the most recent Interaction.

		Purpose:
			Provides normalized grounding-source records consumed by Jeni response renderers.

		Returns:
			List[Dict[str, Any]]: Grounding sources from the latest response.
		"""
		return list( self.grounding_sources )

	def get_structured_history( self ) -> List[ Dict[ str, Any ] ]:
		"""Return the complete stateless conversation history.

		Purpose:
			Combines the submitted input timeline with the output steps returned by the latest
			Interaction so Jeni can preserve client-managed conversation state.

		Returns:
			List[Dict[str, Any]]: Complete Interactions-compatible history.

		Raises:
			Error: Raised when output steps cannot be normalized.
		"""
		try:
			self.structured_history: List[ Dict[ str, Any ] ] = [ ]
			for step in self.input_steps:
				self.input_step = self.normalize_value( step )
				if isinstance( self.input_step, dict ) and self.input_step:
					self.structured_history.append( self.input_step )

			for step in self.steps:
				self.output_step = self.normalize_value( step )
				if isinstance( self.output_step, dict ) and self.output_step:
					self.structured_history.append( self.output_step )

			return self.structured_history
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('get_structured_history( self ) -> List[ Dict[ str, Any ] ]')
			Logger( ).write( exception )
			raise exception

	def generate_text_stream( self ) -> str:
		"""Execute the prepared streaming Interactions request.

		Purpose:
			Submits the active request, forwards text deltas to the application callback,
			accumulates the complete generated text, and captures final usage metadata.

		Returns:
			str: Complete generated text.

		Raises:
			Error: Raised when streaming execution or event handling fails.
		"""
		try:
			self.request = { 'model': self.model, 'input': self.input_steps, 'stream': True,
				'store': False, }

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

			if self.tool_objects:
				self.request[ 'tools' ] = self.tool_objects

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

			if self.interaction_response_format is not None:
				self.request[ 'response_format' ] = (self.interaction_response_format)

			self.stream_response = self.client.interactions.create( **self.request )
			self.text_chunks: List[ str ] = [ ]
			self.completed_interaction = None

			for event in self.stream_response:
				self.event_type = str( getattr( event, 'event_type', '' ) or '' ).strip( )

				if self.event_type == 'step.delta':
					self.delta = getattr( event, 'delta', None )
					self.delta_type = str( getattr( self.delta, 'type', '' ) or '' ).strip( )

					if self.delta_type == 'text':
						self.delta_text = str( getattr( self.delta, 'text', '' ) or '' )

						if self.delta_text:
							self.text_chunks.append( self.delta_text )

							if callable( self.stream_handler ):
								self.stream_handler( self.delta_text )

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

				elif self.event_type == 'error':
					self.stream_error = getattr( event, 'error', None )
					self.stream_message = str( getattr( self.stream_error, 'message',
						'' ) or self.stream_error or 'Gemini streaming request failed.' )
					raise RuntimeError( self.stream_message )

			self.output_text = ''.join( self.text_chunks ).strip( )
			self.steps = [ ]

			if self.output_text:
				self.steps.append( { 'type': 'model_output',
					'content': [ { 'type': 'text', 'text': self.output_text, }, ], } )

			if self.completed_interaction is not None:
				self.interaction = self.completed_interaction
				self.response = self.completed_interaction
				self.content_response = self.completed_interaction
				self.interaction_id = getattr( self.completed_interaction, 'id', None )
			else:
				self.response = self.stream_response
				self.content_response = self.stream_response

			self.grounding_sources = [ ]

			if not self.output_text:
				raise ValueError( 'Gemini returned an empty streaming response.' )

			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = 'generate_text_stream( self ) -> str'
			Logger( ).write( exception )
			raise exception

	def generate_text( self, prompt: str, model: str, number: int=1, temperature: float=0.0,
		top_p: float=0.0, top_k: int=0, frequency: float=0.0, presence: float=0.0,
		max_tokens: int=0, stops: Optional[ List[ str ] ] = None, instruct: str='',
		response_format: str='', tools: Optional[ List[ str ] ] = None,
		tool_choice: Optional[ str ] = None, reasoning: str='',
		modalities: Optional[ List[ str ] ] = None, media_resolution: str='',
		context: Optional[ List[ Dict[ str, Any ] ] ] = None, content: str='',
		urls: Optional[ List[ str ] ] = None, max_urls: int=0, response_schema: Any = '',
		safety_profile: str='', file_search_store_names: Optional[ List[ str ] ] = None,
		stream: bool = False, stream_handler: Optional[ Callable[ [ str ], None ] ] = None ) -> (
			str):
		"""Generate text through the Gemini Interactions API.

		Purpose:
			Preserves Jeni's text-generation method contract while routing model execution
			through the Interactions API. Existing client-managed history is converted into
			Interactions steps and returned through ``get_structured_history()`` after the call.

		Args:
			prompt (str): Current user prompt.
			model (str): Gemini model identifier.
			number (int): Candidate-count value retained for compatibility.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			top_k (int): Top-k sampling value.
			frequency (float): Frequency penalty retained for compatibility.
			presence (float): Presence penalty retained for compatibility.
			max_tokens (int): Maximum output-token count.
			stops (Optional[List[str]]): Stop sequences.
			instruct (str): System instruction text.
			response_format (str): Requested response MIME type.
			tools (Optional[List[str]]): Server-side tool identifiers.
			tool_choice (Optional[str]): Tool-selection behavior.
			reasoning (str): Thinking-level value.
			modalities (Optional[List[str]]): Requested output modalities.
			media_resolution (str): Media-resolution value retained for compatibility.
			context (Optional[List[Dict[str, Any]]]): Client-managed conversation history.
			content (str): Additional application content.
			urls (Optional[List[str]]): URL-context values.
			max_urls (int): Maximum number of URLs.
			response_schema (Any): Optional JSON Schema mapping or JSON string.
			safety_profile (str): Safety-profile value retained for compatibility.
			file_search_store_names (Optional[List[str]]): File Search Store names.
			stream (bool): Whether to stream response text.
			stream_handler (Optional[Callable[[str], None]]): Text-delta callback.

		Returns:
			str: Generated response text.

		Raises:
			Error: Raised when validation, request construction, or execution fails.
			ValueError: Raised when a required prompt, model, or API key is missing.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.prompt = prompt
			self.model = model
			self.number = number
			self.candidate_count = self.number
			self.temperature = temperature
			self.top_p = top_p
			self.top_k = top_k
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_tokens = max_tokens
			self.stops = stops if isinstance( stops, list ) else [ ]
			self.instructions = instruct
			self.response_format = response_format
			self.tools = tools if isinstance( tools, list ) else [ ]
			self.tool_choice = tool_choice
			self.reasoning = reasoning
			self.response_modalities = (modalities if isinstance( modalities, list ) else [ ])
			self.media_resolution = media_resolution
			self.context = context if isinstance( context, list ) else [ ]
			self.content_block = content
			self.urls = urls if isinstance( urls, list ) else [ ]
			self.max_urls = max_urls
			self.response_schema = response_schema
			self.safety_profile = safety_profile
			self.file_search_store_names = (
				file_search_store_names if isinstance( file_search_store_names, list ) else [ ])
			self.stream = stream
			self.stream_handler = stream_handler
			self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
				'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
			throw_if( 'api_key', self.api_key )

			self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )

			self.input_steps = self.build_input( prompt=self.prompt, content=self.content_block,
				context=self.context, urls=self.urls, max_urls=self.max_urls )

			self.generation_config = self.build_generation_config( temperature=self.temperature,
				top_p=self.top_p, top_k=self.top_k, max_tokens=self.max_tokens, stops=self.stops,
				reasoning=self.reasoning, tool_choice=self.tool_choice )

			self.interaction_response_format = self.build_response_format(
				response_format=self.response_format, response_schema=self.response_schema,
				modalities=self.response_modalities )

			self.tool_objects = self.build_tools( tools=self.tools, urls=self.urls,
				file_search_store_names=self.file_search_store_names )

			if self.stream:
				return self.generate_text_stream( )

			self.request = { 'model': self.model, 'input': self.input_steps, 'stream': False,
				'store': False, }

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

			if self.tool_objects:
				self.request[ 'tools' ] = self.tool_objects

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

			if self.interaction_response_format is not None:
				self.request[ 'response_format' ] = (self.interaction_response_format)

			self.interaction = self.client.interactions.create( **self.request )
			self.capture_interaction( self.interaction )

			if not self.output_text:
				raise ValueError( 'Gemini returned an empty Interactions response.' )

			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Chat'
			exception.method = ('generate_text( self, prompt: str, model: str, number: int, '
			                    'temperature: float, top_p: float, top_k: int, frequency: float, '
			                    'presence: float, max_tokens: int, stops: Optional[List[str]], '
			                    'instruct: str, response_format: str, tools: Optional[List[str]], '
			                    'tool_choice: Optional[str], reasoning: str, modalities: Optional['
			                    'List[str]], media_resolution: str, context: Optional[List[Dict['
			                    'str, Any]]], content: str, urls: Optional[List[str]], max_urls: '
			                    'int, response_schema: Any, safety_profile: str, '
			                    'file_search_store_names: Optional[List[str]], stream: bool, '
			                    'stream_handler: Optional[Callable[[str], None]] ) -> str')
			Logger( ).write( exception )
			raise exception

model_options property

model_options: List[str]

Return supported Gemini text-generation models.

Purpose

Provides the text-generation model identifiers exposed by the Jeni Text, Document Q&A, File Search Stores, and Google Cloud Buckets interfaces.

Returns:

Type Description
List[str]

List[str]: Supported Gemini text-generation model identifiers.

tool_options property

tool_options: List[str]

Return supported Interactions server-side tools.

Purpose

Provides the server-side tools exposed by the Jeni Text interface.

Returns:

Type Description
List[str]

List[str]: Supported Interactions tool identifiers.

reasoning_options property

reasoning_options: List[str]

Return supported thinking levels.

Purpose

Provides the thinking-level values exposed by the Jeni model controls.

Returns:

Type Description
List[str]

List[str]: Supported thinking-level values.

media_options property

media_options: List[str]

Return supported media-resolution values.

Purpose

Preserves the media-resolution option contract used by the Jeni interface.

Returns:

Type Description
List[str]

List[str]: Supported media-resolution values.

choice_options property

choice_options: List[str]

Return supported tool-choice values.

Purpose

Provides the tool-selection values accepted by the Interactions API.

Returns:

Type Description
List[str]

List[str]: Supported tool-choice values.

include_options property

include_options: List[str]

Return compatibility include options.

Purpose

Preserves the option values consumed by existing Jeni controls while citations and tool execution are retrieved from typed Interaction steps.

Returns:

Type Description
List[str]

List[str]: Existing Jeni include-option values.

modality_options property

modality_options: List[str]

Return supported response modalities.

Purpose

Provides response-modality values used by the Jeni Text interface.

Returns:

Type Description
List[str]

List[str]: Supported response modalities.

format_options property

format_options: List[str]

Return supported text response MIME types.

Purpose

Provides text and structured-output MIME types used by the Text interface.

Returns:

Type Description
List[str]

List[str]: Supported response MIME types.

__init__

__init__(model: str = 'gemini-2.5-flash-lite') -> None

Initialize the Chat wrapper.

Purpose

Initializes text-generation configuration, Interactions request state, grounding state, conversation-history state, and response placeholders. The constructor performs local state assignment only.

Parameters:

Name Type Description Default
model str

Default Gemini text-generation model.

'gemini-2.5-flash-lite'

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self, model: str='gemini-2.5-flash-lite' ) -> None:
	"""Initialize the Chat wrapper.

	Purpose:
		Initializes text-generation configuration, Interactions request state, grounding
		state, conversation-history state, and response placeholders. The constructor
		performs local state assignment only.

	Args:
		model (str): Default Gemini text-generation model.

	Returns:
		None: This method initializes object state through side effects.
	"""
	super( ).__init__( )
	self.gemini_api_key = cfg.GEMINI_API_KEY
	self.google_api_key = cfg.GOOGLE_API_KEY
	self.api_version = 'v1beta'
	self.http_options = types.HttpOptions( api_version=self.api_version )
	self.use_vertex = False
	self.client = None
	self.storage_client = None
	self.model = model
	self.prompt = None
	self.instructions = None
	self.number = 1
	self.candidate_count = 1
	self.temperature = 0.0
	self.top_p = 0.0
	self.top_k = 0
	self.frequency_penalty = 0.0
	self.presence_penalty = 0.0
	self.max_tokens = 0
	self.stops = [ ]
	self.response_format = None
	self.response_schema = None
	self.response_modalities = [ ]
	self.media_resolution = None
	self.tool_choice = None
	self.tools = [ ]
	self.tool_objects = [ ]
	self.generation_config = { }
	self.interaction_response_format = None
	self.safety_profile = ''
	self.safety_settings = None
	self.contents = None
	self.input_steps = [ ]
	self.content_block = ''
	self.context = [ ]
	self.urls = [ ]
	self.max_urls = 0
	self.files = [ ]
	self.file_search_store_names = [ ]
	self.image_uri = None
	self.audio_uri = None
	self.file_path = None
	self.interaction = None
	self.interaction_id = None
	self.steps = [ ]
	self.response = None
	self.content_response = None
	self.output_text = ''
	self.grounding_metadata = None
	self.grounding_sources = [ ]
	self.stream = False
	self.stream_handler = None

get_supported_tools

get_supported_tools(model: str) -> List[str]

Return tools supported by the selected model.

Purpose

Builds the tool list consumed by the Jeni Text controls and conditionally includes Google Maps for models that expose that capability.

Parameters:

Name Type Description Default
model str

Gemini model identifier.

required

Returns:

Type Description
List[str]

List[str]: Tool identifiers supported by the selected model.

Raises:

Type Description
Error

Raised when validation or tool-list construction fails.

ValueError

Raised when model is missing.

Source code in gemini.py
def get_supported_tools( self, model: str ) -> List[ str ]:
	"""Return tools supported by the selected model.

	Purpose:
		Builds the tool list consumed by the Jeni Text controls and conditionally includes
		Google Maps for models that expose that capability.

	Args:
		model (str): Gemini model identifier.

	Returns:
		List[str]: Tool identifiers supported by the selected model.

	Raises:
		Error: Raised when validation or tool-list construction fails.
		ValueError: Raised when ``model`` is missing.
	"""
	try:
		throw_if( 'model', model )
		self.model = model
		self.options = [ 'google_search', 'url_context', 'file_search', 'code_execution', ]

		if self.supports_google_maps( self.model ):
			self.options.append( 'google_maps' )

		return self.options
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = 'get_supported_tools( self, model: str ) -> List[ str ]'
		Logger( ).write( exception )
		raise exception

supports_google_maps

supports_google_maps(model: str) -> bool

Return whether a model supports Google Maps grounding.

Purpose

Centralizes Google Maps feature gating for the Jeni Text controls.

Parameters:

Name Type Description Default
model str

Gemini model identifier.

required

Returns:

Name Type Description
bool bool

True when Google Maps may be exposed; otherwise False.

Raises:

Type Description
Error

Raised when validation or model comparison fails.

ValueError

Raised when model is missing.

Source code in gemini.py
def supports_google_maps( self, model: str ) -> bool:
	"""Return whether a model supports Google Maps grounding.

	Purpose:
		Centralizes Google Maps feature gating for the Jeni Text controls.

	Args:
		model (str): Gemini model identifier.

	Returns:
		bool: True when Google Maps may be exposed; otherwise False.

	Raises:
		Error: Raised when validation or model comparison fails.
		ValueError: Raised when ``model`` is missing.
	"""
	try:
		throw_if( 'model', model )
		self.model = model
		self.model_name = self.model.strip( ).lower( )
		self.maps_models = { 'gemini-3.5-flash', 'gemini-3.6-flash', }
		return self.model_name in self.maps_models
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = 'supports_google_maps( self, model: str ) -> bool'
		Logger( ).write( exception )
		raise exception

normalize_value

normalize_value(value: Any) -> Any

Convert an SDK value into standard Python data.

Purpose

Recursively converts SDK response models, dictionaries, and sequences into ordinary Python values used by history and citation processing.

Parameters:

Name Type Description Default
value Any

SDK or Python value to normalize.

required

Returns:

Name Type Description
Any Any

Equivalent standard Python value.

Raises:

Type Description
Error

Raised when value normalization fails.

Source code in gemini.py
def normalize_value( self, value: Any ) -> Any:
	"""Convert an SDK value into standard Python data.

	Purpose:
		Recursively converts SDK response models, dictionaries, and sequences into
		ordinary Python values used by history and citation processing.

	Args:
		value (Any): SDK or Python value to normalize.

	Returns:
		Any: Equivalent standard Python value.

	Raises:
		Error: Raised when value normalization fails.
	"""
	try:
		self.value = value

		if self.value is None or isinstance( self.value, (str, int, float, bool) ):
			return self.value

		if isinstance( self.value, dict ):
			return { key: self.normalize_value( item ) for key, item in self.value.items( ) }

		if isinstance( self.value, (list, tuple, set) ):
			return [ self.normalize_value( item ) for item in self.value ]

		if hasattr( self.value, 'model_dump' ):
			self.value_data = self.value.model_dump( exclude_none=True )
			return self.normalize_value( self.value_data )

		if hasattr( self.value, 'to_dict' ):
			self.value_data = self.value.to_dict( )
			return self.normalize_value( self.value_data )

		return str( self.value )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = 'normalize_value( self, value: Any ) -> Any'
		Logger( ).write( exception )
		raise exception

normalize_context

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

Convert application history into Interactions steps.

Purpose

Preserves existing Interactions steps and converts Jeni role/content dictionaries into user_input and model_output steps for stateless conversation history.

Parameters:

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

Existing conversation history.

None

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Interactions-compatible history steps.

Raises:

Type Description
Error

Raised when conversation history cannot be normalized.

Source code in gemini.py
def normalize_context( self,
	context: Optional[ List[ Dict[ str, Any ] ] ] = None ) -> List[ Dict[ str, Any ] ]:
	"""Convert application history into Interactions steps.

	Purpose:
		Preserves existing Interactions steps and converts Jeni role/content dictionaries
		into ``user_input`` and ``model_output`` steps for stateless conversation history.

	Args:
		context (Optional[List[Dict[str, Any]]]): Existing conversation history.

	Returns:
		List[Dict[str, Any]]: Interactions-compatible history steps.

	Raises:
		Error: Raised when conversation history cannot be normalized.
	"""
	try:
		self.context = context if isinstance( context, list ) else [ ]
		self.history_steps: List[ Dict[ str, Any ] ] = [ ]
		for message in self.context:
			if not isinstance( message, dict ):
				continue

			self.context_type = str( message.get( 'type', '' ) or '' ).strip( )
			if self.context_type:
				self.context_step = self.normalize_value( message )
				if isinstance( self.context_step, dict ) and self.context_step:
					self.history_steps.append( self.context_step )

				continue

			self.message_role = str( message.get( 'role', '' ) or '' ).strip( ).lower( )
			self.message_content = message.get( 'content', '' )

			if isinstance( self.message_content, list ):
				self.message_text = '\n'.join(
					str( item ).strip( ) for item in self.message_content if
						item is not None and str( item ).strip( ) )
			else:
				self.message_text = str( self.message_content or '' ).strip( )

			if not self.message_text:
				continue

			if self.message_role in ('assistant', 'model'):
				self.step_type = 'model_output'
			else:
				self.step_type = 'user_input'

			self.history_steps.append( { 'type': self.step_type,
				'content': [ { 'type': 'text', 'text': self.message_text, }, ], } )

		self.context = self.history_steps
		return self.context
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = (
			'normalize_context( self, context: Optional[ List[ Dict[ str, Any ] ] ] ) '
			'-> List[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

build_urls

build_urls(
    urls: Optional[List[str]] = None, max_urls: int = 0
) -> List[str]

Build the normalized URL list.

Purpose

Removes blank and duplicate URL values while preserving order and applies the configured maximum before URL values are supplied to the active request.

Parameters:

Name Type Description Default
urls Optional[List[str]]

Candidate URL values.

None
max_urls int

Maximum URLs to retain; zero retains all values.

0

Returns:

Type Description
List[str]

List[str]: Normalized URL values.

Raises:

Type Description
Error

Raised when URL normalization fails.

Source code in gemini.py
def build_urls( self, urls: Optional[ List[ str ] ]=None, max_urls: int=0 ) -> List[ str ]:
	"""Build the normalized URL list.

	Purpose:
		Removes blank and duplicate URL values while preserving order and applies the
		configured maximum before URL values are supplied to the active request.

	Args:
		urls (Optional[List[str]]): Candidate URL values.
		max_urls (int): Maximum URLs to retain; zero retains all values.

	Returns:
		List[str]: Normalized URL values.

	Raises:
		Error: Raised when URL normalization fails.
	"""
	try:
		self.urls = urls if isinstance( urls, list ) else [ ]
		self.max_urls = max_urls
		self.normalized_urls: List[ str ] = [ ]

		for url in self.urls:
			if url is None:
				continue

			self.url = str( url ).strip( )
			if not self.url:
				continue

			if self.url not in self.normalized_urls:
				self.normalized_urls.append( self.url )

		if self.max_urls > 0:
			self.normalized_urls = self.normalized_urls[ :self.max_urls ]

		self.urls = self.normalized_urls
		return self.urls
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('build_urls( self, **kwargs ) -> List[ str ]')
		Logger( ).write( exception )
		raise exception

build_input

build_input(
    prompt: str,
    content: str = "",
    context: Optional[List[Dict[str, Any]]] = None,
    urls: Optional[List[str]] = None,
    max_urls: int = 0,
) -> List[Dict[str, Any]]

Build the complete Interactions input timeline.

Purpose

Combines existing client-managed conversation history with optional content, reference URLs, and the current user prompt.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
content str

Optional content prepended to the prompt.

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

Existing conversation history.

None
urls Optional[List[str]]

URL-context values.

None
max_urls int

Maximum number of URLs.

0

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Complete Interactions input timeline.

Raises:

Type Description
Error

Raised when validation or input construction fails.

ValueError

Raised when prompt is missing.

Source code in gemini.py
def build_input( self, prompt: str, content: str='',
	context: Optional[ List[ Dict[ str, Any ] ] ]=None, urls: Optional[ List[ str ] ]=None,
	max_urls: int=0 ) -> List[ Dict[ str, Any ] ]:
	"""Build the complete Interactions input timeline.

	Purpose:
		Combines existing client-managed conversation history with optional content,
		reference URLs, and the current user prompt.

	Args:
		prompt (str): Current user prompt.
		content (str): Optional content prepended to the prompt.
		context (Optional[List[Dict[str, Any]]]): Existing conversation history.
		urls (Optional[List[str]]): URL-context values.
		max_urls (int): Maximum number of URLs.

	Returns:
		List[Dict[str, Any]]: Complete Interactions input timeline.

	Raises:
		Error: Raised when validation or input construction fails.
		ValueError: Raised when ``prompt`` is missing.
	"""
	try:
		throw_if( 'prompt', prompt )
		self.prompt = prompt
		self.content_block = content
		self.context = context if isinstance( context, list ) else [ ]
		self.urls = urls if isinstance( urls, list ) else [ ]
		self.max_urls = max_urls
		self.input_steps = self.normalize_context( self.context )
		self.urls = self.build_urls( self.urls, self.max_urls )
		self.current_parts: List[ str ] = [ ]
		if self.content_block and self.content_block.strip( ):
			self.current_parts.append( self.content_block.strip( ) )

		if self.urls:
			self.current_parts.append(
				'Reference URLs:\n' + '\n'.join( f'- {url}' for url in self.urls ) )

		self.current_parts.append( self.prompt.strip( ) )
		self.current_text = '\n\n'.join( part for part in self.current_parts if part ).strip( )

		self.input_steps.append( { 'type': 'user_input',
			'content': [ { 'type': 'text', 'text': self.current_text, }, ], } )

		self.contents = self.input_steps
		return self.input_steps
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('build_input( self, **kwargs ) -> List[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

build_generation_config

build_generation_config(
    temperature: float = 0.0,
    top_p: float = 0.0,
    top_k: int = 0,
    max_tokens: int = 0,
    stops: Optional[List[str]] = None,
    reasoning: str = "",
    tool_choice: Optional[str] = None,
) -> Dict[str, Any]

Build the Interactions generation configuration.

Purpose

Converts supported Jeni inference controls into the Interactions generation configuration without submitting blank or zero-valued optional controls.

Parameters:

Name Type Description Default
temperature float

Sampling temperature.

0.0
top_p float

Top-p sampling value.

0.0
top_k int

Top-k sampling value.

0
max_tokens int

Maximum output-token count.

0
stops Optional[List[str]]

Stop sequences.

None
reasoning str

Thinking-level value.

''
tool_choice Optional[str]

Tool-selection behavior.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Interactions generation configuration.

Raises:

Type Description
Error

Raised when generation configuration construction fails.

Source code in gemini.py
def build_generation_config( self, temperature: float=0.0, top_p: float=0.0, top_k: int=0,
	max_tokens: int=0, stops: Optional[ List[ str ] ]=None, reasoning: str='',
	tool_choice: Optional[ str ]=None ) -> Dict[ str, Any ]:
	"""Build the Interactions generation configuration.

	Purpose:
		Converts supported Jeni inference controls into the Interactions generation
		configuration without submitting blank or zero-valued optional controls.

	Args:
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		top_k (int): Top-k sampling value.
		max_tokens (int): Maximum output-token count.
		stops (Optional[List[str]]): Stop sequences.
		reasoning (str): Thinking-level value.
		tool_choice (Optional[str]): Tool-selection behavior.

	Returns:
		Dict[str, Any]: Interactions generation configuration.

	Raises:
		Error: Raised when generation configuration construction fails.
	"""
	try:
		self.temperature = temperature
		self.top_p = top_p
		self.top_k = top_k
		self.max_tokens = max_tokens
		self.stops = stops if isinstance( stops, list ) else [ ]
		self.reasoning = reasoning
		self.tool_choice = tool_choice
		self.generation_config = { }
		if self.temperature > 0.0:
			self.generation_config[ 'temperature' ] = self.temperature

		if self.top_p > 0.0:
			self.generation_config[ 'top_p' ] = self.top_p

		if self.top_k > 0:
			self.generation_config[ 'top_k' ] = self.top_k

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

		self.stop_sequences = [ str( value ).strip( ) for value in self.stops if
			value is not None and str( value ).strip( ) ]

		if self.stop_sequences:
			self.generation_config[ 'stop_sequences' ] = self.stop_sequences

		self.thinking_level = str( self.reasoning or '' ).strip( ).lower( )

		if self.thinking_level not in ('', 'thinking_level_unspecified', 'unspecified',):
			self.generation_config[ 'thinking_level' ] = self.thinking_level

		self.tool_choice_value = str( self.tool_choice or '' ).strip( ).lower( )

		if self.tool_choice_value:
			self.generation_config[ 'tool_choice' ] = self.tool_choice_value

		return self.generation_config
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('build_generation_config( self, **kwargs -> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

parse_response_schema

parse_response_schema(
    response_schema: Any = None,
) -> Optional[Dict[str, Any]]

Parse an optional structured-output schema.

Purpose

Accepts a dictionary or JSON string and converts it into the JSON Schema mapping required by the Interactions API.

Parameters:

Name Type Description Default
response_schema Any

Optional JSON Schema dictionary or JSON string.

None

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[Dict[str, Any]]: Parsed JSON Schema, or None when absent.

Raises:

Type Description
Error

Raised when a nonblank schema cannot be parsed.

Source code in gemini.py
def parse_response_schema( self, response_schema: Any = None ) -> Optional[ Dict[ str, Any ] ]:
	"""Parse an optional structured-output schema.

	Purpose:
		Accepts a dictionary or JSON string and converts it into the JSON Schema mapping
		required by the Interactions API.

	Args:
		response_schema (Any): Optional JSON Schema dictionary or JSON string.

	Returns:
		Optional[Dict[str, Any]]: Parsed JSON Schema, or None when absent.

	Raises:
		Error: Raised when a nonblank schema cannot be parsed.
	"""
	try:
		self.response_schema = response_schema
		if self.response_schema is None:
			return None

		if isinstance( self.response_schema, dict ):
			return self.response_schema

		self.schema_text = str( self.response_schema ).strip( )
		if not self.schema_text:
			self.response_schema = None
			return None

		self.schema_value = json.loads( self.schema_text )
		if not isinstance( self.schema_value, dict ):
			raise ValueError( 'The response schema must contain a JSON object.' )

		self.response_schema = self.schema_value
		return self.response_schema
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('parse_response_schema( self, response_schema: Any ) '
		                    '-> Optional[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

build_response_format

build_response_format(
    response_format: str = "",
    response_schema: Any = None,
    modalities: Optional[List[str]] = None,
) -> Optional[Any]

Build the Interactions response format.

Purpose

Converts the Jeni MIME type, response modalities, and optional JSON Schema into the polymorphic response-format structure used by the current Interactions API.

Parameters:

Name Type Description Default
response_format str

Requested text MIME type.

''
response_schema Any

Optional JSON Schema mapping or JSON string.

None
modalities Optional[List[str]]

Requested response modalities.

None

Returns:

Type Description
Optional[Any]

Optional[Any]: Interactions response-format value.

Raises:

Type Description
Error

Raised when response-format construction fails.

Source code in gemini.py
def build_response_format( self, response_format: str='', response_schema: Any = None,
	modalities: Optional[ List[ str ] ] = None ) -> Optional[ Any ]:
	"""Build the Interactions response format.

	Purpose:
		Converts the Jeni MIME type, response modalities, and optional JSON Schema into
		the polymorphic response-format structure used by the current Interactions API.

	Args:
		response_format (str): Requested text MIME type.
		response_schema (Any): Optional JSON Schema mapping or JSON string.
		modalities (Optional[List[str]]): Requested response modalities.

	Returns:
		Optional[Any]: Interactions response-format value.

	Raises:
		Error: Raised when response-format construction fails.
	"""
	try:
		self.response_format = response_format
		self.response_schema = response_schema
		self.response_modalities = (modalities if isinstance( modalities, list ) else [ ])
		self.response_schema = self.parse_response_schema( self.response_schema )
		self.response_mime_type = str( self.response_format or '' ).strip( )
		self.normalized_modalities = [ str( value ).strip( ).lower( ) for value in
			self.response_modalities if value is not None and str( value ).strip( ) ]

		if self.normalized_modalities and 'text' not in self.normalized_modalities:
			self.interaction_response_format = None
			return None

		if self.response_schema is not None:
			self.interaction_response_format = [
				{ 'type': 'text', 'mime_type': 'application/json',
					'schema': self.response_schema, }, ]
			return self.interaction_response_format

		if self.response_mime_type in ('application/json', 'text/x.enum'):
			self.interaction_response_format = [
				{ 'type': 'text', 'mime_type': self.response_mime_type, }, ]
			return self.interaction_response_format

		self.interaction_response_format = None
		return None
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('build_response_format( self, **kwargs ) -> Optional[ Any ]')
		Logger( ).write( exception )
		raise exception

build_tools

build_tools(
    tools: Optional[List[str]] = None,
    urls: Optional[List[str]] = None,
    file_search_store_names: Optional[List[str]] = None,
) -> List[Dict[str, Any]]

Build Interactions server-side tools.

Purpose

Translates Jeni tool identifiers into Interactions tool declarations. URL Context is enabled when selected or when URLs are supplied. File Search is enabled when File Search Store resource names are supplied.

Parameters:

Name Type Description Default
tools Optional[List[str]]

Selected tool identifiers.

None
urls Optional[List[str]]

Normalized URL-context values.

None
file_search_store_names Optional[List[str]]

File Search Store names.

None

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Interactions server-side tool declarations.

Raises:

Type Description
Error

Raised when tool construction fails.

Source code in gemini.py
def build_tools( self, tools: Optional[ List[ str ] ] = None,
	urls: Optional[ List[ str ] ] = None,
	file_search_store_names: Optional[ List[ str ] ] = None ) -> List[ Dict[ str, Any ] ]:
	"""Build Interactions server-side tools.

	Purpose:
		Translates Jeni tool identifiers into Interactions tool declarations. URL Context
		is enabled when selected or when URLs are supplied. File Search is enabled when
		File Search Store resource names are supplied.

	Args:
		tools (Optional[List[str]]): Selected tool identifiers.
		urls (Optional[List[str]]): Normalized URL-context values.
		file_search_store_names (Optional[List[str]]): File Search Store names.

	Returns:
		List[Dict[str, Any]]: Interactions server-side tool declarations.

	Raises:
		Error: Raised when tool construction fails.
	"""
	try:
		self.tools = tools if isinstance( tools, list ) else [ ]
		self.urls = urls if isinstance( urls, list ) else [ ]
		self.file_search_store_names = (
			file_search_store_names if isinstance( file_search_store_names, list ) else [ ])
		self.selected_tools = [ str( value ).strip( ).lower( ) for value in self.tools if
			value is not None and str( value ).strip( ) ]
		self.file_search_store_names = [ str( value ).strip( ) for value in
			self.file_search_store_names if value is not None and str( value ).strip( ) ]
		self.tool_objects = [ ]
		if 'google_search' in self.selected_tools:
			self.tool_objects.append( { 'type': 'google_search', } )

		if ('google_maps' in self.selected_tools and self.supports_google_maps( self.model )):
			self.tool_objects.append( { 'type': 'google_maps', } )

		if 'url_context' in self.selected_tools or self.urls:
			self.tool_objects.append( { 'type': 'url_context', } )

		if 'code_execution' in self.selected_tools:
			self.tool_objects.append( { 'type': 'code_execution', } )

		if self.file_search_store_names:
			self.tool_objects.append( { 'type': 'file_search',
				'file_search_store_names': self.file_search_store_names, } )

		return self.tool_objects
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('build_tools( self, **kwargs ) -> List[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

append_source

append_source(
    source: Dict[str, Any], default_type: str
) -> None

Append one normalized grounding source.

Purpose

Converts provider citation and tool-result fields into the stable source shape consumed by Jeni and prevents duplicate records.

Parameters:

Name Type Description Default
source Dict[str, Any]

Provider citation or result mapping.

required
default_type str

Source type used when omitted by the mapping.

required

Returns:

Name Type Description
None None

This method updates source state through side effects.

Raises:

Type Description
Error

Raised when validation or source normalization fails.

ValueError

Raised when a required argument is missing.

Source code in gemini.py
def append_source( self, source: Dict[ str, Any ], default_type: str ) -> None:
	"""Append one normalized grounding source.

	Purpose:
		Converts provider citation and tool-result fields into the stable source shape
		consumed by Jeni and prevents duplicate records.

	Args:
		source (Dict[str, Any]): Provider citation or result mapping.
		default_type (str): Source type used when omitted by the mapping.

	Returns:
		None: This method updates source state through side effects.

	Raises:
		Error: Raised when validation or source normalization fails.
		ValueError: Raised when a required argument is missing.
	"""
	try:
		throw_if( 'source', source )
		throw_if( 'default_type', default_type )
		self.source = source
		self.default_type = default_type
		self.source_type = str(
			self.source.get( 'type', self.default_type ) or self.default_type ).strip( )
		self.source_title = str(
			self.source.get( 'title' ) or self.source.get( 'display_name' ) or self.source.get(
				'file_name' ) or self.source.get( 'name' ) or '' ).strip( )
		self.source_url = str(
			self.source.get( 'uri' ) or self.source.get( 'url' ) or self.source.get(
				'source_url' ) or '' ).strip( )
		self.source_text = str(
			self.source.get( 'text' ) or self.source.get( 'snippet' ) or self.source.get(
				'quote' ) or self.source.get( 'search_suggestions' ) or '' ).strip( )
		self.source_file_id = str(
			self.source.get( 'file_id' ) or self.source.get( 'file_name' ) or self.source.get(
				'document_name' ) or '' ).strip( )

		if not any( [ self.source_title, self.source_url, self.source_text,
			self.source_file_id, ] ):
			return

		self.source_key = (self.source_type, self.source_url or self.source_file_id,
			self.source_text,)

		if self.source_key in self.source_keys:
			return

		self.source_keys.add( self.source_key )
		self.source_values.append( { 'type': self.source_type, 'title': self.source_title or None,
				'snippet': self.source_text or None, 'url': self.source_url or None,
				'files_id': self.source_file_id or None, 'metadata': self.source, } )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('append_source( self, *kwargs ) -> None')
		Logger( ).write( exception )
		raise exception

extract_grounding_sources

extract_grounding_sources(
    interaction: Any,
) -> List[Dict[str, Any]]

Extract grounding citations from an Interaction.

Purpose

Collects model-output annotations and supported server-side tool-result data from the current Interaction steps.

Parameters:

Name Type Description Default
interaction Any

Completed Gemini Interaction.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized grounding-source records.

Raises:

Type Description
Error

Raised when validation or citation extraction fails.

ValueError

Raised when interaction is missing.

Source code in gemini.py
def extract_grounding_sources( self, interaction: Any ) -> List[ Dict[ str, Any ] ]:
	"""Extract grounding citations from an Interaction.

	Purpose:
		Collects model-output annotations and supported server-side tool-result data
		from the current Interaction steps.

	Args:
		interaction (Any): Completed Gemini Interaction.

	Returns:
		List[Dict[str, Any]]: Normalized grounding-source records.

	Raises:
		Error: Raised when validation or citation extraction fails.
		ValueError: Raised when ``interaction`` is missing.
	"""
	try:
		throw_if( 'interaction', interaction )
		self.source_interaction = interaction
		self.source_values: List[ Dict[ str, Any ] ] = [ ]
		self.source_keys: Set[ Tuple[ str, str, str ] ] = set( )
		self.source_steps = getattr( self.source_interaction, 'steps', None ) or [ ]
		for step in self.source_steps:
			self.source_step_type = str( getattr( step, 'type', '' ) or '' ).strip( )
			if self.source_step_type == 'model_output':
				self.source_content = getattr( step, 'content', None ) or [ ]
				for block in self.source_content:
					self.annotations = getattr( block, 'annotations', None ) or [ ]

					for annotation in self.annotations:
						self.annotation_value = self.normalize_value( annotation )

						if not isinstance( self.annotation_value, dict ):
							continue

						self.append_source( self.annotation_value, str(
							self.annotation_value.get( 'type', 'citation' ) or 'citation' ) )

			elif self.source_step_type in ('google_search_result', 'file_search_result',
				'url_context_result', 'google_maps_result', 'code_execution_result',):
				self.result_value = self.normalize_value( getattr( step, 'result', None ) )
				if isinstance( self.result_value, list ):
					for result in self.result_value:
						if isinstance( result, dict ) and result:
							self.append_source( result, self.source_step_type )

				elif isinstance( self.result_value, dict ) and self.result_value:
					self.append_source( self.result_value, self.source_step_type )

		return self.source_values
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('extract_grounding_sources( self, **kwargs) -> List[Dict[str, Any]]')
		Logger( ).write( exception )
		raise exception

capture_interaction

capture_interaction(interaction: Any) -> None

Capture a completed Gemini Interaction.

Purpose

Stores the raw response, identifier, output steps, generated text, and grounding sources on the members consumed by the Jeni application.

Parameters:

Name Type Description Default
interaction Any

Completed Gemini Interaction.

required

Returns:

Name Type Description
None None

This method updates response state through side effects.

Raises:

Type Description
Error

Raised when validation or response extraction fails.

ValueError

Raised when interaction is missing.

Source code in gemini.py
def capture_interaction( self, interaction: Any ) -> None:
	"""Capture a completed Gemini Interaction.

	Purpose:
		Stores the raw response, identifier, output steps, generated text, and grounding
		sources on the members consumed by the Jeni application.

	Args:
		interaction (Any): Completed Gemini Interaction.

	Returns:
		None: This method updates response state through side effects.

	Raises:
		Error: Raised when validation or response extraction fails.
		ValueError: Raised when ``interaction`` is missing.
	"""
	try:
		throw_if( 'interaction', interaction )
		self.interaction = interaction
		self.response = self.interaction
		self.content_response = self.interaction
		self.interaction_id = getattr( self.interaction, 'id', None )
		self.steps = list( getattr( self.interaction, 'steps', None ) or [ ] )
		self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
		self.grounding_sources = self.extract_grounding_sources( self.interaction )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('capture_interaction( self, interaction: Any ) -> None')
		Logger( ).write( exception )
		raise exception

get_grounding_sources

get_grounding_sources() -> List[Dict[str, Any]]

Return sources from the most recent Interaction.

Purpose

Provides normalized grounding-source records consumed by Jeni response renderers.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Grounding sources from the latest response.

Source code in gemini.py
def get_grounding_sources( self ) -> List[ Dict[ str, Any ] ]:
	"""Return sources from the most recent Interaction.

	Purpose:
		Provides normalized grounding-source records consumed by Jeni response renderers.

	Returns:
		List[Dict[str, Any]]: Grounding sources from the latest response.
	"""
	return list( self.grounding_sources )

get_structured_history

get_structured_history() -> List[Dict[str, Any]]

Return the complete stateless conversation history.

Purpose

Combines the submitted input timeline with the output steps returned by the latest Interaction so Jeni can preserve client-managed conversation state.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Complete Interactions-compatible history.

Raises:

Type Description
Error

Raised when output steps cannot be normalized.

Source code in gemini.py
def get_structured_history( self ) -> List[ Dict[ str, Any ] ]:
	"""Return the complete stateless conversation history.

	Purpose:
		Combines the submitted input timeline with the output steps returned by the latest
		Interaction so Jeni can preserve client-managed conversation state.

	Returns:
		List[Dict[str, Any]]: Complete Interactions-compatible history.

	Raises:
		Error: Raised when output steps cannot be normalized.
	"""
	try:
		self.structured_history: List[ Dict[ str, Any ] ] = [ ]
		for step in self.input_steps:
			self.input_step = self.normalize_value( step )
			if isinstance( self.input_step, dict ) and self.input_step:
				self.structured_history.append( self.input_step )

		for step in self.steps:
			self.output_step = self.normalize_value( step )
			if isinstance( self.output_step, dict ) and self.output_step:
				self.structured_history.append( self.output_step )

		return self.structured_history
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('get_structured_history( self ) -> List[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

generate_text_stream

generate_text_stream() -> str

Execute the prepared streaming Interactions request.

Purpose

Submits the active request, forwards text deltas to the application callback, accumulates the complete generated text, and captures final usage metadata.

Returns:

Name Type Description
str str

Complete generated text.

Raises:

Type Description
Error

Raised when streaming execution or event handling fails.

Source code in gemini.py
def generate_text_stream( self ) -> str:
	"""Execute the prepared streaming Interactions request.

	Purpose:
		Submits the active request, forwards text deltas to the application callback,
		accumulates the complete generated text, and captures final usage metadata.

	Returns:
		str: Complete generated text.

	Raises:
		Error: Raised when streaming execution or event handling fails.
	"""
	try:
		self.request = { 'model': self.model, 'input': self.input_steps, 'stream': True,
			'store': False, }

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

		if self.tool_objects:
			self.request[ 'tools' ] = self.tool_objects

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

		if self.interaction_response_format is not None:
			self.request[ 'response_format' ] = (self.interaction_response_format)

		self.stream_response = self.client.interactions.create( **self.request )
		self.text_chunks: List[ str ] = [ ]
		self.completed_interaction = None

		for event in self.stream_response:
			self.event_type = str( getattr( event, 'event_type', '' ) or '' ).strip( )

			if self.event_type == 'step.delta':
				self.delta = getattr( event, 'delta', None )
				self.delta_type = str( getattr( self.delta, 'type', '' ) or '' ).strip( )

				if self.delta_type == 'text':
					self.delta_text = str( getattr( self.delta, 'text', '' ) or '' )

					if self.delta_text:
						self.text_chunks.append( self.delta_text )

						if callable( self.stream_handler ):
							self.stream_handler( self.delta_text )

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

			elif self.event_type == 'error':
				self.stream_error = getattr( event, 'error', None )
				self.stream_message = str( getattr( self.stream_error, 'message',
					'' ) or self.stream_error or 'Gemini streaming request failed.' )
				raise RuntimeError( self.stream_message )

		self.output_text = ''.join( self.text_chunks ).strip( )
		self.steps = [ ]

		if self.output_text:
			self.steps.append( { 'type': 'model_output',
				'content': [ { 'type': 'text', 'text': self.output_text, }, ], } )

		if self.completed_interaction is not None:
			self.interaction = self.completed_interaction
			self.response = self.completed_interaction
			self.content_response = self.completed_interaction
			self.interaction_id = getattr( self.completed_interaction, 'id', None )
		else:
			self.response = self.stream_response
			self.content_response = self.stream_response

		self.grounding_sources = [ ]

		if not self.output_text:
			raise ValueError( 'Gemini returned an empty streaming response.' )

		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = 'generate_text_stream( self ) -> str'
		Logger( ).write( exception )
		raise exception

generate_text

generate_text(
    prompt: str,
    model: str,
    number: int = 1,
    temperature: float = 0.0,
    top_p: float = 0.0,
    top_k: int = 0,
    frequency: float = 0.0,
    presence: float = 0.0,
    max_tokens: int = 0,
    stops: Optional[List[str]] = None,
    instruct: str = "",
    response_format: str = "",
    tools: Optional[List[str]] = None,
    tool_choice: Optional[str] = None,
    reasoning: str = "",
    modalities: Optional[List[str]] = None,
    media_resolution: str = "",
    context: Optional[List[Dict[str, Any]]] = None,
    content: str = "",
    urls: Optional[List[str]] = None,
    max_urls: int = 0,
    response_schema: Any = "",
    safety_profile: str = "",
    file_search_store_names: Optional[List[str]] = None,
    stream: bool = False,
    stream_handler: Optional[Callable[[str], None]] = None,
) -> str

Generate text through the Gemini Interactions API.

Purpose

Preserves Jeni's text-generation method contract while routing model execution through the Interactions API. Existing client-managed history is converted into Interactions steps and returned through get_structured_history() after the call.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
model str

Gemini model identifier.

required
number int

Candidate-count value retained for compatibility.

1
temperature float

Sampling temperature.

0.0
top_p float

Top-p sampling value.

0.0
top_k int

Top-k sampling value.

0
frequency float

Frequency penalty retained for compatibility.

0.0
presence float

Presence penalty retained for compatibility.

0.0
max_tokens int

Maximum output-token count.

0
stops Optional[List[str]]

Stop sequences.

None
instruct str

System instruction text.

''
response_format str

Requested response MIME type.

''
tools Optional[List[str]]

Server-side tool identifiers.

None
tool_choice Optional[str]

Tool-selection behavior.

None
reasoning str

Thinking-level value.

''
modalities Optional[List[str]]

Requested output modalities.

None
media_resolution str

Media-resolution value retained for compatibility.

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

Client-managed conversation history.

None
content str

Additional application content.

''
urls Optional[List[str]]

URL-context values.

None
max_urls int

Maximum number of URLs.

0
response_schema Any

Optional JSON Schema mapping or JSON string.

''
safety_profile str

Safety-profile value retained for compatibility.

''
file_search_store_names Optional[List[str]]

File Search Store names.

None
stream bool

Whether to stream response text.

False
stream_handler Optional[Callable[[str], None]]

Text-delta callback.

None

Returns:

Name Type Description
str str

Generated response text.

Raises:

Type Description
Error

Raised when validation, request construction, or execution fails.

ValueError

Raised when a required prompt, model, or API key is missing.

Source code in gemini.py
def generate_text( self, prompt: str, model: str, number: int=1, temperature: float=0.0,
	top_p: float=0.0, top_k: int=0, frequency: float=0.0, presence: float=0.0,
	max_tokens: int=0, stops: Optional[ List[ str ] ] = None, instruct: str='',
	response_format: str='', tools: Optional[ List[ str ] ] = None,
	tool_choice: Optional[ str ] = None, reasoning: str='',
	modalities: Optional[ List[ str ] ] = None, media_resolution: str='',
	context: Optional[ List[ Dict[ str, Any ] ] ] = None, content: str='',
	urls: Optional[ List[ str ] ] = None, max_urls: int=0, response_schema: Any = '',
	safety_profile: str='', file_search_store_names: Optional[ List[ str ] ] = None,
	stream: bool = False, stream_handler: Optional[ Callable[ [ str ], None ] ] = None ) -> (
		str):
	"""Generate text through the Gemini Interactions API.

	Purpose:
		Preserves Jeni's text-generation method contract while routing model execution
		through the Interactions API. Existing client-managed history is converted into
		Interactions steps and returned through ``get_structured_history()`` after the call.

	Args:
		prompt (str): Current user prompt.
		model (str): Gemini model identifier.
		number (int): Candidate-count value retained for compatibility.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		top_k (int): Top-k sampling value.
		frequency (float): Frequency penalty retained for compatibility.
		presence (float): Presence penalty retained for compatibility.
		max_tokens (int): Maximum output-token count.
		stops (Optional[List[str]]): Stop sequences.
		instruct (str): System instruction text.
		response_format (str): Requested response MIME type.
		tools (Optional[List[str]]): Server-side tool identifiers.
		tool_choice (Optional[str]): Tool-selection behavior.
		reasoning (str): Thinking-level value.
		modalities (Optional[List[str]]): Requested output modalities.
		media_resolution (str): Media-resolution value retained for compatibility.
		context (Optional[List[Dict[str, Any]]]): Client-managed conversation history.
		content (str): Additional application content.
		urls (Optional[List[str]]): URL-context values.
		max_urls (int): Maximum number of URLs.
		response_schema (Any): Optional JSON Schema mapping or JSON string.
		safety_profile (str): Safety-profile value retained for compatibility.
		file_search_store_names (Optional[List[str]]): File Search Store names.
		stream (bool): Whether to stream response text.
		stream_handler (Optional[Callable[[str], None]]): Text-delta callback.

	Returns:
		str: Generated response text.

	Raises:
		Error: Raised when validation, request construction, or execution fails.
		ValueError: Raised when a required prompt, model, or API key is missing.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.prompt = prompt
		self.model = model
		self.number = number
		self.candidate_count = self.number
		self.temperature = temperature
		self.top_p = top_p
		self.top_k = top_k
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.stops = stops if isinstance( stops, list ) else [ ]
		self.instructions = instruct
		self.response_format = response_format
		self.tools = tools if isinstance( tools, list ) else [ ]
		self.tool_choice = tool_choice
		self.reasoning = reasoning
		self.response_modalities = (modalities if isinstance( modalities, list ) else [ ])
		self.media_resolution = media_resolution
		self.context = context if isinstance( context, list ) else [ ]
		self.content_block = content
		self.urls = urls if isinstance( urls, list ) else [ ]
		self.max_urls = max_urls
		self.response_schema = response_schema
		self.safety_profile = safety_profile
		self.file_search_store_names = (
			file_search_store_names if isinstance( file_search_store_names, list ) else [ ])
		self.stream = stream
		self.stream_handler = stream_handler
		self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
			'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
		throw_if( 'api_key', self.api_key )

		self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )

		self.input_steps = self.build_input( prompt=self.prompt, content=self.content_block,
			context=self.context, urls=self.urls, max_urls=self.max_urls )

		self.generation_config = self.build_generation_config( temperature=self.temperature,
			top_p=self.top_p, top_k=self.top_k, max_tokens=self.max_tokens, stops=self.stops,
			reasoning=self.reasoning, tool_choice=self.tool_choice )

		self.interaction_response_format = self.build_response_format(
			response_format=self.response_format, response_schema=self.response_schema,
			modalities=self.response_modalities )

		self.tool_objects = self.build_tools( tools=self.tools, urls=self.urls,
			file_search_store_names=self.file_search_store_names )

		if self.stream:
			return self.generate_text_stream( )

		self.request = { 'model': self.model, 'input': self.input_steps, 'stream': False,
			'store': False, }

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

		if self.tool_objects:
			self.request[ 'tools' ] = self.tool_objects

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

		if self.interaction_response_format is not None:
			self.request[ 'response_format' ] = (self.interaction_response_format)

		self.interaction = self.client.interactions.create( **self.request )
		self.capture_interaction( self.interaction )

		if not self.output_text:
			raise ValueError( 'Gemini returned an empty Interactions response.' )

		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Chat'
		exception.method = ('generate_text( self, prompt: str, model: str, number: int, '
		                    'temperature: float, top_p: float, top_k: int, frequency: float, '
		                    'presence: float, max_tokens: int, stops: Optional[List[str]], '
		                    'instruct: str, response_format: str, tools: Optional[List[str]], '
		                    'tool_choice: Optional[str], reasoning: str, modalities: Optional['
		                    'List[str]], media_resolution: str, context: Optional[List[Dict['
		                    'str, Any]]], content: str, urls: Optional[List[str]], max_urls: '
		                    'int, response_schema: Any, safety_profile: str, '
		                    'file_search_store_names: Optional[List[str]], stream: bool, '
		                    'stream_handler: Optional[Callable[[str], None]] ) -> str')
		Logger( ).write( exception )
		raise exception

Images

Bases: Gemini

Gemini image-generation, analysis, and editing wrapper.

Purpose

Executes image generation, image understanding, and image editing through the Gemini Interactions API. The class converts local images into Interactions image-content blocks, builds image and text response formats, configures supported Google Search grounding, captures generated image or text output, and preserves the application-facing method contracts consumed by the Jeni Images mode.

Attributes:

Name Type Description
client Optional[Client]

Active Gemini client.

http_options HttpOptions

Gemini client HTTP configuration.

aspect_ratio Optional[str]

Requested output-image aspect ratio.

size Optional[str]

Requested output-image size.

resolution Optional[str]

Media-resolution value retained for UI compatibility.

max_output_tokens Optional[int]

Maximum text-output token count.

output_mime_type Optional[str]

Requested output-image MIME type.

response_mode Optional[str]

Requested response-modality selection.

response_format_value Optional[Any]

Interactions response-format configuration.

generation_config Dict[str, Any]

Interactions generation configuration.

input_content List[Dict[str, Any]]

Multimodal Interactions input.

tool_objects List[Dict[str, Any]]

Interactions Google Search tool declarations.

interaction Optional[Any]

Most recent Gemini Interaction.

response Optional[Any]

Raw response used by application token accounting.

output_text str

Text extracted from the latest Interaction.

output_image_content Optional[Any]

Image content from the latest Interaction.

grounding_metadata Optional[Any]

Grounding data retained for UI compatibility.

grounding_sources List[Dict[str, Any]]

Normalized grounding records.

Source code in gemini.py
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
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
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
2345
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
class Images( Gemini ):
	"""Gemini image-generation, analysis, and editing wrapper.

	Purpose:
		Executes image generation, image understanding, and image editing through the Gemini
		Interactions API. The class converts local images into Interactions image-content
		blocks, builds image and text response formats, configures supported Google Search
		grounding, captures generated image or text output, and preserves the application-facing
		method contracts consumed by the Jeni Images mode.

	Attributes:
		client (Optional[genai.Client]): Active Gemini client.
		http_options (HttpOptions): Gemini client HTTP configuration.
		aspect_ratio (Optional[str]): Requested output-image aspect ratio.
		size (Optional[str]): Requested output-image size.
		resolution (Optional[str]): Media-resolution value retained for UI compatibility.
		max_output_tokens (Optional[int]): Maximum text-output token count.
		output_mime_type (Optional[str]): Requested output-image MIME type.
		response_mode (Optional[str]): Requested response-modality selection.
		response_format_value (Optional[Any]): Interactions response-format configuration.
		generation_config (Dict[str, Any]): Interactions generation configuration.
		input_content (List[Dict[str, Any]]): Multimodal Interactions input.
		tool_objects (List[Dict[str, Any]]): Interactions Google Search tool declarations.
		interaction (Optional[Any]): Most recent Gemini Interaction.
		response (Optional[Any]): Raw response used by application token accounting.
		output_text (str): Text extracted from the latest Interaction.
		output_image_content (Optional[Any]): Image content from the latest Interaction.
		grounding_metadata (Optional[Any]): Grounding data retained for UI compatibility.
		grounding_sources (List[Dict[str, Any]]): Normalized grounding records.
	"""

	client: Optional[ genai.Client ]
	http_options: HttpOptions
	aspect_ratio: Optional[ str ]
	size: Optional[ str ]
	resolution: Optional[ str ]
	max_output_tokens: Optional[ int ]
	output_mime_type: Optional[ str ]
	response_mode: Optional[ str ]
	response_format_value: Optional[ Any ]
	generation_config: Dict[ str, Any ]
	input_content: List[ Dict[ str, Any ] ]
	tool_objects: List[ Dict[ str, Any ] ]
	interaction: Optional[ Any ]
	response: Optional[ Any ]
	output_text: str
	output_image_content: Optional[ Any ]
	grounding_metadata: Optional[ Any ]
	grounding_sources: List[ Dict[ str, Any ] ]

	def __init__( self, model: str='gemini-3.1-flash-image' ) -> None:
		"""Initialize the Images wrapper.

		Purpose:
			Initializes image-model configuration, Interactions request state, output
			configuration, and response placeholders. The constructor performs local state
			assignment only and does not create a client or submit a provider request.

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

		Returns:
			None: This method initializes object state through side effects.
		"""
		super( ).__init__( )
		self.model = model
		self.api_version = 'v1beta'
		self.http_options = types.HttpOptions( api_version=self.api_version )
		self.client = None
		self.number = 1
		self.instructions = None
		self.temperature = None
		self.top_p = None
		self.top_k = None
		self.frequency_penalty = None
		self.presence_penalty = None
		self.candidate_count = None
		self.max_tokens = None
		self.max_output_tokens = None
		self.aspect_ratio = None
		self.size = None
		self.resolution = None
		self.media_resolution = None
		self.output_mime_type = None
		self.response_mode = None
		self.response_modalities = [ ]
		self.tools = [ ]
		self.tool_choice = None
		self.input_content = [ ]
		self.response_format_value = None
		self.generation_config = { }
		self.tool_objects = [ ]
		self.interaction = None
		self.response = None
		self.content_response = None
		self.image_response = None
		self.output_text = ''
		self.output_image_content = None
		self.grounding_metadata = None
		self.grounding_sources = [ ]

	@property
	def model_options( self ) -> List[ str ]:
		"""Return supported Gemini image models.

		Purpose:
			Provides image-generation and image-editing model identifiers exposed by the Jeni
			Images mode.

		Returns:
			List[str]: Supported Gemini image-model identifiers.
		"""
		return [ 'gemini-3.1-flash-lite-image', 'gemini-3.1-flash-image', 'gemini-3-pro-image', ]

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

		Purpose:
			Preserves the option contract consumed by existing Jeni controls.

		Returns:
			List[str]: Existing include-option values.
		"""
		return [ 'file_search_call.results', 'message.input_image.image_url',
			'message.output_text.logprobs', 'reasoning.encrypted_content', ]

	@property
	def aspect_options( self ) -> List[ str ]:
		"""Return supported output-image aspect ratios.

		Purpose:
			Provides aspect-ratio values accepted by Gemini image response formats.

		Returns:
			List[str]: Supported aspect ratios.
		"""
		return [ '1:1', '1:4', '1:8', '2:3', '3:2', '3:4', '4:1', '4:3', '4:5', '5:4', '8:1',
			'9:16', '16:9', '21:9', ]

	@property
	def media_options( self ) -> List[ str ]:
		"""Return supported media-resolution values.

		Purpose:
			Provides media-resolution values retained by the Jeni image controls.

		Returns:
			List[str]: Supported media-resolution values.
		"""
		return [ 'media_resolution_high', 'media_resolution_medium', 'media_resolution_low', ]

	@property
	def modality_options( self ) -> List[ str ]:
		"""Return supported image response modes.

		Purpose:
			Provides text-only, image-only, and combined text-and-image output selections.

		Returns:
			List[str]: Supported response-mode values.
		"""
		return [ 'text', 'image', 'text_and_image', ]

	@property
	def reasoning_options( self ) -> List[ str ]:
		"""Return supported thinking levels.

		Purpose:
			Provides thinking-level values accepted by supported image models.

		Returns:
			List[str]: Supported thinking-level values.
		"""
		return [ 'unspecified', 'minimal', 'low', 'medium', 'high', ]

	@property
	def size_options( self ) -> List[ str ]:
		"""Return supported output-image sizes.

		Purpose:
			Provides output-image sizes accepted through the Interactions response format.

		Returns:
			List[str]: Supported image-size values.
		"""
		return [ '512', '1K', '2K', '4K', ]

	@property
	def tool_options( self ) -> List[ str ]:
		"""Return supported image grounding tools.

		Purpose:
			Provides Google Web Search and Google Image Search selections used by the Jeni
			Images mode.

		Returns:
			List[str]: Supported image tool identifiers.
		"""
		return [ 'google_search', 'image_search', ]

	@property
	def choice_options( self ) -> List[ str ]:
		"""Return supported tool-choice values.

		Purpose:
			Preserves the existing Jeni tool-choice option contract.

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

	@property
	def format_options( self ) -> List[ str ]:
		"""Return supported text-output MIME types.

		Purpose:
			Provides text MIME types retained by the Jeni image controls.

		Returns:
			List[str]: Supported text-output MIME types.
		"""
		return [ 'text/plain', 'application/json', 'text/x.enum', ]

	@property
	def mime_options( self ) -> List[ str ]:
		"""Return supported generated-image MIME types.

		Purpose:
			Provides image MIME types accepted by the Interactions image response format.

		Returns:
			List[str]: Supported generated-image MIME types.
		"""
		return [ 'image/jpeg', 'image/png', 'image/webp', ]

	@property
	def resolution_options( self ) -> List[ str ]:
		"""Return supported output-image resolution options.

		Purpose:
			Provides the output-size values exposed by the Jeni Images mode.

		Returns:
			List[str]: Supported output-image sizes.
		"""
		return list( self.size_options )

	def supports_image_size( self, model: str ) -> bool:
		"""Return whether the selected model supports explicit image size.

		Purpose:
			Centralizes output-image-size feature gating for the Jeni image controls.

		Args:
			model (str): Gemini image-model identifier.

		Returns:
			bool: True when the model supports explicit image size.

		Raises:
			Error: Raised when validation or model comparison fails.
			ValueError: Raised when ``model`` is missing.
		"""
		try:
			throw_if( 'model', model )
			self.model = model
			self.model_name = self.model.strip( ).lower( )
			self.image_size_models = { 'gemini-3.1-flash-lite-image', 'gemini-3.1-flash-image',
				'gemini-3-pro-image', }
			return self.model_name in self.image_size_models
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = 'supports_image_size( self, model: str ) -> bool'
			Logger( ).write( exception )
			raise exception

	def supports_search_grounding( self, model: str ) -> bool:
		"""Return whether the model supports Google Search grounding.

		Purpose:
			Centralizes Google Search grounding feature gating for image generation.

		Args:
			model (str): Gemini image-model identifier.

		Returns:
			bool: True when the model supports Google Search grounding.

		Raises:
			Error: Raised when validation or model comparison fails.
			ValueError: Raised when ``model`` is missing.
		"""
		try:
			throw_if( 'model', model )
			self.model = model
			self.model_name = self.model.strip( ).lower( )
			self.search_grounding_models = { 'gemini-3.1-flash-image', 'gemini-3-pro-image', }
			return self.model_name in self.search_grounding_models
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = 'supports_search_grounding( self, model: str ) -> bool'
			Logger( ).write( exception )
			raise exception

	def supports_image_search( self, model: str ) -> bool:
		"""Return whether the model supports Google Image Search grounding.

		Purpose:
			Restricts Google Image Search grounding to the model documented for that feature.

		Args:
			model (str): Gemini image-model identifier.

		Returns:
			bool: True when Google Image Search is supported.

		Raises:
			Error: Raised when validation or model comparison fails.
			ValueError: Raised when ``model`` is missing.
		"""
		try:
			throw_if( 'model', model )
			self.model = model
			self.model_name = self.model.strip( ).lower( )
			return self.model_name == 'gemini-3.1-flash-image'
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = 'supports_image_search( self, model: str ) -> bool'
			Logger( ).write( exception )
			raise exception

	def normalize_response_modalities( self, response_modalities: Optional[ str ],
		image_only: bool = False ) -> List[ str ]:
		"""Normalize the requested response modes.

		Purpose:
			Converts the Jeni response-mode value into text and image modality identifiers used
			to build the Interactions response format.

		Args:
			response_modalities (Optional[str]): Jeni response-mode value.
			image_only (bool): Whether image output must be included.

		Returns:
			List[str]: Normalized response modes.

		Raises:
			Error: Raised when response-mode normalization fails.
		"""
		try:
			self.response_mode = response_modalities
			self.image_only = image_only
			self.mode_name = str( self.response_mode or '' ).strip( ).lower( )
			if self.mode_name == 'text_and_image':
				return [ 'text', 'image', ]

			if self.mode_name == 'text':
				return [ 'text', ]

			if self.mode_name == 'image':
				return [ 'image', ]

			if self.image_only:
				return [ 'image', ]

			return [ 'text', ]
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('normalize_response_modalities( self, response_modalities: '
			                    'Optional[str], image_only: bool ) -> List[str]')
			Logger( ).write( exception )
			raise exception

	def get_image_mime_type( self, path: str ) -> str:
		"""Return the MIME type for a local image.

		Purpose:
			Uses the local file suffix to produce the image MIME type required by an
			Interactions image-content block.

		Args:
			path (str): Local image path.

		Returns:
			str: Image MIME type.

		Raises:
			Error: Raised when validation or MIME-type resolution fails.
			ValueError: Raised when ``path`` is missing.
		"""
		try:
			throw_if( 'path', path )
			self.file_path = path
			self.file_suffix = Path( self.file_path ).suffix.lower( )
			if self.file_suffix in ('.jpg', '.jpeg'):
				return 'image/jpeg'

			if self.file_suffix == '.webp':
				return 'image/webp'

			if self.file_suffix == '.gif':
				return 'image/gif'

			return 'image/png'
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = 'get_image_mime_type( self, path: str ) -> str'
			Logger( ).write( exception )
			raise exception

	def build_image_input( self, prompt: str, path: Optional[ str ] = None ) -> List[
		Dict[ str, Any ] ]:
		"""Build Interactions text and image input.

		Purpose:
			Creates a text content block and, when supplied, a base64-encoded local image
			content block for image analysis or editing.

		Args:
			prompt (str): Image-generation, analysis, or editing instruction.
			path (Optional[str]): Optional local image path.

		Returns:
			List[Dict[str, Any]]: Interactions-compatible input content.

		Raises:
			Error: Raised when validation, file reading, or input construction fails.
			ValueError: Raised when ``prompt`` is missing.
		"""
		try:
			throw_if( 'prompt', prompt )
			self.prompt = prompt
			self.file_path = path
			self.input_content = [ { 'type': 'text', 'text': self.prompt.strip( ), }, ]
			if self.file_path:
				self.image_bytes = Path( self.file_path ).read_bytes( )
				throw_if( 'image_bytes', self.image_bytes )
				self.image_data = base64.b64encode( self.image_bytes ).decode( 'utf-8' )
				self.image_mime_type = self.get_image_mime_type( self.file_path )
				self.input_content.append( { 'type': 'image', 'data': self.image_data,
					'mime_type': self.image_mime_type, } )

			return self.input_content
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('build_image_input( self, prompt: str, path: Optional[str] ) -> '
			                    'List[Dict[str, Any]]')
			Logger( ).write( exception )
			raise exception

	def build_generation_config( self, temperature: Optional[ float ] = None,
		top_p: Optional[ float ] = None, max_tokens: Optional[ int ] = None ) -> Dict[ str, Any ]:
		"""Build the Interactions image generation configuration.

		Purpose:
			Converts supported Jeni inference values into the Interactions generation
			configuration.

		Args:
			temperature (Optional[float]): Sampling temperature.
			top_p (Optional[float]): Top-p sampling value.
			max_tokens (Optional[int]): Maximum output-token count.

		Returns:
			Dict[str, Any]: Interactions generation configuration.

		Raises:
			Error: Raised when generation configuration construction fails.
		"""
		try:
			self.temperature = temperature
			self.top_p = top_p
			self.max_output_tokens = max_tokens
			self.generation_config = { }
			if self.temperature is not None:
				self.generation_config[ 'temperature' ] = self.temperature

			if self.top_p is not None:
				self.generation_config[ 'top_p' ] = self.top_p

			if self.max_output_tokens is not None and self.max_output_tokens > 0:
				self.generation_config[ 'max_output_tokens' ] = (self.max_output_tokens)

			return self.generation_config
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('build_generation_config( self, temperature: Optional[float], '
			                    'top_p: Optional[float], max_tokens: Optional[int] ) -> Dict[str, '
			                    'Any]')
			Logger( ).write( exception )
			raise exception

	def build_response_format( self, response_modalities: Optional[ str ], image_only: bool =
	False,
		aspect: Optional[ str ] = None, resolution: Optional[ str ] = None,
		output_mime_type: Optional[ str ] = None ) -> Any:
		"""Build the Interactions image response format.

		Purpose:
			Constructs text, image, or combined response formats and applies supported image
			MIME type, aspect ratio, and output-size settings to the image format.

		Args:
			response_modalities (Optional[str]): Jeni response-mode value.
			image_only (bool): Whether image output must be included.
			aspect (Optional[str]): Requested output-image aspect ratio.
			resolution (Optional[str]): Requested output-image size.
			output_mime_type (Optional[str]): Requested generated-image MIME type.

		Returns:
			Any: Interactions response-format object or list.

		Raises:
			Error: Raised when response-format construction fails.
		"""
		try:
			self.response_mode = response_modalities
			self.image_only = image_only
			self.aspect_ratio = aspect
			self.size = resolution
			self.output_mime_type = output_mime_type
			self.response_modalities = self.normalize_response_modalities(
				response_modalities=self.response_mode, image_only=self.image_only )
			self.response_formats: List[ Dict[ str, Any ] ] = [ ]
			for modality in self.response_modalities:
				if modality == 'text':
					self.response_formats.append( { 'type': 'text', } )

				elif modality == 'image':
					self.image_format: Dict[ str, Any ] = { 'type': 'image', }
					if self.output_mime_type:
						self.image_format[ 'mime_type' ] = (self.output_mime_type)

					if self.aspect_ratio:
						self.image_format[ 'aspect_ratio' ] = (self.aspect_ratio)

					if (self.size and self.supports_image_size( self.model )):
						self.image_format[ 'image_size' ] = self.size

					self.response_formats.append( self.image_format )

			if len( self.response_formats ) == 1:
				self.response_format_value = self.response_formats[ 0 ]
			else:
				self.response_format_value = self.response_formats

			return self.response_format_value
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('build_response_format( self, response_modalities: Optional[str], '
			                    'image_only: bool, aspect: Optional[str], resolution: Optional['
			                    'str], output_mime_type: Optional[str] ) -> Any')
			Logger( ).write( exception )
			raise exception

	def build_grounding_tools( self, grounded: bool = False, image_search: bool = False ) -> List[
		Dict[ str, Any ] ]:
		"""Build image grounding tool declarations.

		Purpose:
			Creates the Interactions Google Search tool declaration for web grounding and
			optionally enables Google Image Search when supported by the selected model.

		Args:
			grounded (bool): Whether Google Web Search grounding is enabled.
			image_search (bool): Whether Google Image Search grounding is enabled.

		Returns:
			List[Dict[str, Any]]: Interactions tool declarations.

		Raises:
			Error: Raised when grounding-tool construction fails.
		"""
		try:
			self.grounded = grounded
			self.image_search = image_search
			self.tool_objects = [ ]
			if not self.grounded and not self.image_search:
				return self.tool_objects

			if not self.supports_search_grounding( self.model ):
				return self.tool_objects

			self.search_types: List[ str ] = [ ]
			if self.grounded:
				self.search_types.append( 'web_search' )

			if (self.image_search and self.supports_image_search( self.model )):
				self.search_types.append( 'image_search' )

			self.search_tool: Dict[ str, Any ] = { 'type': 'google_search', }

			if self.search_types:
				self.search_tool[ 'search_types' ] = self.search_types

			self.tool_objects.append( self.search_tool )
			return self.tool_objects
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('build_grounding_tools( self, grounded: bool, image_search: bool ) '
			                    '-> List[Dict[str, Any]]')
			Logger( ).write( exception )
			raise exception

	def extract_image( self, interaction: Any ) -> Optional[ PIL.Image.Image ]:
		"""Extract a generated image from an Interaction.

		Purpose:
			Reads the SDK ``output_image`` convenience property, decodes its base64 content,
			and returns an independent Pillow image object.

		Args:
			interaction (Any): Completed Gemini Interaction.

		Returns:
			Optional[PIL.Image.Image]: Generated image, or None when no image was returned.

		Raises:
			Error: Raised when validation or image extraction fails.
			ValueError: Raised when ``interaction`` is missing.
		"""
		try:
			throw_if( 'interaction', interaction )
			self.interaction = interaction
			self.output_image_content = getattr( self.interaction, 'output_image', None )
			if self.output_image_content is None:
				return None

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

			self.decoded_image = base64.b64decode( self.output_image_data )
			with PIL.Image.open( io.BytesIO( self.decoded_image ) ) as source:
				return source.copy( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = 'extract_image( self, interaction: Any ) -> Optional[ Image ]'
			Logger( ).write( exception )
			raise exception

	def extract_text( self, interaction: Any ) -> Optional[ str ]:
		"""Extract generated text from an Interaction.

		Purpose:
			Reads the Interactions SDK ``output_text`` convenience property and returns the
			normalized text expected by the Jeni image-analysis workflow.

		Args:
			interaction (Any): Completed Gemini Interaction.

		Returns:
			Optional[str]: Generated text, or None when no text was returned.

		Raises:
			Error: Raised when validation or text extraction fails.
			ValueError: Raised when ``interaction`` is missing.
		"""
		try:
			throw_if( 'interaction', interaction )
			self.interaction = interaction
			self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
			return self.output_text or None
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('extract_text( self, interaction: Any ) -> Optional[ str ]')
			Logger( ).write( exception )
			raise exception

	def capture_metadata( self ) -> None:
		"""Capture grounding information from the latest Interaction.

		Purpose:
			Retains the latest Interaction steps and Google Search result metadata for
			application display and diagnostics.

		Returns:
			None: This method updates response state through side effects.

		Raises:
			Error: Raised when grounding metadata cannot be captured.
		"""
		try:
			self.grounding_metadata = None
			self.grounding_sources = [ ]

			if self.interaction is None:
				return

			self.steps = getattr( self.interaction, 'steps', None ) or [ ]
			for step in self.steps:
				self.step_type = str( getattr( step, 'type', '' ) or '' ).strip( )
				if self.step_type != 'google_search_result':
					continue

				self.result = getattr( step, 'result', None )
				self.grounding_sources.append( { 'type': self.step_type, 'result': self.result, } )

			if self.grounding_sources:
				self.grounding_metadata = self.grounding_sources
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = 'capture_metadata( self ) -> None'
			Logger( ).write( exception )
			raise exception

	def execute_interaction( self, prompt: str, model: str, path: Optional[ str ] = None,
		aspect: Optional[ str ] = None, number: Optional[ int ] = None,
		temperature: Optional[ float ] = None, top_p: Optional[ float ] = None,
		frequency: Optional[ float ] = None, presence: Optional[ float ] = None,
		max_tokens: Optional[ int ] = None, resolution: Optional[ str ] = None,
		instruct: Optional[ str ] = None, output_mime_type: Optional[ str ] = None,
		response_modalities: Optional[ str ] = None, image_only: bool = False,
		grounded: bool = False, image_search: bool = False ) -> Any:
		"""Execute an image Interaction.

		Purpose:
			Validates required inputs, creates the Gemini client, builds multimodal input,
			generation settings, output formats, and grounding tools, submits the request, and
			captures the response state shared by generation, analysis, and editing workflows.

		Args:
			prompt (str): Image-generation, analysis, or editing instruction.
			model (str): Gemini image-model identifier.
			path (Optional[str]): Optional local image path.
			aspect (Optional[str]): Requested output-image aspect ratio.
			number (Optional[int]): Requested result count retained for compatibility.
			temperature (Optional[float]): Sampling temperature.
			top_p (Optional[float]): Top-p sampling value.
			frequency (Optional[float]): Frequency penalty retained for compatibility.
			presence (Optional[float]): Presence penalty retained for compatibility.
			max_tokens (Optional[int]): Maximum output-token count.
			resolution (Optional[str]): Requested generated-image size.
			instruct (Optional[str]): System instruction text.
			output_mime_type (Optional[str]): Requested generated-image MIME type.
			response_modalities (Optional[str]): Requested response-mode value.
			image_only (bool): Whether image output must be included.
			grounded (bool): Whether Google Search grounding is enabled.
			image_search (bool): Whether Google Image Search grounding is enabled.

		Returns:
			Any: Completed Gemini Interaction.

		Raises:
			Error: Raised when validation, request construction, or provider execution fails.
			ValueError: Raised when ``prompt``, ``model``, or the API key is missing.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.prompt = prompt
			self.model = model
			self.file_path = path
			self.aspect_ratio = aspect
			self.number = number
			self.temperature = temperature
			self.top_p = top_p
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_output_tokens = max_tokens
			self.size = resolution
			self.instructions = instruct
			self.output_mime_type = output_mime_type
			self.response_mode = response_modalities
			self.image_only = image_only
			self.grounded = grounded
			self.image_search = image_search
			self.api_key = self.gemini_api_key or self.google_api_key
			self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )
			self.input_content = self.build_image_input( prompt=self.prompt, path=self.file_path )
			self.generation_config = self.build_generation_config( temperature=self.temperature,
				top_p=self.top_p, max_tokens=self.max_output_tokens )

			self.response_format_value = self.build_response_format(
				response_modalities=self.response_mode, image_only=self.image_only,
				aspect=self.aspect_ratio, resolution=self.size,
				output_mime_type=self.output_mime_type )

			self.tool_objects = self.build_grounding_tools( grounded=self.grounded,
				image_search=self.image_search )

			self.request: Dict[ str, Any ] = { 'model': self.model, 'input': self.input_content,
				'response_format': self.response_format_value, 'store': False, }

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

			if self.generation_config:
				self.request[ 'generation_config' ] = (self.generation_config)

			if self.tool_objects:
				self.request[ 'tools' ] = self.tool_objects

			self.interaction = self.client.interactions.create( **self.request )
			self.response = self.interaction
			self.content_response = self.interaction
			self.image_response = self.interaction
			self.capture_metadata( )
			return self.interaction
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('execute_interaction( self, prompt: str, model: str, '
			                    'path: Optional[str], aspect: Optional[str], number: Optional['
			                    'int], temperature: Optional[float], top_p: Optional[float], '
			                    'frequency: Optional[float], presence: Optional[float], '
			                    'max_tokens: Optional[int], resolution: Optional[str], instruct: '
			                    'Optional[str], output_mime_type: Optional[str], '
			                    'response_modalities: Optional[str], image_only: bool, grounded: '
			                    'bool, image_search: bool ) -> Any')
			Logger( ).write( exception )
			raise exception

	def get_first_image( self ) -> Optional[ PIL.Image.Image ]:
		"""Return the image from the most recent Interaction.

		Purpose:
			Preserves the existing Jeni helper contract by extracting the generated image from
			the latest Interaction.

		Returns:
			Optional[PIL.Image.Image]: Generated image, or None when unavailable.

		Raises:
			Error: Raised when image extraction fails.
		"""
		try:
			if self.interaction is None:
				return None

			return self.extract_image( self.interaction )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('get_first_image( self ) -> Optional[ PIL.Image.Image ]')
			Logger( ).write( exception )
			raise exception

	def get_output_text( self ) -> Optional[ str ]:
		"""Return text from the most recent Interaction.

		Purpose:
			Preserves the existing Jeni helper contract by extracting generated text from the
			latest Interaction.

		Returns:
			Optional[str]: Generated text, or None when unavailable.

		Raises:
			Error: Raised when text extraction fails.
		"""
		try:
			if self.interaction is None:
				return None

			return self.extract_text( self.interaction )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('get_output_text( self ) -> Optional[ str ]')
			Logger( ).write( exception )
			raise exception

	def generate( self, prompt: str, model: str='gemini-3.1-flash-image', aspect: str=None,
		number: int=None, temperature: float=None, top_p: float=None, frequency: float =
		None,
		presence: float=None, max_tokens: int=None, resolution: str=None,
		instruct: str=None, output_mime_type: str=None, response_modalities: str=None,
		grounded: bool = False, image_search: bool = False ) -> Optional[ PIL.Image.Image ]:
		"""Generate an image through the Gemini Interactions API.

		Purpose:
			Submits a text-to-image Interaction and returns the generated Pillow image expected
			by the Jeni Image Generation workflow.

		Args:
			prompt (str): Image-generation instruction.
			model (str): Gemini image-model identifier.
			aspect (str): Requested output-image aspect ratio.
			number (int): Requested result count retained for compatibility.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			frequency (float): Frequency penalty retained for compatibility.
			presence (float): Presence penalty retained for compatibility.
			max_tokens (int): Maximum output-token count.
			resolution (str): Requested generated-image size.
			instruct (str): System instruction text.
			output_mime_type (str): Requested generated-image MIME type.
			response_modalities (str): Requested response-mode value.
			grounded (bool): Whether Google Search grounding is enabled.
			image_search (bool): Whether Google Image Search grounding is enabled.

		Returns:
			Optional[PIL.Image.Image]: Generated image, or None when no image is returned.

		Raises:
			Error: Raised when request execution or image extraction fails.
			ValueError: Raised when a required argument is missing.
		"""
		try:
			self.interaction = self.execute_interaction( prompt=prompt, model=model, path=None,
				aspect=aspect, number=number, temperature=temperature, top_p=top_p,
				frequency=frequency, presence=presence, max_tokens=max_tokens,
				resolution=resolution, instruct=instruct, output_mime_type=output_mime_type,
				response_modalities=response_modalities, image_only=True, grounded=grounded,
				image_search=image_search )

			return self.extract_image( self.interaction )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('generate( self, prompt: str, model: str, aspect: str, number: int, '
			                    'temperature: float, top_p: float, frequency: float, presence: '
			                    'float, max_tokens: int, resolution: str, instruct: str, '
			                    'output_mime_type: str, response_modalities: str, grounded: bool, '
			                    'image_search: bool ) -> Optional[PIL.Image.Image]')
			Logger( ).write( exception )
			raise exception

	def analyze( self, prompt: str, path: str, model: str='gemini-3.1-flash-image',
		aspect: str=None, number: int=None, temperature: float=None, top_p: float=None,
		frequency: float=None, presence: float=None, max_tokens: int=None,
		resolution: str=None, instruct: str=None, output_mime_type: str=None,
		response_modalities: str=None, grounded: bool = False, image_search: bool = False ) -> \
	Optional[ str ]:
		"""Analyze an image through the Gemini Interactions API.

		Purpose:
			Submits text and a local image as multimodal Interaction input and returns the
			generated text expected by the Jeni Image Analysis workflow.

		Args:
			prompt (str): Image-analysis instruction.
			path (str): Local image path.
			model (str): Gemini image-model identifier.
			aspect (str): Aspect-ratio value retained for compatibility.
			number (int): Requested result count retained for compatibility.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			frequency (float): Frequency penalty retained for compatibility.
			presence (float): Presence penalty retained for compatibility.
			max_tokens (int): Maximum output-token count.
			resolution (str): Media-resolution value retained for compatibility.
			instruct (str): System instruction text.
			output_mime_type (str): Output MIME type retained for compatibility.
			response_modalities (str): Requested response-mode value.
			grounded (bool): Whether Google Search grounding is enabled.
			image_search (bool): Whether Google Image Search grounding is enabled.

		Returns:
			Optional[str]: Generated image analysis, or None when no text is returned.

		Raises:
			Error: Raised when request execution or text extraction fails.
			ValueError: Raised when a required argument is missing.
		"""
		try:
			throw_if( 'path', path )
			self.file_path = path
			self.interaction = self.execute_interaction( prompt=prompt, model=model,
				path=self.file_path, aspect=aspect, number=number, temperature=temperature,
				top_p=top_p, frequency=frequency, presence=presence, max_tokens=max_tokens,
				resolution=resolution, instruct=instruct, output_mime_type=output_mime_type,
				response_modalities=response_modalities or 'text', image_only=False,
				grounded=grounded, image_search=image_search )

			return self.extract_text( self.interaction )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('analyze( self, **kwargs ) -> Optional[str]')
			Logger( ).write( exception )
			raise exception

	def edit( self, prompt: str, path: str, model: str='gemini-3.1-flash-image',
		aspect: str=None, number: int=None, temperature: float=None, top_p: float=None,
		frequency: float=None, presence: float=None, max_tokens: int=None,
		resolution: str=None, instruct: str=None, output_mime_type: str=None,
		response_modalities: str=None, grounded: bool=False, image_search: bool=False ) -> Image:
		"""Edit an image through the Gemini Interactions API.

		Purpose:
			Submits an editing instruction and local image as multimodal Interaction input and
			returns the generated Pillow image expected by the Jeni Image Editing workflow.

		Args:
			prompt (str): Image-editing instruction.
			path (str): Local source-image path.
			model (str): Gemini image-model identifier.
			aspect (str): Requested output-image aspect ratio.
			number (int): Requested result count retained for compatibility.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			frequency (float): Frequency penalty retained for compatibility.
			presence (float): Presence penalty retained for compatibility.
			max_tokens (int): Maximum output-token count.
			resolution (str): Requested generated-image size.
			instruct (str): System instruction text.
			output_mime_type (str): Requested generated-image MIME type.
			response_modalities (str): Requested response-mode value.
			grounded (bool): Whether Google Search grounding is enabled.
			image_search (bool): Whether Google Image Search grounding is enabled.

		Returns:
			Optional[PIL.Image.Image]: Edited image, or None when no image is returned.

		Raises:
			Error: Raised when request execution or image extraction fails.
			ValueError: Raised when a required argument is missing.
		"""
		try:
			throw_if( 'path', path )
			self.file_path = path
			self.interaction = self.execute_interaction( prompt=prompt, model=model,
				path=self.file_path, aspect=aspect, number=number, temperature=temperature,
				top_p=top_p, frequency=frequency, presence=presence, max_tokens=max_tokens,
				resolution=resolution, instruct=instruct, output_mime_type=output_mime_type,
				response_modalities=response_modalities or 'image', image_only=True,
				grounded=grounded, image_search=image_search )

			return self.extract_image( self.interaction )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Images'
			exception.method = ('edit( self, **kwargs ) -> Optional[PIL.Image.Image]')
			Logger( ).write( exception )
			raise exception

model_options property

model_options: List[str]

Return supported Gemini image models.

Purpose

Provides image-generation and image-editing model identifiers exposed by the Jeni Images mode.

Returns:

Type Description
List[str]

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

include_options property

include_options: List[str]

Return compatibility include options.

Purpose

Preserves the option contract consumed by existing Jeni controls.

Returns:

Type Description
List[str]

List[str]: Existing include-option values.

aspect_options property

aspect_options: List[str]

Return supported output-image aspect ratios.

Purpose

Provides aspect-ratio values accepted by Gemini image response formats.

Returns:

Type Description
List[str]

List[str]: Supported aspect ratios.

media_options property

media_options: List[str]

Return supported media-resolution values.

Purpose

Provides media-resolution values retained by the Jeni image controls.

Returns:

Type Description
List[str]

List[str]: Supported media-resolution values.

modality_options property

modality_options: List[str]

Return supported image response modes.

Purpose

Provides text-only, image-only, and combined text-and-image output selections.

Returns:

Type Description
List[str]

List[str]: Supported response-mode values.

reasoning_options property

reasoning_options: List[str]

Return supported thinking levels.

Purpose

Provides thinking-level values accepted by supported image models.

Returns:

Type Description
List[str]

List[str]: Supported thinking-level values.

size_options property

size_options: List[str]

Return supported output-image sizes.

Purpose

Provides output-image sizes accepted through the Interactions response format.

Returns:

Type Description
List[str]

List[str]: Supported image-size values.

tool_options property

tool_options: List[str]

Return supported image grounding tools.

Purpose

Provides Google Web Search and Google Image Search selections used by the Jeni Images mode.

Returns:

Type Description
List[str]

List[str]: Supported image tool identifiers.

choice_options property

choice_options: List[str]

Return supported tool-choice values.

Purpose

Preserves the existing Jeni tool-choice option contract.

Returns:

Type Description
List[str]

List[str]: Supported tool-choice values.

format_options property

format_options: List[str]

Return supported text-output MIME types.

Purpose

Provides text MIME types retained by the Jeni image controls.

Returns:

Type Description
List[str]

List[str]: Supported text-output MIME types.

mime_options property

mime_options: List[str]

Return supported generated-image MIME types.

Purpose

Provides image MIME types accepted by the Interactions image response format.

Returns:

Type Description
List[str]

List[str]: Supported generated-image MIME types.

resolution_options property

resolution_options: List[str]

Return supported output-image resolution options.

Purpose

Provides the output-size values exposed by the Jeni Images mode.

Returns:

Type Description
List[str]

List[str]: Supported output-image sizes.

__init__

__init__(model: str = 'gemini-3.1-flash-image') -> None

Initialize the Images wrapper.

Purpose

Initializes image-model configuration, Interactions request state, output configuration, and response placeholders. The constructor performs local state assignment only and does not create a client or submit a provider request.

Parameters:

Name Type Description Default
model str

Default Gemini image model.

'gemini-3.1-flash-image'

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self, model: str='gemini-3.1-flash-image' ) -> None:
	"""Initialize the Images wrapper.

	Purpose:
		Initializes image-model configuration, Interactions request state, output
		configuration, and response placeholders. The constructor performs local state
		assignment only and does not create a client or submit a provider request.

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

	Returns:
		None: This method initializes object state through side effects.
	"""
	super( ).__init__( )
	self.model = model
	self.api_version = 'v1beta'
	self.http_options = types.HttpOptions( api_version=self.api_version )
	self.client = None
	self.number = 1
	self.instructions = None
	self.temperature = None
	self.top_p = None
	self.top_k = None
	self.frequency_penalty = None
	self.presence_penalty = None
	self.candidate_count = None
	self.max_tokens = None
	self.max_output_tokens = None
	self.aspect_ratio = None
	self.size = None
	self.resolution = None
	self.media_resolution = None
	self.output_mime_type = None
	self.response_mode = None
	self.response_modalities = [ ]
	self.tools = [ ]
	self.tool_choice = None
	self.input_content = [ ]
	self.response_format_value = None
	self.generation_config = { }
	self.tool_objects = [ ]
	self.interaction = None
	self.response = None
	self.content_response = None
	self.image_response = None
	self.output_text = ''
	self.output_image_content = None
	self.grounding_metadata = None
	self.grounding_sources = [ ]

supports_image_size

supports_image_size(model: str) -> bool

Return whether the selected model supports explicit image size.

Purpose

Centralizes output-image-size feature gating for the Jeni image controls.

Parameters:

Name Type Description Default
model str

Gemini image-model identifier.

required

Returns:

Name Type Description
bool bool

True when the model supports explicit image size.

Raises:

Type Description
Error

Raised when validation or model comparison fails.

ValueError

Raised when model is missing.

Source code in gemini.py
def supports_image_size( self, model: str ) -> bool:
	"""Return whether the selected model supports explicit image size.

	Purpose:
		Centralizes output-image-size feature gating for the Jeni image controls.

	Args:
		model (str): Gemini image-model identifier.

	Returns:
		bool: True when the model supports explicit image size.

	Raises:
		Error: Raised when validation or model comparison fails.
		ValueError: Raised when ``model`` is missing.
	"""
	try:
		throw_if( 'model', model )
		self.model = model
		self.model_name = self.model.strip( ).lower( )
		self.image_size_models = { 'gemini-3.1-flash-lite-image', 'gemini-3.1-flash-image',
			'gemini-3-pro-image', }
		return self.model_name in self.image_size_models
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = 'supports_image_size( self, model: str ) -> bool'
		Logger( ).write( exception )
		raise exception

supports_search_grounding

supports_search_grounding(model: str) -> bool

Return whether the model supports Google Search grounding.

Purpose

Centralizes Google Search grounding feature gating for image generation.

Parameters:

Name Type Description Default
model str

Gemini image-model identifier.

required

Returns:

Name Type Description
bool bool

True when the model supports Google Search grounding.

Raises:

Type Description
Error

Raised when validation or model comparison fails.

ValueError

Raised when model is missing.

Source code in gemini.py
def supports_search_grounding( self, model: str ) -> bool:
	"""Return whether the model supports Google Search grounding.

	Purpose:
		Centralizes Google Search grounding feature gating for image generation.

	Args:
		model (str): Gemini image-model identifier.

	Returns:
		bool: True when the model supports Google Search grounding.

	Raises:
		Error: Raised when validation or model comparison fails.
		ValueError: Raised when ``model`` is missing.
	"""
	try:
		throw_if( 'model', model )
		self.model = model
		self.model_name = self.model.strip( ).lower( )
		self.search_grounding_models = { 'gemini-3.1-flash-image', 'gemini-3-pro-image', }
		return self.model_name in self.search_grounding_models
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = 'supports_search_grounding( self, model: str ) -> bool'
		Logger( ).write( exception )
		raise exception
supports_image_search(model: str) -> bool

Return whether the model supports Google Image Search grounding.

Purpose

Restricts Google Image Search grounding to the model documented for that feature.

Parameters:

Name Type Description Default
model str

Gemini image-model identifier.

required

Returns:

Name Type Description
bool bool

True when Google Image Search is supported.

Raises:

Type Description
Error

Raised when validation or model comparison fails.

ValueError

Raised when model is missing.

Source code in gemini.py
def supports_image_search( self, model: str ) -> bool:
	"""Return whether the model supports Google Image Search grounding.

	Purpose:
		Restricts Google Image Search grounding to the model documented for that feature.

	Args:
		model (str): Gemini image-model identifier.

	Returns:
		bool: True when Google Image Search is supported.

	Raises:
		Error: Raised when validation or model comparison fails.
		ValueError: Raised when ``model`` is missing.
	"""
	try:
		throw_if( 'model', model )
		self.model = model
		self.model_name = self.model.strip( ).lower( )
		return self.model_name == 'gemini-3.1-flash-image'
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = 'supports_image_search( self, model: str ) -> bool'
		Logger( ).write( exception )
		raise exception

normalize_response_modalities

normalize_response_modalities(
    response_modalities: Optional[str],
    image_only: bool = False,
) -> List[str]

Normalize the requested response modes.

Purpose

Converts the Jeni response-mode value into text and image modality identifiers used to build the Interactions response format.

Parameters:

Name Type Description Default
response_modalities Optional[str]

Jeni response-mode value.

required
image_only bool

Whether image output must be included.

False

Returns:

Type Description
List[str]

List[str]: Normalized response modes.

Raises:

Type Description
Error

Raised when response-mode normalization fails.

Source code in gemini.py
def normalize_response_modalities( self, response_modalities: Optional[ str ],
	image_only: bool = False ) -> List[ str ]:
	"""Normalize the requested response modes.

	Purpose:
		Converts the Jeni response-mode value into text and image modality identifiers used
		to build the Interactions response format.

	Args:
		response_modalities (Optional[str]): Jeni response-mode value.
		image_only (bool): Whether image output must be included.

	Returns:
		List[str]: Normalized response modes.

	Raises:
		Error: Raised when response-mode normalization fails.
	"""
	try:
		self.response_mode = response_modalities
		self.image_only = image_only
		self.mode_name = str( self.response_mode or '' ).strip( ).lower( )
		if self.mode_name == 'text_and_image':
			return [ 'text', 'image', ]

		if self.mode_name == 'text':
			return [ 'text', ]

		if self.mode_name == 'image':
			return [ 'image', ]

		if self.image_only:
			return [ 'image', ]

		return [ 'text', ]
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('normalize_response_modalities( self, response_modalities: '
		                    'Optional[str], image_only: bool ) -> List[str]')
		Logger( ).write( exception )
		raise exception

get_image_mime_type

get_image_mime_type(path: str) -> str

Return the MIME type for a local image.

Purpose

Uses the local file suffix to produce the image MIME type required by an Interactions image-content block.

Parameters:

Name Type Description Default
path str

Local image path.

required

Returns:

Name Type Description
str str

Image MIME type.

Raises:

Type Description
Error

Raised when validation or MIME-type resolution fails.

ValueError

Raised when path is missing.

Source code in gemini.py
def get_image_mime_type( self, path: str ) -> str:
	"""Return the MIME type for a local image.

	Purpose:
		Uses the local file suffix to produce the image MIME type required by an
		Interactions image-content block.

	Args:
		path (str): Local image path.

	Returns:
		str: Image MIME type.

	Raises:
		Error: Raised when validation or MIME-type resolution fails.
		ValueError: Raised when ``path`` is missing.
	"""
	try:
		throw_if( 'path', path )
		self.file_path = path
		self.file_suffix = Path( self.file_path ).suffix.lower( )
		if self.file_suffix in ('.jpg', '.jpeg'):
			return 'image/jpeg'

		if self.file_suffix == '.webp':
			return 'image/webp'

		if self.file_suffix == '.gif':
			return 'image/gif'

		return 'image/png'
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = 'get_image_mime_type( self, path: str ) -> str'
		Logger( ).write( exception )
		raise exception

build_image_input

build_image_input(
    prompt: str, path: Optional[str] = None
) -> List[Dict[str, Any]]

Build Interactions text and image input.

Purpose

Creates a text content block and, when supplied, a base64-encoded local image content block for image analysis or editing.

Parameters:

Name Type Description Default
prompt str

Image-generation, analysis, or editing instruction.

required
path Optional[str]

Optional local image path.

None

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Interactions-compatible input content.

Raises:

Type Description
Error

Raised when validation, file reading, or input construction fails.

ValueError

Raised when prompt is missing.

Source code in gemini.py
def build_image_input( self, prompt: str, path: Optional[ str ] = None ) -> List[
	Dict[ str, Any ] ]:
	"""Build Interactions text and image input.

	Purpose:
		Creates a text content block and, when supplied, a base64-encoded local image
		content block for image analysis or editing.

	Args:
		prompt (str): Image-generation, analysis, or editing instruction.
		path (Optional[str]): Optional local image path.

	Returns:
		List[Dict[str, Any]]: Interactions-compatible input content.

	Raises:
		Error: Raised when validation, file reading, or input construction fails.
		ValueError: Raised when ``prompt`` is missing.
	"""
	try:
		throw_if( 'prompt', prompt )
		self.prompt = prompt
		self.file_path = path
		self.input_content = [ { 'type': 'text', 'text': self.prompt.strip( ), }, ]
		if self.file_path:
			self.image_bytes = Path( self.file_path ).read_bytes( )
			throw_if( 'image_bytes', self.image_bytes )
			self.image_data = base64.b64encode( self.image_bytes ).decode( 'utf-8' )
			self.image_mime_type = self.get_image_mime_type( self.file_path )
			self.input_content.append( { 'type': 'image', 'data': self.image_data,
				'mime_type': self.image_mime_type, } )

		return self.input_content
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('build_image_input( self, prompt: str, path: Optional[str] ) -> '
		                    'List[Dict[str, Any]]')
		Logger( ).write( exception )
		raise exception

build_generation_config

build_generation_config(
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
) -> Dict[str, Any]

Build the Interactions image generation configuration.

Purpose

Converts supported Jeni inference values into the Interactions generation configuration.

Parameters:

Name Type Description Default
temperature Optional[float]

Sampling temperature.

None
top_p Optional[float]

Top-p sampling value.

None
max_tokens Optional[int]

Maximum output-token count.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Interactions generation configuration.

Raises:

Type Description
Error

Raised when generation configuration construction fails.

Source code in gemini.py
def build_generation_config( self, temperature: Optional[ float ] = None,
	top_p: Optional[ float ] = None, max_tokens: Optional[ int ] = None ) -> Dict[ str, Any ]:
	"""Build the Interactions image generation configuration.

	Purpose:
		Converts supported Jeni inference values into the Interactions generation
		configuration.

	Args:
		temperature (Optional[float]): Sampling temperature.
		top_p (Optional[float]): Top-p sampling value.
		max_tokens (Optional[int]): Maximum output-token count.

	Returns:
		Dict[str, Any]: Interactions generation configuration.

	Raises:
		Error: Raised when generation configuration construction fails.
	"""
	try:
		self.temperature = temperature
		self.top_p = top_p
		self.max_output_tokens = max_tokens
		self.generation_config = { }
		if self.temperature is not None:
			self.generation_config[ 'temperature' ] = self.temperature

		if self.top_p is not None:
			self.generation_config[ 'top_p' ] = self.top_p

		if self.max_output_tokens is not None and self.max_output_tokens > 0:
			self.generation_config[ 'max_output_tokens' ] = (self.max_output_tokens)

		return self.generation_config
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('build_generation_config( self, temperature: Optional[float], '
		                    'top_p: Optional[float], max_tokens: Optional[int] ) -> Dict[str, '
		                    'Any]')
		Logger( ).write( exception )
		raise exception

build_response_format

build_response_format(
    response_modalities: Optional[str],
    image_only: bool = False,
    aspect: Optional[str] = None,
    resolution: Optional[str] = None,
    output_mime_type: Optional[str] = None,
) -> Any

Build the Interactions image response format.

Purpose

Constructs text, image, or combined response formats and applies supported image MIME type, aspect ratio, and output-size settings to the image format.

Parameters:

Name Type Description Default
response_modalities Optional[str]

Jeni response-mode value.

required
image_only bool

Whether image output must be included.

False
aspect Optional[str]

Requested output-image aspect ratio.

None
resolution Optional[str]

Requested output-image size.

None
output_mime_type Optional[str]

Requested generated-image MIME type.

None

Returns:

Name Type Description
Any Any

Interactions response-format object or list.

Raises:

Type Description
Error

Raised when response-format construction fails.

Source code in gemini.py
def build_response_format( self, response_modalities: Optional[ str ], image_only: bool =
False,
	aspect: Optional[ str ] = None, resolution: Optional[ str ] = None,
	output_mime_type: Optional[ str ] = None ) -> Any:
	"""Build the Interactions image response format.

	Purpose:
		Constructs text, image, or combined response formats and applies supported image
		MIME type, aspect ratio, and output-size settings to the image format.

	Args:
		response_modalities (Optional[str]): Jeni response-mode value.
		image_only (bool): Whether image output must be included.
		aspect (Optional[str]): Requested output-image aspect ratio.
		resolution (Optional[str]): Requested output-image size.
		output_mime_type (Optional[str]): Requested generated-image MIME type.

	Returns:
		Any: Interactions response-format object or list.

	Raises:
		Error: Raised when response-format construction fails.
	"""
	try:
		self.response_mode = response_modalities
		self.image_only = image_only
		self.aspect_ratio = aspect
		self.size = resolution
		self.output_mime_type = output_mime_type
		self.response_modalities = self.normalize_response_modalities(
			response_modalities=self.response_mode, image_only=self.image_only )
		self.response_formats: List[ Dict[ str, Any ] ] = [ ]
		for modality in self.response_modalities:
			if modality == 'text':
				self.response_formats.append( { 'type': 'text', } )

			elif modality == 'image':
				self.image_format: Dict[ str, Any ] = { 'type': 'image', }
				if self.output_mime_type:
					self.image_format[ 'mime_type' ] = (self.output_mime_type)

				if self.aspect_ratio:
					self.image_format[ 'aspect_ratio' ] = (self.aspect_ratio)

				if (self.size and self.supports_image_size( self.model )):
					self.image_format[ 'image_size' ] = self.size

				self.response_formats.append( self.image_format )

		if len( self.response_formats ) == 1:
			self.response_format_value = self.response_formats[ 0 ]
		else:
			self.response_format_value = self.response_formats

		return self.response_format_value
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('build_response_format( self, response_modalities: Optional[str], '
		                    'image_only: bool, aspect: Optional[str], resolution: Optional['
		                    'str], output_mime_type: Optional[str] ) -> Any')
		Logger( ).write( exception )
		raise exception

build_grounding_tools

build_grounding_tools(
    grounded: bool = False, image_search: bool = False
) -> List[Dict[str, Any]]

Build image grounding tool declarations.

Purpose

Creates the Interactions Google Search tool declaration for web grounding and optionally enables Google Image Search when supported by the selected model.

Parameters:

Name Type Description Default
grounded bool

Whether Google Web Search grounding is enabled.

False
image_search bool

Whether Google Image Search grounding is enabled.

False

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Interactions tool declarations.

Raises:

Type Description
Error

Raised when grounding-tool construction fails.

Source code in gemini.py
def build_grounding_tools( self, grounded: bool = False, image_search: bool = False ) -> List[
	Dict[ str, Any ] ]:
	"""Build image grounding tool declarations.

	Purpose:
		Creates the Interactions Google Search tool declaration for web grounding and
		optionally enables Google Image Search when supported by the selected model.

	Args:
		grounded (bool): Whether Google Web Search grounding is enabled.
		image_search (bool): Whether Google Image Search grounding is enabled.

	Returns:
		List[Dict[str, Any]]: Interactions tool declarations.

	Raises:
		Error: Raised when grounding-tool construction fails.
	"""
	try:
		self.grounded = grounded
		self.image_search = image_search
		self.tool_objects = [ ]
		if not self.grounded and not self.image_search:
			return self.tool_objects

		if not self.supports_search_grounding( self.model ):
			return self.tool_objects

		self.search_types: List[ str ] = [ ]
		if self.grounded:
			self.search_types.append( 'web_search' )

		if (self.image_search and self.supports_image_search( self.model )):
			self.search_types.append( 'image_search' )

		self.search_tool: Dict[ str, Any ] = { 'type': 'google_search', }

		if self.search_types:
			self.search_tool[ 'search_types' ] = self.search_types

		self.tool_objects.append( self.search_tool )
		return self.tool_objects
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('build_grounding_tools( self, grounded: bool, image_search: bool ) '
		                    '-> List[Dict[str, Any]]')
		Logger( ).write( exception )
		raise exception

extract_image

extract_image(interaction: Any) -> Optional[Image]

Extract a generated image from an Interaction.

Purpose

Reads the SDK output_image convenience property, decodes its base64 content, and returns an independent Pillow image object.

Parameters:

Name Type Description Default
interaction Any

Completed Gemini Interaction.

required

Returns:

Type Description
Optional[Image]

Optional[PIL.Image.Image]: Generated image, or None when no image was returned.

Raises:

Type Description
Error

Raised when validation or image extraction fails.

ValueError

Raised when interaction is missing.

Source code in gemini.py
def extract_image( self, interaction: Any ) -> Optional[ PIL.Image.Image ]:
	"""Extract a generated image from an Interaction.

	Purpose:
		Reads the SDK ``output_image`` convenience property, decodes its base64 content,
		and returns an independent Pillow image object.

	Args:
		interaction (Any): Completed Gemini Interaction.

	Returns:
		Optional[PIL.Image.Image]: Generated image, or None when no image was returned.

	Raises:
		Error: Raised when validation or image extraction fails.
		ValueError: Raised when ``interaction`` is missing.
	"""
	try:
		throw_if( 'interaction', interaction )
		self.interaction = interaction
		self.output_image_content = getattr( self.interaction, 'output_image', None )
		if self.output_image_content is None:
			return None

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

		self.decoded_image = base64.b64decode( self.output_image_data )
		with PIL.Image.open( io.BytesIO( self.decoded_image ) ) as source:
			return source.copy( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = 'extract_image( self, interaction: Any ) -> Optional[ Image ]'
		Logger( ).write( exception )
		raise exception

extract_text

extract_text(interaction: Any) -> Optional[str]

Extract generated text from an Interaction.

Purpose

Reads the Interactions SDK output_text convenience property and returns the normalized text expected by the Jeni image-analysis workflow.

Parameters:

Name Type Description Default
interaction Any

Completed Gemini Interaction.

required

Returns:

Type Description
Optional[str]

Optional[str]: Generated text, or None when no text was returned.

Raises:

Type Description
Error

Raised when validation or text extraction fails.

ValueError

Raised when interaction is missing.

Source code in gemini.py
def extract_text( self, interaction: Any ) -> Optional[ str ]:
	"""Extract generated text from an Interaction.

	Purpose:
		Reads the Interactions SDK ``output_text`` convenience property and returns the
		normalized text expected by the Jeni image-analysis workflow.

	Args:
		interaction (Any): Completed Gemini Interaction.

	Returns:
		Optional[str]: Generated text, or None when no text was returned.

	Raises:
		Error: Raised when validation or text extraction fails.
		ValueError: Raised when ``interaction`` is missing.
	"""
	try:
		throw_if( 'interaction', interaction )
		self.interaction = interaction
		self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
		return self.output_text or None
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('extract_text( self, interaction: Any ) -> Optional[ str ]')
		Logger( ).write( exception )
		raise exception

capture_metadata

capture_metadata() -> None

Capture grounding information from the latest Interaction.

Purpose

Retains the latest Interaction steps and Google Search result metadata for application display and diagnostics.

Returns:

Name Type Description
None None

This method updates response state through side effects.

Raises:

Type Description
Error

Raised when grounding metadata cannot be captured.

Source code in gemini.py
def capture_metadata( self ) -> None:
	"""Capture grounding information from the latest Interaction.

	Purpose:
		Retains the latest Interaction steps and Google Search result metadata for
		application display and diagnostics.

	Returns:
		None: This method updates response state through side effects.

	Raises:
		Error: Raised when grounding metadata cannot be captured.
	"""
	try:
		self.grounding_metadata = None
		self.grounding_sources = [ ]

		if self.interaction is None:
			return

		self.steps = getattr( self.interaction, 'steps', None ) or [ ]
		for step in self.steps:
			self.step_type = str( getattr( step, 'type', '' ) or '' ).strip( )
			if self.step_type != 'google_search_result':
				continue

			self.result = getattr( step, 'result', None )
			self.grounding_sources.append( { 'type': self.step_type, 'result': self.result, } )

		if self.grounding_sources:
			self.grounding_metadata = self.grounding_sources
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = 'capture_metadata( self ) -> None'
		Logger( ).write( exception )
		raise exception

execute_interaction

execute_interaction(
    prompt: str,
    model: str,
    path: Optional[str] = None,
    aspect: Optional[str] = None,
    number: Optional[int] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    frequency: Optional[float] = None,
    presence: Optional[float] = None,
    max_tokens: Optional[int] = None,
    resolution: Optional[str] = None,
    instruct: Optional[str] = None,
    output_mime_type: Optional[str] = None,
    response_modalities: Optional[str] = None,
    image_only: bool = False,
    grounded: bool = False,
    image_search: bool = False,
) -> Any

Execute an image Interaction.

Purpose

Validates required inputs, creates the Gemini client, builds multimodal input, generation settings, output formats, and grounding tools, submits the request, and captures the response state shared by generation, analysis, and editing workflows.

Parameters:

Name Type Description Default
prompt str

Image-generation, analysis, or editing instruction.

required
model str

Gemini image-model identifier.

required
path Optional[str]

Optional local image path.

None
aspect Optional[str]

Requested output-image aspect ratio.

None
number Optional[int]

Requested result count retained for compatibility.

None
temperature Optional[float]

Sampling temperature.

None
top_p Optional[float]

Top-p sampling value.

None
frequency Optional[float]

Frequency penalty retained for compatibility.

None
presence Optional[float]

Presence penalty retained for compatibility.

None
max_tokens Optional[int]

Maximum output-token count.

None
resolution Optional[str]

Requested generated-image size.

None
instruct Optional[str]

System instruction text.

None
output_mime_type Optional[str]

Requested generated-image MIME type.

None
response_modalities Optional[str]

Requested response-mode value.

None
image_only bool

Whether image output must be included.

False
grounded bool

Whether Google Search grounding is enabled.

False
image_search bool

Whether Google Image Search grounding is enabled.

False

Returns:

Name Type Description
Any Any

Completed Gemini Interaction.

Raises:

Type Description
Error

Raised when validation, request construction, or provider execution fails.

ValueError

Raised when prompt, model, or the API key is missing.

Source code in gemini.py
def execute_interaction( self, prompt: str, model: str, path: Optional[ str ] = None,
	aspect: Optional[ str ] = None, number: Optional[ int ] = None,
	temperature: Optional[ float ] = None, top_p: Optional[ float ] = None,
	frequency: Optional[ float ] = None, presence: Optional[ float ] = None,
	max_tokens: Optional[ int ] = None, resolution: Optional[ str ] = None,
	instruct: Optional[ str ] = None, output_mime_type: Optional[ str ] = None,
	response_modalities: Optional[ str ] = None, image_only: bool = False,
	grounded: bool = False, image_search: bool = False ) -> Any:
	"""Execute an image Interaction.

	Purpose:
		Validates required inputs, creates the Gemini client, builds multimodal input,
		generation settings, output formats, and grounding tools, submits the request, and
		captures the response state shared by generation, analysis, and editing workflows.

	Args:
		prompt (str): Image-generation, analysis, or editing instruction.
		model (str): Gemini image-model identifier.
		path (Optional[str]): Optional local image path.
		aspect (Optional[str]): Requested output-image aspect ratio.
		number (Optional[int]): Requested result count retained for compatibility.
		temperature (Optional[float]): Sampling temperature.
		top_p (Optional[float]): Top-p sampling value.
		frequency (Optional[float]): Frequency penalty retained for compatibility.
		presence (Optional[float]): Presence penalty retained for compatibility.
		max_tokens (Optional[int]): Maximum output-token count.
		resolution (Optional[str]): Requested generated-image size.
		instruct (Optional[str]): System instruction text.
		output_mime_type (Optional[str]): Requested generated-image MIME type.
		response_modalities (Optional[str]): Requested response-mode value.
		image_only (bool): Whether image output must be included.
		grounded (bool): Whether Google Search grounding is enabled.
		image_search (bool): Whether Google Image Search grounding is enabled.

	Returns:
		Any: Completed Gemini Interaction.

	Raises:
		Error: Raised when validation, request construction, or provider execution fails.
		ValueError: Raised when ``prompt``, ``model``, or the API key is missing.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.prompt = prompt
		self.model = model
		self.file_path = path
		self.aspect_ratio = aspect
		self.number = number
		self.temperature = temperature
		self.top_p = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_output_tokens = max_tokens
		self.size = resolution
		self.instructions = instruct
		self.output_mime_type = output_mime_type
		self.response_mode = response_modalities
		self.image_only = image_only
		self.grounded = grounded
		self.image_search = image_search
		self.api_key = self.gemini_api_key or self.google_api_key
		self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )
		self.input_content = self.build_image_input( prompt=self.prompt, path=self.file_path )
		self.generation_config = self.build_generation_config( temperature=self.temperature,
			top_p=self.top_p, max_tokens=self.max_output_tokens )

		self.response_format_value = self.build_response_format(
			response_modalities=self.response_mode, image_only=self.image_only,
			aspect=self.aspect_ratio, resolution=self.size,
			output_mime_type=self.output_mime_type )

		self.tool_objects = self.build_grounding_tools( grounded=self.grounded,
			image_search=self.image_search )

		self.request: Dict[ str, Any ] = { 'model': self.model, 'input': self.input_content,
			'response_format': self.response_format_value, 'store': False, }

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

		if self.generation_config:
			self.request[ 'generation_config' ] = (self.generation_config)

		if self.tool_objects:
			self.request[ 'tools' ] = self.tool_objects

		self.interaction = self.client.interactions.create( **self.request )
		self.response = self.interaction
		self.content_response = self.interaction
		self.image_response = self.interaction
		self.capture_metadata( )
		return self.interaction
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('execute_interaction( self, prompt: str, model: str, '
		                    'path: Optional[str], aspect: Optional[str], number: Optional['
		                    'int], temperature: Optional[float], top_p: Optional[float], '
		                    'frequency: Optional[float], presence: Optional[float], '
		                    'max_tokens: Optional[int], resolution: Optional[str], instruct: '
		                    'Optional[str], output_mime_type: Optional[str], '
		                    'response_modalities: Optional[str], image_only: bool, grounded: '
		                    'bool, image_search: bool ) -> Any')
		Logger( ).write( exception )
		raise exception

get_first_image

get_first_image() -> Optional[Image]

Return the image from the most recent Interaction.

Purpose

Preserves the existing Jeni helper contract by extracting the generated image from the latest Interaction.

Returns:

Type Description
Optional[Image]

Optional[PIL.Image.Image]: Generated image, or None when unavailable.

Raises:

Type Description
Error

Raised when image extraction fails.

Source code in gemini.py
def get_first_image( self ) -> Optional[ PIL.Image.Image ]:
	"""Return the image from the most recent Interaction.

	Purpose:
		Preserves the existing Jeni helper contract by extracting the generated image from
		the latest Interaction.

	Returns:
		Optional[PIL.Image.Image]: Generated image, or None when unavailable.

	Raises:
		Error: Raised when image extraction fails.
	"""
	try:
		if self.interaction is None:
			return None

		return self.extract_image( self.interaction )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('get_first_image( self ) -> Optional[ PIL.Image.Image ]')
		Logger( ).write( exception )
		raise exception

get_output_text

get_output_text() -> Optional[str]

Return text from the most recent Interaction.

Purpose

Preserves the existing Jeni helper contract by extracting generated text from the latest Interaction.

Returns:

Type Description
Optional[str]

Optional[str]: Generated text, or None when unavailable.

Raises:

Type Description
Error

Raised when text extraction fails.

Source code in gemini.py
def get_output_text( self ) -> Optional[ str ]:
	"""Return text from the most recent Interaction.

	Purpose:
		Preserves the existing Jeni helper contract by extracting generated text from the
		latest Interaction.

	Returns:
		Optional[str]: Generated text, or None when unavailable.

	Raises:
		Error: Raised when text extraction fails.
	"""
	try:
		if self.interaction is None:
			return None

		return self.extract_text( self.interaction )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('get_output_text( self ) -> Optional[ str ]')
		Logger( ).write( exception )
		raise exception

generate

generate(
    prompt: str,
    model: str = "gemini-3.1-flash-image",
    aspect: str = None,
    number: int = None,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    resolution: str = None,
    instruct: str = None,
    output_mime_type: str = None,
    response_modalities: str = None,
    grounded: bool = False,
    image_search: bool = False,
) -> Optional[Image]

Generate an image through the Gemini Interactions API.

Purpose

Submits a text-to-image Interaction and returns the generated Pillow image expected by the Jeni Image Generation workflow.

Parameters:

Name Type Description Default
prompt str

Image-generation instruction.

required
model str

Gemini image-model identifier.

'gemini-3.1-flash-image'
aspect str

Requested output-image aspect ratio.

None
number int

Requested result count retained for compatibility.

None
temperature float

Sampling temperature.

None
top_p float

Top-p sampling value.

None
frequency float

Frequency penalty retained for compatibility.

None
presence float

Presence penalty retained for compatibility.

None
max_tokens int

Maximum output-token count.

None
resolution str

Requested generated-image size.

None
instruct str

System instruction text.

None
output_mime_type str

Requested generated-image MIME type.

None
response_modalities str

Requested response-mode value.

None
grounded bool

Whether Google Search grounding is enabled.

False
image_search bool

Whether Google Image Search grounding is enabled.

False

Returns:

Type Description
Optional[Image]

Optional[PIL.Image.Image]: Generated image, or None when no image is returned.

Raises:

Type Description
Error

Raised when request execution or image extraction fails.

ValueError

Raised when a required argument is missing.

Source code in gemini.py
def generate( self, prompt: str, model: str='gemini-3.1-flash-image', aspect: str=None,
	number: int=None, temperature: float=None, top_p: float=None, frequency: float =
	None,
	presence: float=None, max_tokens: int=None, resolution: str=None,
	instruct: str=None, output_mime_type: str=None, response_modalities: str=None,
	grounded: bool = False, image_search: bool = False ) -> Optional[ PIL.Image.Image ]:
	"""Generate an image through the Gemini Interactions API.

	Purpose:
		Submits a text-to-image Interaction and returns the generated Pillow image expected
		by the Jeni Image Generation workflow.

	Args:
		prompt (str): Image-generation instruction.
		model (str): Gemini image-model identifier.
		aspect (str): Requested output-image aspect ratio.
		number (int): Requested result count retained for compatibility.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		frequency (float): Frequency penalty retained for compatibility.
		presence (float): Presence penalty retained for compatibility.
		max_tokens (int): Maximum output-token count.
		resolution (str): Requested generated-image size.
		instruct (str): System instruction text.
		output_mime_type (str): Requested generated-image MIME type.
		response_modalities (str): Requested response-mode value.
		grounded (bool): Whether Google Search grounding is enabled.
		image_search (bool): Whether Google Image Search grounding is enabled.

	Returns:
		Optional[PIL.Image.Image]: Generated image, or None when no image is returned.

	Raises:
		Error: Raised when request execution or image extraction fails.
		ValueError: Raised when a required argument is missing.
	"""
	try:
		self.interaction = self.execute_interaction( prompt=prompt, model=model, path=None,
			aspect=aspect, number=number, temperature=temperature, top_p=top_p,
			frequency=frequency, presence=presence, max_tokens=max_tokens,
			resolution=resolution, instruct=instruct, output_mime_type=output_mime_type,
			response_modalities=response_modalities, image_only=True, grounded=grounded,
			image_search=image_search )

		return self.extract_image( self.interaction )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('generate( self, prompt: str, model: str, aspect: str, number: int, '
		                    'temperature: float, top_p: float, frequency: float, presence: '
		                    'float, max_tokens: int, resolution: str, instruct: str, '
		                    'output_mime_type: str, response_modalities: str, grounded: bool, '
		                    'image_search: bool ) -> Optional[PIL.Image.Image]')
		Logger( ).write( exception )
		raise exception

analyze

analyze(
    prompt: str,
    path: str,
    model: str = "gemini-3.1-flash-image",
    aspect: str = None,
    number: int = None,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    resolution: str = None,
    instruct: str = None,
    output_mime_type: str = None,
    response_modalities: str = None,
    grounded: bool = False,
    image_search: bool = False,
) -> Optional[str]

Analyze an image through the Gemini Interactions API.

Purpose

Submits text and a local image as multimodal Interaction input and returns the generated text expected by the Jeni Image Analysis workflow.

Parameters:

Name Type Description Default
prompt str

Image-analysis instruction.

required
path str

Local image path.

required
model str

Gemini image-model identifier.

'gemini-3.1-flash-image'
aspect str

Aspect-ratio value retained for compatibility.

None
number int

Requested result count retained for compatibility.

None
temperature float

Sampling temperature.

None
top_p float

Top-p sampling value.

None
frequency float

Frequency penalty retained for compatibility.

None
presence float

Presence penalty retained for compatibility.

None
max_tokens int

Maximum output-token count.

None
resolution str

Media-resolution value retained for compatibility.

None
instruct str

System instruction text.

None
output_mime_type str

Output MIME type retained for compatibility.

None
response_modalities str

Requested response-mode value.

None
grounded bool

Whether Google Search grounding is enabled.

False
image_search bool

Whether Google Image Search grounding is enabled.

False

Returns:

Type Description
Optional[str]

Optional[str]: Generated image analysis, or None when no text is returned.

Raises:

Type Description
Error

Raised when request execution or text extraction fails.

ValueError

Raised when a required argument is missing.

Source code in gemini.py
def analyze( self, prompt: str, path: str, model: str='gemini-3.1-flash-image',
	aspect: str=None, number: int=None, temperature: float=None, top_p: float=None,
	frequency: float=None, presence: float=None, max_tokens: int=None,
	resolution: str=None, instruct: str=None, output_mime_type: str=None,
	response_modalities: str=None, grounded: bool = False, image_search: bool = False ) -> \
Optional[ str ]:
	"""Analyze an image through the Gemini Interactions API.

	Purpose:
		Submits text and a local image as multimodal Interaction input and returns the
		generated text expected by the Jeni Image Analysis workflow.

	Args:
		prompt (str): Image-analysis instruction.
		path (str): Local image path.
		model (str): Gemini image-model identifier.
		aspect (str): Aspect-ratio value retained for compatibility.
		number (int): Requested result count retained for compatibility.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		frequency (float): Frequency penalty retained for compatibility.
		presence (float): Presence penalty retained for compatibility.
		max_tokens (int): Maximum output-token count.
		resolution (str): Media-resolution value retained for compatibility.
		instruct (str): System instruction text.
		output_mime_type (str): Output MIME type retained for compatibility.
		response_modalities (str): Requested response-mode value.
		grounded (bool): Whether Google Search grounding is enabled.
		image_search (bool): Whether Google Image Search grounding is enabled.

	Returns:
		Optional[str]: Generated image analysis, or None when no text is returned.

	Raises:
		Error: Raised when request execution or text extraction fails.
		ValueError: Raised when a required argument is missing.
	"""
	try:
		throw_if( 'path', path )
		self.file_path = path
		self.interaction = self.execute_interaction( prompt=prompt, model=model,
			path=self.file_path, aspect=aspect, number=number, temperature=temperature,
			top_p=top_p, frequency=frequency, presence=presence, max_tokens=max_tokens,
			resolution=resolution, instruct=instruct, output_mime_type=output_mime_type,
			response_modalities=response_modalities or 'text', image_only=False,
			grounded=grounded, image_search=image_search )

		return self.extract_text( self.interaction )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('analyze( self, **kwargs ) -> Optional[str]')
		Logger( ).write( exception )
		raise exception

edit

edit(
    prompt: str,
    path: str,
    model: str = "gemini-3.1-flash-image",
    aspect: str = None,
    number: int = None,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    resolution: str = None,
    instruct: str = None,
    output_mime_type: str = None,
    response_modalities: str = None,
    grounded: bool = False,
    image_search: bool = False,
) -> Image

Edit an image through the Gemini Interactions API.

Purpose

Submits an editing instruction and local image as multimodal Interaction input and returns the generated Pillow image expected by the Jeni Image Editing workflow.

Parameters:

Name Type Description Default
prompt str

Image-editing instruction.

required
path str

Local source-image path.

required
model str

Gemini image-model identifier.

'gemini-3.1-flash-image'
aspect str

Requested output-image aspect ratio.

None
number int

Requested result count retained for compatibility.

None
temperature float

Sampling temperature.

None
top_p float

Top-p sampling value.

None
frequency float

Frequency penalty retained for compatibility.

None
presence float

Presence penalty retained for compatibility.

None
max_tokens int

Maximum output-token count.

None
resolution str

Requested generated-image size.

None
instruct str

System instruction text.

None
output_mime_type str

Requested generated-image MIME type.

None
response_modalities str

Requested response-mode value.

None
grounded bool

Whether Google Search grounding is enabled.

False
image_search bool

Whether Google Image Search grounding is enabled.

False

Returns:

Type Description
Image

Optional[PIL.Image.Image]: Edited image, or None when no image is returned.

Raises:

Type Description
Error

Raised when request execution or image extraction fails.

ValueError

Raised when a required argument is missing.

Source code in gemini.py
def edit( self, prompt: str, path: str, model: str='gemini-3.1-flash-image',
	aspect: str=None, number: int=None, temperature: float=None, top_p: float=None,
	frequency: float=None, presence: float=None, max_tokens: int=None,
	resolution: str=None, instruct: str=None, output_mime_type: str=None,
	response_modalities: str=None, grounded: bool=False, image_search: bool=False ) -> Image:
	"""Edit an image through the Gemini Interactions API.

	Purpose:
		Submits an editing instruction and local image as multimodal Interaction input and
		returns the generated Pillow image expected by the Jeni Image Editing workflow.

	Args:
		prompt (str): Image-editing instruction.
		path (str): Local source-image path.
		model (str): Gemini image-model identifier.
		aspect (str): Requested output-image aspect ratio.
		number (int): Requested result count retained for compatibility.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		frequency (float): Frequency penalty retained for compatibility.
		presence (float): Presence penalty retained for compatibility.
		max_tokens (int): Maximum output-token count.
		resolution (str): Requested generated-image size.
		instruct (str): System instruction text.
		output_mime_type (str): Requested generated-image MIME type.
		response_modalities (str): Requested response-mode value.
		grounded (bool): Whether Google Search grounding is enabled.
		image_search (bool): Whether Google Image Search grounding is enabled.

	Returns:
		Optional[PIL.Image.Image]: Edited image, or None when no image is returned.

	Raises:
		Error: Raised when request execution or image extraction fails.
		ValueError: Raised when a required argument is missing.
	"""
	try:
		throw_if( 'path', path )
		self.file_path = path
		self.interaction = self.execute_interaction( prompt=prompt, model=model,
			path=self.file_path, aspect=aspect, number=number, temperature=temperature,
			top_p=top_p, frequency=frequency, presence=presence, max_tokens=max_tokens,
			resolution=resolution, instruct=instruct, output_mime_type=output_mime_type,
			response_modalities=response_modalities or 'image', image_only=True,
			grounded=grounded, image_search=image_search )

		return self.extract_image( self.interaction )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Images'
		exception.method = ('edit( self, **kwargs ) -> Optional[PIL.Image.Image]')
		Logger( ).write( exception )
		raise exception

Embeddings

Bases: Gemini

Gemini embedding wrapper.

Purpose

Creates numerical vector representations of text through the Gemini embeddings API. The class validates and normalizes text input, builds provider-supported embedding configuration, executes the specialized models.embed_content() operation, and extracts vectors from the returned embedding response.

Attributes:

Name Type Description
client Optional[Client]

Active Google Gen AI client.

response Optional[EmbedContentResponse]

Most recent embedding response.

embedding Optional[List[float] | List[List[float]]]

Extracted embedding result.

embeddings Optional[List[List[float]]]

Extracted embedding vectors.

encoding_format str

Application-facing embedding encoding selection.

dimensions Optional[int]

Requested output dimensionality.

task_type Optional[str]

Embedding task type.

title Optional[str]

Retrieval-document title.

embedding_config Optional[EmbedContentConfig]

Embedding request configuration.

contents Optional[str | List[str]]

Normalized provider input.

input_text Optional[str | List[str]]

Original normalized text input.

Source code in gemini.py
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
2653
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
class Embeddings( Gemini ):
	"""Gemini embedding wrapper.

	Purpose:
		Creates numerical vector representations of text through the Gemini embeddings API.
		The class validates and normalizes text input, builds provider-supported embedding
		configuration, executes the specialized ``models.embed_content()`` operation, and
		extracts vectors from the returned embedding response.

	Attributes:
		client (Optional[genai.Client]): Active Google Gen AI client.
		response (Optional[EmbedContentResponse]): Most recent embedding response.
		embedding (Optional[List[float] | List[List[float]]]): Extracted embedding result.
		embeddings (Optional[List[List[float]]]): Extracted embedding vectors.
		encoding_format (str): Application-facing embedding encoding selection.
		dimensions (Optional[int]): Requested output dimensionality.
		task_type (Optional[str]): Embedding task type.
		title (Optional[str]): Retrieval-document title.
		embedding_config (Optional[EmbedContentConfig]): Embedding request configuration.
		contents (Optional[str | List[str]]): Normalized provider input.
		input_text (Optional[str | List[str]]): Original normalized text input.
	"""

	client: Optional[ genai.Client ]
	response: Optional[ EmbedContentResponse ]
	embedding: Optional[ List[ float ] | List[ List[ float ] ] ]
	embeddings: Optional[ List[ List[ float ] ] ]
	encoding_format: str
	dimensions: Optional[ int ]
	task_type: Optional[ str ]
	title: Optional[ str ]
	embedding_config: Optional[ EmbedContentConfig ]
	contents: Optional[ str | List[ str ] ]
	input_text: Optional[ str | List[ str ] ]

	def __init__( self, model: str='gemini-embedding-2' ) -> None:
		"""Initialize the embeddings wrapper.

		Purpose:
			Initializes the embedding model, request configuration, input state, response state,
			and extracted-vector placeholders. The constructor performs local assignment only.

		Args:
			model (str): Default Gemini embedding model.

		Returns:
			None: This method initializes object state through side effects.
		"""
		super( ).__init__( )
		self.model = model
		self.client = None
		self.response = None
		self.embedding = None
		self.embeddings = None
		self.encoding_format = 'float'
		self.dimensions = None
		self.task_type = None
		self.title = None
		self.embedding_config = None
		self.contents = None
		self.input_text = None
		self.api_key = None

	@property
	def model_options( self ) -> List[ str ]:
		"""Return supported Gemini embedding models.

		Purpose:
			Provides the active embedding model identifiers exposed by the Jeni Embeddings mode.

		Returns:
			List[str]: Supported Gemini embedding model identifiers.
		"""
		return [ 'gemini-embedding-2', 'gemini-embedding-001' ]

	@property
	def encoding_options( self ) -> List[ str ]:
		"""Return supported embedding encodings.

		Purpose:
			Provides the native numerical encoding returned by the Gemini embeddings API.

		Returns:
			List[str]: Supported embedding encoding values.
		"""
		return [ 'float' ]

	@property
	def task_options( self ) -> List[ str ]:
		"""Return supported embedding task types.

		Purpose:
			Provides the embedding task types accepted for text embedding requests.

		Returns:
			List[str]: Supported embedding task types.
		"""
		return [ '', 'RETRIEVAL_QUERY', 'RETRIEVAL_DOCUMENT', 'SEMANTIC_SIMILARITY',
			'CLASSIFICATION', 'CLUSTERING', 'QUESTION_ANSWERING', 'FACT_VERIFICATION',
			'CODE_RETRIEVAL_QUERY', ]

	def normalize_dimensions( self, dimensions: int=0 ) -> Optional[ int ]:
		"""Normalize the requested output dimensionality.

		Purpose:
			Converts a zero-valued UI selection into an omitted provider setting and validates
			positive dimensionality values against the range exposed by the application.

		Args:
			dimensions (int): Requested output dimensionality.

		Returns:
			Optional[int]: Positive output dimensionality, or None when omitted.

		Raises:
			Error: Raised when dimensionality validation fails.
			ValueError: Raised when dimensionality exceeds the supported application range.
		"""
		try:
			self.dimensions = dimensions
			if self.dimensions <= 0:
				self.dimensions = None
				return None

			if self.dimensions > 2048:
				raise ValueError( 'Embedding dimensions must be between 1 and 2048.' )

			return self.dimensions
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Embeddings'
			exception.method = ('normalize_dimensions( self, dimensions: int ) -> Optional[ int ]')
			Logger( ).write( exception )
			raise exception

	def normalize_contents( self, text: str | List[ str ] ) -> str | List[ str ]:
		"""Normalize embedding input.

		Purpose:
			Removes blank values while preserving whether the caller supplied one string or a
			list of independent strings.

		Args:
			text (str | List[str]): Text or text values to embed.

		Returns:
			str | List[str]: Normalized embedding input.

		Raises:
			Error: Raised when input validation or normalization fails.
			ValueError: Raised when no usable text remains.
		"""
		try:
			throw_if( 'text', text )
			self.input_text = text
			if isinstance( self.input_text, list ):
				self.contents = [ str( item ).strip( ) for item in self.input_text if
					item is not None and str( item ).strip( ) ]
				throw_if( 'text', self.contents )
				return self.contents

			self.contents = str( self.input_text ).strip( )
			throw_if( 'text', self.contents )
			return self.contents
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Embeddings'
			exception.method = ('normalize_contents( self, text: str | List[str] ) -> str | List['
			                    'str]')
			Logger( ).write( exception )
			raise exception

	def build_embedding_config( self, model: str, dimensions: int=0, task_type: str='',
		title: str='' ) -> EmbedContentConfig:
		"""Build the embedding request configuration.

		Purpose:
			Constructs the provider configuration from output dimensionality, task type, and
			retrieval-document title settings supported by the selected embedding model.

		Args:
			model (str): Gemini embedding model identifier.
			dimensions (int): Requested output dimensionality.
			task_type (str): Optional embedding task type.
			title (str): Optional retrieval-document title.

		Returns:
			EmbedContentConfig: Provider embedding configuration.

		Raises:
			Error: Raised when validation or configuration construction fails.
			ValueError: Raised when ``model`` is missing.
		"""
		try:
			throw_if( 'model', model )
			self.model = model
			self.dimensions = self.normalize_dimensions( dimensions )
			self.task_type = str( task_type or '' ).strip( ).upper( )
			self.title = str( title or '' ).strip( )
			self.config_values: Dict[ str, Any ] = { }
			if self.dimensions is not None:
				self.config_values[ 'output_dimensionality' ] = self.dimensions

			if self.task_type:
				self.config_values[ 'task_type' ] = self.task_type

			if self.title and self.task_type == 'RETRIEVAL_DOCUMENT':
				self.config_values[ 'title' ] = self.title

			self.embedding_config = EmbedContentConfig( **self.config_values )
			return self.embedding_config
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Embeddings'
			exception.method = ('build_embedding_config( self, model: str, dimensions: int, '
			                    'task_type: str, title: str ) -> EmbedContentConfig')
			Logger( ).write( exception )
			raise exception

	def extract_embeddings( self ) -> Optional[ List[ float ] | List[ List[ float ] ] ]:
		"""Extract vectors from the embedding response.

		Purpose:
			Converts SDK embedding objects into ordinary lists of floating-point values and
			preserves the single-vector return shape for a single string input.

		Returns:
			Optional[List[float] | List[List[float]]]: Extracted embedding vector or vectors.

		Raises:
			Error: Raised when response extraction fails.
		"""
		try:
			if self.response is None:
				return None

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

			self.embeddings = [ ]
			for item in self.response_embeddings:
				if item is None:
					continue

				self.values = getattr( item, 'values', None )
				if self.values is not None:
					self.embeddings.append( [ float( value ) for value in self.values ] )

			if not self.embeddings:
				return None

			if len( self.embeddings ) == 1 and isinstance( self.input_text, str ):
				self.embedding = self.embeddings[ 0 ]
			else:
				self.embedding = self.embeddings

			return self.embedding
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Embeddings'
			exception.method = 'extract_embeddings( self ) -> Optional[ List[ float ] ]'
			Logger( ).write( exception )
			raise exception

	def create( self, text: str | List[ str ], model: str='gemini-embedding-2',
		dimensions: int=0, task_type: str='', title: str='',
		encoding_format: str='float' ) -> Optional[ List[ float ] | List[ List[ float ] ] ]:
		"""Create text embeddings.

		Purpose:
			Validates and normalizes text input, constructs the provider configuration, executes
			the specialized Gemini embeddings operation, and returns the extracted vector data.

		Args:
			text (str | List[str]): Text or independent text values to embed.
			model (str): Gemini embedding model identifier.
			dimensions (int): Requested output dimensionality.
			task_type (str): Optional embedding task type.
			title (str): Optional retrieval-document title.
			encoding_format (str): Application-facing encoding selection.

		Returns:
			Optional[List[float] | List[List[float]]]: Generated embedding vector or vectors.

		Raises:
			Error: Raised when validation, provider execution, or extraction fails.
			ValueError: Raised when required input, model, API key, or encoding is invalid.
		"""
		try:
			throw_if( 'text', text )
			throw_if( 'model', model )
			self.input_text = text
			self.model = model
			self.dimensions = dimensions
			self.task_type = task_type
			self.title = title
			self.encoding_format = str( encoding_format or 'float' ).strip( ).lower( )
			if self.encoding_format != 'float':
				raise ValueError( 'The Gemini embeddings API returns float vectors only.' )

			self.contents = self.normalize_contents( self.input_text )
			self.embedding_config = self.build_embedding_config( model=self.model,
				dimensions=self.dimensions, task_type=self.task_type, title=self.title )

			self.api_key = self.gemini_api_key or self.google_api_key
			throw_if( 'api_key', self.api_key )

			self.client = genai.Client( api_key=self.api_key )
			self.response = self.client.models.embed_content( model=self.model,
				contents=self.contents, config=self.embedding_config )

			return self.extract_embeddings( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Embeddings'
			exception.method = ('create( self, text: str | List[str], model: str, dimensions: int, '
			                    'task_type: str, title: str, encoding_format: str ) -> Optional['
			                    'List[float] | List[List[float]]]')
			Logger( ).write( exception )
			raise exception

model_options property

model_options: List[str]

Return supported Gemini embedding models.

Purpose

Provides the active embedding model identifiers exposed by the Jeni Embeddings mode.

Returns:

Type Description
List[str]

List[str]: Supported Gemini embedding model identifiers.

encoding_options property

encoding_options: List[str]

Return supported embedding encodings.

Purpose

Provides the native numerical encoding returned by the Gemini embeddings API.

Returns:

Type Description
List[str]

List[str]: Supported embedding encoding values.

task_options property

task_options: List[str]

Return supported embedding task types.

Purpose

Provides the embedding task types accepted for text embedding requests.

Returns:

Type Description
List[str]

List[str]: Supported embedding task types.

__init__

__init__(model: str = 'gemini-embedding-2') -> None

Initialize the embeddings wrapper.

Purpose

Initializes the embedding model, request configuration, input state, response state, and extracted-vector placeholders. The constructor performs local assignment only.

Parameters:

Name Type Description Default
model str

Default Gemini embedding model.

'gemini-embedding-2'

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self, model: str='gemini-embedding-2' ) -> None:
	"""Initialize the embeddings wrapper.

	Purpose:
		Initializes the embedding model, request configuration, input state, response state,
		and extracted-vector placeholders. The constructor performs local assignment only.

	Args:
		model (str): Default Gemini embedding model.

	Returns:
		None: This method initializes object state through side effects.
	"""
	super( ).__init__( )
	self.model = model
	self.client = None
	self.response = None
	self.embedding = None
	self.embeddings = None
	self.encoding_format = 'float'
	self.dimensions = None
	self.task_type = None
	self.title = None
	self.embedding_config = None
	self.contents = None
	self.input_text = None
	self.api_key = None

normalize_dimensions

normalize_dimensions(dimensions: int = 0) -> Optional[int]

Normalize the requested output dimensionality.

Purpose

Converts a zero-valued UI selection into an omitted provider setting and validates positive dimensionality values against the range exposed by the application.

Parameters:

Name Type Description Default
dimensions int

Requested output dimensionality.

0

Returns:

Type Description
Optional[int]

Optional[int]: Positive output dimensionality, or None when omitted.

Raises:

Type Description
Error

Raised when dimensionality validation fails.

ValueError

Raised when dimensionality exceeds the supported application range.

Source code in gemini.py
def normalize_dimensions( self, dimensions: int=0 ) -> Optional[ int ]:
	"""Normalize the requested output dimensionality.

	Purpose:
		Converts a zero-valued UI selection into an omitted provider setting and validates
		positive dimensionality values against the range exposed by the application.

	Args:
		dimensions (int): Requested output dimensionality.

	Returns:
		Optional[int]: Positive output dimensionality, or None when omitted.

	Raises:
		Error: Raised when dimensionality validation fails.
		ValueError: Raised when dimensionality exceeds the supported application range.
	"""
	try:
		self.dimensions = dimensions
		if self.dimensions <= 0:
			self.dimensions = None
			return None

		if self.dimensions > 2048:
			raise ValueError( 'Embedding dimensions must be between 1 and 2048.' )

		return self.dimensions
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Embeddings'
		exception.method = ('normalize_dimensions( self, dimensions: int ) -> Optional[ int ]')
		Logger( ).write( exception )
		raise exception

normalize_contents

normalize_contents(
    text: str | List[str],
) -> str | List[str]

Normalize embedding input.

Purpose

Removes blank values while preserving whether the caller supplied one string or a list of independent strings.

Parameters:

Name Type Description Default
text str | List[str]

Text or text values to embed.

required

Returns:

Type Description
str | List[str]

str | List[str]: Normalized embedding input.

Raises:

Type Description
Error

Raised when input validation or normalization fails.

ValueError

Raised when no usable text remains.

Source code in gemini.py
def normalize_contents( self, text: str | List[ str ] ) -> str | List[ str ]:
	"""Normalize embedding input.

	Purpose:
		Removes blank values while preserving whether the caller supplied one string or a
		list of independent strings.

	Args:
		text (str | List[str]): Text or text values to embed.

	Returns:
		str | List[str]: Normalized embedding input.

	Raises:
		Error: Raised when input validation or normalization fails.
		ValueError: Raised when no usable text remains.
	"""
	try:
		throw_if( 'text', text )
		self.input_text = text
		if isinstance( self.input_text, list ):
			self.contents = [ str( item ).strip( ) for item in self.input_text if
				item is not None and str( item ).strip( ) ]
			throw_if( 'text', self.contents )
			return self.contents

		self.contents = str( self.input_text ).strip( )
		throw_if( 'text', self.contents )
		return self.contents
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Embeddings'
		exception.method = ('normalize_contents( self, text: str | List[str] ) -> str | List['
		                    'str]')
		Logger( ).write( exception )
		raise exception

build_embedding_config

build_embedding_config(
    model: str,
    dimensions: int = 0,
    task_type: str = "",
    title: str = "",
) -> EmbedContentConfig

Build the embedding request configuration.

Purpose

Constructs the provider configuration from output dimensionality, task type, and retrieval-document title settings supported by the selected embedding model.

Parameters:

Name Type Description Default
model str

Gemini embedding model identifier.

required
dimensions int

Requested output dimensionality.

0
task_type str

Optional embedding task type.

''
title str

Optional retrieval-document title.

''

Returns:

Name Type Description
EmbedContentConfig EmbedContentConfig

Provider embedding configuration.

Raises:

Type Description
Error

Raised when validation or configuration construction fails.

ValueError

Raised when model is missing.

Source code in gemini.py
def build_embedding_config( self, model: str, dimensions: int=0, task_type: str='',
	title: str='' ) -> EmbedContentConfig:
	"""Build the embedding request configuration.

	Purpose:
		Constructs the provider configuration from output dimensionality, task type, and
		retrieval-document title settings supported by the selected embedding model.

	Args:
		model (str): Gemini embedding model identifier.
		dimensions (int): Requested output dimensionality.
		task_type (str): Optional embedding task type.
		title (str): Optional retrieval-document title.

	Returns:
		EmbedContentConfig: Provider embedding configuration.

	Raises:
		Error: Raised when validation or configuration construction fails.
		ValueError: Raised when ``model`` is missing.
	"""
	try:
		throw_if( 'model', model )
		self.model = model
		self.dimensions = self.normalize_dimensions( dimensions )
		self.task_type = str( task_type or '' ).strip( ).upper( )
		self.title = str( title or '' ).strip( )
		self.config_values: Dict[ str, Any ] = { }
		if self.dimensions is not None:
			self.config_values[ 'output_dimensionality' ] = self.dimensions

		if self.task_type:
			self.config_values[ 'task_type' ] = self.task_type

		if self.title and self.task_type == 'RETRIEVAL_DOCUMENT':
			self.config_values[ 'title' ] = self.title

		self.embedding_config = EmbedContentConfig( **self.config_values )
		return self.embedding_config
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Embeddings'
		exception.method = ('build_embedding_config( self, model: str, dimensions: int, '
		                    'task_type: str, title: str ) -> EmbedContentConfig')
		Logger( ).write( exception )
		raise exception

extract_embeddings

extract_embeddings() -> (
    Optional[List[float] | List[List[float]]]
)

Extract vectors from the embedding response.

Purpose

Converts SDK embedding objects into ordinary lists of floating-point values and preserves the single-vector return shape for a single string input.

Returns:

Type Description
Optional[List[float] | List[List[float]]]

Optional[List[float] | List[List[float]]]: Extracted embedding vector or vectors.

Raises:

Type Description
Error

Raised when response extraction fails.

Source code in gemini.py
def extract_embeddings( self ) -> Optional[ List[ float ] | List[ List[ float ] ] ]:
	"""Extract vectors from the embedding response.

	Purpose:
		Converts SDK embedding objects into ordinary lists of floating-point values and
		preserves the single-vector return shape for a single string input.

	Returns:
		Optional[List[float] | List[List[float]]]: Extracted embedding vector or vectors.

	Raises:
		Error: Raised when response extraction fails.
	"""
	try:
		if self.response is None:
			return None

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

		self.embeddings = [ ]
		for item in self.response_embeddings:
			if item is None:
				continue

			self.values = getattr( item, 'values', None )
			if self.values is not None:
				self.embeddings.append( [ float( value ) for value in self.values ] )

		if not self.embeddings:
			return None

		if len( self.embeddings ) == 1 and isinstance( self.input_text, str ):
			self.embedding = self.embeddings[ 0 ]
		else:
			self.embedding = self.embeddings

		return self.embedding
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Embeddings'
		exception.method = 'extract_embeddings( self ) -> Optional[ List[ float ] ]'
		Logger( ).write( exception )
		raise exception

create

create(
    text: str | List[str],
    model: str = "gemini-embedding-2",
    dimensions: int = 0,
    task_type: str = "",
    title: str = "",
    encoding_format: str = "float",
) -> Optional[List[float] | List[List[float]]]

Create text embeddings.

Purpose

Validates and normalizes text input, constructs the provider configuration, executes the specialized Gemini embeddings operation, and returns the extracted vector data.

Parameters:

Name Type Description Default
text str | List[str]

Text or independent text values to embed.

required
model str

Gemini embedding model identifier.

'gemini-embedding-2'
dimensions int

Requested output dimensionality.

0
task_type str

Optional embedding task type.

''
title str

Optional retrieval-document title.

''
encoding_format str

Application-facing encoding selection.

'float'

Returns:

Type Description
Optional[List[float] | List[List[float]]]

Optional[List[float] | List[List[float]]]: Generated embedding vector or vectors.

Raises:

Type Description
Error

Raised when validation, provider execution, or extraction fails.

ValueError

Raised when required input, model, API key, or encoding is invalid.

Source code in gemini.py
def create( self, text: str | List[ str ], model: str='gemini-embedding-2',
	dimensions: int=0, task_type: str='', title: str='',
	encoding_format: str='float' ) -> Optional[ List[ float ] | List[ List[ float ] ] ]:
	"""Create text embeddings.

	Purpose:
		Validates and normalizes text input, constructs the provider configuration, executes
		the specialized Gemini embeddings operation, and returns the extracted vector data.

	Args:
		text (str | List[str]): Text or independent text values to embed.
		model (str): Gemini embedding model identifier.
		dimensions (int): Requested output dimensionality.
		task_type (str): Optional embedding task type.
		title (str): Optional retrieval-document title.
		encoding_format (str): Application-facing encoding selection.

	Returns:
		Optional[List[float] | List[List[float]]]: Generated embedding vector or vectors.

	Raises:
		Error: Raised when validation, provider execution, or extraction fails.
		ValueError: Raised when required input, model, API key, or encoding is invalid.
	"""
	try:
		throw_if( 'text', text )
		throw_if( 'model', model )
		self.input_text = text
		self.model = model
		self.dimensions = dimensions
		self.task_type = task_type
		self.title = title
		self.encoding_format = str( encoding_format or 'float' ).strip( ).lower( )
		if self.encoding_format != 'float':
			raise ValueError( 'The Gemini embeddings API returns float vectors only.' )

		self.contents = self.normalize_contents( self.input_text )
		self.embedding_config = self.build_embedding_config( model=self.model,
			dimensions=self.dimensions, task_type=self.task_type, title=self.title )

		self.api_key = self.gemini_api_key or self.google_api_key
		throw_if( 'api_key', self.api_key )

		self.client = genai.Client( api_key=self.api_key )
		self.response = self.client.models.embed_content( model=self.model,
			contents=self.contents, config=self.embedding_config )

		return self.extract_embeddings( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Embeddings'
		exception.method = ('create( self, text: str | List[str], model: str, dimensions: int, '
		                    'task_type: str, title: str, encoding_format: str ) -> Optional['
		                    'List[float] | List[List[float]]]')
		Logger( ).write( exception )
		raise exception

TTS

Bases: Gemini

Gemini text-to-speech wrapper.

Purpose

Converts text into single-speaker audio through the Gemini Interactions API. The class builds controllable speech prompts, applies the selected prebuilt voice, retrieves PCM audio from the completed Interaction, wraps the PCM data in a WAV container, and optionally writes the generated audio to disk.

Attributes:

Name Type Description
client Optional[Client]

Active Gemini SDK client.

http_options HttpOptions

Gemini client HTTP configuration.

speed Optional[float]

Requested speech-rate control.

voice Optional[str]

Selected prebuilt Gemini voice.

response Optional[Any]

Most recent Gemini Interaction.

interaction Optional[Any]

Most recent Gemini Interaction.

audio_path Optional[str]

Optional output WAV path.

response_format Optional[str]

Application-facing audio format.

input_text Optional[str]

Complete text and performance instruction sent to Gemini.

audio_bytes Optional[bytes]

Generated WAV audio.

pcm_bytes Optional[bytes]

Raw PCM audio returned by Gemini.

generation_config Dict[str, Any]

Interactions speech-generation configuration.

Source code in gemini.py
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
3072
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
class TTS( Gemini ):
	"""Gemini text-to-speech wrapper.

	Purpose:
		Converts text into single-speaker audio through the Gemini Interactions API. The class
		builds controllable speech prompts, applies the selected prebuilt voice, retrieves PCM
		audio from the completed Interaction, wraps the PCM data in a WAV container, and
		optionally writes the generated audio to disk.

	Attributes:
		client (Optional[genai.Client]): Active Gemini SDK client.
		http_options (HttpOptions): Gemini client HTTP configuration.
		speed (Optional[float]): Requested speech-rate control.
		voice (Optional[str]): Selected prebuilt Gemini voice.
		response (Optional[Any]): Most recent Gemini Interaction.
		interaction (Optional[Any]): Most recent Gemini Interaction.
		audio_path (Optional[str]): Optional output WAV path.
		response_format (Optional[str]): Application-facing audio format.
		input_text (Optional[str]): Complete text and performance instruction sent to Gemini.
		audio_bytes (Optional[bytes]): Generated WAV audio.
		pcm_bytes (Optional[bytes]): Raw PCM audio returned by Gemini.
		generation_config (Dict[str, Any]): Interactions speech-generation configuration.
	"""

	client: Optional[ genai.Client ]
	http_options: HttpOptions
	speed: Optional[ float ]
	voice: Optional[ str ]
	response: Optional[ Any ]
	interaction: Optional[ Any ]
	audio_path: Optional[ str ]
	response_format: Optional[ str ]
	input_text: Optional[ str ]
	audio_bytes: Optional[ bytes ]
	pcm_bytes: Optional[ bytes ]
	generation_config: Dict[ str, Any ]

	def __init__( self, model: str='gemini-3.1-flash-tts-preview' ) -> None:
		"""Initialize the TTS wrapper.

		Purpose:
			Initializes model configuration, speech settings, request state, and audio-output
			placeholders. The constructor performs local state assignment only and does not
			create a provider client or submit a request.

		Args:
			model (str): Default Gemini text-to-speech model.

		Returns:
			None: This method initializes object state through side effects.
		"""
		super( ).__init__( )
		self.model = model
		self.api_version = 'v1beta'
		self.http_options = types.HttpOptions( api_version=self.api_version )
		self.client = None
		self.number = None
		self.temperature = None
		self.top_p = None
		self.frequency_penalty = None
		self.presence_penalty = None
		self.max_tokens = None
		self.instructions = None
		self.voice = None
		self.speed = None
		self.response = None
		self.interaction = None
		self.response_format = None
		self.audio_path = None
		self.input_text = None
		self.audio_bytes = None
		self.pcm_bytes = None
		self.generation_config = { }
		self.response_modalities = [ 'audio' ]

	@property
	def model_options( self ) -> List[ str ]:
		"""Return supported Gemini text-to-speech models.

		Purpose:
			Provides the Gemini TTS model identifiers exposed by the Jeni Audio mode.

		Returns:
			List[str]: Supported Gemini text-to-speech model identifiers.
		"""
		return [ 'gemini-3.1-flash-tts-preview', 'gemini-2.5-flash-preview-tts',
			'gemini-2.5-pro-preview-tts', ]

	@property
	def format_options( self ) -> List[ str ]:
		"""Return supported application audio formats.

		Purpose:
			Provides the local WAV output format supported by the Jeni Audio mode.

		Returns:
			List[str]: Supported application audio formats.
		"""
		return [ 'audio/wav', ]

	@property
	def voice_options( self ) -> List[ str ]:
		"""Return supported prebuilt Gemini voices.

		Purpose:
			Provides the prebuilt single-speaker voices exposed by the Jeni Audio controls.

		Returns:
			List[str]: Supported Gemini prebuilt voice names.
		"""
		return [ 'Achernar', 'Achird', 'Algenib', 'Algieba', 'Alnilam', 'Aoede', 'Autonoe',
			'Callirrhoe', 'Charon', 'Despina', 'Enceladus', 'Erinome', 'Fenrir', 'Gacrux',
			'Iapetus', 'Kore', 'Laomedeia', 'Leda', 'Orus', 'Puck', 'Pulcherrima', 'Rasalgethi',
			'Sadachbia', 'Sadaltager', 'Schedar', 'Sulafat', 'Umbriel', 'Vindemiatrix', 'Zephyr',
			'Zubenelgenubi', ]

	def to_wave_bytes( self, pcm_data: bytes, rate: int=24000, channels: int=1,
		sample_width: int=2 ) -> bytes:
		"""Wrap PCM audio in a WAV container.

		Purpose:
			Writes raw Gemini PCM output into an in-memory WAV file using the channel count,
			sampling rate, and sample width documented for Gemini TTS output.

		Args:
			pcm_data (bytes): Raw PCM audio.
			rate (int): Audio sample rate in hertz.
			channels (int): Audio channel count.
			sample_width (int): Sample width in bytes.

		Returns:
			bytes: Complete WAV file bytes.

		Raises:
			Error: Raised when validation or WAV encoding fails.
			ValueError: Raised when ``pcm_data`` is missing.
		"""
		try:
			import io
			import wave

			throw_if( 'pcm_data', pcm_data )
			self.pcm_data = pcm_data
			self.sample_rate = rate
			self.channel_count = channels
			self.sample_width = sample_width

			with io.BytesIO( ) as buffer:
				with wave.open( buffer, 'wb' ) as wave_file:
					wave_file.setnchannels( self.channel_count )
					wave_file.setsampwidth( self.sample_width )
					wave_file.setframerate( self.sample_rate )
					wave_file.writeframes( self.pcm_data )

				return buffer.getvalue( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'TTS'
			exception.method = ('to_wave_bytes( self, pcm_data: bytes, rate: int, channels: int, '
			                    'sample_width: int ) -> bytes')
			Logger( ).write( exception )
			raise exception

	def normalize_voice( self, voice: Optional[ str ] = None ) -> str:
		"""Normalize the selected Gemini voice.

		Purpose:
			Returns the selected prebuilt voice when supported and otherwise uses Kore as the
			stable default voice.

		Args:
			voice (Optional[str]): Candidate Gemini voice name.

		Returns:
			str: Supported Gemini voice name.

		Raises:
			Error: Raised when voice normalization fails.
		"""
		try:
			self.voice = voice
			self.voice_name = str( self.voice or '' ).strip( )

			if self.voice_name in set( self.voice_options ):
				return self.voice_name

			return 'Kore'
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'TTS'
			exception.method = ('normalize_voice( self, voice: Optional[ str ] ) -> str')
			Logger( ).write( exception )
			raise exception

	def normalize_tts_prompt( self, text: str, speed: Optional[ float ] = None,
		instruct: Optional[ str ] = None ) -> str:
		"""Build the controllable TTS prompt.

		Purpose:
			Combines optional system-style performance instructions, speech-rate guidance, and
			the exact source text into the single text input accepted by Gemini TTS models.

		Args:
			text (str): Text to synthesize.
			speed (Optional[float]): Relative speech-rate control.
			instruct (Optional[str]): Optional performance instruction.

		Returns:
			str: Complete Gemini TTS prompt.

		Raises:
			Error: Raised when validation or prompt construction fails.
			ValueError: Raised when ``text`` is missing.
		"""
		try:
			throw_if( 'text', text )
			self.text = text
			self.speed = speed
			self.instructions = instruct
			self.prompt_parts: List[ str ] = [ ]

			if self.instructions is not None and str( self.instructions ).strip( ):
				self.prompt_parts.append( str( self.instructions ).strip( ) )

			if self.speed is not None:
				if self.speed < 0.9:
					self.prompt_parts.append( 'Read the following text slowly and clearly.' )

				elif self.speed > 1.1:
					self.prompt_parts.append(
						'Read the following text at a faster, energetic pace.' )

			self.prompt_parts.append( str( self.text ).strip( ) )
			self.input_text = '\n\n'.join( self.prompt_parts )
			return self.input_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'TTS'
			exception.method = ('normalize_tts_prompt( self, text: str, '
			                    'speed: Optional[ float ], instruct: Optional[ str ] ) -> str')
			Logger( ).write( exception )
			raise exception

	def build_generation_config( self, voice: str, temperature: Optional[ float ] = None,
		top_p: Optional[ float ] = None, max_tokens: Optional[ int ] = None ) -> Dict[ str, Any ]:
		"""Build the Interactions speech-generation configuration.

		Purpose:
			Constructs the single-speaker speech configuration and adds supported inference
			settings without submitting legacy Generate Content configuration objects.

		Args:
			voice (str): Supported Gemini voice name.
			temperature (Optional[float]): Sampling temperature.
			top_p (Optional[float]): Top-p sampling value.
			max_tokens (Optional[int]): Maximum output-token count.

		Returns:
			Dict[str, Any]: Interactions generation configuration.

		Raises:
			Error: Raised when validation or configuration construction fails.
			ValueError: Raised when ``voice`` is missing.
		"""
		try:
			throw_if( 'voice', voice )
			self.voice = voice
			self.temperature = temperature
			self.top_p = top_p
			self.max_tokens = max_tokens
			self.generation_config = { 'speech_config': [ { 'voice': self.voice, }, ], }

			if self.temperature is not None:
				self.generation_config[ 'temperature' ] = self.temperature

			if self.top_p is not None:
				self.generation_config[ 'top_p' ] = self.top_p

			if self.max_tokens is not None and self.max_tokens > 0:
				self.generation_config[ 'max_output_tokens' ] = (self.max_tokens)

			return self.generation_config
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'TTS'
			exception.method = ('build_generation_config( self, voice: str, '
			                    'temperature: Optional[ float ], top_p: Optional[ float ], '
			                    'max_tokens: Optional[ int ] ) -> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def create_speech( self, text: str, filepath: str=None,
		model: str='gemini-3.1-flash-tts-preview', format: str='audio/wav', speed: float =
		None,
		voice: str=None, frequency: float=None, presense: float=None, max_tokens: int=None,
		instruct: str=None, temperature: float=None,
		top_p: float=None ) -> bytes | str | None:
		"""Generate speech through the Gemini Interactions API.

		Purpose:
			Builds the controllable TTS prompt, submits an audio-only Interaction, decodes the
			returned base64 PCM audio, wraps it in a WAV container, and returns the WAV bytes or
			the path written by the method.

		Args:
			text (str): Text to synthesize.
			filepath (str): Optional output WAV path.
			model (str): Gemini text-to-speech model.
			format (str): Application-facing audio format.
			speed (float): Relative speech-rate control.
			voice (str): Prebuilt Gemini voice.
			frequency (float): Frequency penalty retained for UI compatibility.
			presense (float): Presence penalty retained for UI compatibility.
			max_tokens (int): Maximum output-token count.
			instruct (str): Optional speech-performance instruction.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.

		Returns:
			bytes | str | None: WAV bytes when no path is supplied, or the written file path.

		Raises:
			Error: Raised when validation, request execution, decoding, or file writing fails.
			ValueError: Raised when required input is missing or no audio is returned.
		"""
		try:
			throw_if( 'text', text )
			self.text = text
			self.audio_path = filepath
			self.model = model
			self.response_format = format
			self.speed = speed
			self.voice = voice
			self.frequency_penalty = frequency
			self.presence_penalty = presense
			self.max_tokens = max_tokens
			self.instructions = instruct
			self.temperature = temperature
			self.top_p = top_p

			if self.response_format != 'audio/wav':
				raise ValueError( 'Gemini TTS wrapper supports WAV output only.' )

			if self.model not in self.model_options:
				raise ValueError( f'Unsupported Gemini TTS model: {self.model}' )

			self.input_text = self.normalize_tts_prompt( text=self.text, speed=self.speed,
				instruct=self.instructions )

			self.voice = self.normalize_voice( self.voice )

			self.generation_config = self.build_generation_config( voice=self.voice,
				temperature=self.temperature, top_p=self.top_p, max_tokens=self.max_tokens )

			self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
				'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
			throw_if( 'api_key', self.api_key )

			self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )

			self.interaction = self.client.interactions.create( model=self.model,
				input=self.input_text, response_format={ 'type': 'audio', },
				generation_config=self.generation_config, store=False )

			self.response = self.interaction
			self.content_response = self.interaction
			self.output_audio = getattr( self.interaction, 'output_audio', None )

			if self.output_audio is None:
				raise ValueError( 'No audio output was returned by Gemini TTS.' )

			self.encoded_audio = getattr( self.output_audio, 'data', None )

			if not self.encoded_audio:
				raise ValueError( 'Gemini TTS returned an empty audio payload.' )

			self.pcm_bytes = base64.b64decode( self.encoded_audio )
			self.audio_bytes = self.to_wave_bytes( pcm_data=self.pcm_bytes )

			if self.audio_path is not None and str( self.audio_path ).strip( ):
				self.audio_path = str( self.audio_path ).strip( )

				with open( self.audio_path, 'wb' ) as audio_file:
					audio_file.write( self.audio_bytes )

				return self.audio_path

			return self.audio_bytes
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'TTS'
			exception.method = ('create_speech( self, text: str, filepath: str, model: str, '
			                    'format: str, speed: float, voice: str, frequency: float, '
			                    'presense: float, max_tokens: int, instruct: str, temperature: '
			                    'float, top_p: float ) -> bytes | str | None')
			Logger( ).write( exception )
			raise exception

model_options property

model_options: List[str]

Return supported Gemini text-to-speech models.

Purpose

Provides the Gemini TTS model identifiers exposed by the Jeni Audio mode.

Returns:

Type Description
List[str]

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

format_options property

format_options: List[str]

Return supported application audio formats.

Purpose

Provides the local WAV output format supported by the Jeni Audio mode.

Returns:

Type Description
List[str]

List[str]: Supported application audio formats.

voice_options property

voice_options: List[str]

Return supported prebuilt Gemini voices.

Purpose

Provides the prebuilt single-speaker voices exposed by the Jeni Audio controls.

Returns:

Type Description
List[str]

List[str]: Supported Gemini prebuilt voice names.

__init__

__init__(
    model: str = "gemini-3.1-flash-tts-preview",
) -> None

Initialize the TTS wrapper.

Purpose

Initializes model configuration, speech settings, request state, and audio-output placeholders. The constructor performs local state assignment only and does not create a provider client or submit a request.

Parameters:

Name Type Description Default
model str

Default Gemini text-to-speech model.

'gemini-3.1-flash-tts-preview'

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self, model: str='gemini-3.1-flash-tts-preview' ) -> None:
	"""Initialize the TTS wrapper.

	Purpose:
		Initializes model configuration, speech settings, request state, and audio-output
		placeholders. The constructor performs local state assignment only and does not
		create a provider client or submit a request.

	Args:
		model (str): Default Gemini text-to-speech model.

	Returns:
		None: This method initializes object state through side effects.
	"""
	super( ).__init__( )
	self.model = model
	self.api_version = 'v1beta'
	self.http_options = types.HttpOptions( api_version=self.api_version )
	self.client = None
	self.number = None
	self.temperature = None
	self.top_p = None
	self.frequency_penalty = None
	self.presence_penalty = None
	self.max_tokens = None
	self.instructions = None
	self.voice = None
	self.speed = None
	self.response = None
	self.interaction = None
	self.response_format = None
	self.audio_path = None
	self.input_text = None
	self.audio_bytes = None
	self.pcm_bytes = None
	self.generation_config = { }
	self.response_modalities = [ 'audio' ]

to_wave_bytes

to_wave_bytes(
    pcm_data: bytes,
    rate: int = 24000,
    channels: int = 1,
    sample_width: int = 2,
) -> bytes

Wrap PCM audio in a WAV container.

Purpose

Writes raw Gemini PCM output into an in-memory WAV file using the channel count, sampling rate, and sample width documented for Gemini TTS output.

Parameters:

Name Type Description Default
pcm_data bytes

Raw PCM audio.

required
rate int

Audio sample rate in hertz.

24000
channels int

Audio channel count.

1
sample_width int

Sample width in bytes.

2

Returns:

Name Type Description
bytes bytes

Complete WAV file bytes.

Raises:

Type Description
Error

Raised when validation or WAV encoding fails.

ValueError

Raised when pcm_data is missing.

Source code in gemini.py
def to_wave_bytes( self, pcm_data: bytes, rate: int=24000, channels: int=1,
	sample_width: int=2 ) -> bytes:
	"""Wrap PCM audio in a WAV container.

	Purpose:
		Writes raw Gemini PCM output into an in-memory WAV file using the channel count,
		sampling rate, and sample width documented for Gemini TTS output.

	Args:
		pcm_data (bytes): Raw PCM audio.
		rate (int): Audio sample rate in hertz.
		channels (int): Audio channel count.
		sample_width (int): Sample width in bytes.

	Returns:
		bytes: Complete WAV file bytes.

	Raises:
		Error: Raised when validation or WAV encoding fails.
		ValueError: Raised when ``pcm_data`` is missing.
	"""
	try:
		import io
		import wave

		throw_if( 'pcm_data', pcm_data )
		self.pcm_data = pcm_data
		self.sample_rate = rate
		self.channel_count = channels
		self.sample_width = sample_width

		with io.BytesIO( ) as buffer:
			with wave.open( buffer, 'wb' ) as wave_file:
				wave_file.setnchannels( self.channel_count )
				wave_file.setsampwidth( self.sample_width )
				wave_file.setframerate( self.sample_rate )
				wave_file.writeframes( self.pcm_data )

			return buffer.getvalue( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'TTS'
		exception.method = ('to_wave_bytes( self, pcm_data: bytes, rate: int, channels: int, '
		                    'sample_width: int ) -> bytes')
		Logger( ).write( exception )
		raise exception

normalize_voice

normalize_voice(voice: Optional[str] = None) -> str

Normalize the selected Gemini voice.

Purpose

Returns the selected prebuilt voice when supported and otherwise uses Kore as the stable default voice.

Parameters:

Name Type Description Default
voice Optional[str]

Candidate Gemini voice name.

None

Returns:

Name Type Description
str str

Supported Gemini voice name.

Raises:

Type Description
Error

Raised when voice normalization fails.

Source code in gemini.py
def normalize_voice( self, voice: Optional[ str ] = None ) -> str:
	"""Normalize the selected Gemini voice.

	Purpose:
		Returns the selected prebuilt voice when supported and otherwise uses Kore as the
		stable default voice.

	Args:
		voice (Optional[str]): Candidate Gemini voice name.

	Returns:
		str: Supported Gemini voice name.

	Raises:
		Error: Raised when voice normalization fails.
	"""
	try:
		self.voice = voice
		self.voice_name = str( self.voice or '' ).strip( )

		if self.voice_name in set( self.voice_options ):
			return self.voice_name

		return 'Kore'
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'TTS'
		exception.method = ('normalize_voice( self, voice: Optional[ str ] ) -> str')
		Logger( ).write( exception )
		raise exception

normalize_tts_prompt

normalize_tts_prompt(
    text: str,
    speed: Optional[float] = None,
    instruct: Optional[str] = None,
) -> str

Build the controllable TTS prompt.

Purpose

Combines optional system-style performance instructions, speech-rate guidance, and the exact source text into the single text input accepted by Gemini TTS models.

Parameters:

Name Type Description Default
text str

Text to synthesize.

required
speed Optional[float]

Relative speech-rate control.

None
instruct Optional[str]

Optional performance instruction.

None

Returns:

Name Type Description
str str

Complete Gemini TTS prompt.

Raises:

Type Description
Error

Raised when validation or prompt construction fails.

ValueError

Raised when text is missing.

Source code in gemini.py
def normalize_tts_prompt( self, text: str, speed: Optional[ float ] = None,
	instruct: Optional[ str ] = None ) -> str:
	"""Build the controllable TTS prompt.

	Purpose:
		Combines optional system-style performance instructions, speech-rate guidance, and
		the exact source text into the single text input accepted by Gemini TTS models.

	Args:
		text (str): Text to synthesize.
		speed (Optional[float]): Relative speech-rate control.
		instruct (Optional[str]): Optional performance instruction.

	Returns:
		str: Complete Gemini TTS prompt.

	Raises:
		Error: Raised when validation or prompt construction fails.
		ValueError: Raised when ``text`` is missing.
	"""
	try:
		throw_if( 'text', text )
		self.text = text
		self.speed = speed
		self.instructions = instruct
		self.prompt_parts: List[ str ] = [ ]

		if self.instructions is not None and str( self.instructions ).strip( ):
			self.prompt_parts.append( str( self.instructions ).strip( ) )

		if self.speed is not None:
			if self.speed < 0.9:
				self.prompt_parts.append( 'Read the following text slowly and clearly.' )

			elif self.speed > 1.1:
				self.prompt_parts.append(
					'Read the following text at a faster, energetic pace.' )

		self.prompt_parts.append( str( self.text ).strip( ) )
		self.input_text = '\n\n'.join( self.prompt_parts )
		return self.input_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'TTS'
		exception.method = ('normalize_tts_prompt( self, text: str, '
		                    'speed: Optional[ float ], instruct: Optional[ str ] ) -> str')
		Logger( ).write( exception )
		raise exception

build_generation_config

build_generation_config(
    voice: str,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    max_tokens: Optional[int] = None,
) -> Dict[str, Any]

Build the Interactions speech-generation configuration.

Purpose

Constructs the single-speaker speech configuration and adds supported inference settings without submitting legacy Generate Content configuration objects.

Parameters:

Name Type Description Default
voice str

Supported Gemini voice name.

required
temperature Optional[float]

Sampling temperature.

None
top_p Optional[float]

Top-p sampling value.

None
max_tokens Optional[int]

Maximum output-token count.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Interactions generation configuration.

Raises:

Type Description
Error

Raised when validation or configuration construction fails.

ValueError

Raised when voice is missing.

Source code in gemini.py
def build_generation_config( self, voice: str, temperature: Optional[ float ] = None,
	top_p: Optional[ float ] = None, max_tokens: Optional[ int ] = None ) -> Dict[ str, Any ]:
	"""Build the Interactions speech-generation configuration.

	Purpose:
		Constructs the single-speaker speech configuration and adds supported inference
		settings without submitting legacy Generate Content configuration objects.

	Args:
		voice (str): Supported Gemini voice name.
		temperature (Optional[float]): Sampling temperature.
		top_p (Optional[float]): Top-p sampling value.
		max_tokens (Optional[int]): Maximum output-token count.

	Returns:
		Dict[str, Any]: Interactions generation configuration.

	Raises:
		Error: Raised when validation or configuration construction fails.
		ValueError: Raised when ``voice`` is missing.
	"""
	try:
		throw_if( 'voice', voice )
		self.voice = voice
		self.temperature = temperature
		self.top_p = top_p
		self.max_tokens = max_tokens
		self.generation_config = { 'speech_config': [ { 'voice': self.voice, }, ], }

		if self.temperature is not None:
			self.generation_config[ 'temperature' ] = self.temperature

		if self.top_p is not None:
			self.generation_config[ 'top_p' ] = self.top_p

		if self.max_tokens is not None and self.max_tokens > 0:
			self.generation_config[ 'max_output_tokens' ] = (self.max_tokens)

		return self.generation_config
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'TTS'
		exception.method = ('build_generation_config( self, voice: str, '
		                    'temperature: Optional[ float ], top_p: Optional[ float ], '
		                    'max_tokens: Optional[ int ] ) -> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

create_speech

create_speech(
    text: str,
    filepath: str = None,
    model: str = "gemini-3.1-flash-tts-preview",
    format: str = "audio/wav",
    speed: float = None,
    voice: str = None,
    frequency: float = None,
    presense: float = None,
    max_tokens: int = None,
    instruct: str = None,
    temperature: float = None,
    top_p: float = None,
) -> bytes | str | None

Generate speech through the Gemini Interactions API.

Purpose

Builds the controllable TTS prompt, submits an audio-only Interaction, decodes the returned base64 PCM audio, wraps it in a WAV container, and returns the WAV bytes or the path written by the method.

Parameters:

Name Type Description Default
text str

Text to synthesize.

required
filepath str

Optional output WAV path.

None
model str

Gemini text-to-speech model.

'gemini-3.1-flash-tts-preview'
format str

Application-facing audio format.

'audio/wav'
speed float

Relative speech-rate control.

None
voice str

Prebuilt Gemini voice.

None
frequency float

Frequency penalty retained for UI compatibility.

None
presense float

Presence penalty retained for UI compatibility.

None
max_tokens int

Maximum output-token count.

None
instruct str

Optional speech-performance instruction.

None
temperature float

Sampling temperature.

None
top_p float

Top-p sampling value.

None

Returns:

Type Description
bytes | str | None

bytes | str | None: WAV bytes when no path is supplied, or the written file path.

Raises:

Type Description
Error

Raised when validation, request execution, decoding, or file writing fails.

ValueError

Raised when required input is missing or no audio is returned.

Source code in gemini.py
def create_speech( self, text: str, filepath: str=None,
	model: str='gemini-3.1-flash-tts-preview', format: str='audio/wav', speed: float =
	None,
	voice: str=None, frequency: float=None, presense: float=None, max_tokens: int=None,
	instruct: str=None, temperature: float=None,
	top_p: float=None ) -> bytes | str | None:
	"""Generate speech through the Gemini Interactions API.

	Purpose:
		Builds the controllable TTS prompt, submits an audio-only Interaction, decodes the
		returned base64 PCM audio, wraps it in a WAV container, and returns the WAV bytes or
		the path written by the method.

	Args:
		text (str): Text to synthesize.
		filepath (str): Optional output WAV path.
		model (str): Gemini text-to-speech model.
		format (str): Application-facing audio format.
		speed (float): Relative speech-rate control.
		voice (str): Prebuilt Gemini voice.
		frequency (float): Frequency penalty retained for UI compatibility.
		presense (float): Presence penalty retained for UI compatibility.
		max_tokens (int): Maximum output-token count.
		instruct (str): Optional speech-performance instruction.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.

	Returns:
		bytes | str | None: WAV bytes when no path is supplied, or the written file path.

	Raises:
		Error: Raised when validation, request execution, decoding, or file writing fails.
		ValueError: Raised when required input is missing or no audio is returned.
	"""
	try:
		throw_if( 'text', text )
		self.text = text
		self.audio_path = filepath
		self.model = model
		self.response_format = format
		self.speed = speed
		self.voice = voice
		self.frequency_penalty = frequency
		self.presence_penalty = presense
		self.max_tokens = max_tokens
		self.instructions = instruct
		self.temperature = temperature
		self.top_p = top_p

		if self.response_format != 'audio/wav':
			raise ValueError( 'Gemini TTS wrapper supports WAV output only.' )

		if self.model not in self.model_options:
			raise ValueError( f'Unsupported Gemini TTS model: {self.model}' )

		self.input_text = self.normalize_tts_prompt( text=self.text, speed=self.speed,
			instruct=self.instructions )

		self.voice = self.normalize_voice( self.voice )

		self.generation_config = self.build_generation_config( voice=self.voice,
			temperature=self.temperature, top_p=self.top_p, max_tokens=self.max_tokens )

		self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
			'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
		throw_if( 'api_key', self.api_key )

		self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )

		self.interaction = self.client.interactions.create( model=self.model,
			input=self.input_text, response_format={ 'type': 'audio', },
			generation_config=self.generation_config, store=False )

		self.response = self.interaction
		self.content_response = self.interaction
		self.output_audio = getattr( self.interaction, 'output_audio', None )

		if self.output_audio is None:
			raise ValueError( 'No audio output was returned by Gemini TTS.' )

		self.encoded_audio = getattr( self.output_audio, 'data', None )

		if not self.encoded_audio:
			raise ValueError( 'Gemini TTS returned an empty audio payload.' )

		self.pcm_bytes = base64.b64decode( self.encoded_audio )
		self.audio_bytes = self.to_wave_bytes( pcm_data=self.pcm_bytes )

		if self.audio_path is not None and str( self.audio_path ).strip( ):
			self.audio_path = str( self.audio_path ).strip( )

			with open( self.audio_path, 'wb' ) as audio_file:
				audio_file.write( self.audio_bytes )

			return self.audio_path

		return self.audio_bytes
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'TTS'
		exception.method = ('create_speech( self, text: str, filepath: str, model: str, '
		                    'format: str, speed: float, voice: str, frequency: float, '
		                    'presense: float, max_tokens: int, instruct: str, temperature: '
		                    'float, top_p: float ) -> bytes | str | None')
		Logger( ).write( exception )
		raise exception

Transcription

Bases: Gemini

Gemini audio-transcription wrapper.

Purpose

Transcribes local audio files into text through the Gemini Interactions API. The class normalizes audio MIME types, builds transcription instructions with optional language and time-range constraints, uploads the local audio through the Gemini Files API, and submits the uploaded audio as multimodal Interactions input.

Attributes:

Name Type Description
client Optional[Client]

Active Gemini SDK client.

http_options HttpOptions

Gemini client HTTP configuration.

transcript Optional[str]

Text returned by the transcription request.

file_path Optional[str]

Local audio-file path.

mime_type Optional[str]

Normalized audio MIME type.

uploaded_file Optional[File]

File resource uploaded to Gemini.

interaction Optional[Any]

Most recent Gemini Interaction.

response Optional[Any]

Raw Interaction consumed by application token accounting.

generation_config Dict[str, Any]

Interactions generation configuration.

Source code in gemini.py
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
class Transcription( Gemini ):
	"""Gemini audio-transcription wrapper.

	Purpose:
		Transcribes local audio files into text through the Gemini Interactions API. The class
		normalizes audio MIME types, builds transcription instructions with optional language
		and time-range constraints, uploads the local audio through the Gemini Files API, and
		submits the uploaded audio as multimodal Interactions input.

	Attributes:
		client (Optional[genai.Client]): Active Gemini SDK client.
		http_options (HttpOptions): Gemini client HTTP configuration.
		transcript (Optional[str]): Text returned by the transcription request.
		file_path (Optional[str]): Local audio-file path.
		mime_type (Optional[str]): Normalized audio MIME type.
		uploaded_file (Optional[File]): File resource uploaded to Gemini.
		interaction (Optional[Any]): Most recent Gemini Interaction.
		response (Optional[Any]): Raw Interaction consumed by application token accounting.
		generation_config (Dict[str, Any]): Interactions generation configuration.
	"""

	client: Optional[ genai.Client ]
	http_options: HttpOptions
	transcript: Optional[ str ]
	file_path: Optional[ str ]
	mime_type: Optional[ str ]
	uploaded_file: Optional[ File ]
	interaction: Optional[ Any ]
	response: Optional[ Any ]
	generation_config: Dict[ str, Any ]

	def __init__( self, n: int=1, model: str='gemini-3.6-flash', temperature: float=0.8,
		top_p: float=0.9, frequency: float=0.0, presence: float=0.0, max_tokens: int=10000,
		instruct: str=None ) -> None:
		"""Initialize the Transcription wrapper.

		Purpose:
			Initializes transcription settings, local file state, request configuration, and
			response placeholders. The constructor performs local state assignment only and does
			not create a provider client or submit a request.

		Args:
			n (int): Candidate-count value retained for interface compatibility.
			model (str): Default Gemini audio-understanding model.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			frequency (float): Frequency penalty retained for interface compatibility.
			presence (float): Presence penalty retained for interface compatibility.
			max_tokens (int): Maximum output-token count.
			instruct (str): Optional system instruction text.

		Returns:
			None: This method initializes object state through side effects.
		"""
		super( ).__init__( )
		self.number = n
		self.model = model
		self.temperature = temperature
		self.top_p = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.instructions = instruct
		self.api_version = 'v1beta'
		self.http_options = types.HttpOptions( api_version=self.api_version )
		self.client = None
		self.transcript = None
		self.file_path = None
		self.mime_type = None
		self.uploaded_file = None
		self.interaction = None
		self.response = None
		self.content_response = None
		self.generation_config = { }

	@property
	def model_options( self ) -> List[ str ]:
		"""Return supported audio-transcription models.

		Purpose:
			Provides the Gemini audio-understanding model identifiers exposed by the Jeni Audio
			mode.

		Returns:
			List[str]: Supported Gemini transcription-model identifiers.
		"""
		return [ 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.1-pro-preview',
			'gemini-2.5-flash', 'gemini-2.5-pro', ]

	@property
	def language_options( self ) -> List[ str ]:
		"""Return supported transcription language hints.

		Purpose:
			Provides optional spoken-language hints consumed by the Jeni Audio controls.

		Returns:
			List[str]: Supported language-hint values.
		"""
		return [ '', 'Auto Detect', 'English', 'Spanish', 'French', 'German', 'Italian',
			'Portuguese', 'Dutch', 'Russian', 'Ukrainian', 'Polish', 'Arabic', 'Hebrew', 'Hindi',
			'Bengali', 'Urdu', 'Chinese', 'Japanese', 'Korean', 'Vietnamese', 'Thai', 'Indonesian',
			'Filipino', ]

	@property
	def mime_options( self ) -> List[ str ]:
		"""Return supported audio MIME types.

		Purpose:
			Provides audio MIME-type values accepted by the Jeni Audio mode.

		Returns:
			List[str]: Supported audio MIME types.
		"""
		return [ 'audio/wav', 'audio/mpeg', 'audio/mp3', 'audio/mp4', 'audio/x-m4a', 'audio/aac',
			'audio/ogg', 'audio/flac', 'audio/webm', ]

	def normalize_mime_type( self, path: str, mime_type: str=None ) -> str:
		"""Normalize an audio MIME type.

		Purpose:
			Uses an explicitly supplied MIME type when available and otherwise derives the MIME
			type from the local file extension.

		Args:
			path (str): Local audio-file path.
			mime_type (str): Optional explicit audio MIME type.

		Returns:
			str: Normalized audio MIME type.

		Raises:
			Error: Raised when validation or MIME-type normalization fails.
			ValueError: Raised when ``path`` is missing.
		"""
		try:
			import mimetypes

			throw_if( 'path', path )
			self.file_path = path
			self.mime_type = mime_type

			if self.mime_type is not None and str( self.mime_type ).strip( ):
				return str( self.mime_type ).strip( )

			self.guessed_mime_type = mimetypes.guess_type( self.file_path )[ 0 ]

			if self.guessed_mime_type:
				return self.guessed_mime_type

			self.file_suffix = Path( self.file_path ).suffix.lower( )
			self.mime_types = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.mpeg': 'audio/mpeg',
				'.mp4': 'audio/mp4', '.m4a': 'audio/x-m4a', '.aac': 'audio/aac',
				'.ogg': 'audio/ogg', '.oga': 'audio/ogg', '.flac': 'audio/flac',
				'.webm': 'audio/webm', }

			return self.mime_types.get( self.file_suffix, 'application/octet-stream' )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Transcription'
			exception.method = ('normalize_mime_type( self, path: str, mime_type: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def build_prompt( self, language: str=None, start_time: float=0.0,
		end_time: float=0.0 ) -> str:
		"""Build the transcription prompt.

		Purpose:
			Constructs the transcription instruction and adds optional spoken-language and
			time-range constraints without altering the source audio.

		Args:
			language (str): Optional spoken-language hint.
			start_time (float): Optional starting timestamp in seconds.
			end_time (float): Optional ending timestamp in seconds.

		Returns:
			str: Complete transcription prompt.

		Raises:
			Error: Raised when prompt construction fails.
		"""
		try:
			self.language = language
			self.start_time = start_time
			self.end_time = end_time
			self.prompt_parts: List[ str ] = [
				'Transcribe the spoken content in this audio accurately.',
				'Return only the transcript unless the supplied instructions require '
				'additional formatting.', ]

			self.language_name = str( self.language or '' ).strip( )

			if self.language_name and self.language_name.lower( ) != 'auto detect':
				self.prompt_parts.append( f'The expected spoken language is '
				                          f'{self.language_name}.' )

			if self.start_time > 0.0 and self.end_time > self.start_time:
				self.prompt_parts.append(
					f'Transcribe only the segment from {self.start_time:.3f} seconds '
					f'through {self.end_time:.3f} seconds.' )

			elif self.start_time > 0.0:
				self.prompt_parts.append( f'Begin transcription at {self.start_time:.3f} '
				                          f'seconds.' )

			elif self.end_time > 0.0:
				self.prompt_parts.append( f'Stop transcription at {self.end_time:.3f} seconds.' )

			self.prompt = '\n'.join( self.prompt_parts )
			return self.prompt
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Transcription'
			exception.method = ('build_prompt( self, language: str, start_time: float, '
			                    'end_time: float ) -> str')
			Logger( ).write( exception )
			raise exception

	def build_generation_config( self, temperature: float, top_p: float, max_tokens: int ) -> Dict[
		str, Any ]:
		"""Build the transcription generation configuration.

		Purpose:
			Converts supported Jeni inference controls into the Interactions generation
			configuration.

		Args:
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			max_tokens (int): Maximum output-token count.

		Returns:
			Dict[str, Any]: Interactions generation configuration.

		Raises:
			Error: Raised when configuration construction fails.
		"""
		try:
			self.temperature = temperature
			self.top_p = top_p
			self.max_tokens = max_tokens
			self.generation_config = { }
			if self.temperature is not None:
				self.generation_config[ 'temperature' ] = self.temperature

			if self.top_p is not None:
				self.generation_config[ 'top_p' ] = self.top_p

			if self.max_tokens is not None and self.max_tokens > 0:
				self.generation_config[ 'max_output_tokens' ] = (self.max_tokens)

			return self.generation_config
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Transcription'
			exception.method = ('build_generation_config( self, temperature: float, top_p: float, '
			                    'max_tokens: int ) -> Dict[str, Any]')
			Logger( ).write( exception )
			raise exception

	def transcribe( self, path: str, model: str='gemini-3.6-flash', language: str=None,
		mime_type: str=None, temperature: float=None, top_p: float=None,
		frequency: float=None, presence: float=None, max_tokens: int=None,
		start_time: float=0.0, end_time: float=0.0, instruct: str=None ) -> str:
		"""Transcribe audio through the Gemini Interactions API.

		Purpose:
			Uploads the local audio file, constructs a multimodal Interactions request using the
			uploaded file URI and MIME type, and returns the generated transcript.

		Args:
			path (str): Local audio-file path.
			model (str): Gemini audio-understanding model.
			language (str): Optional spoken-language hint.
			mime_type (str): Optional explicit audio MIME type.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			frequency (float): Frequency penalty retained for UI compatibility.
			presence (float): Presence penalty retained for UI compatibility.
			max_tokens (int): Maximum output-token count.
			start_time (float): Optional starting timestamp in seconds.
			end_time (float): Optional ending timestamp in seconds.
			instruct (str): Optional system instruction text.

		Returns:
			str: Generated transcript.

		Raises:
			Error: Raised when validation, upload, request execution, or response extraction
				fails.
			ValueError: Raised when required input is missing or the transcript is empty.
		"""
		try:
			throw_if( 'path', path )
			self.file_path = path
			self.model = str( model or self.model or 'gemini-3.6-flash' ).strip( )
			throw_if( 'model', self.model )
			self.language = language
			self.mime_type = mime_type
			self.temperature = (temperature if temperature is not None else self.temperature)
			self.top_p = top_p if top_p is not None else self.top_p
			self.frequency_penalty = (
				frequency if frequency is not None else self.frequency_penalty)
			self.presence_penalty = (presence if presence is not None else self.presence_penalty)
			self.max_tokens = (max_tokens if max_tokens is not None else self.max_tokens)
			self.start_time = start_time
			self.end_time = end_time
			self.instructions = (instruct if instruct is not None else self.instructions)
			self.mime_type = self.normalize_mime_type( path=self.file_path,
				mime_type=self.mime_type )
			self.prompt = self.build_prompt( language=self.language, start_time=self.start_time,
				end_time=self.end_time )
			self.generation_config = self.build_generation_config( temperature=self.temperature,
				top_p=self.top_p, max_tokens=self.max_tokens )
			self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
				'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
			throw_if( 'api_key', self.api_key )

			self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )
			self.uploaded_file = self.client.files.upload( file=self.file_path )
			self.file_uri = str( getattr( self.uploaded_file, 'uri', '' ) or '' ).strip( )
			throw_if( 'file_uri', self.file_uri )

			self.uploaded_mime_type = str(
				getattr( self.uploaded_file, 'mime_type', '' ) or self.mime_type ).strip( )

			self.request: Dict[ str, Any ] = { 'model': self.model,
				'input': [ { 'type': 'text', 'text': self.prompt, },
					{ 'type': 'audio', 'uri': self.file_uri,
						'mime_type': self.uploaded_mime_type, }, ],
				'response_format': { 'type': 'text', }, 'store': False, }
			if self.instructions is not None and str( self.instructions ).strip( ):
				self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

			if self.generation_config:
				self.request[ 'generation_config' ] = (self.generation_config)

			self.interaction = self.client.interactions.create( **self.request )
			self.response = self.interaction
			self.content_response = self.interaction
			self.transcript = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )

			if not self.transcript:
				raise ValueError( 'Gemini returned an empty transcription.' )

			return self.transcript
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Transcription'
			exception.method = ('transcribe( self, path: str, model: str, language: str, mime_type: '
			                    'str, temperature: float, top_p: float, frequency: float, '
			                    'presence: float, max_tokens: int, start_time: float, end_time: '
			                    'float, instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

model_options property

model_options: List[str]

Return supported audio-transcription models.

Purpose

Provides the Gemini audio-understanding model identifiers exposed by the Jeni Audio mode.

Returns:

Type Description
List[str]

List[str]: Supported Gemini transcription-model identifiers.

language_options property

language_options: List[str]

Return supported transcription language hints.

Purpose

Provides optional spoken-language hints consumed by the Jeni Audio controls.

Returns:

Type Description
List[str]

List[str]: Supported language-hint values.

mime_options property

mime_options: List[str]

Return supported audio MIME types.

Purpose

Provides audio MIME-type values accepted by the Jeni Audio mode.

Returns:

Type Description
List[str]

List[str]: Supported audio MIME types.

__init__

__init__(
    n: int = 1,
    model: str = "gemini-3.6-flash",
    temperature: float = 0.8,
    top_p: float = 0.9,
    frequency: float = 0.0,
    presence: float = 0.0,
    max_tokens: int = 10000,
    instruct: str = None,
) -> None

Initialize the Transcription wrapper.

Purpose

Initializes transcription settings, local file state, request configuration, and response placeholders. The constructor performs local state assignment only and does not create a provider client or submit a request.

Parameters:

Name Type Description Default
n int

Candidate-count value retained for interface compatibility.

1
model str

Default Gemini audio-understanding model.

'gemini-3.6-flash'
temperature float

Sampling temperature.

0.8
top_p float

Top-p sampling value.

0.9
frequency float

Frequency penalty retained for interface compatibility.

0.0
presence float

Presence penalty retained for interface compatibility.

0.0
max_tokens int

Maximum output-token count.

10000
instruct str

Optional system instruction text.

None

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self, n: int=1, model: str='gemini-3.6-flash', temperature: float=0.8,
	top_p: float=0.9, frequency: float=0.0, presence: float=0.0, max_tokens: int=10000,
	instruct: str=None ) -> None:
	"""Initialize the Transcription wrapper.

	Purpose:
		Initializes transcription settings, local file state, request configuration, and
		response placeholders. The constructor performs local state assignment only and does
		not create a provider client or submit a request.

	Args:
		n (int): Candidate-count value retained for interface compatibility.
		model (str): Default Gemini audio-understanding model.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		frequency (float): Frequency penalty retained for interface compatibility.
		presence (float): Presence penalty retained for interface compatibility.
		max_tokens (int): Maximum output-token count.
		instruct (str): Optional system instruction text.

	Returns:
		None: This method initializes object state through side effects.
	"""
	super( ).__init__( )
	self.number = n
	self.model = model
	self.temperature = temperature
	self.top_p = top_p
	self.frequency_penalty = frequency
	self.presence_penalty = presence
	self.max_tokens = max_tokens
	self.instructions = instruct
	self.api_version = 'v1beta'
	self.http_options = types.HttpOptions( api_version=self.api_version )
	self.client = None
	self.transcript = None
	self.file_path = None
	self.mime_type = None
	self.uploaded_file = None
	self.interaction = None
	self.response = None
	self.content_response = None
	self.generation_config = { }

normalize_mime_type

normalize_mime_type(
    path: str, mime_type: str = None
) -> str

Normalize an audio MIME type.

Purpose

Uses an explicitly supplied MIME type when available and otherwise derives the MIME type from the local file extension.

Parameters:

Name Type Description Default
path str

Local audio-file path.

required
mime_type str

Optional explicit audio MIME type.

None

Returns:

Name Type Description
str str

Normalized audio MIME type.

Raises:

Type Description
Error

Raised when validation or MIME-type normalization fails.

ValueError

Raised when path is missing.

Source code in gemini.py
def normalize_mime_type( self, path: str, mime_type: str=None ) -> str:
	"""Normalize an audio MIME type.

	Purpose:
		Uses an explicitly supplied MIME type when available and otherwise derives the MIME
		type from the local file extension.

	Args:
		path (str): Local audio-file path.
		mime_type (str): Optional explicit audio MIME type.

	Returns:
		str: Normalized audio MIME type.

	Raises:
		Error: Raised when validation or MIME-type normalization fails.
		ValueError: Raised when ``path`` is missing.
	"""
	try:
		import mimetypes

		throw_if( 'path', path )
		self.file_path = path
		self.mime_type = mime_type

		if self.mime_type is not None and str( self.mime_type ).strip( ):
			return str( self.mime_type ).strip( )

		self.guessed_mime_type = mimetypes.guess_type( self.file_path )[ 0 ]

		if self.guessed_mime_type:
			return self.guessed_mime_type

		self.file_suffix = Path( self.file_path ).suffix.lower( )
		self.mime_types = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.mpeg': 'audio/mpeg',
			'.mp4': 'audio/mp4', '.m4a': 'audio/x-m4a', '.aac': 'audio/aac',
			'.ogg': 'audio/ogg', '.oga': 'audio/ogg', '.flac': 'audio/flac',
			'.webm': 'audio/webm', }

		return self.mime_types.get( self.file_suffix, 'application/octet-stream' )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Transcription'
		exception.method = ('normalize_mime_type( self, path: str, mime_type: str ) -> str')
		Logger( ).write( exception )
		raise exception

build_prompt

build_prompt(
    language: str = None,
    start_time: float = 0.0,
    end_time: float = 0.0,
) -> str

Build the transcription prompt.

Purpose

Constructs the transcription instruction and adds optional spoken-language and time-range constraints without altering the source audio.

Parameters:

Name Type Description Default
language str

Optional spoken-language hint.

None
start_time float

Optional starting timestamp in seconds.

0.0
end_time float

Optional ending timestamp in seconds.

0.0

Returns:

Name Type Description
str str

Complete transcription prompt.

Raises:

Type Description
Error

Raised when prompt construction fails.

Source code in gemini.py
def build_prompt( self, language: str=None, start_time: float=0.0,
	end_time: float=0.0 ) -> str:
	"""Build the transcription prompt.

	Purpose:
		Constructs the transcription instruction and adds optional spoken-language and
		time-range constraints without altering the source audio.

	Args:
		language (str): Optional spoken-language hint.
		start_time (float): Optional starting timestamp in seconds.
		end_time (float): Optional ending timestamp in seconds.

	Returns:
		str: Complete transcription prompt.

	Raises:
		Error: Raised when prompt construction fails.
	"""
	try:
		self.language = language
		self.start_time = start_time
		self.end_time = end_time
		self.prompt_parts: List[ str ] = [
			'Transcribe the spoken content in this audio accurately.',
			'Return only the transcript unless the supplied instructions require '
			'additional formatting.', ]

		self.language_name = str( self.language or '' ).strip( )

		if self.language_name and self.language_name.lower( ) != 'auto detect':
			self.prompt_parts.append( f'The expected spoken language is '
			                          f'{self.language_name}.' )

		if self.start_time > 0.0 and self.end_time > self.start_time:
			self.prompt_parts.append(
				f'Transcribe only the segment from {self.start_time:.3f} seconds '
				f'through {self.end_time:.3f} seconds.' )

		elif self.start_time > 0.0:
			self.prompt_parts.append( f'Begin transcription at {self.start_time:.3f} '
			                          f'seconds.' )

		elif self.end_time > 0.0:
			self.prompt_parts.append( f'Stop transcription at {self.end_time:.3f} seconds.' )

		self.prompt = '\n'.join( self.prompt_parts )
		return self.prompt
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Transcription'
		exception.method = ('build_prompt( self, language: str, start_time: float, '
		                    'end_time: float ) -> str')
		Logger( ).write( exception )
		raise exception

build_generation_config

build_generation_config(
    temperature: float, top_p: float, max_tokens: int
) -> Dict[str, Any]

Build the transcription generation configuration.

Purpose

Converts supported Jeni inference controls into the Interactions generation configuration.

Parameters:

Name Type Description Default
temperature float

Sampling temperature.

required
top_p float

Top-p sampling value.

required
max_tokens int

Maximum output-token count.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Interactions generation configuration.

Raises:

Type Description
Error

Raised when configuration construction fails.

Source code in gemini.py
def build_generation_config( self, temperature: float, top_p: float, max_tokens: int ) -> Dict[
	str, Any ]:
	"""Build the transcription generation configuration.

	Purpose:
		Converts supported Jeni inference controls into the Interactions generation
		configuration.

	Args:
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		max_tokens (int): Maximum output-token count.

	Returns:
		Dict[str, Any]: Interactions generation configuration.

	Raises:
		Error: Raised when configuration construction fails.
	"""
	try:
		self.temperature = temperature
		self.top_p = top_p
		self.max_tokens = max_tokens
		self.generation_config = { }
		if self.temperature is not None:
			self.generation_config[ 'temperature' ] = self.temperature

		if self.top_p is not None:
			self.generation_config[ 'top_p' ] = self.top_p

		if self.max_tokens is not None and self.max_tokens > 0:
			self.generation_config[ 'max_output_tokens' ] = (self.max_tokens)

		return self.generation_config
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Transcription'
		exception.method = ('build_generation_config( self, temperature: float, top_p: float, '
		                    'max_tokens: int ) -> Dict[str, Any]')
		Logger( ).write( exception )
		raise exception

transcribe

transcribe(
    path: str,
    model: str = "gemini-3.6-flash",
    language: str = None,
    mime_type: str = None,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    start_time: float = 0.0,
    end_time: float = 0.0,
    instruct: str = None,
) -> str

Transcribe audio through the Gemini Interactions API.

Purpose

Uploads the local audio file, constructs a multimodal Interactions request using the uploaded file URI and MIME type, and returns the generated transcript.

Parameters:

Name Type Description Default
path str

Local audio-file path.

required
model str

Gemini audio-understanding model.

'gemini-3.6-flash'
language str

Optional spoken-language hint.

None
mime_type str

Optional explicit audio MIME type.

None
temperature float

Sampling temperature.

None
top_p float

Top-p sampling value.

None
frequency float

Frequency penalty retained for UI compatibility.

None
presence float

Presence penalty retained for UI compatibility.

None
max_tokens int

Maximum output-token count.

None
start_time float

Optional starting timestamp in seconds.

0.0
end_time float

Optional ending timestamp in seconds.

0.0
instruct str

Optional system instruction text.

None

Returns:

Name Type Description
str str

Generated transcript.

Raises:

Type Description
Error

Raised when validation, upload, request execution, or response extraction fails.

ValueError

Raised when required input is missing or the transcript is empty.

Source code in gemini.py
def transcribe( self, path: str, model: str='gemini-3.6-flash', language: str=None,
	mime_type: str=None, temperature: float=None, top_p: float=None,
	frequency: float=None, presence: float=None, max_tokens: int=None,
	start_time: float=0.0, end_time: float=0.0, instruct: str=None ) -> str:
	"""Transcribe audio through the Gemini Interactions API.

	Purpose:
		Uploads the local audio file, constructs a multimodal Interactions request using the
		uploaded file URI and MIME type, and returns the generated transcript.

	Args:
		path (str): Local audio-file path.
		model (str): Gemini audio-understanding model.
		language (str): Optional spoken-language hint.
		mime_type (str): Optional explicit audio MIME type.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		frequency (float): Frequency penalty retained for UI compatibility.
		presence (float): Presence penalty retained for UI compatibility.
		max_tokens (int): Maximum output-token count.
		start_time (float): Optional starting timestamp in seconds.
		end_time (float): Optional ending timestamp in seconds.
		instruct (str): Optional system instruction text.

	Returns:
		str: Generated transcript.

	Raises:
		Error: Raised when validation, upload, request execution, or response extraction
			fails.
		ValueError: Raised when required input is missing or the transcript is empty.
	"""
	try:
		throw_if( 'path', path )
		self.file_path = path
		self.model = str( model or self.model or 'gemini-3.6-flash' ).strip( )
		throw_if( 'model', self.model )
		self.language = language
		self.mime_type = mime_type
		self.temperature = (temperature if temperature is not None else self.temperature)
		self.top_p = top_p if top_p is not None else self.top_p
		self.frequency_penalty = (
			frequency if frequency is not None else self.frequency_penalty)
		self.presence_penalty = (presence if presence is not None else self.presence_penalty)
		self.max_tokens = (max_tokens if max_tokens is not None else self.max_tokens)
		self.start_time = start_time
		self.end_time = end_time
		self.instructions = (instruct if instruct is not None else self.instructions)
		self.mime_type = self.normalize_mime_type( path=self.file_path,
			mime_type=self.mime_type )
		self.prompt = self.build_prompt( language=self.language, start_time=self.start_time,
			end_time=self.end_time )
		self.generation_config = self.build_generation_config( temperature=self.temperature,
			top_p=self.top_p, max_tokens=self.max_tokens )
		self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
			'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
		throw_if( 'api_key', self.api_key )

		self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )
		self.uploaded_file = self.client.files.upload( file=self.file_path )
		self.file_uri = str( getattr( self.uploaded_file, 'uri', '' ) or '' ).strip( )
		throw_if( 'file_uri', self.file_uri )

		self.uploaded_mime_type = str(
			getattr( self.uploaded_file, 'mime_type', '' ) or self.mime_type ).strip( )

		self.request: Dict[ str, Any ] = { 'model': self.model,
			'input': [ { 'type': 'text', 'text': self.prompt, },
				{ 'type': 'audio', 'uri': self.file_uri,
					'mime_type': self.uploaded_mime_type, }, ],
			'response_format': { 'type': 'text', }, 'store': False, }
		if self.instructions is not None and str( self.instructions ).strip( ):
			self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

		if self.generation_config:
			self.request[ 'generation_config' ] = (self.generation_config)

		self.interaction = self.client.interactions.create( **self.request )
		self.response = self.interaction
		self.content_response = self.interaction
		self.transcript = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )

		if not self.transcript:
			raise ValueError( 'Gemini returned an empty transcription.' )

		return self.transcript
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Transcription'
		exception.method = ('transcribe( self, path: str, model: str, language: str, mime_type: '
		                    'str, temperature: float, top_p: float, frequency: float, '
		                    'presence: float, max_tokens: int, start_time: float, end_time: '
		                    'float, instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception

Translation

Bases: Gemini

Gemini audio-translation wrapper.

Purpose

Translates spoken audio into target-language text through the Gemini Interactions API. The class normalizes audio MIME types, builds translation instructions with source and target language hints, uploads the local audio through the Gemini Files API, and submits the uploaded audio as multimodal Interactions input.

Attributes:

Name Type Description
client Optional[Client]

Active Gemini SDK client.

http_options HttpOptions

Gemini client HTTP configuration.

target_language Optional[str]

Requested translation target language.

source_language Optional[str]

Optional spoken source-language hint.

file_path Optional[str]

Local audio-file path.

mime_type Optional[str]

Normalized audio MIME type.

translation Optional[str]

Text returned by the translation request.

uploaded_file Optional[File]

File resource uploaded to Gemini.

interaction Optional[Any]

Most recent Gemini Interaction.

response Optional[Any]

Raw Interaction consumed by application token accounting.

generation_config Dict[str, Any]

Interactions generation configuration.

Source code in gemini.py
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
3716
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
class Translation( Gemini ):
	"""Gemini audio-translation wrapper.

	Purpose:
		Translates spoken audio into target-language text through the Gemini Interactions API.
		The class normalizes audio MIME types, builds translation instructions with source and
		target language hints, uploads the local audio through the Gemini Files API, and submits
		the uploaded audio as multimodal Interactions input.

	Attributes:
		client (Optional[genai.Client]): Active Gemini SDK client.
		http_options (HttpOptions): Gemini client HTTP configuration.
		target_language (Optional[str]): Requested translation target language.
		source_language (Optional[str]): Optional spoken source-language hint.
		file_path (Optional[str]): Local audio-file path.
		mime_type (Optional[str]): Normalized audio MIME type.
		translation (Optional[str]): Text returned by the translation request.
		uploaded_file (Optional[File]): File resource uploaded to Gemini.
		interaction (Optional[Any]): Most recent Gemini Interaction.
		response (Optional[Any]): Raw Interaction consumed by application token accounting.
		generation_config (Dict[str, Any]): Interactions generation configuration.
	"""

	client: Optional[ genai.Client ]
	http_options: HttpOptions
	target_language: Optional[ str ]
	source_language: Optional[ str ]
	file_path: Optional[ str ]
	mime_type: Optional[ str ]
	translation: Optional[ str ]
	uploaded_file: Optional[ File ]
	interaction: Optional[ Any ]
	response: Optional[ Any ]
	generation_config: Dict[ str, Any ]

	def __init__( self, n: int=1, model: str='gemini-3.6-flash', temperature: float=0.8,
		top_p: float=0.9, frequency: float=0.0, presence: float=0.0, max_tokens: int=10000,
		instruct: str=None ) -> None:
		"""Initialize the Translation wrapper.

		Purpose:
			Initializes translation settings, language state, local file state, request
			configuration, and response placeholders. The constructor performs local state
			assignment only.

		Args:
			n (int): Candidate-count value retained for interface compatibility.
			model (str): Default Gemini audio-understanding model.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			frequency (float): Frequency penalty retained for interface compatibility.
			presence (float): Presence penalty retained for interface compatibility.
			max_tokens (int): Maximum output-token count.
			instruct (str): Optional system instruction text.

		Returns:
			None: This method initializes object state through side effects.
		"""
		super( ).__init__( )
		self.number = n
		self.model = model
		self.temperature = temperature
		self.top_p = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.instructions = instruct
		self.api_version = 'v1beta'
		self.http_options = types.HttpOptions( api_version=self.api_version )
		self.client = None
		self.target_language = None
		self.source_language = None
		self.file_path = None
		self.mime_type = None
		self.translation = None
		self.uploaded_file = None
		self.interaction = None
		self.response = None
		self.content_response = None
		self.generation_config = { }

	@property
	def model_options( self ) -> List[ str ]:
		"""Return supported audio-translation models.

		Purpose:
			Provides the Gemini audio-understanding model identifiers exposed by the Jeni Audio
			mode.

		Returns:
			List[str]: Supported Gemini translation-model identifiers.
		"""
		return [ 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.1-pro-preview',
			'gemini-2.5-flash', 'gemini-2.5-pro', ]

	@property
	def language_options( self ) -> List[ str ]:
		"""Return supported translation languages.

		Purpose:
			Provides source and target language values consumed by the Jeni Audio controls.

		Returns:
			List[str]: Supported translation language values.
		"""
		return [ 'English', 'Spanish', 'French', 'German', 'Italian', 'Portuguese', 'Dutch',
			'Russian', 'Ukrainian', 'Polish', 'Arabic', 'Hebrew', 'Hindi', 'Bengali', 'Urdu',
			'Chinese', 'Japanese', 'Korean', 'Vietnamese', 'Thai', 'Indonesian', 'Filipino', ]

	def normalize_mime_type( self, path: str, mime_type: str=None ) -> str:
		"""Normalize an audio MIME type.

		Purpose:
			Uses an explicitly supplied MIME type when available and otherwise derives the MIME
			type from the local file extension.

		Args:
			path (str): Local audio-file path.
			mime_type (str): Optional explicit audio MIME type.

		Returns:
			str: Normalized audio MIME type.

		Raises:
			Error: Raised when validation or MIME-type normalization fails.
			ValueError: Raised when ``path`` is missing.
		"""
		try:
			import mimetypes

			throw_if( 'path', path )
			self.file_path = path
			self.mime_type = mime_type
			if self.mime_type is not None and str( self.mime_type ).strip( ):
				return str( self.mime_type ).strip( )

			self.guessed_mime_type = mimetypes.guess_type( self.file_path )[ 0 ]
			if self.guessed_mime_type:
				return self.guessed_mime_type

			self.file_suffix = Path( self.file_path ).suffix.lower( )
			self.mime_types = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.mpeg': 'audio/mpeg',
				'.mp4': 'audio/mp4', '.m4a': 'audio/x-m4a', '.aac': 'audio/aac',
				'.ogg': 'audio/ogg', '.oga': 'audio/ogg', '.flac': 'audio/flac',
				'.webm': 'audio/webm', }

			return self.mime_types.get( self.file_suffix, 'application/octet-stream' )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Translation'
			exception.method = ('normalize_mime_type( self, path: str, mime_type: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def build_prompt( self, target_language: str, source_language: str=None,
		start_time: float=0.0, end_time: float=0.0 ) -> str:
		"""Build the audio-translation prompt.

		Purpose:
			Constructs a target-language translation instruction and adds optional source-language
			and time-range constraints.

		Args:
			target_language (str): Requested translation target language.
			source_language (str): Optional spoken source-language hint.
			start_time (float): Optional starting timestamp in seconds.
			end_time (float): Optional ending timestamp in seconds.

		Returns:
			str: Complete translation prompt.

		Raises:
			Error: Raised when validation or prompt construction fails.
			ValueError: Raised when ``target_language`` is missing.
		"""
		try:
			throw_if( 'target_language', target_language )
			self.target_language = target_language
			self.source_language = source_language
			self.start_time = start_time
			self.end_time = end_time
			self.prompt_parts: List[ str ] = [ f'Translate all spoken content in this audio into '
			                                   f'{self.target_language}.',
				'Return only the translated text unless the supplied instructions require '
				'additional formatting.',
				'Preserve the original meaning, tone, names, numbers, and technical '
				'terminology.', ]

			self.source_language_name = str( self.source_language or '' ).strip( )
			if self.source_language_name and self.source_language_name.lower( ) != 'auto detect':
				self.prompt_parts.append( f'The expected source language is '
				                          f'{self.source_language_name}.' )

			if self.start_time > 0.0 and self.end_time > self.start_time:
				self.prompt_parts.append(
					f'Translate only the segment from {self.start_time:.3f} seconds '
					f'through {self.end_time:.3f} seconds.' )

			elif self.start_time > 0.0:
				self.prompt_parts.append( f'Begin translation at {self.start_time:.3f} seconds.' )

			elif self.end_time > 0.0:
				self.prompt_parts.append( f'Stop translation at {self.end_time:.3f} seconds.' )

			self.prompt = '\n'.join( self.prompt_parts )
			return self.prompt
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Translation'
			exception.method = ('build_prompt( self, target_language: str, source_language: str, '
			                    'start_time: float, end_time: float ) -> str')
			Logger( ).write( exception )
			raise exception

	def build_generation_config( self, temperature: float, top_p: float, max_tokens: int ) -> Dict[
		str, Any ]:
		"""Build the translation generation configuration.

		Purpose:
			Converts supported Jeni inference controls into the Interactions generation
			configuration.

		Args:
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			max_tokens (int): Maximum output-token count.

		Returns:
			Dict[str, Any]: Interactions generation configuration.

		Raises:
			Error: Raised when configuration construction fails.
		"""
		try:
			self.temperature = temperature
			self.top_p = top_p
			self.max_tokens = max_tokens
			self.generation_config = { }
			if self.temperature is not None:
				self.generation_config[ 'temperature' ] = self.temperature

			if self.top_p is not None:
				self.generation_config[ 'top_p' ] = self.top_p

			if self.max_tokens is not None and self.max_tokens > 0:
				self.generation_config[ 'max_output_tokens' ] = (self.max_tokens)

			return self.generation_config
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Translation'
			exception.method = ('build_generation_config( self, temperature: float, top_p: float, '
			                    'max_tokens: int ) -> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def translate( self, path: str, target_language: str, model: str='gemini-3.6-flash',
		source_language: str=None, mime_type: str=None, temperature: float=None,
		top_p: float=None, frequency: float=None, presence: float=None,
		max_tokens: int=None, start_time: float=0.0, end_time: float=0.0,
		instruct: str=None ) -> str:
		"""Translate audio through the Gemini Interactions API.

		Purpose:
			Uploads the local audio file, constructs a multimodal Interactions request using the
			uploaded file URI and MIME type, and returns the generated target-language text.

		Args:
			path (str): Local audio-file path.
			target_language (str): Requested translation target language.
			model (str): Gemini audio-understanding model.
			source_language (str): Optional spoken source-language hint.
			mime_type (str): Optional explicit audio MIME type.
			temperature (float): Sampling temperature.
			top_p (float): Top-p sampling value.
			frequency (float): Frequency penalty retained for UI compatibility.
			presence (float): Presence penalty retained for UI compatibility.
			max_tokens (int): Maximum output-token count.
			start_time (float): Optional starting timestamp in seconds.
			end_time (float): Optional ending timestamp in seconds.
			instruct (str): Optional system instruction text.

		Returns:
			str: Generated target-language translation.

		Raises:
			Error: Raised when validation, upload, request execution, or response extraction
				fails.
			ValueError: Raised when required input is missing or the translation is empty.
		"""
		try:
			throw_if( 'path', path )
			throw_if( 'target_language', target_language )
			self.file_path = path
			self.target_language = target_language
			self.model = str( model or self.model or 'gemini-3.6-flash' ).strip( )
			throw_if( 'model', self.model )
			self.source_language = source_language
			self.mime_type = mime_type
			self.temperature = (temperature if temperature is not None else self.temperature)
			self.top_p = top_p if top_p is not None else self.top_p
			self.frequency_penalty = (
				frequency if frequency is not None else self.frequency_penalty)
			self.presence_penalty = (presence if presence is not None else self.presence_penalty)
			self.max_tokens = (max_tokens if max_tokens is not None else self.max_tokens)
			self.start_time = start_time
			self.end_time = end_time
			self.instructions = (instruct if instruct is not None else self.instructions)
			self.mime_type = self.normalize_mime_type( path=self.file_path,
				mime_type=self.mime_type )
			self.prompt = self.build_prompt( target_language=self.target_language,
				source_language=self.source_language, start_time=self.start_time,
				end_time=self.end_time )
			self.generation_config = self.build_generation_config( temperature=self.temperature,
				top_p=self.top_p, max_tokens=self.max_tokens )
			self.api_key = self.gemini_api_key or self.google_api_key
			self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )
			self.uploaded_file = self.client.files.upload( file=self.file_path )
			self.file_uri = str( getattr( self.uploaded_file, 'uri', '' ) or '' ).strip( )
			throw_if( 'file_uri', self.file_uri )
			self.uploaded_mime_type = str(
				getattr( self.uploaded_file, 'mime_type', '' ) or self.mime_type ).strip( )

			self.request: Dict[ str, Any ] = { 'model': self.model,
				'input': [ { 'type': 'text', 'text': self.prompt, },
					{ 'type': 'audio', 'uri': self.file_uri,
						'mime_type': self.uploaded_mime_type, }, ],
				'response_format': { 'type': 'text', }, 'store': False, }

			if self.instructions is not None and str( self.instructions ).strip( ):
				self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

			if self.generation_config:
				self.request[ 'generation_config' ] = (self.generation_config)

			self.interaction = self.client.interactions.create( **self.request )
			self.response = self.interaction
			self.content_response = self.interaction
			self.translation = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
			if not self.translation:
				raise ValueError( 'Gemini returned an empty audio translation.' )

			return self.translation
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Translation'
			exception.method = ('translate( self, path: str, target_language: str, model: str, '
			                    'source_language: str, mime_type: str, temperature: float, '
			                    'top_p: float, frequency: float, presence: float, max_tokens: int, '
			                    'start_time: float, end_time: float, instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

model_options property

model_options: List[str]

Return supported audio-translation models.

Purpose

Provides the Gemini audio-understanding model identifiers exposed by the Jeni Audio mode.

Returns:

Type Description
List[str]

List[str]: Supported Gemini translation-model identifiers.

language_options property

language_options: List[str]

Return supported translation languages.

Purpose

Provides source and target language values consumed by the Jeni Audio controls.

Returns:

Type Description
List[str]

List[str]: Supported translation language values.

__init__

__init__(
    n: int = 1,
    model: str = "gemini-3.6-flash",
    temperature: float = 0.8,
    top_p: float = 0.9,
    frequency: float = 0.0,
    presence: float = 0.0,
    max_tokens: int = 10000,
    instruct: str = None,
) -> None

Initialize the Translation wrapper.

Purpose

Initializes translation settings, language state, local file state, request configuration, and response placeholders. The constructor performs local state assignment only.

Parameters:

Name Type Description Default
n int

Candidate-count value retained for interface compatibility.

1
model str

Default Gemini audio-understanding model.

'gemini-3.6-flash'
temperature float

Sampling temperature.

0.8
top_p float

Top-p sampling value.

0.9
frequency float

Frequency penalty retained for interface compatibility.

0.0
presence float

Presence penalty retained for interface compatibility.

0.0
max_tokens int

Maximum output-token count.

10000
instruct str

Optional system instruction text.

None

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self, n: int=1, model: str='gemini-3.6-flash', temperature: float=0.8,
	top_p: float=0.9, frequency: float=0.0, presence: float=0.0, max_tokens: int=10000,
	instruct: str=None ) -> None:
	"""Initialize the Translation wrapper.

	Purpose:
		Initializes translation settings, language state, local file state, request
		configuration, and response placeholders. The constructor performs local state
		assignment only.

	Args:
		n (int): Candidate-count value retained for interface compatibility.
		model (str): Default Gemini audio-understanding model.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		frequency (float): Frequency penalty retained for interface compatibility.
		presence (float): Presence penalty retained for interface compatibility.
		max_tokens (int): Maximum output-token count.
		instruct (str): Optional system instruction text.

	Returns:
		None: This method initializes object state through side effects.
	"""
	super( ).__init__( )
	self.number = n
	self.model = model
	self.temperature = temperature
	self.top_p = top_p
	self.frequency_penalty = frequency
	self.presence_penalty = presence
	self.max_tokens = max_tokens
	self.instructions = instruct
	self.api_version = 'v1beta'
	self.http_options = types.HttpOptions( api_version=self.api_version )
	self.client = None
	self.target_language = None
	self.source_language = None
	self.file_path = None
	self.mime_type = None
	self.translation = None
	self.uploaded_file = None
	self.interaction = None
	self.response = None
	self.content_response = None
	self.generation_config = { }

normalize_mime_type

normalize_mime_type(
    path: str, mime_type: str = None
) -> str

Normalize an audio MIME type.

Purpose

Uses an explicitly supplied MIME type when available and otherwise derives the MIME type from the local file extension.

Parameters:

Name Type Description Default
path str

Local audio-file path.

required
mime_type str

Optional explicit audio MIME type.

None

Returns:

Name Type Description
str str

Normalized audio MIME type.

Raises:

Type Description
Error

Raised when validation or MIME-type normalization fails.

ValueError

Raised when path is missing.

Source code in gemini.py
def normalize_mime_type( self, path: str, mime_type: str=None ) -> str:
	"""Normalize an audio MIME type.

	Purpose:
		Uses an explicitly supplied MIME type when available and otherwise derives the MIME
		type from the local file extension.

	Args:
		path (str): Local audio-file path.
		mime_type (str): Optional explicit audio MIME type.

	Returns:
		str: Normalized audio MIME type.

	Raises:
		Error: Raised when validation or MIME-type normalization fails.
		ValueError: Raised when ``path`` is missing.
	"""
	try:
		import mimetypes

		throw_if( 'path', path )
		self.file_path = path
		self.mime_type = mime_type
		if self.mime_type is not None and str( self.mime_type ).strip( ):
			return str( self.mime_type ).strip( )

		self.guessed_mime_type = mimetypes.guess_type( self.file_path )[ 0 ]
		if self.guessed_mime_type:
			return self.guessed_mime_type

		self.file_suffix = Path( self.file_path ).suffix.lower( )
		self.mime_types = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.mpeg': 'audio/mpeg',
			'.mp4': 'audio/mp4', '.m4a': 'audio/x-m4a', '.aac': 'audio/aac',
			'.ogg': 'audio/ogg', '.oga': 'audio/ogg', '.flac': 'audio/flac',
			'.webm': 'audio/webm', }

		return self.mime_types.get( self.file_suffix, 'application/octet-stream' )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Translation'
		exception.method = ('normalize_mime_type( self, path: str, mime_type: str ) -> str')
		Logger( ).write( exception )
		raise exception

build_prompt

build_prompt(
    target_language: str,
    source_language: str = None,
    start_time: float = 0.0,
    end_time: float = 0.0,
) -> str

Build the audio-translation prompt.

Purpose

Constructs a target-language translation instruction and adds optional source-language and time-range constraints.

Parameters:

Name Type Description Default
target_language str

Requested translation target language.

required
source_language str

Optional spoken source-language hint.

None
start_time float

Optional starting timestamp in seconds.

0.0
end_time float

Optional ending timestamp in seconds.

0.0

Returns:

Name Type Description
str str

Complete translation prompt.

Raises:

Type Description
Error

Raised when validation or prompt construction fails.

ValueError

Raised when target_language is missing.

Source code in gemini.py
def build_prompt( self, target_language: str, source_language: str=None,
	start_time: float=0.0, end_time: float=0.0 ) -> str:
	"""Build the audio-translation prompt.

	Purpose:
		Constructs a target-language translation instruction and adds optional source-language
		and time-range constraints.

	Args:
		target_language (str): Requested translation target language.
		source_language (str): Optional spoken source-language hint.
		start_time (float): Optional starting timestamp in seconds.
		end_time (float): Optional ending timestamp in seconds.

	Returns:
		str: Complete translation prompt.

	Raises:
		Error: Raised when validation or prompt construction fails.
		ValueError: Raised when ``target_language`` is missing.
	"""
	try:
		throw_if( 'target_language', target_language )
		self.target_language = target_language
		self.source_language = source_language
		self.start_time = start_time
		self.end_time = end_time
		self.prompt_parts: List[ str ] = [ f'Translate all spoken content in this audio into '
		                                   f'{self.target_language}.',
			'Return only the translated text unless the supplied instructions require '
			'additional formatting.',
			'Preserve the original meaning, tone, names, numbers, and technical '
			'terminology.', ]

		self.source_language_name = str( self.source_language or '' ).strip( )
		if self.source_language_name and self.source_language_name.lower( ) != 'auto detect':
			self.prompt_parts.append( f'The expected source language is '
			                          f'{self.source_language_name}.' )

		if self.start_time > 0.0 and self.end_time > self.start_time:
			self.prompt_parts.append(
				f'Translate only the segment from {self.start_time:.3f} seconds '
				f'through {self.end_time:.3f} seconds.' )

		elif self.start_time > 0.0:
			self.prompt_parts.append( f'Begin translation at {self.start_time:.3f} seconds.' )

		elif self.end_time > 0.0:
			self.prompt_parts.append( f'Stop translation at {self.end_time:.3f} seconds.' )

		self.prompt = '\n'.join( self.prompt_parts )
		return self.prompt
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Translation'
		exception.method = ('build_prompt( self, target_language: str, source_language: str, '
		                    'start_time: float, end_time: float ) -> str')
		Logger( ).write( exception )
		raise exception

build_generation_config

build_generation_config(
    temperature: float, top_p: float, max_tokens: int
) -> Dict[str, Any]

Build the translation generation configuration.

Purpose

Converts supported Jeni inference controls into the Interactions generation configuration.

Parameters:

Name Type Description Default
temperature float

Sampling temperature.

required
top_p float

Top-p sampling value.

required
max_tokens int

Maximum output-token count.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Interactions generation configuration.

Raises:

Type Description
Error

Raised when configuration construction fails.

Source code in gemini.py
def build_generation_config( self, temperature: float, top_p: float, max_tokens: int ) -> Dict[
	str, Any ]:
	"""Build the translation generation configuration.

	Purpose:
		Converts supported Jeni inference controls into the Interactions generation
		configuration.

	Args:
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		max_tokens (int): Maximum output-token count.

	Returns:
		Dict[str, Any]: Interactions generation configuration.

	Raises:
		Error: Raised when configuration construction fails.
	"""
	try:
		self.temperature = temperature
		self.top_p = top_p
		self.max_tokens = max_tokens
		self.generation_config = { }
		if self.temperature is not None:
			self.generation_config[ 'temperature' ] = self.temperature

		if self.top_p is not None:
			self.generation_config[ 'top_p' ] = self.top_p

		if self.max_tokens is not None and self.max_tokens > 0:
			self.generation_config[ 'max_output_tokens' ] = (self.max_tokens)

		return self.generation_config
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Translation'
		exception.method = ('build_generation_config( self, temperature: float, top_p: float, '
		                    'max_tokens: int ) -> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

translate

translate(
    path: str,
    target_language: str,
    model: str = "gemini-3.6-flash",
    source_language: str = None,
    mime_type: str = None,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    start_time: float = 0.0,
    end_time: float = 0.0,
    instruct: str = None,
) -> str

Translate audio through the Gemini Interactions API.

Purpose

Uploads the local audio file, constructs a multimodal Interactions request using the uploaded file URI and MIME type, and returns the generated target-language text.

Parameters:

Name Type Description Default
path str

Local audio-file path.

required
target_language str

Requested translation target language.

required
model str

Gemini audio-understanding model.

'gemini-3.6-flash'
source_language str

Optional spoken source-language hint.

None
mime_type str

Optional explicit audio MIME type.

None
temperature float

Sampling temperature.

None
top_p float

Top-p sampling value.

None
frequency float

Frequency penalty retained for UI compatibility.

None
presence float

Presence penalty retained for UI compatibility.

None
max_tokens int

Maximum output-token count.

None
start_time float

Optional starting timestamp in seconds.

0.0
end_time float

Optional ending timestamp in seconds.

0.0
instruct str

Optional system instruction text.

None

Returns:

Name Type Description
str str

Generated target-language translation.

Raises:

Type Description
Error

Raised when validation, upload, request execution, or response extraction fails.

ValueError

Raised when required input is missing or the translation is empty.

Source code in gemini.py
def translate( self, path: str, target_language: str, model: str='gemini-3.6-flash',
	source_language: str=None, mime_type: str=None, temperature: float=None,
	top_p: float=None, frequency: float=None, presence: float=None,
	max_tokens: int=None, start_time: float=0.0, end_time: float=0.0,
	instruct: str=None ) -> str:
	"""Translate audio through the Gemini Interactions API.

	Purpose:
		Uploads the local audio file, constructs a multimodal Interactions request using the
		uploaded file URI and MIME type, and returns the generated target-language text.

	Args:
		path (str): Local audio-file path.
		target_language (str): Requested translation target language.
		model (str): Gemini audio-understanding model.
		source_language (str): Optional spoken source-language hint.
		mime_type (str): Optional explicit audio MIME type.
		temperature (float): Sampling temperature.
		top_p (float): Top-p sampling value.
		frequency (float): Frequency penalty retained for UI compatibility.
		presence (float): Presence penalty retained for UI compatibility.
		max_tokens (int): Maximum output-token count.
		start_time (float): Optional starting timestamp in seconds.
		end_time (float): Optional ending timestamp in seconds.
		instruct (str): Optional system instruction text.

	Returns:
		str: Generated target-language translation.

	Raises:
		Error: Raised when validation, upload, request execution, or response extraction
			fails.
		ValueError: Raised when required input is missing or the translation is empty.
	"""
	try:
		throw_if( 'path', path )
		throw_if( 'target_language', target_language )
		self.file_path = path
		self.target_language = target_language
		self.model = str( model or self.model or 'gemini-3.6-flash' ).strip( )
		throw_if( 'model', self.model )
		self.source_language = source_language
		self.mime_type = mime_type
		self.temperature = (temperature if temperature is not None else self.temperature)
		self.top_p = top_p if top_p is not None else self.top_p
		self.frequency_penalty = (
			frequency if frequency is not None else self.frequency_penalty)
		self.presence_penalty = (presence if presence is not None else self.presence_penalty)
		self.max_tokens = (max_tokens if max_tokens is not None else self.max_tokens)
		self.start_time = start_time
		self.end_time = end_time
		self.instructions = (instruct if instruct is not None else self.instructions)
		self.mime_type = self.normalize_mime_type( path=self.file_path,
			mime_type=self.mime_type )
		self.prompt = self.build_prompt( target_language=self.target_language,
			source_language=self.source_language, start_time=self.start_time,
			end_time=self.end_time )
		self.generation_config = self.build_generation_config( temperature=self.temperature,
			top_p=self.top_p, max_tokens=self.max_tokens )
		self.api_key = self.gemini_api_key or self.google_api_key
		self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )
		self.uploaded_file = self.client.files.upload( file=self.file_path )
		self.file_uri = str( getattr( self.uploaded_file, 'uri', '' ) or '' ).strip( )
		throw_if( 'file_uri', self.file_uri )
		self.uploaded_mime_type = str(
			getattr( self.uploaded_file, 'mime_type', '' ) or self.mime_type ).strip( )

		self.request: Dict[ str, Any ] = { 'model': self.model,
			'input': [ { 'type': 'text', 'text': self.prompt, },
				{ 'type': 'audio', 'uri': self.file_uri,
					'mime_type': self.uploaded_mime_type, }, ],
			'response_format': { 'type': 'text', }, 'store': False, }

		if self.instructions is not None and str( self.instructions ).strip( ):
			self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

		if self.generation_config:
			self.request[ 'generation_config' ] = (self.generation_config)

		self.interaction = self.client.interactions.create( **self.request )
		self.response = self.interaction
		self.content_response = self.interaction
		self.translation = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
		if not self.translation:
			raise ValueError( 'Gemini returned an empty audio translation.' )

		return self.translation
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Translation'
		exception.method = ('translate( self, path: str, target_language: str, model: str, '
		                    'source_language: str, mime_type: str, temperature: float, '
		                    'top_p: float, frequency: float, presence: float, max_tokens: int, '
		                    'start_time: float, end_time: float, instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception

Files

Bases: Gemini

Gemini file and document workflow wrapper.

Purpose

Manages Gemini Files API resources and executes document, web-search, and Google Maps model workflows. File lifecycle operations remain on the specialized Files API, while document reasoning and grounded generation use the Gemini Interactions API.

Attributes:

Name Type Description
client Optional[Client]

Active Google Gen AI client.

storage_client Optional[Client]

Google Cloud Storage client.

project_id Optional[str]

Google Cloud project identifier.

project_location Optional[str]

Google Cloud location.

file_id Optional[str]

Active Gemini file resource name.

bucket_id Optional[str]

Active Google Cloud Storage bucket name.

display_name Optional[str]

Uploaded file display name.

mime_type Optional[str]

Active file MIME type.

file_path Optional[str]

Active local file path.

file_list List[str]

Google Cloud Storage object names returned by the latest list operation.

file_paths List[str]

Local paths used by a multi-document request.

file_lists List[File]

Uploaded Gemini file resources used by a multi-document request.

response Optional[Any]

Most recent Files API or Interactions response.

interaction Optional[Any]

Most recent Gemini Interaction.

use_vertex bool

Compatibility flag retained for application configuration.

collections Dict[str, str]

Compatibility collection mapping.

documents Dict[str, str]

Compatibility document mapping.

Source code in gemini.py
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
class Files( Gemini ):
	"""Gemini file and document workflow wrapper.

	Purpose:
		Manages Gemini Files API resources and executes document, web-search, and Google Maps
		model workflows. File lifecycle operations remain on the specialized Files API, while
		document reasoning and grounded generation use the Gemini Interactions API.

	Attributes:
		client (Optional[genai.Client]): Active Google Gen AI client.
		storage_client (Optional[storage.Client]): Google Cloud Storage client.
		project_id (Optional[str]): Google Cloud project identifier.
		project_location (Optional[str]): Google Cloud location.
		file_id (Optional[str]): Active Gemini file resource name.
		bucket_id (Optional[str]): Active Google Cloud Storage bucket name.
		display_name (Optional[str]): Uploaded file display name.
		mime_type (Optional[str]): Active file MIME type.
		file_path (Optional[str]): Active local file path.
		file_list (List[str]): Google Cloud Storage object names returned by the latest list
			operation.
		file_paths (List[str]): Local paths used by a multi-document request.
		file_lists (List[File]): Uploaded Gemini file resources used by a multi-document request.
		response (Optional[Any]): Most recent Files API or Interactions response.
		interaction (Optional[Any]): Most recent Gemini Interaction.
		use_vertex (bool): Compatibility flag retained for application configuration.
		collections (Dict[str, str]): Compatibility collection mapping.
		documents (Dict[str, str]): Compatibility document mapping.
	"""

	client: Optional[ genai.Client ]
	storage_client: Optional[ storage.Client ]
	project_id: Optional[ str ]
	project_location: Optional[ str ]
	file_id: Optional[ str ]
	bucket_id: Optional[ str ]
	display_name: Optional[ str ]
	mime_type: Optional[ str ]
	file_path: Optional[ str ]
	file_list: List[ str ]
	file_paths: List[ str ]
	file_lists: List[ File ]
	response: Optional[ Any ]
	interaction: Optional[ Any ]
	use_vertex: bool
	collections: Dict[ str, str ]
	documents: Dict[ str, str ]

	def __init__( self, model: str='gemini-3.6-flash' ) -> None:
		"""Initialize the Files wrapper.

		Purpose:
			Initializes file lifecycle, document request, storage, and response state. The
			constructor performs local assignment only.

		Args:
			model (str): Default Gemini model used for document workflows.

		Returns:
			None: This method initializes object state through side effects.
		"""
		super( ).__init__( )
		self.google_api_key = cfg.GOOGLE_API_KEY
		self.gemini_api_key = cfg.GEMINI_API_KEY
		self.project_id = cfg.GOOGLE_CLOUD_PROJECT_ID
		self.project_location = cfg.GOOGLE_CLOUD_LOCATION
		self.model = model
		self.api_version = 'v1beta'
		self.http_options = types.HttpOptions( api_version=self.api_version )
		self.client = None
		self.storage_client = None
		self.bucket_id = None
		self.file_id = None
		self.display_name = None
		self.mime_type = None
		self.file_path = None
		self.file_list = [ ]
		self.file_paths = [ ]
		self.file_lists = [ ]
		self.files = [ ]
		self.response = None
		self.interaction = None
		self.use_vertex = False
		self.collections = { }
		self.documents = { }
		self.contents = None
		self.generation_config = { }
		self.tool_config = [ ]
		self.grounding_sources = [ ]

	@property
	def file_options( self ) -> List[ str ]:
		"""Return cached file resource names.

		Returns:
			List[str]: Cached Gemini file resource names.
		"""
		return list( self.files )

	@property
	def model_options( self ) -> List[ str ]:
		"""Return supported document models.

		Returns:
			List[str]: Supported Gemini model identifiers.
		"""
		return [ 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.5-flash-lite',
			'gemini-3.1-pro-preview', 'gemini-3.1-flash-lite', 'gemini-2.5-pro',
			'gemini-2.5-flash',
			'gemini-2.5-flash-lite' ]

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

		Returns:
			List[str]: Existing application include-option values.
		"""
		return [ 'file_search_call.results', 'message.input_image.image_url',
			'message.output_text.logprobs', 'reasoning.encrypted_content' ]

	@property
	def reasoning_options( self ) -> List[ str ]:
		"""Return supported thinking levels.

		Returns:
			List[str]: Supported thinking-level values.
		"""
		return [ 'THINKING_LEVEL_UNSPECIFIED', 'MINIMAL', 'LOW', 'MEDIUM', 'HIGH' ]

	@property
	def choice_options( self ) -> List[ str ]:
		"""Return supported tool-choice values.

		Returns:
			List[str]: Supported tool-choice values.
		"""
		return [ 'AUTO', 'ANY', 'NONE', 'VALIDATED' ]

	@property
	def tool_options( self ) -> List[ str ]:
		"""Return supported Interactions tools.

		Returns:
			List[str]: Supported tool identifiers.
		"""
		return [ 'google_search', 'google_maps', 'url_context', 'code_execution' ]

	@property
	def modality_options( self ) -> List[ str ]:
		"""Return supported response modalities.

		Returns:
			List[str]: Supported response modality values.
		"""
		return [ 'TEXT' ]

	@property
	def media_options( self ) -> List[ str ]:
		"""Return supported media-resolution values.

		Returns:
			List[str]: Supported media-resolution values.
		"""
		return [ 'media_resolution_high', 'media_resolution_medium', 'media_resolution_low' ]

	def create_client( self ) -> genai.Client:
		"""Create the Google Gen AI client.

		Returns:
			genai.Client: Configured provider client.

		Raises:
			Error: Raised when API-key validation or client creation fails.
		"""
		try:
			self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
				'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
			throw_if( 'api_key', self.api_key )
			self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )
			return self.client
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = 'create_client( self ) -> genai.Client'
			Logger( ).write( exception )
			raise exception

	def normalize_mime_type( self, filepath: str ) -> str:
		"""Resolve the MIME type for a local file.

		Args:
			filepath (str): Local file path.

		Returns:
			str: Resolved MIME type.

		Raises:
			Error: Raised when validation or MIME-type resolution fails.
		"""
		try:
			import mimetypes

			throw_if( 'filepath', filepath )
			self.file_path = filepath
			self.mime_type = mimetypes.guess_type( self.file_path )[ 0 ]

			if self.mime_type:
				return self.mime_type

			self.suffix = Path( self.file_path ).suffix.lower( )
			self.mime_types = { '.pdf': 'application/pdf', '.txt': 'text/plain',
				'.md': 'text/markdown',
				'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
				'.csv': 'text/csv', '.json': 'application/json', '.png': 'image/png',
				'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', }
			return self.mime_types.get( self.suffix, 'application/octet-stream' )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('normalize_mime_type( self, filepath: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def upload( self, filepath: str, name: str=None ) -> File:
		"""Upload a local file through the Gemini Files API.

		Args:
			filepath (str): Local file path.
			name (str): Optional display name.

		Returns:
			File: Uploaded Gemini file resource.

		Raises:
			Error: Raised when validation or upload fails.
		"""
		try:
			throw_if( 'filepath', filepath )
			self.file_path = filepath
			self.display_name = name
			self.client = self.create_client( )
			self.upload_config = None

			if self.display_name is not None and str( self.display_name ).strip( ):
				self.upload_config = types.UploadFileConfig(
					display_name=str( self.display_name ).strip( ) )

			if self.upload_config is None:
				self.response = self.client.files.upload( file=self.file_path )
			else:
				self.response = self.client.files.upload( file=self.file_path,
					config=self.upload_config )

			return self.response
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('upload( self, filepath: str, name: str ) -> File')
			Logger( ).write( exception )
			raise exception

	def list( self, model: str='gemini-3.6-flash', top_p: float=0.8, top_k: int=50,
		temperature: float=0.5, frequency: float=0.0, presence: float=0.0,
		max_tokens: int=8192, tool_choice: str='auto', stops: List[ str ] = None,
		tools: List[ str ] = None, domains: List[ str ] = None, modalities: List[ str ] = None,
		media_resolution: str='media_resolution_medium' ) -> List[ str ]:
		"""List configured Google Cloud Storage document objects.

		Purpose:
			Preserves the existing Files wrapper contract by listing objects from the
			``jeni-financial`` bucket under the ``regulations`` prefix. The model and
			generation arguments remain accepted because they are part of the existing
			application-facing signature, but they are not provider inputs for this storage
			operation.

		Args:
			model (str): Model value retained by the wrapper.
			top_p (float): Top-P value retained by the wrapper.
			top_k (int): Top-K value retained by the wrapper.
			temperature (float): Temperature value retained by the wrapper.
			frequency (float): Frequency-penalty value retained by the wrapper.
			presence (float): Presence-penalty value retained by the wrapper.
			max_tokens (int): Maximum-token value retained by the wrapper.
			tool_choice (str): Tool-choice value retained by the wrapper.
			stops (List[str]): Stop sequences retained by the wrapper.
			tools (List[str]): Tool identifiers retained by the wrapper.
			domains (List[str]): Domain values retained by the wrapper.
			modalities (List[str]): Response modalities retained by the wrapper.
			media_resolution (str): Media-resolution value retained by the wrapper.

		Returns:
			List[str]: Object names under the configured regulations prefix.

		Raises:
			Error: Raised when the Google Cloud Storage listing fails.
		"""
		try:
			self.model = model
			self.top_p = top_p
			self.top_k = top_k
			self.temperature = temperature
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_tokens = max_tokens
			self.tool_choice = tool_choice
			self.stops = stops if isinstance( stops, list ) else [ ]
			self.tools = tools if isinstance( tools, list ) else [ ]
			self.domains = domains if isinstance( domains, list ) else [ ]
			self.response_modalities = (modalities if isinstance( modalities, list ) else [ ])
			self.media_resolution = media_resolution
			self.bucket_id = 'jeni-financial'
			self.prefix = 'regulations'
			self.storage_client = storage.Client( )
			self.bucket = self.storage_client.bucket( bucket_name=self.bucket_id )
			self.files = [ blob.name for blob in self.bucket.list_blobs( prefix=self.prefix ) ]
			self.file_list = list( self.files )
			self.response = self.file_list
			return self.file_list
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('list( self, model: str, top_p: float, top_k: int, '
			                    'temperature: float, frequency: float, presence: float, '
			                    'max_tokens: int, tool_choice: str, stops: List[ str ], '
			                    'tools: List[ str ], domains: List[ str ], '
			                    'modalities: List[ str ], media_resolution: str ) '
			                    '-> List[ str ]')
			Logger( ).write( exception )
			raise exception

	def retrieve( self, file_id: str ) -> File:
		"""Retrieve a Gemini file resource.

		Args:
			file_id (str): Gemini file resource name.

		Returns:
			File: Retrieved Gemini file resource.

		Raises:
			Error: Raised when validation or retrieval fails.
		"""
		try:
			throw_if( 'file_id', file_id )
			self.file_id = file_id
			self.client = self.create_client( )
			self.response = self.client.files.get( name=self.file_id )
			return self.response
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('retrieve( self, file_id: str ) -> File')
			Logger( ).write( exception )
			raise exception

	def build_generation_config( self, temperature: float=None, top_p: float=None,
		max_tokens: int=None, stops: List[ str ] = None ) -> Dict[ str, Any ]:
		"""Build an Interactions generation configuration.

		Args:
			temperature (float): Sampling temperature.
			top_p (float): Top-P sampling value.
			max_tokens (int): Maximum output-token count.
			stops (List[str]): Stop sequences.

		Returns:
			Dict[str, Any]: Interactions generation configuration.
		"""
		self.temperature = temperature
		self.top_p = top_p
		self.max_tokens = max_tokens
		self.stops = stops if isinstance( stops, list ) else [ ]
		self.generation_config = { }

		if self.temperature is not None:
			self.generation_config[ 'temperature' ] = self.temperature

		if self.top_p is not None:
			self.generation_config[ 'top_p' ] = self.top_p

		if self.max_tokens is not None and self.max_tokens > 0:
			self.generation_config[ 'max_output_tokens' ] = (self.max_tokens)

		self.stop_sequences = [ str( item ).strip( ) for item in self.stops if
			item is not None and str( item ).strip( ) ]

		if self.stop_sequences:
			self.generation_config[ 'stop_sequences' ] = (self.stop_sequences)

		return self.generation_config

	def build_document_block( self, filepath: str ) -> Dict[ str, Any ]:
		"""Build an inline Interactions document block.

		Args:
			filepath (str): Local document path.

		Returns:
			Dict[str, Any]: Interactions document content block.

		Raises:
			Error: Raised when validation or file encoding fails.
		"""
		try:
			throw_if( 'filepath', filepath )
			self.file_path = filepath
			self.mime_type = self.normalize_mime_type( self.file_path )
			self.file_bytes = Path( self.file_path ).read_bytes( )
			throw_if( 'file_bytes', self.file_bytes )
			self.file_data = base64.b64encode( self.file_bytes ).decode( 'utf-8' )
			return { 'type': 'document', 'data': self.file_data, 'mime_type': self.mime_type, }
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('build_document_block( self, filepath: str ) '
			                    '-> Dict[ str, Any ]')
			Logger( ).write( exception )
			raise exception

	def execute_document_interaction( self, prompt: str, filepaths: List[ str ], model: str,
		temperature: float=None, top_p: float=None, frequency: float=None,
		presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
		instruct: str=None ) -> str:
		"""Execute a document Interaction.

		Args:
			prompt (str): Document instruction or question.
			filepaths (List[str]): Local document paths.
			model (str): Gemini model identifier.
			temperature (float): Sampling temperature.
			top_p (float): Top-P sampling value.
			frequency (float): Compatibility frequency-penalty value.
			presence (float): Compatibility presence-penalty value.
			max_tokens (int): Maximum output-token count.
			stops (List[str]): Stop sequences.
			instruct (str): Optional system instruction.

		Returns:
			str: Generated document response.

		Raises:
			Error: Raised when validation, request construction, or execution fails.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'filepaths', filepaths )
			throw_if( 'model', model )
			self.prompt = prompt
			self.file_paths = filepaths
			self.model = model
			self.temperature = temperature
			self.top_p = top_p
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_tokens = max_tokens
			self.stops = stops if isinstance( stops, list ) else [ ]
			self.instructions = instruct
			self.contents = [ { 'type': 'text', 'text': self.prompt }, ]

			for filepath in self.file_paths:
				self.contents.append( self.build_document_block( filepath ) )

			self.generation_config = self.build_generation_config( temperature=self.temperature,
				top_p=self.top_p, max_tokens=self.max_tokens, stops=self.stops )
			self.client = self.create_client( )
			self.request = { 'model': self.model, 'input': self.contents,
				'response_format': { 'type': 'text' }, 'store': False, }

			if self.instructions is not None and str( self.instructions ).strip( ):
				self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

			if self.generation_config:
				self.request[ 'generation_config' ] = (self.generation_config)

			self.interaction = self.client.interactions.create( **self.request )
			self.response = self.interaction
			self.content_response = self.interaction
			self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
			throw_if( 'output_text', self.output_text )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('execute_document_interaction( self, prompt: str, '
			                    'filepaths: List[ str ], model: str, temperature: float, '
			                    'top_p: float, frequency: float, presence: float, '
			                    'max_tokens: int, stops: List[ str ], instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def summarize( self, prompt: str, filepath: str, model: str='gemini-3.6-flash',
		temperature: float=None, top_p: float=None, frequency: float=None,
		presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
		instruct: str=None ) -> str:
		"""Summarize a local document through Interactions."""
		try:
			throw_if( 'filepath', filepath )
			self.file_path = filepath
			return self.execute_document_interaction( prompt=prompt, filepaths=[ self.file_path ],
				model=model, temperature=temperature, top_p=top_p, frequency=frequency,
				presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('summarize( self, prompt: str, filepath: str, model: str, '
			                    'temperature: float, top_p: float, frequency: float, '
			                    'presence: float, max_tokens: int, stops: List[ str ], '
			                    'instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def search( self, prompt: str, filepath: str, model: str='gemini-3.6-flash',
		temperature: float=None, top_p: float=None, frequency: float=None,
		presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
		instruct: str=None ) -> str:
		"""Answer a question about a local document through Interactions."""
		try:
			throw_if( 'filepath', filepath )
			self.file_path = filepath
			return self.execute_document_interaction( prompt=prompt, filepaths=[ self.file_path ],
				model=model, temperature=temperature, top_p=top_p, frequency=frequency,
				presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('search( self, prompt: str, filepath: str, model: str, '
			                    'temperature: float, top_p: float, frequency: float, '
			                    'presence: float, max_tokens: int, stops: List[ str ], '
			                    'instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def survey( self, prompt: str, filepaths: List[ str ], model: str='gemini-3.6-flash',
		temperature: float=None, top_p: float=None, frequency: float=None,
		presence: float=None, max_tokens: int=None, stops: List[ str ] = None ) -> str:
		"""Analyze multiple local documents through Interactions."""
		try:
			return self.execute_document_interaction( prompt=prompt, filepaths=filepaths,
				model=model, temperature=temperature, top_p=top_p, frequency=frequency,
				presence=presence, max_tokens=max_tokens, stops=stops, instruct=None )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('survey( self, prompt: str, filepaths: List[ str ], '
			                    'model: str, temperature: float, top_p: float, '
			                    'frequency: float, presence: float, max_tokens: int, '
			                    'stops: List[ str ] ) -> str')
			Logger( ).write( exception )
			raise exception

	def execute_grounded_interaction( self, prompt: str, model: str, tool_type: str,
		temperature: float=None, top_p: float=None, frequency: float=None,
		presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
		instruct: str=None ) -> str:
		"""Execute a Google Search or Google Maps Interaction."""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			throw_if( 'tool_type', tool_type )
			self.prompt = prompt
			self.model = model
			self.tool_type = tool_type
			self.temperature = temperature
			self.top_p = top_p
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_tokens = max_tokens
			self.stops = stops if isinstance( stops, list ) else [ ]
			self.instructions = instruct

			if self.tool_type not in ('google_search', 'google_maps'):
				raise ValueError( f'Unsupported grounding tool: {self.tool_type}' )

			self.generation_config = self.build_generation_config( temperature=self.temperature,
				top_p=self.top_p, max_tokens=self.max_tokens, stops=self.stops )
			self.client = self.create_client( )
			self.request = { 'model': self.model, 'input': self.prompt,
				'tools': [ { 'type': self.tool_type } ], 'response_format': { 'type': 'text' },
				'store': False, }

			if self.instructions is not None and str( self.instructions ).strip( ):
				self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

			if self.generation_config:
				self.request[ 'generation_config' ] = (self.generation_config)

			self.interaction = self.client.interactions.create( **self.request )
			self.response = self.interaction
			self.content_response = self.interaction
			self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
			throw_if( 'output_text', self.output_text )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('execute_grounded_interaction( self, prompt: str, model: str, '
			                    'tool_type: str, temperature: float, top_p: float, '
			                    'frequency: float, presence: float, max_tokens: int, '
			                    'stops: List[ str ], instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def web_search( self, prompt: str, model: str='gemini-3.6-flash', temperature: float=None,
		top_p: float=None, frequency: float=None, presence: float=None,
		max_tokens: int=None, stops: List[ str ] = None, instruct: str=None ) -> str:
		"""Generate a Google Search-grounded response."""
		try:
			return self.execute_grounded_interaction( prompt=prompt, model=model,
				tool_type='google_search', temperature=temperature, top_p=top_p,
				frequency=frequency, presence=presence, max_tokens=max_tokens, stops=stops,
				instruct=instruct )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('web_search( self, prompt: str, model: str, '
			                    'temperature: float, top_p: float, frequency: float, '
			                    'presence: float, max_tokens: int, stops: List[ str ], '
			                    'instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def search_maps( self, prompt: str, model: str='gemini-3.6-flash', temperature: float=None,
		top_p: float=None, frequency: float=None, presence: float=None,
		max_tokens: int=None, stops: List[ str ] = None, instruct: str=None ) -> str:
		"""Generate a Google Maps-grounded response."""
		try:
			return self.execute_grounded_interaction( prompt=prompt, model=model,
				tool_type='google_maps', temperature=temperature, top_p=top_p, frequency=frequency,
				presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('search_maps( self, prompt: str, model: str, '
			                    'temperature: float, top_p: float, frequency: float, '
			                    'presence: float, max_tokens: int, stops: List[ str ], '
			                    'instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def delete( self, file_id: str ) -> bool:
		"""Delete a Gemini file resource.

		Args:
			file_id (str): Gemini file resource name.

		Returns:
			bool: True after successful deletion.

		Raises:
			Error: Raised when validation or deletion fails.
		"""
		try:
			throw_if( 'file_id', file_id )
			self.file_id = file_id
			self.client = self.create_client( )
			self.response = self.client.files.delete( name=self.file_id )
			return True
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'Files'
			exception.method = ('delete( self, file_id: str ) -> bool')
			Logger( ).write( exception )
			raise exception

file_options property

file_options: List[str]

Return cached file resource names.

Returns:

Type Description
List[str]

List[str]: Cached Gemini file resource names.

model_options property

model_options: List[str]

Return supported document models.

Returns:

Type Description
List[str]

List[str]: Supported Gemini model identifiers.

include_options property

include_options: List[str]

Return compatibility include options.

Returns:

Type Description
List[str]

List[str]: Existing application include-option values.

reasoning_options property

reasoning_options: List[str]

Return supported thinking levels.

Returns:

Type Description
List[str]

List[str]: Supported thinking-level values.

choice_options property

choice_options: List[str]

Return supported tool-choice values.

Returns:

Type Description
List[str]

List[str]: Supported tool-choice values.

tool_options property

tool_options: List[str]

Return supported Interactions tools.

Returns:

Type Description
List[str]

List[str]: Supported tool identifiers.

modality_options property

modality_options: List[str]

Return supported response modalities.

Returns:

Type Description
List[str]

List[str]: Supported response modality values.

media_options property

media_options: List[str]

Return supported media-resolution values.

Returns:

Type Description
List[str]

List[str]: Supported media-resolution values.

__init__

__init__(model: str = 'gemini-3.6-flash') -> None

Initialize the Files wrapper.

Purpose

Initializes file lifecycle, document request, storage, and response state. The constructor performs local assignment only.

Parameters:

Name Type Description Default
model str

Default Gemini model used for document workflows.

'gemini-3.6-flash'

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self, model: str='gemini-3.6-flash' ) -> None:
	"""Initialize the Files wrapper.

	Purpose:
		Initializes file lifecycle, document request, storage, and response state. The
		constructor performs local assignment only.

	Args:
		model (str): Default Gemini model used for document workflows.

	Returns:
		None: This method initializes object state through side effects.
	"""
	super( ).__init__( )
	self.google_api_key = cfg.GOOGLE_API_KEY
	self.gemini_api_key = cfg.GEMINI_API_KEY
	self.project_id = cfg.GOOGLE_CLOUD_PROJECT_ID
	self.project_location = cfg.GOOGLE_CLOUD_LOCATION
	self.model = model
	self.api_version = 'v1beta'
	self.http_options = types.HttpOptions( api_version=self.api_version )
	self.client = None
	self.storage_client = None
	self.bucket_id = None
	self.file_id = None
	self.display_name = None
	self.mime_type = None
	self.file_path = None
	self.file_list = [ ]
	self.file_paths = [ ]
	self.file_lists = [ ]
	self.files = [ ]
	self.response = None
	self.interaction = None
	self.use_vertex = False
	self.collections = { }
	self.documents = { }
	self.contents = None
	self.generation_config = { }
	self.tool_config = [ ]
	self.grounding_sources = [ ]

create_client

create_client() -> Client

Create the Google Gen AI client.

Returns:

Type Description
Client

genai.Client: Configured provider client.

Raises:

Type Description
Error

Raised when API-key validation or client creation fails.

Source code in gemini.py
def create_client( self ) -> genai.Client:
	"""Create the Google Gen AI client.

	Returns:
		genai.Client: Configured provider client.

	Raises:
		Error: Raised when API-key validation or client creation fails.
	"""
	try:
		self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
			'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
		throw_if( 'api_key', self.api_key )
		self.client = genai.Client( api_key=self.api_key, http_options=self.http_options )
		return self.client
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = 'create_client( self ) -> genai.Client'
		Logger( ).write( exception )
		raise exception

normalize_mime_type

normalize_mime_type(filepath: str) -> str

Resolve the MIME type for a local file.

Parameters:

Name Type Description Default
filepath str

Local file path.

required

Returns:

Name Type Description
str str

Resolved MIME type.

Raises:

Type Description
Error

Raised when validation or MIME-type resolution fails.

Source code in gemini.py
def normalize_mime_type( self, filepath: str ) -> str:
	"""Resolve the MIME type for a local file.

	Args:
		filepath (str): Local file path.

	Returns:
		str: Resolved MIME type.

	Raises:
		Error: Raised when validation or MIME-type resolution fails.
	"""
	try:
		import mimetypes

		throw_if( 'filepath', filepath )
		self.file_path = filepath
		self.mime_type = mimetypes.guess_type( self.file_path )[ 0 ]

		if self.mime_type:
			return self.mime_type

		self.suffix = Path( self.file_path ).suffix.lower( )
		self.mime_types = { '.pdf': 'application/pdf', '.txt': 'text/plain',
			'.md': 'text/markdown',
			'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
			'.csv': 'text/csv', '.json': 'application/json', '.png': 'image/png',
			'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', }
		return self.mime_types.get( self.suffix, 'application/octet-stream' )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('normalize_mime_type( self, filepath: str ) -> str')
		Logger( ).write( exception )
		raise exception

upload

upload(filepath: str, name: str = None) -> File

Upload a local file through the Gemini Files API.

Parameters:

Name Type Description Default
filepath str

Local file path.

required
name str

Optional display name.

None

Returns:

Name Type Description
File File

Uploaded Gemini file resource.

Raises:

Type Description
Error

Raised when validation or upload fails.

Source code in gemini.py
def upload( self, filepath: str, name: str=None ) -> File:
	"""Upload a local file through the Gemini Files API.

	Args:
		filepath (str): Local file path.
		name (str): Optional display name.

	Returns:
		File: Uploaded Gemini file resource.

	Raises:
		Error: Raised when validation or upload fails.
	"""
	try:
		throw_if( 'filepath', filepath )
		self.file_path = filepath
		self.display_name = name
		self.client = self.create_client( )
		self.upload_config = None

		if self.display_name is not None and str( self.display_name ).strip( ):
			self.upload_config = types.UploadFileConfig(
				display_name=str( self.display_name ).strip( ) )

		if self.upload_config is None:
			self.response = self.client.files.upload( file=self.file_path )
		else:
			self.response = self.client.files.upload( file=self.file_path,
				config=self.upload_config )

		return self.response
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('upload( self, filepath: str, name: str ) -> File')
		Logger( ).write( exception )
		raise exception

list

list(
    model: str = "gemini-3.6-flash",
    top_p: float = 0.8,
    top_k: int = 50,
    temperature: float = 0.5,
    frequency: float = 0.0,
    presence: float = 0.0,
    max_tokens: int = 8192,
    tool_choice: str = "auto",
    stops: List[str] = None,
    tools: List[str] = None,
    domains: List[str] = None,
    modalities: List[str] = None,
    media_resolution: str = "media_resolution_medium",
) -> List[str]

List configured Google Cloud Storage document objects.

Purpose

Preserves the existing Files wrapper contract by listing objects from the jeni-financial bucket under the regulations prefix. The model and generation arguments remain accepted because they are part of the existing application-facing signature, but they are not provider inputs for this storage operation.

Parameters:

Name Type Description Default
model str

Model value retained by the wrapper.

'gemini-3.6-flash'
top_p float

Top-P value retained by the wrapper.

0.8
top_k int

Top-K value retained by the wrapper.

50
temperature float

Temperature value retained by the wrapper.

0.5
frequency float

Frequency-penalty value retained by the wrapper.

0.0
presence float

Presence-penalty value retained by the wrapper.

0.0
max_tokens int

Maximum-token value retained by the wrapper.

8192
tool_choice str

Tool-choice value retained by the wrapper.

'auto'
stops List[str]

Stop sequences retained by the wrapper.

None
tools List[str]

Tool identifiers retained by the wrapper.

None
domains List[str]

Domain values retained by the wrapper.

None
modalities List[str]

Response modalities retained by the wrapper.

None
media_resolution str

Media-resolution value retained by the wrapper.

'media_resolution_medium'

Returns:

Type Description
List[str]

List[str]: Object names under the configured regulations prefix.

Raises:

Type Description
Error

Raised when the Google Cloud Storage listing fails.

Source code in gemini.py
def list( self, model: str='gemini-3.6-flash', top_p: float=0.8, top_k: int=50,
	temperature: float=0.5, frequency: float=0.0, presence: float=0.0,
	max_tokens: int=8192, tool_choice: str='auto', stops: List[ str ] = None,
	tools: List[ str ] = None, domains: List[ str ] = None, modalities: List[ str ] = None,
	media_resolution: str='media_resolution_medium' ) -> List[ str ]:
	"""List configured Google Cloud Storage document objects.

	Purpose:
		Preserves the existing Files wrapper contract by listing objects from the
		``jeni-financial`` bucket under the ``regulations`` prefix. The model and
		generation arguments remain accepted because they are part of the existing
		application-facing signature, but they are not provider inputs for this storage
		operation.

	Args:
		model (str): Model value retained by the wrapper.
		top_p (float): Top-P value retained by the wrapper.
		top_k (int): Top-K value retained by the wrapper.
		temperature (float): Temperature value retained by the wrapper.
		frequency (float): Frequency-penalty value retained by the wrapper.
		presence (float): Presence-penalty value retained by the wrapper.
		max_tokens (int): Maximum-token value retained by the wrapper.
		tool_choice (str): Tool-choice value retained by the wrapper.
		stops (List[str]): Stop sequences retained by the wrapper.
		tools (List[str]): Tool identifiers retained by the wrapper.
		domains (List[str]): Domain values retained by the wrapper.
		modalities (List[str]): Response modalities retained by the wrapper.
		media_resolution (str): Media-resolution value retained by the wrapper.

	Returns:
		List[str]: Object names under the configured regulations prefix.

	Raises:
		Error: Raised when the Google Cloud Storage listing fails.
	"""
	try:
		self.model = model
		self.top_p = top_p
		self.top_k = top_k
		self.temperature = temperature
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.tool_choice = tool_choice
		self.stops = stops if isinstance( stops, list ) else [ ]
		self.tools = tools if isinstance( tools, list ) else [ ]
		self.domains = domains if isinstance( domains, list ) else [ ]
		self.response_modalities = (modalities if isinstance( modalities, list ) else [ ])
		self.media_resolution = media_resolution
		self.bucket_id = 'jeni-financial'
		self.prefix = 'regulations'
		self.storage_client = storage.Client( )
		self.bucket = self.storage_client.bucket( bucket_name=self.bucket_id )
		self.files = [ blob.name for blob in self.bucket.list_blobs( prefix=self.prefix ) ]
		self.file_list = list( self.files )
		self.response = self.file_list
		return self.file_list
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('list( self, model: str, top_p: float, top_k: int, '
		                    'temperature: float, frequency: float, presence: float, '
		                    'max_tokens: int, tool_choice: str, stops: List[ str ], '
		                    'tools: List[ str ], domains: List[ str ], '
		                    'modalities: List[ str ], media_resolution: str ) '
		                    '-> List[ str ]')
		Logger( ).write( exception )
		raise exception

retrieve

retrieve(file_id: str) -> File

Retrieve a Gemini file resource.

Parameters:

Name Type Description Default
file_id str

Gemini file resource name.

required

Returns:

Name Type Description
File File

Retrieved Gemini file resource.

Raises:

Type Description
Error

Raised when validation or retrieval fails.

Source code in gemini.py
def retrieve( self, file_id: str ) -> File:
	"""Retrieve a Gemini file resource.

	Args:
		file_id (str): Gemini file resource name.

	Returns:
		File: Retrieved Gemini file resource.

	Raises:
		Error: Raised when validation or retrieval fails.
	"""
	try:
		throw_if( 'file_id', file_id )
		self.file_id = file_id
		self.client = self.create_client( )
		self.response = self.client.files.get( name=self.file_id )
		return self.response
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('retrieve( self, file_id: str ) -> File')
		Logger( ).write( exception )
		raise exception

build_generation_config

build_generation_config(
    temperature: float = None,
    top_p: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
) -> Dict[str, Any]

Build an Interactions generation configuration.

Parameters:

Name Type Description Default
temperature float

Sampling temperature.

None
top_p float

Top-P sampling value.

None
max_tokens int

Maximum output-token count.

None
stops List[str]

Stop sequences.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Interactions generation configuration.

Source code in gemini.py
def build_generation_config( self, temperature: float=None, top_p: float=None,
	max_tokens: int=None, stops: List[ str ] = None ) -> Dict[ str, Any ]:
	"""Build an Interactions generation configuration.

	Args:
		temperature (float): Sampling temperature.
		top_p (float): Top-P sampling value.
		max_tokens (int): Maximum output-token count.
		stops (List[str]): Stop sequences.

	Returns:
		Dict[str, Any]: Interactions generation configuration.
	"""
	self.temperature = temperature
	self.top_p = top_p
	self.max_tokens = max_tokens
	self.stops = stops if isinstance( stops, list ) else [ ]
	self.generation_config = { }

	if self.temperature is not None:
		self.generation_config[ 'temperature' ] = self.temperature

	if self.top_p is not None:
		self.generation_config[ 'top_p' ] = self.top_p

	if self.max_tokens is not None and self.max_tokens > 0:
		self.generation_config[ 'max_output_tokens' ] = (self.max_tokens)

	self.stop_sequences = [ str( item ).strip( ) for item in self.stops if
		item is not None and str( item ).strip( ) ]

	if self.stop_sequences:
		self.generation_config[ 'stop_sequences' ] = (self.stop_sequences)

	return self.generation_config

build_document_block

build_document_block(filepath: str) -> Dict[str, Any]

Build an inline Interactions document block.

Parameters:

Name Type Description Default
filepath str

Local document path.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Interactions document content block.

Raises:

Type Description
Error

Raised when validation or file encoding fails.

Source code in gemini.py
def build_document_block( self, filepath: str ) -> Dict[ str, Any ]:
	"""Build an inline Interactions document block.

	Args:
		filepath (str): Local document path.

	Returns:
		Dict[str, Any]: Interactions document content block.

	Raises:
		Error: Raised when validation or file encoding fails.
	"""
	try:
		throw_if( 'filepath', filepath )
		self.file_path = filepath
		self.mime_type = self.normalize_mime_type( self.file_path )
		self.file_bytes = Path( self.file_path ).read_bytes( )
		throw_if( 'file_bytes', self.file_bytes )
		self.file_data = base64.b64encode( self.file_bytes ).decode( 'utf-8' )
		return { 'type': 'document', 'data': self.file_data, 'mime_type': self.mime_type, }
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('build_document_block( self, filepath: str ) '
		                    '-> Dict[ str, Any ]')
		Logger( ).write( exception )
		raise exception

execute_document_interaction

execute_document_interaction(
    prompt: str,
    filepaths: List[str],
    model: str,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Execute a document Interaction.

Parameters:

Name Type Description Default
prompt str

Document instruction or question.

required
filepaths List[str]

Local document paths.

required
model str

Gemini model identifier.

required
temperature float

Sampling temperature.

None
top_p float

Top-P sampling value.

None
frequency float

Compatibility frequency-penalty value.

None
presence float

Compatibility presence-penalty value.

None
max_tokens int

Maximum output-token count.

None
stops List[str]

Stop sequences.

None
instruct str

Optional system instruction.

None

Returns:

Name Type Description
str str

Generated document response.

Raises:

Type Description
Error

Raised when validation, request construction, or execution fails.

Source code in gemini.py
def execute_document_interaction( self, prompt: str, filepaths: List[ str ], model: str,
	temperature: float=None, top_p: float=None, frequency: float=None,
	presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
	instruct: str=None ) -> str:
	"""Execute a document Interaction.

	Args:
		prompt (str): Document instruction or question.
		filepaths (List[str]): Local document paths.
		model (str): Gemini model identifier.
		temperature (float): Sampling temperature.
		top_p (float): Top-P sampling value.
		frequency (float): Compatibility frequency-penalty value.
		presence (float): Compatibility presence-penalty value.
		max_tokens (int): Maximum output-token count.
		stops (List[str]): Stop sequences.
		instruct (str): Optional system instruction.

	Returns:
		str: Generated document response.

	Raises:
		Error: Raised when validation, request construction, or execution fails.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'filepaths', filepaths )
		throw_if( 'model', model )
		self.prompt = prompt
		self.file_paths = filepaths
		self.model = model
		self.temperature = temperature
		self.top_p = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.stops = stops if isinstance( stops, list ) else [ ]
		self.instructions = instruct
		self.contents = [ { 'type': 'text', 'text': self.prompt }, ]

		for filepath in self.file_paths:
			self.contents.append( self.build_document_block( filepath ) )

		self.generation_config = self.build_generation_config( temperature=self.temperature,
			top_p=self.top_p, max_tokens=self.max_tokens, stops=self.stops )
		self.client = self.create_client( )
		self.request = { 'model': self.model, 'input': self.contents,
			'response_format': { 'type': 'text' }, 'store': False, }

		if self.instructions is not None and str( self.instructions ).strip( ):
			self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

		if self.generation_config:
			self.request[ 'generation_config' ] = (self.generation_config)

		self.interaction = self.client.interactions.create( **self.request )
		self.response = self.interaction
		self.content_response = self.interaction
		self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
		throw_if( 'output_text', self.output_text )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('execute_document_interaction( self, prompt: str, '
		                    'filepaths: List[ str ], model: str, temperature: float, '
		                    'top_p: float, frequency: float, presence: float, '
		                    'max_tokens: int, stops: List[ str ], instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception

summarize

summarize(
    prompt: str,
    filepath: str,
    model: str = "gemini-3.6-flash",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Summarize a local document through Interactions.

Source code in gemini.py
def summarize( self, prompt: str, filepath: str, model: str='gemini-3.6-flash',
	temperature: float=None, top_p: float=None, frequency: float=None,
	presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
	instruct: str=None ) -> str:
	"""Summarize a local document through Interactions."""
	try:
		throw_if( 'filepath', filepath )
		self.file_path = filepath
		return self.execute_document_interaction( prompt=prompt, filepaths=[ self.file_path ],
			model=model, temperature=temperature, top_p=top_p, frequency=frequency,
			presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('summarize( self, prompt: str, filepath: str, model: str, '
		                    'temperature: float, top_p: float, frequency: float, '
		                    'presence: float, max_tokens: int, stops: List[ str ], '
		                    'instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception

search

search(
    prompt: str,
    filepath: str,
    model: str = "gemini-3.6-flash",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Answer a question about a local document through Interactions.

Source code in gemini.py
def search( self, prompt: str, filepath: str, model: str='gemini-3.6-flash',
	temperature: float=None, top_p: float=None, frequency: float=None,
	presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
	instruct: str=None ) -> str:
	"""Answer a question about a local document through Interactions."""
	try:
		throw_if( 'filepath', filepath )
		self.file_path = filepath
		return self.execute_document_interaction( prompt=prompt, filepaths=[ self.file_path ],
			model=model, temperature=temperature, top_p=top_p, frequency=frequency,
			presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('search( self, prompt: str, filepath: str, model: str, '
		                    'temperature: float, top_p: float, frequency: float, '
		                    'presence: float, max_tokens: int, stops: List[ str ], '
		                    'instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception

survey

survey(
    prompt: str,
    filepaths: List[str],
    model: str = "gemini-3.6-flash",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
) -> str

Analyze multiple local documents through Interactions.

Source code in gemini.py
def survey( self, prompt: str, filepaths: List[ str ], model: str='gemini-3.6-flash',
	temperature: float=None, top_p: float=None, frequency: float=None,
	presence: float=None, max_tokens: int=None, stops: List[ str ] = None ) -> str:
	"""Analyze multiple local documents through Interactions."""
	try:
		return self.execute_document_interaction( prompt=prompt, filepaths=filepaths,
			model=model, temperature=temperature, top_p=top_p, frequency=frequency,
			presence=presence, max_tokens=max_tokens, stops=stops, instruct=None )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('survey( self, prompt: str, filepaths: List[ str ], '
		                    'model: str, temperature: float, top_p: float, '
		                    'frequency: float, presence: float, max_tokens: int, '
		                    'stops: List[ str ] ) -> str')
		Logger( ).write( exception )
		raise exception

execute_grounded_interaction

execute_grounded_interaction(
    prompt: str,
    model: str,
    tool_type: str,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Execute a Google Search or Google Maps Interaction.

Source code in gemini.py
def execute_grounded_interaction( self, prompt: str, model: str, tool_type: str,
	temperature: float=None, top_p: float=None, frequency: float=None,
	presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
	instruct: str=None ) -> str:
	"""Execute a Google Search or Google Maps Interaction."""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		throw_if( 'tool_type', tool_type )
		self.prompt = prompt
		self.model = model
		self.tool_type = tool_type
		self.temperature = temperature
		self.top_p = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.stops = stops if isinstance( stops, list ) else [ ]
		self.instructions = instruct

		if self.tool_type not in ('google_search', 'google_maps'):
			raise ValueError( f'Unsupported grounding tool: {self.tool_type}' )

		self.generation_config = self.build_generation_config( temperature=self.temperature,
			top_p=self.top_p, max_tokens=self.max_tokens, stops=self.stops )
		self.client = self.create_client( )
		self.request = { 'model': self.model, 'input': self.prompt,
			'tools': [ { 'type': self.tool_type } ], 'response_format': { 'type': 'text' },
			'store': False, }

		if self.instructions is not None and str( self.instructions ).strip( ):
			self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

		if self.generation_config:
			self.request[ 'generation_config' ] = (self.generation_config)

		self.interaction = self.client.interactions.create( **self.request )
		self.response = self.interaction
		self.content_response = self.interaction
		self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
		throw_if( 'output_text', self.output_text )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('execute_grounded_interaction( self, prompt: str, model: str, '
		                    'tool_type: str, temperature: float, top_p: float, '
		                    'frequency: float, presence: float, max_tokens: int, '
		                    'stops: List[ str ], instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception
web_search(
    prompt: str,
    model: str = "gemini-3.6-flash",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Generate a Google Search-grounded response.

Source code in gemini.py
def web_search( self, prompt: str, model: str='gemini-3.6-flash', temperature: float=None,
	top_p: float=None, frequency: float=None, presence: float=None,
	max_tokens: int=None, stops: List[ str ] = None, instruct: str=None ) -> str:
	"""Generate a Google Search-grounded response."""
	try:
		return self.execute_grounded_interaction( prompt=prompt, model=model,
			tool_type='google_search', temperature=temperature, top_p=top_p,
			frequency=frequency, presence=presence, max_tokens=max_tokens, stops=stops,
			instruct=instruct )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('web_search( self, prompt: str, model: str, '
		                    'temperature: float, top_p: float, frequency: float, '
		                    'presence: float, max_tokens: int, stops: List[ str ], '
		                    'instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception

search_maps

search_maps(
    prompt: str,
    model: str = "gemini-3.6-flash",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Generate a Google Maps-grounded response.

Source code in gemini.py
def search_maps( self, prompt: str, model: str='gemini-3.6-flash', temperature: float=None,
	top_p: float=None, frequency: float=None, presence: float=None,
	max_tokens: int=None, stops: List[ str ] = None, instruct: str=None ) -> str:
	"""Generate a Google Maps-grounded response."""
	try:
		return self.execute_grounded_interaction( prompt=prompt, model=model,
			tool_type='google_maps', temperature=temperature, top_p=top_p, frequency=frequency,
			presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('search_maps( self, prompt: str, model: str, '
		                    'temperature: float, top_p: float, frequency: float, '
		                    'presence: float, max_tokens: int, stops: List[ str ], '
		                    'instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception

delete

delete(file_id: str) -> bool

Delete a Gemini file resource.

Parameters:

Name Type Description Default
file_id str

Gemini file resource name.

required

Returns:

Name Type Description
bool bool

True after successful deletion.

Raises:

Type Description
Error

Raised when validation or deletion fails.

Source code in gemini.py
def delete( self, file_id: str ) -> bool:
	"""Delete a Gemini file resource.

	Args:
		file_id (str): Gemini file resource name.

	Returns:
		bool: True after successful deletion.

	Raises:
		Error: Raised when validation or deletion fails.
	"""
	try:
		throw_if( 'file_id', file_id )
		self.file_id = file_id
		self.client = self.create_client( )
		self.response = self.client.files.delete( name=self.file_id )
		return True
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'Files'
		exception.method = ('delete( self, file_id: str ) -> bool')
		Logger( ).write( exception )
		raise exception

CloudBuckets

Bases: Gemini

Google Cloud Storage bucket wrapper.

Purpose

Manages Google Cloud Storage objects and executes Google Search and Google Maps grounded model requests through the Gemini Interactions API.

Attributes:

Name Type Description
project_id Optional[str]

Google Cloud project identifier.

bucket_name Optional[str]

Active bucket name.

object_name Optional[str]

Active object name.

file_path Optional[str]

Active local file path.

file_ids List[str]

Cached file identifiers.

store_ids List[str]

Cached store identifiers.

client Optional[Client]

Active Google Cloud Storage client.

bucket Optional[Bucket]

Active bucket.

response Optional[Any]

Most recent storage or Interactions response.

interaction Optional[Any]

Most recent Gemini Interaction.

collections Dict[str, str]

Named bucket and prefix mappings.

documents Dict[str, str]

Named document mappings.

Source code in gemini.py
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
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
class CloudBuckets( Gemini ):
	"""Google Cloud Storage bucket wrapper.

	Purpose:
		Manages Google Cloud Storage objects and executes Google Search and Google Maps
		grounded model requests through the Gemini Interactions API.

	Attributes:
		project_id (Optional[str]): Google Cloud project identifier.
		bucket_name (Optional[str]): Active bucket name.
		object_name (Optional[str]): Active object name.
		file_path (Optional[str]): Active local file path.
		file_ids (List[str]): Cached file identifiers.
		store_ids (List[str]): Cached store identifiers.
		client (Optional[storage.Client]): Active Google Cloud Storage client.
		bucket (Optional[storage.Bucket]): Active bucket.
		response (Optional[Any]): Most recent storage or Interactions response.
		interaction (Optional[Any]): Most recent Gemini Interaction.
		collections (Dict[str, str]): Named bucket and prefix mappings.
		documents (Dict[str, str]): Named document mappings.
	"""

	project_id: Optional[ str ]
	bucket_name: Optional[ str ]
	object_name: Optional[ str ]
	file_path: Optional[ str ]
	file_ids: List[ str ]
	store_ids: List[ str ]
	client: Optional[ storage.Client ]
	bucket: Optional[ storage.Bucket ]
	response: Optional[ Any ]
	interaction: Optional[ Any ]
	collections: Dict[ str, str ]
	documents: Dict[ str, str ]

	def __init__( self ) -> None:
		"""Initialize the Google Cloud Storage wrapper.

		Purpose:
			Initializes local bucket, object, collection, and response state without creating
			clients or performing network operations.

		Returns:
			None: This method initializes object state through side effects.
		"""
		super( ).__init__( )
		self.project_id = cfg.GOOGLE_CLOUD_PROJECT_ID
		self.bucket_name = None
		self.object_name = None
		self.file_path = None
		self.file_ids = [ ]
		self.store_ids = [ ]
		self.client = None
		self.bucket = None
		self.response = None
		self.interaction = None
		self.collections = { 'Federal Financial Data': 'jeni-financial/data',
			'Federal Financial Regulations': 'jeni-financial/regulations',
			'DoW Financial Data': 'jeni-dow/budget/data',
			'DoW Financial Regulations': 'jeni-dow/budget/regulations',
			'DoA Financial Data': 'jenni-doa/Financial Data', }
		self.documents = { 'Account_Balances.csv': 'file-U6wFeRGSeg38Db5uJzo5sj',
			'SF133.csv': 'file-32s641QK1Xb5QUatY3zfWF',
			'Authority.csv': 'file-Qi2rw2QsdxKBX1iiaQxY3m',
			'Outlays.csv': 'file-GHEwSWR7ezMvHrQ3X648wn', }

	@property
	def model_options( self ) -> List[ str ]:
		"""Return supported grounded-generation models.

		Returns:
			List[str]: Supported Gemini model identifiers.
		"""
		return [ 'gemini-3.6-flash', 'gemini-3.5-flash', 'gemini-3.1-pro-preview',
			'gemini-2.5-flash', 'gemini-2.5-flash-lite' ]

	@property
	def media_options( self ) -> List[ str ]:
		"""Return supported media-resolution values.

		Returns:
			List[str]: Supported media-resolution values.
		"""
		return [ 'media_resolution_high', 'media_resolution_medium', 'media_resolution_low' ]

	def create_storage_client( self ) -> storage.Client:
		"""Create the Google Cloud Storage client.

		Returns:
			storage.Client: Configured storage client.

		Raises:
			Error: Raised when client creation fails.
		"""
		try:
			self.client = storage.Client( project=self.project_id )
			return self.client
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'CloudBuckets'
			exception.method = ('create_storage_client( self ) -> storage.Client')
			Logger( ).write( exception )
			raise exception

	def create( self, bucket: str, name: str ) -> Blob:
		"""Create an empty object in a bucket.

		Args:
			bucket (str): Bucket name.
			name (str): Object name.

		Returns:
			Blob: Created object reference.

		Raises:
			Error: Raised when validation or object creation fails.
		"""
		try:
			throw_if( 'bucket', bucket )
			throw_if( 'name', name )
			self.bucket_name = bucket
			self.object_name = name
			self.client = self.create_storage_client( )
			self.bucket = self.client.bucket( self.bucket_name )
			self.blob = self.bucket.blob( self.object_name )
			self.blob.upload_from_string( b'' )
			self.response = self.blob
			return self.blob
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'CloudBuckets'
			exception.method = ('create( self, bucket: str, name: str ) -> Blob')
			Logger( ).write( exception )
			raise exception

	def upload( self, path: str, bucket: str, name: str=None ) -> Blob:
		"""Upload a local file to a bucket.

		Args:
			path (str): Local file path.
			bucket (str): Bucket name.
			name (str): Optional object name.

		Returns:
			Blob: Uploaded object.

		Raises:
			Error: Raised when validation or upload fails.
		"""
		try:
			throw_if( 'path', path )
			throw_if( 'bucket', bucket )
			self.file_path = path
			self.bucket_name = bucket
			self.object_name = (name if name else Path( self.file_path ).name)
			self.client = self.create_storage_client( )
			self.bucket = self.client.bucket( self.bucket_name )
			self.blob = self.bucket.blob( self.object_name )
			self.blob.upload_from_filename( self.file_path )
			self.response = self.blob
			return self.blob
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'CloudBuckets'
			exception.method = ('upload( self, path: str, bucket: str, '
			                    'name: str ) -> Blob')
			Logger( ).write( exception )
			raise exception

	def retrieve( self, bucket: str, name: str ) -> Optional[ Blob ]:
		"""Retrieve object metadata.

		Args:
			bucket (str): Bucket name.
			name (str): Object name.

		Returns:
			Optional[Blob]: Matching object, or None when absent.

		Raises:
			Error: Raised when validation or retrieval fails.
		"""
		try:
			throw_if( 'bucket', bucket )
			throw_if( 'name', name )
			self.bucket_name = bucket
			self.object_name = name
			self.client = self.create_storage_client( )
			self.bucket = self.client.bucket( self.bucket_name )
			self.response = self.bucket.get_blob( self.object_name )
			return self.response
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'CloudBuckets'
			exception.method = ('retrieve( self, bucket: str, name: str ) '
			                    '-> Optional[ Blob ]')
			Logger( ).write( exception )
			raise exception

	def list( self, bucket: str ) -> List[ Blob ]:
		"""List bucket objects.

		Args:
			bucket (str): Bucket name.

		Returns:
			List[Blob]: Bucket objects.

		Raises:
			Error: Raised when validation or listing fails.
		"""
		try:
			throw_if( 'bucket', bucket )
			self.bucket_name = bucket
			self.client = self.create_storage_client( )
			self.bucket = self.client.bucket( self.bucket_name )
			self.blobs = list( self.bucket.list_blobs( ) )
			self.documents = { blob.name: blob.id for blob in self.blobs }
			self.response = self.blobs
			return self.blobs
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'CloudBuckets'
			exception.method = ('list( self, bucket: str ) -> List[ Blob ]')
			Logger( ).write( exception )
			raise exception

	def execute_grounded_interaction( self, prompt: str, model: str, tool_type: str,
		temperature: float=None, top_p: float=None, frequency: float=None,
		presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
		instruct: str=None ) -> str:
		"""Execute a grounded Interactions request.

		Args:
			prompt (str): User prompt.
			model (str): Gemini model identifier.
			tool_type (str): Grounding tool type.
			temperature (float): Sampling temperature.
			top_p (float): Top-P sampling value.
			frequency (float): Compatibility frequency-penalty value.
			presence (float): Compatibility presence-penalty value.
			max_tokens (int): Maximum output-token count.
			stops (List[str]): Stop sequences.
			instruct (str): Optional system instruction.

		Returns:
			str: Generated grounded response.

		Raises:
			Error: Raised when validation or execution fails.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			throw_if( 'tool_type', tool_type )
			self.prompt = prompt
			self.model = model
			self.tool_type = tool_type
			self.temperature = temperature
			self.top_p = top_p
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_tokens = max_tokens
			self.stops = stops if isinstance( stops, list ) else [ ]
			self.instructions = instruct

			if self.tool_type not in ('google_search', 'google_maps'):
				raise ValueError( f'Unsupported grounding tool: {self.tool_type}' )

			self.generation_config = { }

			if self.temperature is not None:
				self.generation_config[ 'temperature' ] = self.temperature

			if self.top_p is not None:
				self.generation_config[ 'top_p' ] = self.top_p

			if self.max_tokens is not None and self.max_tokens > 0:
				self.generation_config[ 'max_output_tokens' ] = self.max_tokens

			self.stop_sequences = [ str( item ).strip( ) for item in self.stops if
				item is not None and str( item ).strip( ) ]

			if self.stop_sequences:
				self.generation_config[ 'stop_sequences' ] = self.stop_sequences

			self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
				'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
			throw_if( 'api_key', self.api_key )
			self.genai_client = genai.Client( api_key=self.api_key,
				http_options=types.HttpOptions( api_version='v1beta' ) )
			self.request = { 'model': self.model, 'input': self.prompt,
				'tools': [ { 'type': self.tool_type } ], 'response_format': { 'type': 'text' },
				'store': False, }

			if self.instructions is not None and str( self.instructions ).strip( ):
				self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

			if self.generation_config:
				self.request[ 'generation_config' ] = (self.generation_config)

			self.interaction = self.genai_client.interactions.create( **self.request )
			self.response = self.interaction
			self.content_response = self.interaction
			self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
			throw_if( 'output_text', self.output_text )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'CloudBuckets'
			exception.method = ('execute_grounded_interaction( self, prompt: str, '
			                    'model: str, tool_type: str, temperature: float, '
			                    'top_p: float, frequency: float, presence: float, '
			                    'max_tokens: int, stops: List[ str ], '
			                    'instruct: str ) -> str')
			Logger( ).write( exception )
			raise exception

	def web_search( self, prompt: str, model: str='gemini-2.5-flash-lite',
		temperature: float=None, top_p: float=None, frequency: float=None,
		presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
		instruct: str=None ) -> str:
		"""Generate a Google Search-grounded response."""
		return self.execute_grounded_interaction( prompt=prompt, model=model,
			tool_type='google_search', temperature=temperature, top_p=top_p, frequency=frequency,
			presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )

	def search_maps( self, prompt: str, model: str='gemini-2.5-flash-lite',
		temperature: float=None, top_p: float=None, frequency: float=None,
		presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
		instruct: str=None ) -> str:
		"""Generate a Google Maps-grounded response."""
		return self.execute_grounded_interaction( prompt=prompt, model=model,
			tool_type='google_maps', temperature=temperature, top_p=top_p, frequency=frequency,
			presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )

	def delete( self, bucket: str, name: str ) -> bool:
		"""Delete a bucket object.

		Args:
			bucket (str): Bucket name.
			name (str): Object name.

		Returns:
			bool: True after successful deletion.

		Raises:
			Error: Raised when validation or deletion fails.
		"""
		try:
			throw_if( 'bucket', bucket )
			throw_if( 'name', name )
			self.bucket_name = bucket
			self.object_name = name
			self.client = self.create_storage_client( )
			self.bucket = self.client.bucket( self.bucket_name )
			self.blob = self.bucket.blob( self.object_name )
			self.blob.delete( )
			return True
		except Exception as e:
			exception = Error( e )
			exception.module = 'gemini'
			exception.cause = 'CloudBuckets'
			exception.method = ('delete( self, bucket: str, name: str ) -> bool')
			Logger( ).write( exception )
			raise exception

model_options property

model_options: List[str]

Return supported grounded-generation models.

Returns:

Type Description
List[str]

List[str]: Supported Gemini model identifiers.

media_options property

media_options: List[str]

Return supported media-resolution values.

Returns:

Type Description
List[str]

List[str]: Supported media-resolution values.

__init__

__init__() -> None

Initialize the Google Cloud Storage wrapper.

Purpose

Initializes local bucket, object, collection, and response state without creating clients or performing network operations.

Returns:

Name Type Description
None None

This method initializes object state through side effects.

Source code in gemini.py
def __init__( self ) -> None:
	"""Initialize the Google Cloud Storage wrapper.

	Purpose:
		Initializes local bucket, object, collection, and response state without creating
		clients or performing network operations.

	Returns:
		None: This method initializes object state through side effects.
	"""
	super( ).__init__( )
	self.project_id = cfg.GOOGLE_CLOUD_PROJECT_ID
	self.bucket_name = None
	self.object_name = None
	self.file_path = None
	self.file_ids = [ ]
	self.store_ids = [ ]
	self.client = None
	self.bucket = None
	self.response = None
	self.interaction = None
	self.collections = { 'Federal Financial Data': 'jeni-financial/data',
		'Federal Financial Regulations': 'jeni-financial/regulations',
		'DoW Financial Data': 'jeni-dow/budget/data',
		'DoW Financial Regulations': 'jeni-dow/budget/regulations',
		'DoA Financial Data': 'jenni-doa/Financial Data', }
	self.documents = { 'Account_Balances.csv': 'file-U6wFeRGSeg38Db5uJzo5sj',
		'SF133.csv': 'file-32s641QK1Xb5QUatY3zfWF',
		'Authority.csv': 'file-Qi2rw2QsdxKBX1iiaQxY3m',
		'Outlays.csv': 'file-GHEwSWR7ezMvHrQ3X648wn', }

create_storage_client

create_storage_client() -> Client

Create the Google Cloud Storage client.

Returns:

Type Description
Client

storage.Client: Configured storage client.

Raises:

Type Description
Error

Raised when client creation fails.

Source code in gemini.py
def create_storage_client( self ) -> storage.Client:
	"""Create the Google Cloud Storage client.

	Returns:
		storage.Client: Configured storage client.

	Raises:
		Error: Raised when client creation fails.
	"""
	try:
		self.client = storage.Client( project=self.project_id )
		return self.client
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'CloudBuckets'
		exception.method = ('create_storage_client( self ) -> storage.Client')
		Logger( ).write( exception )
		raise exception

create

create(bucket: str, name: str) -> Blob

Create an empty object in a bucket.

Parameters:

Name Type Description Default
bucket str

Bucket name.

required
name str

Object name.

required

Returns:

Name Type Description
Blob Blob

Created object reference.

Raises:

Type Description
Error

Raised when validation or object creation fails.

Source code in gemini.py
def create( self, bucket: str, name: str ) -> Blob:
	"""Create an empty object in a bucket.

	Args:
		bucket (str): Bucket name.
		name (str): Object name.

	Returns:
		Blob: Created object reference.

	Raises:
		Error: Raised when validation or object creation fails.
	"""
	try:
		throw_if( 'bucket', bucket )
		throw_if( 'name', name )
		self.bucket_name = bucket
		self.object_name = name
		self.client = self.create_storage_client( )
		self.bucket = self.client.bucket( self.bucket_name )
		self.blob = self.bucket.blob( self.object_name )
		self.blob.upload_from_string( b'' )
		self.response = self.blob
		return self.blob
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'CloudBuckets'
		exception.method = ('create( self, bucket: str, name: str ) -> Blob')
		Logger( ).write( exception )
		raise exception

upload

upload(path: str, bucket: str, name: str = None) -> Blob

Upload a local file to a bucket.

Parameters:

Name Type Description Default
path str

Local file path.

required
bucket str

Bucket name.

required
name str

Optional object name.

None

Returns:

Name Type Description
Blob Blob

Uploaded object.

Raises:

Type Description
Error

Raised when validation or upload fails.

Source code in gemini.py
def upload( self, path: str, bucket: str, name: str=None ) -> Blob:
	"""Upload a local file to a bucket.

	Args:
		path (str): Local file path.
		bucket (str): Bucket name.
		name (str): Optional object name.

	Returns:
		Blob: Uploaded object.

	Raises:
		Error: Raised when validation or upload fails.
	"""
	try:
		throw_if( 'path', path )
		throw_if( 'bucket', bucket )
		self.file_path = path
		self.bucket_name = bucket
		self.object_name = (name if name else Path( self.file_path ).name)
		self.client = self.create_storage_client( )
		self.bucket = self.client.bucket( self.bucket_name )
		self.blob = self.bucket.blob( self.object_name )
		self.blob.upload_from_filename( self.file_path )
		self.response = self.blob
		return self.blob
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'CloudBuckets'
		exception.method = ('upload( self, path: str, bucket: str, '
		                    'name: str ) -> Blob')
		Logger( ).write( exception )
		raise exception

retrieve

retrieve(bucket: str, name: str) -> Optional[Blob]

Retrieve object metadata.

Parameters:

Name Type Description Default
bucket str

Bucket name.

required
name str

Object name.

required

Returns:

Type Description
Optional[Blob]

Optional[Blob]: Matching object, or None when absent.

Raises:

Type Description
Error

Raised when validation or retrieval fails.

Source code in gemini.py
def retrieve( self, bucket: str, name: str ) -> Optional[ Blob ]:
	"""Retrieve object metadata.

	Args:
		bucket (str): Bucket name.
		name (str): Object name.

	Returns:
		Optional[Blob]: Matching object, or None when absent.

	Raises:
		Error: Raised when validation or retrieval fails.
	"""
	try:
		throw_if( 'bucket', bucket )
		throw_if( 'name', name )
		self.bucket_name = bucket
		self.object_name = name
		self.client = self.create_storage_client( )
		self.bucket = self.client.bucket( self.bucket_name )
		self.response = self.bucket.get_blob( self.object_name )
		return self.response
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'CloudBuckets'
		exception.method = ('retrieve( self, bucket: str, name: str ) '
		                    '-> Optional[ Blob ]')
		Logger( ).write( exception )
		raise exception

list

list(bucket: str) -> List[Blob]

List bucket objects.

Parameters:

Name Type Description Default
bucket str

Bucket name.

required

Returns:

Type Description
List[Blob]

List[Blob]: Bucket objects.

Raises:

Type Description
Error

Raised when validation or listing fails.

Source code in gemini.py
def list( self, bucket: str ) -> List[ Blob ]:
	"""List bucket objects.

	Args:
		bucket (str): Bucket name.

	Returns:
		List[Blob]: Bucket objects.

	Raises:
		Error: Raised when validation or listing fails.
	"""
	try:
		throw_if( 'bucket', bucket )
		self.bucket_name = bucket
		self.client = self.create_storage_client( )
		self.bucket = self.client.bucket( self.bucket_name )
		self.blobs = list( self.bucket.list_blobs( ) )
		self.documents = { blob.name: blob.id for blob in self.blobs }
		self.response = self.blobs
		return self.blobs
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'CloudBuckets'
		exception.method = ('list( self, bucket: str ) -> List[ Blob ]')
		Logger( ).write( exception )
		raise exception

execute_grounded_interaction

execute_grounded_interaction(
    prompt: str,
    model: str,
    tool_type: str,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Execute a grounded Interactions request.

Parameters:

Name Type Description Default
prompt str

User prompt.

required
model str

Gemini model identifier.

required
tool_type str

Grounding tool type.

required
temperature float

Sampling temperature.

None
top_p float

Top-P sampling value.

None
frequency float

Compatibility frequency-penalty value.

None
presence float

Compatibility presence-penalty value.

None
max_tokens int

Maximum output-token count.

None
stops List[str]

Stop sequences.

None
instruct str

Optional system instruction.

None

Returns:

Name Type Description
str str

Generated grounded response.

Raises:

Type Description
Error

Raised when validation or execution fails.

Source code in gemini.py
def execute_grounded_interaction( self, prompt: str, model: str, tool_type: str,
	temperature: float=None, top_p: float=None, frequency: float=None,
	presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
	instruct: str=None ) -> str:
	"""Execute a grounded Interactions request.

	Args:
		prompt (str): User prompt.
		model (str): Gemini model identifier.
		tool_type (str): Grounding tool type.
		temperature (float): Sampling temperature.
		top_p (float): Top-P sampling value.
		frequency (float): Compatibility frequency-penalty value.
		presence (float): Compatibility presence-penalty value.
		max_tokens (int): Maximum output-token count.
		stops (List[str]): Stop sequences.
		instruct (str): Optional system instruction.

	Returns:
		str: Generated grounded response.

	Raises:
		Error: Raised when validation or execution fails.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		throw_if( 'tool_type', tool_type )
		self.prompt = prompt
		self.model = model
		self.tool_type = tool_type
		self.temperature = temperature
		self.top_p = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_tokens = max_tokens
		self.stops = stops if isinstance( stops, list ) else [ ]
		self.instructions = instruct

		if self.tool_type not in ('google_search', 'google_maps'):
			raise ValueError( f'Unsupported grounding tool: {self.tool_type}' )

		self.generation_config = { }

		if self.temperature is not None:
			self.generation_config[ 'temperature' ] = self.temperature

		if self.top_p is not None:
			self.generation_config[ 'top_p' ] = self.top_p

		if self.max_tokens is not None and self.max_tokens > 0:
			self.generation_config[ 'max_output_tokens' ] = self.max_tokens

		self.stop_sequences = [ str( item ).strip( ) for item in self.stops if
			item is not None and str( item ).strip( ) ]

		if self.stop_sequences:
			self.generation_config[ 'stop_sequences' ] = self.stop_sequences

		self.api_key = (os.getenv( 'GEMINI_API_KEY' ) or os.getenv(
			'GOOGLE_API_KEY' ) or self.gemini_api_key or self.google_api_key)
		throw_if( 'api_key', self.api_key )
		self.genai_client = genai.Client( api_key=self.api_key,
			http_options=types.HttpOptions( api_version='v1beta' ) )
		self.request = { 'model': self.model, 'input': self.prompt,
			'tools': [ { 'type': self.tool_type } ], 'response_format': { 'type': 'text' },
			'store': False, }

		if self.instructions is not None and str( self.instructions ).strip( ):
			self.request[ 'system_instruction' ] = str( self.instructions ).strip( )

		if self.generation_config:
			self.request[ 'generation_config' ] = (self.generation_config)

		self.interaction = self.genai_client.interactions.create( **self.request )
		self.response = self.interaction
		self.content_response = self.interaction
		self.output_text = str( getattr( self.interaction, 'output_text', '' ) or '' ).strip( )
		throw_if( 'output_text', self.output_text )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'CloudBuckets'
		exception.method = ('execute_grounded_interaction( self, prompt: str, '
		                    'model: str, tool_type: str, temperature: float, '
		                    'top_p: float, frequency: float, presence: float, '
		                    'max_tokens: int, stops: List[ str ], '
		                    'instruct: str ) -> str')
		Logger( ).write( exception )
		raise exception
web_search(
    prompt: str,
    model: str = "gemini-2.5-flash-lite",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Generate a Google Search-grounded response.

Source code in gemini.py
def web_search( self, prompt: str, model: str='gemini-2.5-flash-lite',
	temperature: float=None, top_p: float=None, frequency: float=None,
	presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
	instruct: str=None ) -> str:
	"""Generate a Google Search-grounded response."""
	return self.execute_grounded_interaction( prompt=prompt, model=model,
		tool_type='google_search', temperature=temperature, top_p=top_p, frequency=frequency,
		presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )

search_maps

search_maps(
    prompt: str,
    model: str = "gemini-2.5-flash-lite",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    stops: List[str] = None,
    instruct: str = None,
) -> str

Generate a Google Maps-grounded response.

Source code in gemini.py
def search_maps( self, prompt: str, model: str='gemini-2.5-flash-lite',
	temperature: float=None, top_p: float=None, frequency: float=None,
	presence: float=None, max_tokens: int=None, stops: List[ str ] = None,
	instruct: str=None ) -> str:
	"""Generate a Google Maps-grounded response."""
	return self.execute_grounded_interaction( prompt=prompt, model=model,
		tool_type='google_maps', temperature=temperature, top_p=top_p, frequency=frequency,
		presence=presence, max_tokens=max_tokens, stops=stops, instruct=instruct )

delete

delete(bucket: str, name: str) -> bool

Delete a bucket object.

Parameters:

Name Type Description Default
bucket str

Bucket name.

required
name str

Object name.

required

Returns:

Name Type Description
bool bool

True after successful deletion.

Raises:

Type Description
Error

Raised when validation or deletion fails.

Source code in gemini.py
def delete( self, bucket: str, name: str ) -> bool:
	"""Delete a bucket object.

	Args:
		bucket (str): Bucket name.
		name (str): Object name.

	Returns:
		bool: True after successful deletion.

	Raises:
		Error: Raised when validation or deletion fails.
	"""
	try:
		throw_if( 'bucket', bucket )
		throw_if( 'name', name )
		self.bucket_name = bucket
		self.object_name = name
		self.client = self.create_storage_client( )
		self.bucket = self.client.bucket( self.bucket_name )
		self.blob = self.bucket.blob( self.object_name )
		self.blob.delete( )
		return True
	except Exception as e:
		exception = Error( e )
		exception.module = 'gemini'
		exception.cause = 'CloudBuckets'
		exception.method = ('delete( self, bucket: str, name: str ) -> bool')
		Logger( ).write( exception )
		raise exception

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 gemini.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 a local image file as base64 text.

Purpose

Reads a local image file and converts its binary content into a base64-encoded string. This supports workflows that need inline image data instead of a file handle or URI.

Parameters:

Name Type Description Default
image_path str

Path to the local image file.

required

Returns:

Type Description
str

Base64-encoded image content.

Source code in gemini.py
def encode_image( image_path: str ) -> str:
	"""Encode a local image file as base64 text.

	Purpose:
		Reads a local image file and converts its binary content into a base64-encoded string.
		This supports workflows that need inline image data instead of a file handle or URI.

	Args:
		image_path (str): Path to the local image file.

	Returns:
		Base64-encoded image content.
	"""
	with open( image_path, "rb" ) as image_file:
		return base64.b64encode( image_file.read( ) ).decode( "utf-8" )