Skip to content

Grok


grok


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

Last Modified By:        Terry D. Eppler
Last Modified On:        12-27-2025

       grok.py
       Copyright ©  2024  Terry Eppler

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

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

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

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

Groq Cloud API wrapper for Streamlit with Hybrid Tool support.

Grok

Grok workflow wrapper.

Purpose

Provides shared xAI configuration state, API-key storage, request defaults, and common runtime containers used by Grok provider workflows.

Attributes:

Name Type Description
api_key Optional[str]

Runtime attribute used by the Grok workflow.

timeout Optional[float]

Runtime attribute used by the Grok workflow.

base_url Optional[str]

Runtime attribute used by the Grok workflow.

model Optional[str]

Runtime attribute used by the Grok workflow.

store_messages Optional[bool]

Runtime attribute used by the Grok workflow.

response_format Optional[str]

Runtime attribute used by the Grok workflow.

temperature Optional[float]

Runtime attribute used by the Grok workflow.

top_percent Optional[float]

Runtime attribute used by the Grok workflow.

frequency_penalty Optional[float]

Runtime attribute used by the Grok workflow.

presence_penalty Optional[float]

Runtime attribute used by the Grok workflow.

max_output_tokens Optional[int]

Runtime attribute used by the Grok workflow.

tool_choice Optional[str]

Runtime attribute used by the Grok workflow.

tools Optional[List[str]]

Runtime attribute used by the Grok workflow.

stops Optional[List[str]]

Runtime attribute used by the Grok workflow.

instructions Optional[str]

Runtime attribute used by the Grok workflow.

content Optional[str]

Runtime attribute used by the Grok workflow.

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

Runtime attribute used by the Grok workflow.

stores Optional[Dict[str, str]]

Runtime attribute used by the Grok workflow.

files Optional[Dict[str, str]]

Runtime attribute used by the Grok workflow.

Source code in grok.py
class Grok( ):
	"""Grok workflow wrapper.

	Purpose:
	    Provides shared xAI configuration state, API-key storage, request defaults, and common runtime containers used by Grok provider workflows.

	Attributes:
	    api_key: Runtime attribute used by the Grok workflow.
	    timeout: Runtime attribute used by the Grok workflow.
	    base_url: Runtime attribute used by the Grok workflow.
	    model: Runtime attribute used by the Grok workflow.
	    store_messages: Runtime attribute used by the Grok workflow.
	    response_format: Runtime attribute used by the Grok workflow.
	    temperature: Runtime attribute used by the Grok workflow.
	    top_percent: Runtime attribute used by the Grok workflow.
	    frequency_penalty: Runtime attribute used by the Grok workflow.
	    presence_penalty: Runtime attribute used by the Grok workflow.
	    max_output_tokens: Runtime attribute used by the Grok workflow.
	    tool_choice: Runtime attribute used by the Grok workflow.
	    tools: Runtime attribute used by the Grok workflow.
	    stops: Runtime attribute used by the Grok workflow.
	    instructions: Runtime attribute used by the Grok workflow.
	    content: Runtime attribute used by the Grok workflow.
	    messages: Runtime attribute used by the Grok workflow.
	    stores: Runtime attribute used by the Grok workflow.
	    files: Runtime attribute used by the Grok workflow.
	"""
	api_key: Optional[ str ]
	timeout: Optional[ float ]
	base_url: Optional[ str ]
	model: Optional[ str ]
	store_messages: Optional[ bool ]
	response_format: Optional[ str ]
	temperature: Optional[ float ]
	top_percent: Optional[ float ]
	frequency_penalty: Optional[ float ]
	presence_penalty: Optional[ float ]
	max_output_tokens: Optional[ int ]
	tool_choice: Optional[ str ]
	tools: Optional[ List[ str ] ]
	stops: Optional[ List[ str ] ]
	instructions: Optional[ str ]
	content: Optional[ str ]
	messages: Optional[ List[ Dict[ str, Any ] ] ]
	stores: Optional[ Dict[ str, str ] ]
	files: Optional[ Dict[ str, str ] ]

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

		Purpose:
		    Initializes Grok state with default configuration values and runtime attributes used by later xAI provider calls.
		"""
		self.api_key = cfg.XAI_API_KEY
		self.base_url = cfg.XAI_BASE_URL
		self.timeout = None
		self.instructions = None
		self.content = None
		self.store_messages = None
		self.model = None
		self.max_output_tokens = None
		self.temperature = None
		self.top_percent = None
		self.tool_choice = None
		self.tools = [ ]
		self.frequency_penalty = None
		self.presence_penalty = None
		self.response_format = None
		self.messages = [ ]
		self.stops = [ ]
		self.collections = None
		self.files = None

Chat

Bases: Grok

Chat workflow wrapper.

Purpose

Builds and executes xAI text, retrieval-augmented, collection-search, web-search, X-search, code-execution, and tool-enabled chat workflows.

Attributes:

Name Type Description
include Optional[List[str]]

Runtime attribute used by the Chat workflow.

tool_choice Optional[str]

Runtime attribute used by the Chat workflow.

previous_id Optional[str]

Runtime attribute used by the Chat workflow.

previous_response_id Optional[str]

Runtime attribute used by the Chat workflow.

conversation_id Optional[str]

Runtime attribute used by the Chat workflow.

parallel_tools Optional[bool]

Runtime attribute used by the Chat workflow.

max_tools Optional[int]

Runtime attribute used by the Chat workflow.

input Optional[List[Dict[str, Any]] | str]

Runtime attribute used by the Chat workflow.

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

Runtime attribute used by the Chat workflow.

reasoning Optional[Dict[str, str]]

Runtime attribute used by the Chat workflow.

allowed_domains Optional[List[str]]

Runtime attribute used by the Chat workflow.

max_search_results Optional[int]

Runtime attribute used by the Chat workflow.

output_text Optional[str]

Runtime attribute used by the Chat workflow.

collections Optional[Dict[str, str]]

Runtime attribute used by the Chat workflow.

files Optional[Dict[str, str]]

Runtime attribute used by the Chat workflow.

content Optional[str]

Runtime attribute used by the Chat workflow.

vector_store_ids Optional[List[str]]

Runtime attribute used by the Chat workflow.

file_ids Optional[List[str]]

Runtime attribute used by the Chat workflow.

response Optional[Any]

Runtime attribute used by the Chat workflow.

file_path Optional[str]

Runtime attribute used by the Chat workflow.

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

	Purpose:
	    Builds and executes xAI text, retrieval-augmented, collection-search, web-search, X-search, code-execution, and tool-enabled chat workflows.

	Attributes:
	    include: Runtime attribute used by the Chat workflow.
	    tool_choice: Runtime attribute used by the Chat workflow.
	    previous_id: Runtime attribute used by the Chat workflow.
	    previous_response_id: Runtime attribute used by the Chat workflow.
	    conversation_id: Runtime attribute used by the Chat workflow.
	    parallel_tools: Runtime attribute used by the Chat workflow.
	    max_tools: Runtime attribute used by the Chat workflow.
	    input: Runtime attribute used by the Chat workflow.
	    tools: Runtime attribute used by the Chat workflow.
	    reasoning: Runtime attribute used by the Chat workflow.
	    allowed_domains: Runtime attribute used by the Chat workflow.
	    max_search_results: Runtime attribute used by the Chat workflow.
	    output_text: Runtime attribute used by the Chat workflow.
	    collections: Runtime attribute used by the Chat workflow.
	    files: Runtime attribute used by the Chat workflow.
	    content: Runtime attribute used by the Chat workflow.
	    vector_store_ids: Runtime attribute used by the Chat workflow.
	    file_ids: Runtime attribute used by the Chat workflow.
	    response: Runtime attribute used by the Chat workflow.
	    file_path: Runtime attribute used by the Chat workflow.
	"""
	include: Optional[ List[ str ] ]
	tool_choice: Optional[ str ]
	previous_id: Optional[ str ]
	previous_response_id: Optional[ str ]
	conversation_id: Optional[ str ]
	parallel_tools: Optional[ bool ]
	max_tools: Optional[ int ]
	input: Optional[ List[ Dict[ str, Any ] ] | str ]
	tools: Optional[ List[ Dict[ str, Any ] ] ]
	reasoning: Optional[ Dict[ str, str ] ]
	allowed_domains: Optional[ List[ str ] ]
	max_search_results: Optional[ int ]
	output_text: Optional[ str ]
	collections: Optional[ Dict[ str, str ] ]
	files: Optional[ Dict[ str, str ] ]
	content: Optional[ str ]
	vector_store_ids: Optional[ List[ str ] ]
	file_ids: Optional[ List[ str ] ]
	response: Optional[ Any ]
	file_path: Optional[ str ]

	def __init__( self, model: str = 'grok-4.20', prompt: str = None, temperature: float = None,
			top_p: float = None, presense: float = None, presence: float = None, store: bool = None,
			stream: bool = None, stops: List[ str ] = None,
			response_format: Dict[ str, Any ] = None,
			number: int = None, instruct: str = None, context: List[ Dict[ str, str ] ] = None,
			allowed_domains: List[ str ] = None, include: List[ str ] = None,
			tools: List[ Dict[ str, Any ] ] = None, max_tools: int = None,
			tool_choice: str = None, file_path: str = None, background: bool = None,
			is_parallel: bool = None, max_tokens: int = None, frequency: float = None,
			input: List[ Dict[ str, Any ] ] = None, file_ids: List[ str ] = None,
			previous_id: str = None, conversation_id: str = None,
			reasoning: Dict[ str, str ] | str = None, output_text: str = None,
			max_search_results: int = None, content: str = None,
			vector_store_ids: List[ str ] = None ):
		"""Initialize instance.

		Purpose:
		    Initializes Chat state with default configuration values and runtime attributes used by later xAI provider calls.

		Args:
		    model (str): Model supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    presense (float): Presense supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    stops (List[str]): Stops supplied to the xAI workflow.
		    response_format (Dict[str, Any]): Response format supplied to the xAI workflow.
		    number (int): Number supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
		    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
		    include (List[str]): Include supplied to the xAI workflow.
		    tools (List[Dict[str, Any]]): Tools supplied to the xAI workflow.
		    max_tools (int): Max tools supplied to the xAI workflow.
		    tool_choice (str): Tool choice supplied to the xAI workflow.
		    file_path (str): File path supplied to the xAI workflow.
		    background (bool): Background supplied to the xAI workflow.
		    is_parallel (bool): Is parallel supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    input (List[Dict[str, Any]]): Input supplied to the xAI workflow.
		    file_ids (List[str]): File ids supplied to the xAI workflow.
		    previous_id (str): Previous id supplied to the xAI workflow.
		    conversation_id (str): Conversation id supplied to the xAI workflow.
		    reasoning (Dict[str, str] | str): Reasoning supplied to the xAI workflow.
		    output_text (str): Output text supplied to the xAI workflow.
		    max_search_results (int): Max search results supplied to the xAI workflow.
		    content (str): Content supplied to the xAI workflow.
		    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.
		"""
		super( ).__init__( )
		self.api_key = cfg.XAI_API_KEY
		self.base_url = cfg.XAI_BASE_URL
		self.client = None
		self.model = model
		self.prompt = prompt
		self.number = number
		self.response_format = response_format if response_format is not None else { }
		self.temperature = temperature
		self.top_percent = top_p
		self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
		self.frequency_penalty = frequency
		self.presence_penalty = presence if presence is not None else presense
		self.max_output_tokens = max_tokens
		self.context = context if context is not None else [ ]
		self.stream = stream
		self.store_messages = store
		self.instructions = instruct
		self.stops = stops if stops is not None else [ ]
		self.background = background
		self.input = input if input is not None else [ ]
		self.include = include if include is not None else [ ]
		self.output_text = output_text
		self.max_tools = max_tools
		self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]
		self.file_ids = file_ids if file_ids is not None else [ ]
		self.tools = tools if tools is not None else [ ]
		self.previous_id = previous_id
		self.previous_response_id = previous_id
		self.conversation_id = conversation_id
		self.reasoning = reasoning
		self.parallel_tools = is_parallel
		self.tool_choice = tool_choice
		self.response = None
		self.file_path = file_path
		self.content = content
		self.max_search_results = max_search_results
		self.request = { }
		self.messages = [ ]
		self.stream_requested = False
		self.background_requested = False
		self.collections = {
				'Federal Financial Regulations': 'collection_9195d847-03a1-443c-9240-294c64dd01e2',
				'Federal Financial Data': 'collection_e28cdcc2-a9e5-430a-bdf5-94fbaf44b6a4',
				'Explanatory Statements': 'collection_41dc3374-24d0-4692-819c-59e3d7b11b93',
				'Public Laws': 'collection_c1d0b83e-2f59-4f10-9cf7-51392b490fee',
		}
		self.files = {
				'Outlays.csv': 'file_b0a448b3-904a-40c7-bae1-64df657fde1c',
				'Authority.csv': 'file_c6ad236f-0c52-45f4-8883-d3be032d07c2',
				'Balances.csv': 'file_0f63d120-406f-49e6-97e5-7855f2cb26b5',
		}

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

		Purpose:
		    Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'grok-4.20',
				'grok-4.20-reasoning',
				'grok-4.20-multi-agent',
				'grok-4',
				'grok-4-latest',
				'grok-4-fast-reasoning',
				'grok-4-fast-non-reasoning',
				'grok-code-fast-1',
				'grok-3',
				'grok-3-mini',
				'grok-3-fast',
				'grok-3-mini-fast',
		]

	@property
	def include_options( self ) -> List[ str ] | None:
		"""Include options.

		Purpose:
		    Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'web_search_call_output',
				'x_search_call_output',
				'code_execution_call_output',
				'collections_search_call_output',
				'attachment_search_call_output',
				'mcp_call_output',
				'inline_citations',
				'verbose_streaming',
		]

	@property
	def tool_options( self ) -> List[ str ] | None:
		"""Tool options.

		Purpose:
		    Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'web_search',
				'x_search',
				'collections_search',
				'code_execution',
		]

	@property
	def choice_options( self ) -> List[ str ] | None:
		"""Choice options.

		Purpose:
		    Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [ 'auto', 'required', 'none', ]

	@property
	def format_options( self ) -> List[ str ] | None:
		"""Format options.

		Purpose:
		    Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'text',
				'json_object',
				'json_schema',
		]

	@property
	def reasoning_options( self ) -> List[ str ] | None:
		"""Reasoning options.

		Purpose:
		    Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'none',
				'low',
				'medium',
				'high',
				'xhigh',
		]

	@property
	def modality_options( self ) -> List[ str ] | None:
		"""Modality options.

		Purpose:
		    Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [ 'text', ]

	@property
	def media_options( self ) -> List[ str ] | None:
		"""Media options.

		Purpose:
		    Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [ 'auto', ]

	def build_reasoning( self, reasoning: str | Dict[ str, str ] = None ) -> Dict[
		                                                                         str, str ] | None:
		"""Build reasoning.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Args:
		    reasoning (str | Dict[str, str]): Reasoning supplied to the xAI workflow.

		Returns:
		    Dict[str, str] | None: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			if reasoning is None:
				return None

			if isinstance( reasoning, dict ):
				value = reasoning.get( 'effort' )
				if isinstance( value, str ) and value.strip( ) in self.reasoning_options:
					if value.strip( ) == 'none':
						return None

					return { 'effort': value.strip( ) }

				return None

			if isinstance( reasoning, str ) and reasoning.strip( ):
				value = reasoning.strip( )
				if value == 'none':
					return None

				if value in self.reasoning_options:
					return { 'effort': value }

			return None
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'build_reasoning( self, reasoning )'
			Logger( ).write( exception )
			raise exception

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

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
		    input_data (List[Dict[str, Any]]): Input data supplied to the xAI workflow.

		Returns:
		    List[Dict[str, Any]]: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			self.messages = [ ]

			if input_data is not None and len( input_data ) > 0:
				self.messages.extend( input_data )
			elif context is not None and len( context ) > 0:
				for item in context:
					if not isinstance( item, dict ):
						continue

					role = str( item.get( 'role', '' ) or '' ).strip( )
					content = item.get( 'content', '' )

					if role not in [ 'user', 'assistant', 'system', 'developer' ]:
						continue

					if not isinstance( content, str ) or not content.strip( ):
						continue

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

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

			return self.messages
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'build_input( self, prompt, context, input_data )'
			Logger( ).write( exception )
			raise exception

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

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Args:
		    tools (List[Any]): Tools supplied to the xAI workflow.
		    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
		    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.

		Returns:
		    List[Dict[str, Any]] | None: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
			self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]
			if tools is None or len( tools ) == 0:
				return None

			self.built_tools = [ ]
			for tool in tools:
				if isinstance( tool, dict ):
					tool_type = str( tool.get( 'type', '' ) or '' ).strip( )
				else:
					tool_type = str( tool or '' ).strip( )

				if not tool_type:
					continue

				if tool_type == 'web_search':
					built_tool = { 'type': 'web_search' }
					if len( self.allowed_domains ) > 0:
						built_tool[ 'allowed_domains' ] = self.allowed_domains

					self.built_tools.append( built_tool )
					continue

				if tool_type == 'x_search':
					self.built_tools.append( { 'type': 'x_search' } )
					continue

				if tool_type in [ 'collections_search', 'file_search' ]:
					if len( self.vector_store_ids ) == 0:
						continue

					self.built_tools.append(
						{
								'type': 'collections_search',
								'collection_ids': self.vector_store_ids,
						} )
					continue

				if tool_type in [ 'code_execution', 'code_interpreter' ]:
					self.built_tools.append( { 'type': 'code_execution' } )
					continue

			return self.built_tools if len( self.built_tools ) > 0 else None
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'build_tools( self, tools, allowed_domains, vector_store_ids )'
			Logger( ).write( exception )
			raise exception

	def build_tool_choice( self, tool_choice: str = None,
			tools: List[ Dict[ str, Any ] ] = None ) -> str | None:
		"""Build tool choice.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Args:
		    tool_choice (str): Tool choice supplied to the xAI workflow.
		    tools (List[Dict[str, Any]]): Tools supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			if not isinstance( tool_choice, str ) or not tool_choice.strip( ):
				return None

			choice = tool_choice.strip( )
			if choice not in self.choice_options:
				return None

			if choice == 'none':
				return 'none'

			if tools is None or len( tools ) == 0:
				return None

			return choice
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'build_tool_choice( self, tool_choice, tools )'
			Logger( ).write( exception )
			raise exception

	def build_include( self, include: List[ str ] = None,
			tools: List[ Dict[ str, Any ] ] = None ) -> List[ str ] | None:
		"""Build include.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Args:
		    include (List[str]): Include supplied to the xAI workflow.
		    tools (List[Dict[str, Any]]): Tools supplied to the xAI workflow.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			if include is None or len( include ) == 0:
				return None

			tool_types = [ ]
			if isinstance( tools, list ):
				for tool in tools:
					if isinstance( tool, dict ) and tool.get( 'type' ):
						tool_types.append( str( tool.get( 'type' ) ) )

			allowed = [ ]
			for value in include:
				if not isinstance( value, str ) or not value.strip( ):
					continue

				name = value.strip( )
				if name in [ 'inline_citations', 'verbose_streaming', 'mcp_call_output' ]:
					allowed.append( name )
					continue

				if name == 'web_search_call_output' and 'web_search' in tool_types:
					allowed.append( name )
					continue

				if name == 'x_search_call_output' and 'x_search' in tool_types:
					allowed.append( name )
					continue

				if name == 'code_execution_call_output' and 'code_execution' in tool_types:
					allowed.append( name )
					continue

				if name == 'collections_search_call_output' and 'collections_search' in tool_types:
					allowed.append( name )
					continue

				if name == 'attachment_search_call_output' and 'collections_search' in tool_types:
					allowed.append( name )
					continue

			return allowed if len( allowed ) > 0 else None
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'build_include( self, include, tools )'
			Logger( ).write( exception )
			raise exception

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

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Args:
		    format (Dict[str, Any] | str): Format supplied to the xAI workflow.
		    response_schema (Any): Response schema supplied to the xAI workflow.

		Returns:
		    Dict[str, Any] | None: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			if format is None:
				return None

			if isinstance( format, dict ) and len( format ) > 0:
				if 'format' in format and isinstance( format.get( 'format' ), dict ):
					return format

				if 'type' in format:
					return { 'format': format }

				return None

			if isinstance( format, str ) and format.strip( ):
				value = format.strip( )
				if value == 'text':
					return { 'format': { 'type': 'text' } }

				if value == 'json_object':
					return { 'format': { 'type': 'json_object' } }

				if value == 'json_schema' and isinstance( response_schema, dict ):
					return { 'format': { 'type': 'json_schema', 'json_schema': response_schema } }

			return None
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'build_text_format( self, format, response_schema )'
			Logger( ).write( exception )
			raise exception

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

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    format (Dict[str, Any]): Format supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    max_tools (int): Max tools supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    background (bool): Background supplied to the xAI workflow.
		    reasoning (str): Reasoning supplied to the xAI workflow.
		    include (List[str]): Include supplied to the xAI workflow.
		    tools (List[Any]): Tools supplied to the xAI workflow.
		    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
		    previous_id (str): Previous id supplied to the xAI workflow.
		    tool_choice (str): Tool choice supplied to the xAI workflow.
		    is_parallel (bool): Is parallel supplied to the xAI workflow.
		    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
		    input_data (List[Dict[str, Any]]): Input data supplied to the xAI workflow.
		    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.
		    conversation_id (str): Conversation id supplied to the xAI workflow.
		    response_schema (Any): Response schema supplied to the xAI workflow.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.model = model
			self.prompt = prompt
			self.temperature = temperature
			self.top_percent = top_p
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_output_tokens = max_tokens
			self.store_messages = store
			self.stream = stream
			self.background = background
			self.instructions = instruct
			self.response_format = self.build_text_format( format, response_schema=response_schema )
			self.max_tools = max_tools
			self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]
			self.previous_id = previous_id if isinstance( previous_id, str ) else None
			self.previous_response_id = self.previous_id
			self.conversation_id = conversation_id if isinstance( conversation_id, str ) else None
			self.parallel_tools = is_parallel
			self.reasoning = self.build_reasoning( reasoning )
			self.tools = self.build_tools( tools=tools, allowed_domains=allowed_domains,
				vector_store_ids=self.vector_store_ids )
			self.tool_choice = self.build_tool_choice( tool_choice=tool_choice, tools=self.tools )
			self.include = self.build_include( include=include, tools=self.tools )
			self.input = self.build_input( prompt=prompt, context=context, input_data=input_data )
			self.request = {
					'model': self.model,
					'input': self.input,
			}

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

			if self.reasoning is not None and self.model == 'grok-4.20-multi-agent':
				self.request[ 'reasoning' ] = self.reasoning

			if isinstance( self.max_output_tokens, int ) and self.max_output_tokens > 0:
				self.request[ 'max_output_tokens' ] = self.max_output_tokens

			if self.temperature is not None:
				self.request[ 'temperature' ] = self.temperature

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

			if self.frequency_penalty is not None:
				self.request[ 'frequency_penalty' ] = self.frequency_penalty

			if self.presence_penalty is not None:
				self.request[ 'presence_penalty' ] = self.presence_penalty

			if self.store_messages is not None:
				self.request[ 'store' ] = self.store_messages

			# Stream and background are retained on self for layout/UI parity. This path returns final text.
			if self.include is not None and len( self.include ) > 0:
				self.request[ 'include' ] = self.include

			if self.tools is not None and len( self.tools ) > 0:
				self.request[ 'tools' ] = self.tools

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

			if self.parallel_tools is not None and self.tools is not None:
				self.request[ 'parallel_tool_calls' ] = self.parallel_tools

			if self.previous_id and self.previous_id.strip( ):
				self.request[ 'previous_response_id' ] = self.previous_id.strip( )

			if self.conversation_id and self.conversation_id.strip( ):
				self.request[ 'conversation' ] = self.conversation_id.strip( )

			if isinstance( self.max_tools, int ) and self.max_tools > 0 and self.tools is not None:
				self.request[ 'max_tool_calls' ] = self.max_tools

			if self.response_format is not None and len( self.response_format ) > 0:
				self.request[ 'text' ] = self.response_format

			return self.request
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'build_request( self, **kwargs )'
			Logger( ).write( exception )
			raise exception

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

		Purpose:
		    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

		Returns:
		    str | None: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			if self.response is None:
				return None

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

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

					if not hasattr( item, 'content' ) or item.content is None:
						continue

					for block in item.content:
						if getattr( block, 'type', None ) == 'output_text':
							text = getattr( block, 'text', None )
							if text:
								text_parts.append( text )

				if len( text_parts ) > 0:
					self.output_text = ''.join( text_parts ).strip( )
					return self.output_text

			return None
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'get_output_text( self ) -> str | None'
			Logger( ).write( exception )
			raise exception

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

		Purpose:
		    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

		Returns:
		    Any: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			if self.response is None:
				return None

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

	def generate_text( self, prompt: str, model: str, temperature: float = None,
			format: Dict[ str, Any ] = None, top_p: float = None, top_k: int = None,
			frequency: float = None, max_tools: int = None, presence: float = None,
			max_tokens: int = None, store: bool = None, stream: bool = None,
			instruct: str = None, background: bool = False, reasoning: str = None,
			include: List[ str ] = None, tools: List[ Any ] = None,
			allowed_domains: List[ str ] = None, previous_id: str = None,
			tool_choice: str = None, is_parallel: bool = None,
			context: List[ Dict[ str, str ] ] = None, input_data: List[ Dict[ str, Any ] ] = None,
			vector_store_ids: List[ str ] = None, conversation_id: str = None,
			response_format: Dict[ str, Any ] | str = None, response_schema: Any = None,
			number: int = None, modalities: List[ str ] = None, media_resolution: str = None,
			content: str = None, urls: List[ str ] = None, max_urls: int = None,
			safety_profile: str = None, **kwargs: Any ) -> str | None:
		"""Generate text.

		Purpose:
		    Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    format (Dict[str, Any]): Format supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    top_k (int): Top k supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    max_tools (int): Max tools supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    background (bool): Background supplied to the xAI workflow.
		    reasoning (str): Reasoning supplied to the xAI workflow.
		    include (List[str]): Include supplied to the xAI workflow.
		    tools (List[Any]): Tools supplied to the xAI workflow.
		    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
		    previous_id (str): Previous id supplied to the xAI workflow.
		    tool_choice (str): Tool choice supplied to the xAI workflow.
		    is_parallel (bool): Is parallel supplied to the xAI workflow.
		    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
		    input_data (List[Dict[str, Any]]): Input data supplied to the xAI workflow.
		    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.
		    conversation_id (str): Conversation id supplied to the xAI workflow.
		    response_format (Dict[str, Any] | str): Response format supplied to the xAI workflow.
		    response_schema (Any): Response schema supplied to the xAI workflow.
		    number (int): Number supplied to the xAI workflow.
		    modalities (List[str]): Modalities supplied to the xAI workflow.
		    media_resolution (str): Media resolution supplied to the xAI workflow.
		    content (str): Content supplied to the xAI workflow.
		    urls (List[str]): Urls supplied to the xAI workflow.
		    max_urls (int): Max urls supplied to the xAI workflow.
		    safety_profile (str): Safety profile supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.client = OpenAI( api_key=cfg.XAI_API_KEY, base_url=self.base_url )
			self.number = number
			self.top_k = top_k
			self.modalities = modalities if modalities is not None else [ ]
			self.media_resolution = media_resolution
			self.content = content
			self.urls = urls if urls is not None else [ ]
			self.max_urls = max_urls
			self.safety_profile = safety_profile
			self.extra_kwargs = kwargs or { }
			self.stream_requested = bool( stream )
			self.background_requested = bool( background )
			self.request = self.build_request( prompt=prompt, model=model,
				temperature=temperature, format=response_format or format, top_p=top_p,
				frequency=frequency, max_tools=max_tools, presence=presence,
				max_tokens=max_tokens, store=store, stream=False, instruct=instruct,
				background=False, reasoning=reasoning, include=include, tools=tools,
				allowed_domains=allowed_domains, previous_id=previous_id,
				tool_choice=tool_choice, is_parallel=is_parallel, context=context,
				input_data=input_data, vector_store_ids=vector_store_ids,
				conversation_id=conversation_id, response_schema=response_schema )
			self.response = self.client.responses.create( **self.request )
			self.previous_id = getattr( self.response, 'id', None )
			self.previous_response_id = self.previous_id
			self.output_text = self.get_output_text( )
			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'generate_text( self, prompt: str ) -> str | None'
			Logger( ).write( exception )
			raise exception

	def get_grounding_sources( self ) -> List[ Dict[ str, Any ] ]:
		"""Get grounding sources.

		Purpose:
		    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

		Returns:
		    List[Dict[str, Any]]: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			if self.response is None:
				return [ ]

			self.sources = [ ]
			output = getattr( self.response, 'output', None )
			if isinstance( output, list ):
				for item in output:
					item_type = getattr( item, 'type', None )

					if item_type in [ 'web_search_call', 'x_search_call' ]:
						action = getattr( item, 'action', None )
						raw_sources = getattr( action, 'sources', None ) if action else None
						if isinstance( raw_sources, list ):
							for source in raw_sources:
								self.sources.append(
									{
											'title': getattr( source, 'title', None ),
											'url': getattr( source, 'url', None ),
											'snippet': getattr( source, 'snippet', None ),
											'file_id': None,
									} )

					if item_type in [ 'collections_search_call', 'file_search_call' ]:
						results = getattr( item, 'results', None )
						if isinstance( results, list ):
							for result in results:
								self.sources.append(
									{
											'title': getattr( result, 'file_name',
												None ) or getattr(
												result, 'title', None ),
											'url': None,
											'snippet': getattr( result, 'text', None ),
											'file_id': getattr( result, 'file_id', None ),
									} )

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

	def answer_document( self, prompt: str, document_text: str, model: str,
			instructions: str = None, temperature: float = None, top_p: float = None,
			frequency: float = None, presence: float = None, max_tokens: int = None,
			store: bool = None, include: List[ str ] = None, tools: List[ str ] = None,
			tool_choice: str = None, reasoning: str = None,
			context: List[ Dict[ str, str ] ] = None,
			vector_store_ids: List[ str ] = None ) -> str | None:
		"""Answer document.

		Purpose:
		    Provides answer document behavior for the Chat workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    document_text (str): Document text supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    instructions (str): Instructions supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    include (List[str]): Include supplied to the xAI workflow.
		    tools (List[str]): Tools supplied to the xAI workflow.
		    tool_choice (str): Tool choice supplied to the xAI workflow.
		    reasoning (str): Reasoning supplied to the xAI workflow.
		    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
		    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.

		Raises:
		    Error: Re-raised after validation or provider execution errors are wrapped and logged.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'document_text', document_text )
			throw_if( 'model', model )

			self.prompt = prompt
			self.content = document_text
			self.model = model
			self.instructions = instructions
			self.temperature = temperature
			self.top_percent = top_p
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_output_tokens = max_tokens
			self.store_messages = store
			self.include = include if include is not None else [ ]
			self.tool_choice = tool_choice
			self.reasoning = reasoning
			self.context = context if context is not None else [ ]
			self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]

			selected_tools = [ ]
			if tools is not None:
				for item in tools:
					if isinstance( item, dict ):
						selected_tools.append( item )
						continue

					if isinstance( item, str ) and item.strip( ):
						selected_tools.append( { 'type': item.strip( ) } )

			self.tools = selected_tools

			if isinstance( self.tool_choice, list ):
				self.tool_choice = self.tool_choice[ 0 ] if len( self.tool_choice ) > 0 else None

			document_prompt = (
					f'Document Context:\n'
					f'{self.content}\n\n'
					f'User Question:\n'
					f'{self.prompt}'
			)

			self.output_text = self.generate_text(
				prompt=document_prompt,
				model=self.model,
				temperature=self.temperature,
				top_p=self.top_percent,
				frequency=self.frequency_penalty,
				presence=self.presence_penalty,
				max_tokens=self.max_output_tokens,
				store=self.store_messages,
				stream=False,
				instruct=self.instructions,
				reasoning=self.reasoning,
				include=self.include,
				tools=self.tools,
				tool_choice=self.tool_choice,
				context=self.context,
				vector_store_ids=self.vector_store_ids )

			return self.output_text
		except Exception as e:
			exception = Error( e )
			exception.module = 'grok'
			exception.cause = 'Chat'
			exception.method = 'answer_document( self, prompt: str, document_text: str, model: str ) -> str | None'
			Logger( ).write( exception )
			raise exception

	def __dir__( self ) -> List[ str ] | None:
		"""Dir.

		Purpose:
		    Provides dir behavior for the Chat workflow while preserving provider request and response state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'api_key',
				'base_url',
				'client',
				'model',
				'prompt',
				'temperature',
				'top_percent',
				'frequency_penalty',
				'presence_penalty',
				'max_output_tokens',
				'stops',
				'store_messages',
				'stream',
				'background',
				'number',
				'response_format',
				'context',
				'instructions',
				'include',
				'tool_choice',
				'previous_id',
				'previous_response_id',
				'conversation_id',
				'parallel_tools',
				'max_tools',
				'input',
				'tools',
				'reasoning',
				'allowed_domains',
				'max_search_results',
				'output_text',
				'vector_store_ids',
				'file_ids',
				'response',
				'file_path',
				'model_options',
				'include_options',
				'tool_options',
				'choice_options',
				'format_options',
				'reasoning_options',
				'modality_options',
				'media_options',
				'build_reasoning',
				'build_input',
				'build_tools',
				'build_tool_choice',
				'build_include',
				'build_text_format',
				'build_request',
				'get_output_text',
				'get_usage',
				'generate_text',
				'get_grounding_sources',
				'answer_documents'
		]

model_options property

model_options: List[str] | None

Model options.

Purpose

Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

include_options property

include_options: List[str] | None

Include options.

Purpose

Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

tool_options property

tool_options: List[str] | None

Tool options.

Purpose

Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

choice_options property

choice_options: List[str] | None

Choice options.

Purpose

Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

format_options property

format_options: List[str] | None

Format options.

Purpose

Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

reasoning_options property

reasoning_options: List[str] | None

Reasoning options.

Purpose

Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

modality_options property

modality_options: List[str] | None

Modality options.

Purpose

Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

media_options property

media_options: List[str] | None

Media options.

Purpose

Returns the configured option values exposed by the Chat workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

build_reasoning

build_reasoning(
    reasoning: str | Dict[str, str] = None,
) -> Dict[str, str] | None

Build reasoning.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Parameters:

Name Type Description Default
reasoning str | Dict[str, str]

Reasoning supplied to the xAI workflow.

None

Returns:

Type Description
Dict[str, str] | None

Dict[str, str] | None: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

Source code in grok.py
def build_reasoning( self, reasoning: str | Dict[ str, str ] = None ) -> Dict[
	                                                                         str, str ] | None:
	"""Build reasoning.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Args:
	    reasoning (str | Dict[str, str]): Reasoning supplied to the xAI workflow.

	Returns:
	    Dict[str, str] | None: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		if reasoning is None:
			return None

		if isinstance( reasoning, dict ):
			value = reasoning.get( 'effort' )
			if isinstance( value, str ) and value.strip( ) in self.reasoning_options:
				if value.strip( ) == 'none':
					return None

				return { 'effort': value.strip( ) }

			return None

		if isinstance( reasoning, str ) and reasoning.strip( ):
			value = reasoning.strip( )
			if value == 'none':
				return None

			if value in self.reasoning_options:
				return { 'effort': value }

		return None
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'build_reasoning( self, reasoning )'
		Logger( ).write( exception )
		raise exception

build_input

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

Build input.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
context List[Dict[str, str]]

Context supplied to the xAI workflow.

None
input_data List[Dict[str, Any]]

Input data supplied to the xAI workflow.

None

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

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

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
	    input_data (List[Dict[str, Any]]): Input data supplied to the xAI workflow.

	Returns:
	    List[Dict[str, Any]]: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		self.messages = [ ]

		if input_data is not None and len( input_data ) > 0:
			self.messages.extend( input_data )
		elif context is not None and len( context ) > 0:
			for item in context:
				if not isinstance( item, dict ):
					continue

				role = str( item.get( 'role', '' ) or '' ).strip( )
				content = item.get( 'content', '' )

				if role not in [ 'user', 'assistant', 'system', 'developer' ]:
					continue

				if not isinstance( content, str ) or not content.strip( ):
					continue

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

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

		return self.messages
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'build_input( self, prompt, context, input_data )'
		Logger( ).write( exception )
		raise exception

build_tools

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

Build tools.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Parameters:

Name Type Description Default
tools List[Any]

Tools supplied to the xAI workflow.

None
allowed_domains List[str]

Allowed domains supplied to the xAI workflow.

None
vector_store_ids List[str]

Vector store ids supplied to the xAI workflow.

None

Returns:

Type Description
List[Dict[str, Any]] | None

List[Dict[str, Any]] | None: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

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

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Args:
	    tools (List[Any]): Tools supplied to the xAI workflow.
	    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
	    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.

	Returns:
	    List[Dict[str, Any]] | None: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
		self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]
		if tools is None or len( tools ) == 0:
			return None

		self.built_tools = [ ]
		for tool in tools:
			if isinstance( tool, dict ):
				tool_type = str( tool.get( 'type', '' ) or '' ).strip( )
			else:
				tool_type = str( tool or '' ).strip( )

			if not tool_type:
				continue

			if tool_type == 'web_search':
				built_tool = { 'type': 'web_search' }
				if len( self.allowed_domains ) > 0:
					built_tool[ 'allowed_domains' ] = self.allowed_domains

				self.built_tools.append( built_tool )
				continue

			if tool_type == 'x_search':
				self.built_tools.append( { 'type': 'x_search' } )
				continue

			if tool_type in [ 'collections_search', 'file_search' ]:
				if len( self.vector_store_ids ) == 0:
					continue

				self.built_tools.append(
					{
							'type': 'collections_search',
							'collection_ids': self.vector_store_ids,
					} )
				continue

			if tool_type in [ 'code_execution', 'code_interpreter' ]:
				self.built_tools.append( { 'type': 'code_execution' } )
				continue

		return self.built_tools if len( self.built_tools ) > 0 else None
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'build_tools( self, tools, allowed_domains, vector_store_ids )'
		Logger( ).write( exception )
		raise exception

build_tool_choice

build_tool_choice(
    tool_choice: str = None,
    tools: List[Dict[str, Any]] = None,
) -> str | None

Build tool choice.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Parameters:

Name Type Description Default
tool_choice str

Tool choice supplied to the xAI workflow.

None
tools List[Dict[str, Any]]

Tools supplied to the xAI workflow.

None

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

Source code in grok.py
def build_tool_choice( self, tool_choice: str = None,
		tools: List[ Dict[ str, Any ] ] = None ) -> str | None:
	"""Build tool choice.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Args:
	    tool_choice (str): Tool choice supplied to the xAI workflow.
	    tools (List[Dict[str, Any]]): Tools supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		if not isinstance( tool_choice, str ) or not tool_choice.strip( ):
			return None

		choice = tool_choice.strip( )
		if choice not in self.choice_options:
			return None

		if choice == 'none':
			return 'none'

		if tools is None or len( tools ) == 0:
			return None

		return choice
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'build_tool_choice( self, tool_choice, tools )'
		Logger( ).write( exception )
		raise exception

build_include

build_include(
    include: List[str] = None,
    tools: List[Dict[str, Any]] = None,
) -> List[str] | None

Build include.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Parameters:

Name Type Description Default
include List[str]

Include supplied to the xAI workflow.

None
tools List[Dict[str, Any]]

Tools supplied to the xAI workflow.

None

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

Source code in grok.py
def build_include( self, include: List[ str ] = None,
		tools: List[ Dict[ str, Any ] ] = None ) -> List[ str ] | None:
	"""Build include.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Args:
	    include (List[str]): Include supplied to the xAI workflow.
	    tools (List[Dict[str, Any]]): Tools supplied to the xAI workflow.

	Returns:
	    List[str] | None: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		if include is None or len( include ) == 0:
			return None

		tool_types = [ ]
		if isinstance( tools, list ):
			for tool in tools:
				if isinstance( tool, dict ) and tool.get( 'type' ):
					tool_types.append( str( tool.get( 'type' ) ) )

		allowed = [ ]
		for value in include:
			if not isinstance( value, str ) or not value.strip( ):
				continue

			name = value.strip( )
			if name in [ 'inline_citations', 'verbose_streaming', 'mcp_call_output' ]:
				allowed.append( name )
				continue

			if name == 'web_search_call_output' and 'web_search' in tool_types:
				allowed.append( name )
				continue

			if name == 'x_search_call_output' and 'x_search' in tool_types:
				allowed.append( name )
				continue

			if name == 'code_execution_call_output' and 'code_execution' in tool_types:
				allowed.append( name )
				continue

			if name == 'collections_search_call_output' and 'collections_search' in tool_types:
				allowed.append( name )
				continue

			if name == 'attachment_search_call_output' and 'collections_search' in tool_types:
				allowed.append( name )
				continue

		return allowed if len( allowed ) > 0 else None
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'build_include( self, include, tools )'
		Logger( ).write( exception )
		raise exception

build_text_format

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

Build text format.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Parameters:

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

Format supplied to the xAI workflow.

None
response_schema Any

Response schema supplied to the xAI workflow.

None

Returns:

Type Description
Dict[str, Any] | None

Dict[str, Any] | None: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

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

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Args:
	    format (Dict[str, Any] | str): Format supplied to the xAI workflow.
	    response_schema (Any): Response schema supplied to the xAI workflow.

	Returns:
	    Dict[str, Any] | None: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		if format is None:
			return None

		if isinstance( format, dict ) and len( format ) > 0:
			if 'format' in format and isinstance( format.get( 'format' ), dict ):
				return format

			if 'type' in format:
				return { 'format': format }

			return None

		if isinstance( format, str ) and format.strip( ):
			value = format.strip( )
			if value == 'text':
				return { 'format': { 'type': 'text' } }

			if value == 'json_object':
				return { 'format': { 'type': 'json_object' } }

			if value == 'json_schema' and isinstance( response_schema, dict ):
				return { 'format': { 'type': 'json_schema', 'json_schema': response_schema } }

		return None
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'build_text_format( self, format, response_schema )'
		Logger( ).write( exception )
		raise exception

build_request

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

Build request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

required
temperature float

Temperature supplied to the xAI workflow.

None
format Dict[str, Any]

Format supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
frequency float

Frequency supplied to the xAI workflow.

None
max_tools int

Max tools supplied to the xAI workflow.

None
presence float

Presence supplied to the xAI workflow.

None
max_tokens int

Max tokens supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

None
stream bool

Stream supplied to the xAI workflow.

None
instruct str

Instruct supplied to the xAI workflow.

None
background bool

Background supplied to the xAI workflow.

False
reasoning str

Reasoning supplied to the xAI workflow.

None
include List[str]

Include supplied to the xAI workflow.

None
tools List[Any]

Tools supplied to the xAI workflow.

None
allowed_domains List[str]

Allowed domains supplied to the xAI workflow.

None
previous_id str

Previous id supplied to the xAI workflow.

None
tool_choice str

Tool choice supplied to the xAI workflow.

None
is_parallel bool

Is parallel supplied to the xAI workflow.

None
context List[Dict[str, str]]

Context supplied to the xAI workflow.

None
input_data List[Dict[str, Any]]

Input data supplied to the xAI workflow.

None
vector_store_ids List[str]

Vector store ids supplied to the xAI workflow.

None
conversation_id str

Conversation id supplied to the xAI workflow.

None
response_schema Any

Response schema supplied to the xAI workflow.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

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

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    format (Dict[str, Any]): Format supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    frequency (float): Frequency supplied to the xAI workflow.
	    max_tools (int): Max tools supplied to the xAI workflow.
	    presence (float): Presence supplied to the xAI workflow.
	    max_tokens (int): Max tokens supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    stream (bool): Stream supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    background (bool): Background supplied to the xAI workflow.
	    reasoning (str): Reasoning supplied to the xAI workflow.
	    include (List[str]): Include supplied to the xAI workflow.
	    tools (List[Any]): Tools supplied to the xAI workflow.
	    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
	    previous_id (str): Previous id supplied to the xAI workflow.
	    tool_choice (str): Tool choice supplied to the xAI workflow.
	    is_parallel (bool): Is parallel supplied to the xAI workflow.
	    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
	    input_data (List[Dict[str, Any]]): Input data supplied to the xAI workflow.
	    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.
	    conversation_id (str): Conversation id supplied to the xAI workflow.
	    response_schema (Any): Response schema supplied to the xAI workflow.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.model = model
		self.prompt = prompt
		self.temperature = temperature
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_output_tokens = max_tokens
		self.store_messages = store
		self.stream = stream
		self.background = background
		self.instructions = instruct
		self.response_format = self.build_text_format( format, response_schema=response_schema )
		self.max_tools = max_tools
		self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]
		self.previous_id = previous_id if isinstance( previous_id, str ) else None
		self.previous_response_id = self.previous_id
		self.conversation_id = conversation_id if isinstance( conversation_id, str ) else None
		self.parallel_tools = is_parallel
		self.reasoning = self.build_reasoning( reasoning )
		self.tools = self.build_tools( tools=tools, allowed_domains=allowed_domains,
			vector_store_ids=self.vector_store_ids )
		self.tool_choice = self.build_tool_choice( tool_choice=tool_choice, tools=self.tools )
		self.include = self.build_include( include=include, tools=self.tools )
		self.input = self.build_input( prompt=prompt, context=context, input_data=input_data )
		self.request = {
				'model': self.model,
				'input': self.input,
		}

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

		if self.reasoning is not None and self.model == 'grok-4.20-multi-agent':
			self.request[ 'reasoning' ] = self.reasoning

		if isinstance( self.max_output_tokens, int ) and self.max_output_tokens > 0:
			self.request[ 'max_output_tokens' ] = self.max_output_tokens

		if self.temperature is not None:
			self.request[ 'temperature' ] = self.temperature

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

		if self.frequency_penalty is not None:
			self.request[ 'frequency_penalty' ] = self.frequency_penalty

		if self.presence_penalty is not None:
			self.request[ 'presence_penalty' ] = self.presence_penalty

		if self.store_messages is not None:
			self.request[ 'store' ] = self.store_messages

		# Stream and background are retained on self for layout/UI parity. This path returns final text.
		if self.include is not None and len( self.include ) > 0:
			self.request[ 'include' ] = self.include

		if self.tools is not None and len( self.tools ) > 0:
			self.request[ 'tools' ] = self.tools

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

		if self.parallel_tools is not None and self.tools is not None:
			self.request[ 'parallel_tool_calls' ] = self.parallel_tools

		if self.previous_id and self.previous_id.strip( ):
			self.request[ 'previous_response_id' ] = self.previous_id.strip( )

		if self.conversation_id and self.conversation_id.strip( ):
			self.request[ 'conversation' ] = self.conversation_id.strip( )

		if isinstance( self.max_tools, int ) and self.max_tools > 0 and self.tools is not None:
			self.request[ 'max_tool_calls' ] = self.max_tools

		if self.response_format is not None and len( self.response_format ) > 0:
			self.request[ 'text' ] = self.response_format

		return self.request
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'build_request( self, **kwargs )'
		Logger( ).write( exception )
		raise exception

get_output_text

get_output_text() -> str | None

Get output text.

Purpose

Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

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

	Purpose:
	    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

	Returns:
	    str | None: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		if self.response is None:
			return None

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

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

				if not hasattr( item, 'content' ) or item.content is None:
					continue

				for block in item.content:
					if getattr( block, 'type', None ) == 'output_text':
						text = getattr( block, 'text', None )
						if text:
							text_parts.append( text )

			if len( text_parts ) > 0:
				self.output_text = ''.join( text_parts ).strip( )
				return self.output_text

		return None
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'get_output_text( self ) -> str | None'
		Logger( ).write( exception )
		raise exception

get_usage

get_usage() -> Any

Get usage.

Purpose

Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

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

	Purpose:
	    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

	Returns:
	    Any: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		if self.response is None:
			return None

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

generate_text

generate_text(
    prompt: str,
    model: str,
    temperature: float = None,
    format: Dict[str, Any] = None,
    top_p: float = None,
    top_k: int = None,
    frequency: float = None,
    max_tools: int = None,
    presence: float = None,
    max_tokens: int = None,
    store: bool = None,
    stream: bool = None,
    instruct: str = None,
    background: bool = False,
    reasoning: str = None,
    include: List[str] = None,
    tools: List[Any] = None,
    allowed_domains: List[str] = None,
    previous_id: str = None,
    tool_choice: str = None,
    is_parallel: bool = None,
    context: List[Dict[str, str]] = None,
    input_data: List[Dict[str, Any]] = None,
    vector_store_ids: List[str] = None,
    conversation_id: str = None,
    response_format: Dict[str, Any] | str = None,
    response_schema: Any = None,
    number: int = None,
    modalities: List[str] = None,
    media_resolution: str = None,
    content: str = None,
    urls: List[str] = None,
    max_urls: int = None,
    safety_profile: str = None,
    **kwargs: Any
) -> str | None

Generate text.

Purpose

Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

required
temperature float

Temperature supplied to the xAI workflow.

None
format Dict[str, Any]

Format supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
top_k int

Top k supplied to the xAI workflow.

None
frequency float

Frequency supplied to the xAI workflow.

None
max_tools int

Max tools supplied to the xAI workflow.

None
presence float

Presence supplied to the xAI workflow.

None
max_tokens int

Max tokens supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

None
stream bool

Stream supplied to the xAI workflow.

None
instruct str

Instruct supplied to the xAI workflow.

None
background bool

Background supplied to the xAI workflow.

False
reasoning str

Reasoning supplied to the xAI workflow.

None
include List[str]

Include supplied to the xAI workflow.

None
tools List[Any]

Tools supplied to the xAI workflow.

None
allowed_domains List[str]

Allowed domains supplied to the xAI workflow.

None
previous_id str

Previous id supplied to the xAI workflow.

None
tool_choice str

Tool choice supplied to the xAI workflow.

None
is_parallel bool

Is parallel supplied to the xAI workflow.

None
context List[Dict[str, str]]

Context supplied to the xAI workflow.

None
input_data List[Dict[str, Any]]

Input data supplied to the xAI workflow.

None
vector_store_ids List[str]

Vector store ids supplied to the xAI workflow.

None
conversation_id str

Conversation id supplied to the xAI workflow.

None
response_format Dict[str, Any] | str

Response format supplied to the xAI workflow.

None
response_schema Any

Response schema supplied to the xAI workflow.

None
number int

Number supplied to the xAI workflow.

None
modalities List[str]

Modalities supplied to the xAI workflow.

None
media_resolution str

Media resolution supplied to the xAI workflow.

None
content str

Content supplied to the xAI workflow.

None
urls List[str]

Urls supplied to the xAI workflow.

None
max_urls int

Max urls supplied to the xAI workflow.

None
safety_profile str

Safety profile supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

Source code in grok.py
def generate_text( self, prompt: str, model: str, temperature: float = None,
		format: Dict[ str, Any ] = None, top_p: float = None, top_k: int = None,
		frequency: float = None, max_tools: int = None, presence: float = None,
		max_tokens: int = None, store: bool = None, stream: bool = None,
		instruct: str = None, background: bool = False, reasoning: str = None,
		include: List[ str ] = None, tools: List[ Any ] = None,
		allowed_domains: List[ str ] = None, previous_id: str = None,
		tool_choice: str = None, is_parallel: bool = None,
		context: List[ Dict[ str, str ] ] = None, input_data: List[ Dict[ str, Any ] ] = None,
		vector_store_ids: List[ str ] = None, conversation_id: str = None,
		response_format: Dict[ str, Any ] | str = None, response_schema: Any = None,
		number: int = None, modalities: List[ str ] = None, media_resolution: str = None,
		content: str = None, urls: List[ str ] = None, max_urls: int = None,
		safety_profile: str = None, **kwargs: Any ) -> str | None:
	"""Generate text.

	Purpose:
	    Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    format (Dict[str, Any]): Format supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    top_k (int): Top k supplied to the xAI workflow.
	    frequency (float): Frequency supplied to the xAI workflow.
	    max_tools (int): Max tools supplied to the xAI workflow.
	    presence (float): Presence supplied to the xAI workflow.
	    max_tokens (int): Max tokens supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    stream (bool): Stream supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    background (bool): Background supplied to the xAI workflow.
	    reasoning (str): Reasoning supplied to the xAI workflow.
	    include (List[str]): Include supplied to the xAI workflow.
	    tools (List[Any]): Tools supplied to the xAI workflow.
	    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
	    previous_id (str): Previous id supplied to the xAI workflow.
	    tool_choice (str): Tool choice supplied to the xAI workflow.
	    is_parallel (bool): Is parallel supplied to the xAI workflow.
	    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
	    input_data (List[Dict[str, Any]]): Input data supplied to the xAI workflow.
	    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.
	    conversation_id (str): Conversation id supplied to the xAI workflow.
	    response_format (Dict[str, Any] | str): Response format supplied to the xAI workflow.
	    response_schema (Any): Response schema supplied to the xAI workflow.
	    number (int): Number supplied to the xAI workflow.
	    modalities (List[str]): Modalities supplied to the xAI workflow.
	    media_resolution (str): Media resolution supplied to the xAI workflow.
	    content (str): Content supplied to the xAI workflow.
	    urls (List[str]): Urls supplied to the xAI workflow.
	    max_urls (int): Max urls supplied to the xAI workflow.
	    safety_profile (str): Safety profile supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.client = OpenAI( api_key=cfg.XAI_API_KEY, base_url=self.base_url )
		self.number = number
		self.top_k = top_k
		self.modalities = modalities if modalities is not None else [ ]
		self.media_resolution = media_resolution
		self.content = content
		self.urls = urls if urls is not None else [ ]
		self.max_urls = max_urls
		self.safety_profile = safety_profile
		self.extra_kwargs = kwargs or { }
		self.stream_requested = bool( stream )
		self.background_requested = bool( background )
		self.request = self.build_request( prompt=prompt, model=model,
			temperature=temperature, format=response_format or format, top_p=top_p,
			frequency=frequency, max_tools=max_tools, presence=presence,
			max_tokens=max_tokens, store=store, stream=False, instruct=instruct,
			background=False, reasoning=reasoning, include=include, tools=tools,
			allowed_domains=allowed_domains, previous_id=previous_id,
			tool_choice=tool_choice, is_parallel=is_parallel, context=context,
			input_data=input_data, vector_store_ids=vector_store_ids,
			conversation_id=conversation_id, response_schema=response_schema )
		self.response = self.client.responses.create( **self.request )
		self.previous_id = getattr( self.response, 'id', None )
		self.previous_response_id = self.previous_id
		self.output_text = self.get_output_text( )
		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'generate_text( self, prompt: str ) -> str | None'
		Logger( ).write( exception )
		raise exception

get_grounding_sources

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

Get grounding sources.

Purpose

Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

Source code in grok.py
def get_grounding_sources( self ) -> List[ Dict[ str, Any ] ]:
	"""Get grounding sources.

	Purpose:
	    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

	Returns:
	    List[Dict[str, Any]]: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		if self.response is None:
			return [ ]

		self.sources = [ ]
		output = getattr( self.response, 'output', None )
		if isinstance( output, list ):
			for item in output:
				item_type = getattr( item, 'type', None )

				if item_type in [ 'web_search_call', 'x_search_call' ]:
					action = getattr( item, 'action', None )
					raw_sources = getattr( action, 'sources', None ) if action else None
					if isinstance( raw_sources, list ):
						for source in raw_sources:
							self.sources.append(
								{
										'title': getattr( source, 'title', None ),
										'url': getattr( source, 'url', None ),
										'snippet': getattr( source, 'snippet', None ),
										'file_id': None,
								} )

				if item_type in [ 'collections_search_call', 'file_search_call' ]:
					results = getattr( item, 'results', None )
					if isinstance( results, list ):
						for result in results:
							self.sources.append(
								{
										'title': getattr( result, 'file_name',
											None ) or getattr(
											result, 'title', None ),
										'url': None,
										'snippet': getattr( result, 'text', None ),
										'file_id': getattr( result, 'file_id', None ),
								} )

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

answer_document

answer_document(
    prompt: str,
    document_text: str,
    model: str,
    instructions: str = None,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    store: bool = None,
    include: List[str] = None,
    tools: List[str] = None,
    tool_choice: str = None,
    reasoning: str = None,
    context: List[Dict[str, str]] = None,
    vector_store_ids: List[str] = None,
) -> str | None

Answer document.

Purpose

Provides answer document behavior for the Chat workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
document_text str

Document text supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

required
instructions str

Instructions supplied to the xAI workflow.

None
temperature float

Temperature supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
frequency float

Frequency supplied to the xAI workflow.

None
presence float

Presence supplied to the xAI workflow.

None
max_tokens int

Max tokens supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

None
include List[str]

Include supplied to the xAI workflow.

None
tools List[str]

Tools supplied to the xAI workflow.

None
tool_choice str

Tool choice supplied to the xAI workflow.

None
reasoning str

Reasoning supplied to the xAI workflow.

None
context List[Dict[str, str]]

Context supplied to the xAI workflow.

None
vector_store_ids List[str]

Vector store ids supplied to the xAI workflow.

None

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Raises:

Type Description
Error

Re-raised after validation or provider execution errors are wrapped and logged.

Source code in grok.py
def answer_document( self, prompt: str, document_text: str, model: str,
		instructions: str = None, temperature: float = None, top_p: float = None,
		frequency: float = None, presence: float = None, max_tokens: int = None,
		store: bool = None, include: List[ str ] = None, tools: List[ str ] = None,
		tool_choice: str = None, reasoning: str = None,
		context: List[ Dict[ str, str ] ] = None,
		vector_store_ids: List[ str ] = None ) -> str | None:
	"""Answer document.

	Purpose:
	    Provides answer document behavior for the Chat workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    document_text (str): Document text supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    instructions (str): Instructions supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    frequency (float): Frequency supplied to the xAI workflow.
	    presence (float): Presence supplied to the xAI workflow.
	    max_tokens (int): Max tokens supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    include (List[str]): Include supplied to the xAI workflow.
	    tools (List[str]): Tools supplied to the xAI workflow.
	    tool_choice (str): Tool choice supplied to the xAI workflow.
	    reasoning (str): Reasoning supplied to the xAI workflow.
	    context (List[Dict[str, str]]): Context supplied to the xAI workflow.
	    vector_store_ids (List[str]): Vector store ids supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.

	Raises:
	    Error: Re-raised after validation or provider execution errors are wrapped and logged.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'document_text', document_text )
		throw_if( 'model', model )

		self.prompt = prompt
		self.content = document_text
		self.model = model
		self.instructions = instructions
		self.temperature = temperature
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_output_tokens = max_tokens
		self.store_messages = store
		self.include = include if include is not None else [ ]
		self.tool_choice = tool_choice
		self.reasoning = reasoning
		self.context = context if context is not None else [ ]
		self.vector_store_ids = vector_store_ids if vector_store_ids is not None else [ ]

		selected_tools = [ ]
		if tools is not None:
			for item in tools:
				if isinstance( item, dict ):
					selected_tools.append( item )
					continue

				if isinstance( item, str ) and item.strip( ):
					selected_tools.append( { 'type': item.strip( ) } )

		self.tools = selected_tools

		if isinstance( self.tool_choice, list ):
			self.tool_choice = self.tool_choice[ 0 ] if len( self.tool_choice ) > 0 else None

		document_prompt = (
				f'Document Context:\n'
				f'{self.content}\n\n'
				f'User Question:\n'
				f'{self.prompt}'
		)

		self.output_text = self.generate_text(
			prompt=document_prompt,
			model=self.model,
			temperature=self.temperature,
			top_p=self.top_percent,
			frequency=self.frequency_penalty,
			presence=self.presence_penalty,
			max_tokens=self.max_output_tokens,
			store=self.store_messages,
			stream=False,
			instruct=self.instructions,
			reasoning=self.reasoning,
			include=self.include,
			tools=self.tools,
			tool_choice=self.tool_choice,
			context=self.context,
			vector_store_ids=self.vector_store_ids )

		return self.output_text
	except Exception as e:
		exception = Error( e )
		exception.module = 'grok'
		exception.cause = 'Chat'
		exception.method = 'answer_document( self, prompt: str, document_text: str, model: str ) -> str | None'
		Logger( ).write( exception )
		raise exception

TTS

Bases: Grok

TTS workflow wrapper.

Purpose

Builds text-to-speech request state for audio generation workflows exposed by the application.

Attributes:

Name Type Description
client Optional[Any]

Runtime attribute used by the TTS workflow.

model Optional[str]

Runtime attribute used by the TTS workflow.

input_text Optional[str]

Runtime attribute used by the TTS workflow.

voice Optional[str]

Runtime attribute used by the TTS workflow.

language Optional[str]

Runtime attribute used by the TTS workflow.

response_format Optional[str]

Runtime attribute used by the TTS workflow.

sample_rate Optional[int]

Runtime attribute used by the TTS workflow.

bit_rate Optional[int]

Runtime attribute used by the TTS workflow.

speed Optional[float]

Runtime attribute used by the TTS workflow.

audio_path Optional[str]

Runtime attribute used by the TTS workflow.

audio_bytes Optional[bytes]

Runtime attribute used by the TTS workflow.

request Optional[Dict[str, Any]]

Runtime attribute used by the TTS workflow.

response Optional[Any]

Runtime attribute used by the TTS workflow.

Source code in grok.py
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
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
class TTS( Grok ):
	"""TTS workflow wrapper.

	Purpose:
	    Builds text-to-speech request state for audio generation workflows exposed by the application.

	Attributes:
	    client: Runtime attribute used by the TTS workflow.
	    model: Runtime attribute used by the TTS workflow.
	    input_text: Runtime attribute used by the TTS workflow.
	    voice: Runtime attribute used by the TTS workflow.
	    language: Runtime attribute used by the TTS workflow.
	    response_format: Runtime attribute used by the TTS workflow.
	    sample_rate: Runtime attribute used by the TTS workflow.
	    bit_rate: Runtime attribute used by the TTS workflow.
	    speed: Runtime attribute used by the TTS workflow.
	    audio_path: Runtime attribute used by the TTS workflow.
	    audio_bytes: Runtime attribute used by the TTS workflow.
	    request: Runtime attribute used by the TTS workflow.
	    response: Runtime attribute used by the TTS workflow.
	"""
	client: Optional[ Any ]
	model: Optional[ str ]
	input_text: Optional[ str ]
	voice: Optional[ str ]
	language: Optional[ str ]
	response_format: Optional[ str ]
	sample_rate: Optional[ int ]
	bit_rate: Optional[ int ]
	speed: Optional[ float ]
	audio_path: Optional[ str ]
	audio_bytes: Optional[ bytes ]
	request: Optional[ Dict[ str, Any ] ]
	response: Optional[ Any ]

	def __init__( self, model: str = 'xai-tts' ):
		"""Initialize instance.

		Purpose:
		    Initializes TTS state with default configuration values and runtime attributes used by later xAI provider calls.

		Args:
		    model (str): Model supplied to the xAI workflow.
		"""
		super( ).__init__( )
		self.api_key = cfg.XAI_API_KEY
		self.base_url = cfg.XAI_BASE_URL
		self.client = None
		self.model = model
		self.number = None
		self.input_text = None
		self.prompt = None
		self.language = 'auto'
		self.voice = 'eve'
		self.response_format = 'mp3'
		self.sample_rate = None
		self.bit_rate = None
		self.speed = 1.0
		self.instructions = None
		self.temperature = None
		self.top_percent = None
		self.frequency_penalty = None
		self.presence_penalty = None
		self.max_completion_tokens = None
		self.store = None
		self.stream = None
		self.audio_path = None
		self.file_path = None
		self.request = { }
		self.response = None
		self.audio_bytes = None
		self.output_format = None
		self.optimize_streaming_latency = None
		self.text_normalization = None
		self.extra_kwargs = { }

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

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'xai-tts',
		]

	@property
	def voice_options( self ) -> List[ str ] | None:
		"""Voice options.

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'eve',
				'ara',
				'rex',
				'sal',
				'leo',
		]

	@property
	def language_options( self ) -> List[ str ] | None:
		"""Language options.

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'auto',
				'en',
				'ar-EG',
				'ar-SA',
				'ar-AE',
				'bn',
				'zh',
				'fr',
				'de',
				'hi',
				'id',
				'it',
				'ja',
				'ko',
				'pt-BR',
				'pt-PT',
				'ru',
				'es-MX',
				'es-ES',
				'tr',
				'vi',
		]

	@property
	def format_options( self ) -> List[ str ] | None:
		"""Format options.

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'mp3',
				'wav',
				'pcm',
				'mulaw',
				'alaw',
		]

	@property
	def response_format_options( self ) -> List[ str ] | None:
		"""Response format options.

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return self.format_options

	@property
	def output_format_options( self ) -> List[ str ] | None:
		"""Output format options.

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return self.format_options

	@property
	def speed_options( self ) -> List[ float ] | None:
		"""Speed options.

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[float] | None: Result produced by the xAI workflow.
		"""
		return [
				0.25,
				0.50,
				0.75,
				1.00,
				1.25,
				1.50,
				2.00,
				3.00,
				4.00,
		]

	@property
	def sample_rate_options( self ) -> List[ int ] | None:
		"""Sample rate options.

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[int] | None: Result produced by the xAI workflow.
		"""
		return [
				8000,
				16000,
				22050,
				24000,
				44100,
				48000,
		]

	@property
	def bit_rate_options( self ) -> List[ int ] | None:
		"""Bit rate options.

		Purpose:
		    Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

		Returns:
		    List[int] | None: Result produced by the xAI workflow.
		"""
		return [
				32000,
				64000,
				96000,
				128000,
				192000,
		]

	def validate_voice( self, voice: str = None ) -> str:
		"""Validate voice.

		Purpose:
		    Provides validate voice behavior for the TTS workflow while preserving provider request and response state.

		Args:
		    voice (str): Voice supplied to the xAI workflow.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			value = str( voice or 'eve' ).strip( ).lower( )
			if value not in self.voice_options:
				return 'eve'

			return value
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'validate_voice( self, voice: str=None ) -> str'
			raise ex

	def validate_language( self, language: str = None ) -> str:
		"""Validate language.

		Purpose:
		    Provides validate language behavior for the TTS workflow while preserving provider request and response state.

		Args:
		    language (str): Language supplied to the xAI workflow.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			value = str( language or 'auto' ).strip( )
			valid_values = self.language_options

			if value not in valid_values:
				return 'auto'

			return value
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'validate_language( self, language: str=None ) -> str'
			raise ex

	def validate_format( self, format: str = None ) -> str:
		"""Validate format.

		Purpose:
		    Provides validate format behavior for the TTS workflow while preserving provider request and response state.

		Args:
		    format (str): Format supplied to the xAI workflow.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			value = str( format or 'mp3' ).strip( ).lower( )

			if value == 'mu-law':
				value = 'mulaw'

			if value == 'a-law':
				value = 'alaw'

			if value not in self.format_options:
				return 'mp3'

			return value
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'validate_format( self, format: str=None ) -> str'
			raise ex

	def validate_sample_rate( self, sample_rate: int = None ) -> int | None:
		"""Validate sample rate.

		Purpose:
		    Provides validate sample rate behavior for the TTS workflow while preserving provider request and response state.

		Args:
		    sample_rate (int): Sample rate supplied to the xAI workflow.

		Returns:
		    int | None: Result produced by the xAI workflow.
		"""
		try:
			if sample_rate is None:
				return None

			value = int( sample_rate )
			if value not in self.sample_rate_options:
				return None

			return value
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'validate_sample_rate( self, sample_rate: int=None ) -> int | None'
			raise ex

	def validate_bit_rate( self, bit_rate: int = None ) -> int | None:
		"""Validate bit rate.

		Purpose:
		    Provides validate bit rate behavior for the TTS workflow while preserving provider request and response state.

		Args:
		    bit_rate (int): Bit rate supplied to the xAI workflow.

		Returns:
		    int | None: Result produced by the xAI workflow.
		"""
		try:
			if bit_rate is None:
				return None

			value = int( bit_rate )
			if value not in self.bit_rate_options:
				return None

			return value
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'validate_bit_rate( self, bit_rate: int=None ) -> int | None'
			raise ex

	def validate_speed( self, speed: float = None ) -> float:
		"""Validate speed.

		Purpose:
		    Provides validate speed behavior for the TTS workflow while preserving provider request and response state.

		Args:
		    speed (float): Speed supplied to the xAI workflow.

		Returns:
		    float: Result produced by the xAI workflow.
		"""
		try:
			value = 1.0 if speed is None else float( speed )

			if value < 0.25:
				return 0.25

			if value > 4.0:
				return 4.0

			return value
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'validate_speed( self, speed: float=None ) -> float'
			raise ex

	def build_output_format( self ) -> Dict[ str, Any ] | None:
		"""Build output format.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any] | None: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'response_format', self.response_format )
			self.output_format = { 'codec': self.response_format, }

			if self.sample_rate is not None:
				self.output_format[ 'sample_rate' ] = self.sample_rate

			if self.response_format == 'mp3' and self.bit_rate is not None:
				self.output_format[ 'bit_rate' ] = self.bit_rate

			return self.output_format
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'build_output_format( self ) -> Dict[ str, Any ] | None'
			raise ex

	def build_request( self ) -> Dict[ str, Any ]:
		"""Build request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'input_text', self.input_text )
			throw_if( 'voice', self.voice )
			throw_if( 'language', self.language )
			self.request = {
					'text': self.input_text,
					'voice_id': self.voice,
					'language': self.language,
			}
			self.output_format = self.build_output_format( )

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

			if self.optimize_streaming_latency is not None:
				self.request[ 'optimize_streaming_latency' ] = self.optimize_streaming_latency

			if self.text_normalization is not None:
				self.request[ 'text_normalization' ] = self.text_normalization

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'build_request( self ) -> Dict[ str, Any ]'
			raise ex

	def execute_request( self ) -> Any:
		"""Execute request.

		Purpose:
		    Provides execute request behavior for the TTS workflow while preserving provider request and response state.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'api_key', self.api_key )
			throw_if( 'base_url', self.base_url )
			throw_if( 'request', self.request )
			self.response = requests.post(
				url=f'{self.base_url.rstrip( "/" )}/tts',
				headers={ 'Authorization': f'Bearer {self.api_key}',
				          'Content-Type': 'application/json', },
				json=self.request, timeout=self.timeout or 3600, )
			self.response.raise_for_status( )
			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'execute_request( self ) -> Any'
			raise ex

	def extract_audio( self ) -> bytes | None:
		"""Extract audio.

		Purpose:
		    Provides extract audio behavior for the TTS workflow while preserving provider request and response state.

		Returns:
		    Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.
		"""
		try:
			if self.response is None:
				return None

			self.audio_bytes = self.response.content
			if not self.audio_bytes:
				return None

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

			return self.audio_bytes
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'extract_audio( self ) -> bytes | None'
			raise ex

	def create_speech( self, text: str, model: str = 'xai-tts', format: str = 'mp3',
			speed: float = 1.0, voice: str = 'eve', instruct: str = None, file_path: str = None,
			language: str = 'auto', sample_rate: int = None, bit_rate: int = None,
			optimize_streaming_latency: int = None, text_normalization: bool = None,
			**kwargs: Any ) -> bytes | None:
		"""Create speech.

		Purpose:
		    Creates the requested xAI resource using validated names, paths, or configuration values.

		Args:
		    text (str): Text supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    format (str): Format supplied to the xAI workflow.
		    speed (float): Speed supplied to the xAI workflow.
		    voice (str): Voice supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    file_path (str): File path supplied to the xAI workflow.
		    language (str): Language supplied to the xAI workflow.
		    sample_rate (int): Sample rate supplied to the xAI workflow.
		    bit_rate (int): Bit rate supplied to the xAI workflow.
		    optimize_streaming_latency (int): Optimize streaming latency supplied to the xAI workflow.
		    text_normalization (bool): Text normalization supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.
		"""
		try:
			throw_if( 'text', text )
			self.input_text = text
			self.prompt = text
			self.model = model or 'xai-tts'
			self.response_format = self.validate_format( format )
			self.speed = self.validate_speed( speed )
			self.voice = self.validate_voice( voice )
			self.language = self.validate_language( language )
			self.instructions = instruct
			self.audio_path = file_path
			self.file_path = file_path
			self.sample_rate = self.validate_sample_rate( sample_rate )
			self.bit_rate = self.validate_bit_rate( bit_rate )
			self.optimize_streaming_latency = optimize_streaming_latency
			self.text_normalization = text_normalization
			self.extra_kwargs = kwargs or { }
			self.build_request( )
			self.execute_request( )
			return self.extract_audio( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'create_speech( self, text: str ) -> bytes | None'
			raise ex

	def synthesize( self, text: str, model: str = 'xai-tts', format: str = 'mp3',
			speed: float = 1.0, voice: str = 'eve', instruct: str = None, file_path: str = None,
			language: str = 'auto', **kwargs: Any ) -> bytes | None:
		"""Synthesize.

		Purpose:
		    Provides synthesize behavior for the TTS workflow while preserving provider request and response state.

		Args:
		    text (str): Text supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    format (str): Format supplied to the xAI workflow.
		    speed (float): Speed supplied to the xAI workflow.
		    voice (str): Voice supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    file_path (str): File path supplied to the xAI workflow.
		    language (str): Language supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.
		"""
		try:
			return self.create_speech( text=text, model=model, format=format, speed=speed,
				voice=voice, instruct=instruct, file_path=file_path, language=language,
				**kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'synthesize( self, text: str ) -> bytes | None'
			raise ex

	def generate( self, text: str = None, prompt: str = None, model: str = 'xai-tts',
			format: str = 'mp3', speed: float = 1.0, voice: str = 'eve', instruct: str = None,
			file_path: str = None, language: str = 'auto', **kwargs: Any ) -> bytes | None:
		"""Generate.

		Purpose:
		    Provides generate behavior for the TTS workflow while preserving provider request and response state.

		Args:
		    text (str): Text supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    format (str): Format supplied to the xAI workflow.
		    speed (float): Speed supplied to the xAI workflow.
		    voice (str): Voice supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    file_path (str): File path supplied to the xAI workflow.
		    language (str): Language supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.
		"""
		try:
			input_text = text or prompt
			throw_if( 'text', input_text )
			return self.create_speech( text=input_text, model=model, format=format, speed=speed,
				voice=voice, instruct=instruct, file_path=file_path, language=language,
				**kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'TTS'
			ex.method = 'generate( self, text: str ) -> bytes | None'
			raise ex

	def __dir__( self ) -> List[ str ] | None:
		"""Dir.

		Purpose:
		    Provides dir behavior for the TTS workflow while preserving provider request and response state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'api_key',
				'base_url',
				'client',
				'model',
				'number',
				'input_text',
				'prompt',
				'language',
				'voice',
				'response_format',
				'sample_rate',
				'bit_rate',
				'speed',
				'instructions',
				'temperature',
				'top_percent',
				'frequency_penalty',
				'presence_penalty',
				'max_completion_tokens',
				'store',
				'stream',
				'audio_path',
				'file_path',
				'request',
				'response',
				'audio_bytes',
				'output_format',
				'optimize_streaming_latency',
				'text_normalization',
				'extra_kwargs',
				'model_options',
				'voice_options',
				'language_options',
				'format_options',
				'response_format_options',
				'output_format_options',
				'speed_options',
				'sample_rate_options',
				'bit_rate_options',
				'validate_voice',
				'validate_language',
				'validate_format',
				'validate_sample_rate',
				'validate_bit_rate',
				'validate_speed',
				'build_output_format',
				'build_request',
				'execute_request',
				'extract_audio',
				'create_speech',
				'synthesize',
				'generate',
		]

model_options property

model_options: List[str]

Model options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

voice_options property

voice_options: List[str] | None

Voice options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

language_options property

language_options: List[str] | None

Language options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

format_options property

format_options: List[str] | None

Format options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

response_format_options property

response_format_options: List[str] | None

Response format options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

output_format_options property

output_format_options: List[str] | None

Output format options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

speed_options property

speed_options: List[float] | None

Speed options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[float] | None

List[float] | None: Result produced by the xAI workflow.

sample_rate_options property

sample_rate_options: List[int] | None

Sample rate options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[int] | None

List[int] | None: Result produced by the xAI workflow.

bit_rate_options property

bit_rate_options: List[int] | None

Bit rate options.

Purpose

Returns the configured option values exposed by the TTS workflow selector without mutating provider state.

Returns:

Type Description
List[int] | None

List[int] | None: Result produced by the xAI workflow.

validate_voice

validate_voice(voice: str = None) -> str

Validate voice.

Purpose

Provides validate voice behavior for the TTS workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
voice str

Voice supplied to the xAI workflow.

None

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def validate_voice( self, voice: str = None ) -> str:
	"""Validate voice.

	Purpose:
	    Provides validate voice behavior for the TTS workflow while preserving provider request and response state.

	Args:
	    voice (str): Voice supplied to the xAI workflow.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		value = str( voice or 'eve' ).strip( ).lower( )
		if value not in self.voice_options:
			return 'eve'

		return value
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'validate_voice( self, voice: str=None ) -> str'
		raise ex

validate_language

validate_language(language: str = None) -> str

Validate language.

Purpose

Provides validate language behavior for the TTS workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
language str

Language supplied to the xAI workflow.

None

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def validate_language( self, language: str = None ) -> str:
	"""Validate language.

	Purpose:
	    Provides validate language behavior for the TTS workflow while preserving provider request and response state.

	Args:
	    language (str): Language supplied to the xAI workflow.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		value = str( language or 'auto' ).strip( )
		valid_values = self.language_options

		if value not in valid_values:
			return 'auto'

		return value
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'validate_language( self, language: str=None ) -> str'
		raise ex

validate_format

validate_format(format: str = None) -> str

Validate format.

Purpose

Provides validate format behavior for the TTS workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
format str

Format supplied to the xAI workflow.

None

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def validate_format( self, format: str = None ) -> str:
	"""Validate format.

	Purpose:
	    Provides validate format behavior for the TTS workflow while preserving provider request and response state.

	Args:
	    format (str): Format supplied to the xAI workflow.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		value = str( format or 'mp3' ).strip( ).lower( )

		if value == 'mu-law':
			value = 'mulaw'

		if value == 'a-law':
			value = 'alaw'

		if value not in self.format_options:
			return 'mp3'

		return value
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'validate_format( self, format: str=None ) -> str'
		raise ex

validate_sample_rate

validate_sample_rate(sample_rate: int = None) -> int | None

Validate sample rate.

Purpose

Provides validate sample rate behavior for the TTS workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
sample_rate int

Sample rate supplied to the xAI workflow.

None

Returns:

Type Description
int | None

int | None: Result produced by the xAI workflow.

Source code in grok.py
def validate_sample_rate( self, sample_rate: int = None ) -> int | None:
	"""Validate sample rate.

	Purpose:
	    Provides validate sample rate behavior for the TTS workflow while preserving provider request and response state.

	Args:
	    sample_rate (int): Sample rate supplied to the xAI workflow.

	Returns:
	    int | None: Result produced by the xAI workflow.
	"""
	try:
		if sample_rate is None:
			return None

		value = int( sample_rate )
		if value not in self.sample_rate_options:
			return None

		return value
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'validate_sample_rate( self, sample_rate: int=None ) -> int | None'
		raise ex

validate_bit_rate

validate_bit_rate(bit_rate: int = None) -> int | None

Validate bit rate.

Purpose

Provides validate bit rate behavior for the TTS workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
bit_rate int

Bit rate supplied to the xAI workflow.

None

Returns:

Type Description
int | None

int | None: Result produced by the xAI workflow.

Source code in grok.py
def validate_bit_rate( self, bit_rate: int = None ) -> int | None:
	"""Validate bit rate.

	Purpose:
	    Provides validate bit rate behavior for the TTS workflow while preserving provider request and response state.

	Args:
	    bit_rate (int): Bit rate supplied to the xAI workflow.

	Returns:
	    int | None: Result produced by the xAI workflow.
	"""
	try:
		if bit_rate is None:
			return None

		value = int( bit_rate )
		if value not in self.bit_rate_options:
			return None

		return value
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'validate_bit_rate( self, bit_rate: int=None ) -> int | None'
		raise ex

validate_speed

validate_speed(speed: float = None) -> float

Validate speed.

Purpose

Provides validate speed behavior for the TTS workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
speed float

Speed supplied to the xAI workflow.

None

Returns:

Name Type Description
float float

Result produced by the xAI workflow.

Source code in grok.py
def validate_speed( self, speed: float = None ) -> float:
	"""Validate speed.

	Purpose:
	    Provides validate speed behavior for the TTS workflow while preserving provider request and response state.

	Args:
	    speed (float): Speed supplied to the xAI workflow.

	Returns:
	    float: Result produced by the xAI workflow.
	"""
	try:
		value = 1.0 if speed is None else float( speed )

		if value < 0.25:
			return 0.25

		if value > 4.0:
			return 4.0

		return value
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'validate_speed( self, speed: float=None ) -> float'
		raise ex

build_output_format

build_output_format() -> Dict[str, Any] | None

Build output format.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any] | None

Dict[str, Any] | None: Result produced by the xAI workflow.

Source code in grok.py
def build_output_format( self ) -> Dict[ str, Any ] | None:
	"""Build output format.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any] | None: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'response_format', self.response_format )
		self.output_format = { 'codec': self.response_format, }

		if self.sample_rate is not None:
			self.output_format[ 'sample_rate' ] = self.sample_rate

		if self.response_format == 'mp3' and self.bit_rate is not None:
			self.output_format[ 'bit_rate' ] = self.bit_rate

		return self.output_format
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'build_output_format( self ) -> Dict[ str, Any ] | None'
		raise ex

build_request

build_request() -> Dict[str, Any]

Build request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_request( self ) -> Dict[ str, Any ]:
	"""Build request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'input_text', self.input_text )
		throw_if( 'voice', self.voice )
		throw_if( 'language', self.language )
		self.request = {
				'text': self.input_text,
				'voice_id': self.voice,
				'language': self.language,
		}
		self.output_format = self.build_output_format( )

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

		if self.optimize_streaming_latency is not None:
			self.request[ 'optimize_streaming_latency' ] = self.optimize_streaming_latency

		if self.text_normalization is not None:
			self.request[ 'text_normalization' ] = self.text_normalization

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'build_request( self ) -> Dict[ str, Any ]'
		raise ex

execute_request

execute_request() -> Any

Execute request.

Purpose

Provides execute request behavior for the TTS workflow while preserving provider request and response state.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def execute_request( self ) -> Any:
	"""Execute request.

	Purpose:
	    Provides execute request behavior for the TTS workflow while preserving provider request and response state.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'api_key', self.api_key )
		throw_if( 'base_url', self.base_url )
		throw_if( 'request', self.request )
		self.response = requests.post(
			url=f'{self.base_url.rstrip( "/" )}/tts',
			headers={ 'Authorization': f'Bearer {self.api_key}',
			          'Content-Type': 'application/json', },
			json=self.request, timeout=self.timeout or 3600, )
		self.response.raise_for_status( )
		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'execute_request( self ) -> Any'
		raise ex

extract_audio

extract_audio() -> bytes | None

Extract audio.

Purpose

Provides extract audio behavior for the TTS workflow while preserving provider request and response state.

Returns:

Type Description
bytes | None

Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.

Source code in grok.py
def extract_audio( self ) -> bytes | None:
	"""Extract audio.

	Purpose:
	    Provides extract audio behavior for the TTS workflow while preserving provider request and response state.

	Returns:
	    Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.
	"""
	try:
		if self.response is None:
			return None

		self.audio_bytes = self.response.content
		if not self.audio_bytes:
			return None

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

		return self.audio_bytes
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'extract_audio( self ) -> bytes | None'
		raise ex

create_speech

create_speech(
    text: str,
    model: str = "xai-tts",
    format: str = "mp3",
    speed: float = 1.0,
    voice: str = "eve",
    instruct: str = None,
    file_path: str = None,
    language: str = "auto",
    sample_rate: int = None,
    bit_rate: int = None,
    optimize_streaming_latency: int = None,
    text_normalization: bool = None,
    **kwargs: Any
) -> bytes | None

Create speech.

Purpose

Creates the requested xAI resource using validated names, paths, or configuration values.

Parameters:

Name Type Description Default
text str

Text supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'xai-tts'
format str

Format supplied to the xAI workflow.

'mp3'
speed float

Speed supplied to the xAI workflow.

1.0
voice str

Voice supplied to the xAI workflow.

'eve'
instruct str

Instruct supplied to the xAI workflow.

None
file_path str

File path supplied to the xAI workflow.

None
language str

Language supplied to the xAI workflow.

'auto'
sample_rate int

Sample rate supplied to the xAI workflow.

None
bit_rate int

Bit rate supplied to the xAI workflow.

None
optimize_streaming_latency int

Optimize streaming latency supplied to the xAI workflow.

None
text_normalization bool

Text normalization supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
bytes | None

Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.

Source code in grok.py
def create_speech( self, text: str, model: str = 'xai-tts', format: str = 'mp3',
		speed: float = 1.0, voice: str = 'eve', instruct: str = None, file_path: str = None,
		language: str = 'auto', sample_rate: int = None, bit_rate: int = None,
		optimize_streaming_latency: int = None, text_normalization: bool = None,
		**kwargs: Any ) -> bytes | None:
	"""Create speech.

	Purpose:
	    Creates the requested xAI resource using validated names, paths, or configuration values.

	Args:
	    text (str): Text supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    format (str): Format supplied to the xAI workflow.
	    speed (float): Speed supplied to the xAI workflow.
	    voice (str): Voice supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    file_path (str): File path supplied to the xAI workflow.
	    language (str): Language supplied to the xAI workflow.
	    sample_rate (int): Sample rate supplied to the xAI workflow.
	    bit_rate (int): Bit rate supplied to the xAI workflow.
	    optimize_streaming_latency (int): Optimize streaming latency supplied to the xAI workflow.
	    text_normalization (bool): Text normalization supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.
	"""
	try:
		throw_if( 'text', text )
		self.input_text = text
		self.prompt = text
		self.model = model or 'xai-tts'
		self.response_format = self.validate_format( format )
		self.speed = self.validate_speed( speed )
		self.voice = self.validate_voice( voice )
		self.language = self.validate_language( language )
		self.instructions = instruct
		self.audio_path = file_path
		self.file_path = file_path
		self.sample_rate = self.validate_sample_rate( sample_rate )
		self.bit_rate = self.validate_bit_rate( bit_rate )
		self.optimize_streaming_latency = optimize_streaming_latency
		self.text_normalization = text_normalization
		self.extra_kwargs = kwargs or { }
		self.build_request( )
		self.execute_request( )
		return self.extract_audio( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'create_speech( self, text: str ) -> bytes | None'
		raise ex

synthesize

synthesize(
    text: str,
    model: str = "xai-tts",
    format: str = "mp3",
    speed: float = 1.0,
    voice: str = "eve",
    instruct: str = None,
    file_path: str = None,
    language: str = "auto",
    **kwargs: Any
) -> bytes | None

Synthesize.

Purpose

Provides synthesize behavior for the TTS workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
text str

Text supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'xai-tts'
format str

Format supplied to the xAI workflow.

'mp3'
speed float

Speed supplied to the xAI workflow.

1.0
voice str

Voice supplied to the xAI workflow.

'eve'
instruct str

Instruct supplied to the xAI workflow.

None
file_path str

File path supplied to the xAI workflow.

None
language str

Language supplied to the xAI workflow.

'auto'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
bytes | None

Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.

Source code in grok.py
def synthesize( self, text: str, model: str = 'xai-tts', format: str = 'mp3',
		speed: float = 1.0, voice: str = 'eve', instruct: str = None, file_path: str = None,
		language: str = 'auto', **kwargs: Any ) -> bytes | None:
	"""Synthesize.

	Purpose:
	    Provides synthesize behavior for the TTS workflow while preserving provider request and response state.

	Args:
	    text (str): Text supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    format (str): Format supplied to the xAI workflow.
	    speed (float): Speed supplied to the xAI workflow.
	    voice (str): Voice supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    file_path (str): File path supplied to the xAI workflow.
	    language (str): Language supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.
	"""
	try:
		return self.create_speech( text=text, model=model, format=format, speed=speed,
			voice=voice, instruct=instruct, file_path=file_path, language=language,
			**kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'synthesize( self, text: str ) -> bytes | None'
		raise ex

generate

generate(
    text: str = None,
    prompt: str = None,
    model: str = "xai-tts",
    format: str = "mp3",
    speed: float = 1.0,
    voice: str = "eve",
    instruct: str = None,
    file_path: str = None,
    language: str = "auto",
    **kwargs: Any
) -> bytes | None

Generate.

Purpose

Provides generate behavior for the TTS workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
text str

Text supplied to the xAI workflow.

None
prompt str

Prompt supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'xai-tts'
format str

Format supplied to the xAI workflow.

'mp3'
speed float

Speed supplied to the xAI workflow.

1.0
voice str

Voice supplied to the xAI workflow.

'eve'
instruct str

Instruct supplied to the xAI workflow.

None
file_path str

File path supplied to the xAI workflow.

None
language str

Language supplied to the xAI workflow.

'auto'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
bytes | None

Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.

Source code in grok.py
def generate( self, text: str = None, prompt: str = None, model: str = 'xai-tts',
		format: str = 'mp3', speed: float = 1.0, voice: str = 'eve', instruct: str = None,
		file_path: str = None, language: str = 'auto', **kwargs: Any ) -> bytes | None:
	"""Generate.

	Purpose:
	    Provides generate behavior for the TTS workflow while preserving provider request and response state.

	Args:
	    text (str): Text supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    format (str): Format supplied to the xAI workflow.
	    speed (float): Speed supplied to the xAI workflow.
	    voice (str): Voice supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    file_path (str): File path supplied to the xAI workflow.
	    language (str): Language supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Optional[bytes]: Audio bytes returned by the xAI speech workflow when generation succeeds.
	"""
	try:
		input_text = text or prompt
		throw_if( 'text', input_text )
		return self.create_speech( text=input_text, model=model, format=format, speed=speed,
			voice=voice, instruct=instruct, file_path=file_path, language=language,
			**kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'TTS'
		ex.method = 'generate( self, text: str ) -> bytes | None'
		raise ex

Transcription

Bases: Grok

Transcription workflow wrapper.

Purpose

Builds speech-to-text request state from uploaded audio files and provider model settings.

Attributes:

Name Type Description
client Optional[Client]

Runtime attribute used by the Transcription workflow.

model Optional[str]

Runtime attribute used by the Transcription workflow.

prompt Optional[str]

Runtime attribute used by the Transcription workflow.

language Optional[str]

Runtime attribute used by the Transcription workflow.

file_path Optional[str]

Runtime attribute used by the Transcription workflow.

audio_file Optional[Any]

Runtime attribute used by the Transcription workflow.

messages Optional[List[Any]]

Runtime attribute used by the Transcription workflow.

response Optional[Any]

Runtime attribute used by the Transcription workflow.

transcript Optional[str]

Runtime attribute used by the Transcription workflow.

request Optional[Dict[str, Any]]

Runtime attribute used by the Transcription workflow.

Source code in grok.py
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
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
class Transcription( Grok ):
	"""Transcription workflow wrapper.

	Purpose:
	    Builds speech-to-text request state from uploaded audio files and provider model settings.

	Attributes:
	    client: Runtime attribute used by the Transcription workflow.
	    model: Runtime attribute used by the Transcription workflow.
	    prompt: Runtime attribute used by the Transcription workflow.
	    language: Runtime attribute used by the Transcription workflow.
	    file_path: Runtime attribute used by the Transcription workflow.
	    audio_file: Runtime attribute used by the Transcription workflow.
	    messages: Runtime attribute used by the Transcription workflow.
	    response: Runtime attribute used by the Transcription workflow.
	    transcript: Runtime attribute used by the Transcription workflow.
	    request: Runtime attribute used by the Transcription workflow.
	"""
	client: Optional[ Client ]
	model: Optional[ str ]
	prompt: Optional[ str ]
	language: Optional[ str ]
	file_path: Optional[ str ]
	audio_file: Optional[ Any ]
	messages: Optional[ List[ Any ] ]
	response: Optional[ Any ]
	transcript: Optional[ str ]
	request: Optional[ Dict[ str, Any ] ]

	def __init__( self, number: int = 1, model: str = 'grok-3-mini-fast',
			temperature: float = 0.8, top_p: float = 0.9, frequency: float = 0.0,
			presence: float = 0.0, max_tokens: int = 10000, store: bool = True,
			stream: bool = False, language: str = 'en', instruct: str = None ):
		"""Initialize instance.

		Purpose:
		    Initializes Transcription state with default configuration values and runtime attributes used by later xAI provider calls.

		Args:
		    number (int): Number supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    language (str): Language supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		"""
		super( ).__init__( )
		self.api_key = os.getenv( 'XAI_API_KEY' ) or cfg.XAI_API_KEY
		self.base_url = getattr( cfg, 'XAI_BASE_URL', 'https://api.x.ai/v1' )
		self.client = None
		self.number = number
		self.model = model
		self.temperature = temperature
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_output_tokens = max_tokens
		self.max_completion_tokens = max_tokens
		self.store = store
		self.stream = stream
		self.language = language
		self.instructions = instruct
		self.prompt = None
		self.file_path = None
		self.audio_file = None
		self.messages = [ ]
		self.request = { }
		self.response = None
		self.chat = None
		self.transcript = None
		self.response_format = None
		self.include = [ ]
		self.extra_kwargs = { }

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

		Purpose:
		    Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'grok-4',
				'grok-4-latest',
				'grok-4-fast-reasoning',
				'grok-4-fast-non-reasoning',
				'grok-3',
				'grok-3-latest',
				'grok-3-mini',
				'grok-3-fast',
				'grok-3-mini-fast',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'auto',
				'en',
				'es',
				'fr',
				'de',
				'it',
				'ja',
				'ko',
				'pt',
				'zh',
				'Tagalog',
				'French',
				'Japanese',
				'German',
				'Italian',
				'Chinese',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'audio/wav',
				'audio/mp3',
				'audio/mpeg',
				'audio/mp4',
				'audio/m4a',
				'audio/webm',
				'audio/ogg',
				'audio/flac',
		]

	@property
	def response_format_options( self ) -> List[ str ]:
		"""Response format options.

		Purpose:
		    Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'text',
				'json',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ ]

	def build_prompt( self ) -> str:
		"""Build prompt.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			if isinstance( self.prompt, str ) and self.prompt.strip( ):
				return self.prompt.strip( )

			language = self.language or 'auto'
			return (
					'Transcribe the attached audio file accurately. '
					f'Use the language hint "{language}" when helpful. '
					'Return only the transcript unless additional instructions require otherwise.'
			)
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Transcription'
			ex.method = 'build_prompt( self )'
			raise ex

	def build_messages( self ) -> List[ Any ]:
		"""Build messages.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    List[Any]: Result produced by the xAI workflow.
		"""
		try:
			self.messages = [ ]

			if isinstance( self.instructions, str ) and self.instructions.strip( ):
				self.messages.append( system( self.instructions.strip( ) ) )

			self.messages.append( user( self.build_prompt( ) ) )
			return self.messages
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Transcription'
			ex.method = 'build_messages( self )'
			raise ex

	def build_request( self ) -> Dict[ str, Any ]:
		"""Build request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'model', self.model )
			throw_if( 'file_path', self.file_path )
			self.build_messages( )
			self.request = {
					'model': self.model,
					'messages': self.messages,
			}
			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Transcription'
			ex.method = 'build_request( self )'
			raise ex

	def execute_request( self ) -> Any:
		"""Execute request.

		Purpose:
		    Provides execute request behavior for the Transcription workflow while preserving provider request and response state.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'api_key', self.api_key )
			throw_if( 'file_path', self.file_path )
			self.client = Client( api_key=cfg.XAI_API_KEY )
			with open( self.file_path, 'rb' ) as self.audio_file:
				self.chat = self.client.chat.create( file=self.audio_file, **self.request )
				self.response = self.chat.sample( )

			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Transcription'
			ex.method = 'execute_request( self )'
			raise ex

	def extract_transcript( self ) -> str:
		"""Extract transcript.

		Purpose:
		    Provides extract transcript behavior for the Transcription workflow while preserving provider request and response state.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			if self.response is None:
				return ''

			output_text = getattr( self.response, 'output_text', None )
			if isinstance( output_text, str ) and output_text.strip( ):
				self.transcript = output_text.strip( )
				return self.transcript

			text = getattr( self.response, 'text', None )
			if isinstance( text, str ) and text.strip( ):
				self.transcript = text.strip( )
				return self.transcript

			content = getattr( self.response, 'content', None )
			if isinstance( content, str ) and content.strip( ):
				self.transcript = content.strip( )
				return self.transcript

			self.transcript = str( self.response ).strip( )
			return self.transcript
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Transcription'
			ex.method = 'extract_transcript( self )'
			raise ex

	def transcribe( self, path: str, model: str = 'grok-3-mini-fast', language: str = 'en',
			prompt: str = None, temperature: float = None, top_p: float = None,
			frequency: float = None, presence: float = None, max_tokens: int = None,
			store: bool = None, stream: bool = None, instruct: str = None,
			response_format: str = None, include: List[ str ] = None, mime_type: str = None,
			start_time: float = None, end_time: float = None, **kwargs: Any ) -> str:
		"""Transcribe.

		Purpose:
		    Executes xAI transcription using validated audio input and model configuration.

		Args:
		    path (str): Path supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    language (str): Language supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    response_format (str): Response format supplied to the xAI workflow.
		    include (List[str]): Include supplied to the xAI workflow.
		    mime_type (str): Mime type supplied to the xAI workflow.
		    start_time (float): Start time supplied to the xAI workflow.
		    end_time (float): End time supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'path', path )
			throw_if( 'model', model )
			self.file_path = path
			self.model = model
			self.language = language
			self.prompt = prompt
			self.temperature = temperature if temperature is not None else self.temperature
			self.top_percent = top_p if top_p is not None else self.top_percent
			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_output_tokens = max_tokens if max_tokens is not None else self.max_output_tokens
			self.max_completion_tokens = self.max_output_tokens
			self.store = store if store is not None else self.store
			self.stream = stream if stream is not None else self.stream
			self.instructions = instruct if instruct is not None else self.instructions
			self.response_format = response_format
			self.include = include if include is not None else [ ]
			self.mime_type = mime_type
			self.start_time = start_time
			self.end_time = end_time
			self.extra_kwargs = kwargs or { }
			self.build_request( )
			self.execute_request( )
			return self.extract_transcript( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Transcription'
			ex.method = 'transcribe( self, path: str, model: str ) -> str'
			raise ex

	def __dir__( self ) -> List[ str ] | None:
		"""Dir.

		Purpose:
		    Provides dir behavior for the Transcription workflow while preserving provider request and response state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'api_key',
				'base_url',
				'client',
				'number',
				'model',
				'temperature',
				'top_percent',
				'frequency_penalty',
				'presence_penalty',
				'max_output_tokens',
				'max_completion_tokens',
				'store',
				'stream',
				'language',
				'instructions',
				'prompt',
				'file_path',
				'audio_file',
				'messages',
				'request',
				'response',
				'chat',
				'transcript',
				'response_format',
				'include',
				'extra_kwargs',
				'model_options',
				'language_options',
				'format_options',
				'response_format_options',
				'include_options',
				'build_prompt',
				'build_messages',
				'build_request',
				'execute_request',
				'extract_transcript',
				'transcribe',
		]

model_options property

model_options: List[str]

Model options.

Purpose

Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

language_options property

language_options: List[str]

Language options.

Purpose

Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

format_options property

format_options: List[str]

Format options.

Purpose

Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

response_format_options property

response_format_options: List[str]

Response format options.

Purpose

Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

include_options property

include_options: List[str]

Include options.

Purpose

Returns the configured option values exposed by the Transcription workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

build_prompt

build_prompt() -> str

Build prompt.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def build_prompt( self ) -> str:
	"""Build prompt.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		if isinstance( self.prompt, str ) and self.prompt.strip( ):
			return self.prompt.strip( )

		language = self.language or 'auto'
		return (
				'Transcribe the attached audio file accurately. '
				f'Use the language hint "{language}" when helpful. '
				'Return only the transcript unless additional instructions require otherwise.'
		)
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Transcription'
		ex.method = 'build_prompt( self )'
		raise ex

build_messages

build_messages() -> List[Any]

Build messages.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
List[Any]

List[Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_messages( self ) -> List[ Any ]:
	"""Build messages.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    List[Any]: Result produced by the xAI workflow.
	"""
	try:
		self.messages = [ ]

		if isinstance( self.instructions, str ) and self.instructions.strip( ):
			self.messages.append( system( self.instructions.strip( ) ) )

		self.messages.append( user( self.build_prompt( ) ) )
		return self.messages
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Transcription'
		ex.method = 'build_messages( self )'
		raise ex

build_request

build_request() -> Dict[str, Any]

Build request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_request( self ) -> Dict[ str, Any ]:
	"""Build request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'model', self.model )
		throw_if( 'file_path', self.file_path )
		self.build_messages( )
		self.request = {
				'model': self.model,
				'messages': self.messages,
		}
		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Transcription'
		ex.method = 'build_request( self )'
		raise ex

execute_request

execute_request() -> Any

Execute request.

Purpose

Provides execute request behavior for the Transcription workflow while preserving provider request and response state.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def execute_request( self ) -> Any:
	"""Execute request.

	Purpose:
	    Provides execute request behavior for the Transcription workflow while preserving provider request and response state.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'api_key', self.api_key )
		throw_if( 'file_path', self.file_path )
		self.client = Client( api_key=cfg.XAI_API_KEY )
		with open( self.file_path, 'rb' ) as self.audio_file:
			self.chat = self.client.chat.create( file=self.audio_file, **self.request )
			self.response = self.chat.sample( )

		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Transcription'
		ex.method = 'execute_request( self )'
		raise ex

extract_transcript

extract_transcript() -> str

Extract transcript.

Purpose

Provides extract transcript behavior for the Transcription workflow while preserving provider request and response state.

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def extract_transcript( self ) -> str:
	"""Extract transcript.

	Purpose:
	    Provides extract transcript behavior for the Transcription workflow while preserving provider request and response state.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		if self.response is None:
			return ''

		output_text = getattr( self.response, 'output_text', None )
		if isinstance( output_text, str ) and output_text.strip( ):
			self.transcript = output_text.strip( )
			return self.transcript

		text = getattr( self.response, 'text', None )
		if isinstance( text, str ) and text.strip( ):
			self.transcript = text.strip( )
			return self.transcript

		content = getattr( self.response, 'content', None )
		if isinstance( content, str ) and content.strip( ):
			self.transcript = content.strip( )
			return self.transcript

		self.transcript = str( self.response ).strip( )
		return self.transcript
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Transcription'
		ex.method = 'extract_transcript( self )'
		raise ex

transcribe

transcribe(
    path: str,
    model: str = "grok-3-mini-fast",
    language: str = "en",
    prompt: str = None,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    store: bool = None,
    stream: bool = None,
    instruct: str = None,
    response_format: str = None,
    include: List[str] = None,
    mime_type: str = None,
    start_time: float = None,
    end_time: float = None,
    **kwargs: Any
) -> str

Transcribe.

Purpose

Executes xAI transcription using validated audio input and model configuration.

Parameters:

Name Type Description Default
path str

Path supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-3-mini-fast'
language str

Language supplied to the xAI workflow.

'en'
prompt str

Prompt supplied to the xAI workflow.

None
temperature float

Temperature supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
frequency float

Frequency supplied to the xAI workflow.

None
presence float

Presence supplied to the xAI workflow.

None
max_tokens int

Max tokens supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

None
stream bool

Stream supplied to the xAI workflow.

None
instruct str

Instruct supplied to the xAI workflow.

None
response_format str

Response format supplied to the xAI workflow.

None
include List[str]

Include supplied to the xAI workflow.

None
mime_type str

Mime type supplied to the xAI workflow.

None
start_time float

Start time supplied to the xAI workflow.

None
end_time float

End time supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def transcribe( self, path: str, model: str = 'grok-3-mini-fast', language: str = 'en',
		prompt: str = None, temperature: float = None, top_p: float = None,
		frequency: float = None, presence: float = None, max_tokens: int = None,
		store: bool = None, stream: bool = None, instruct: str = None,
		response_format: str = None, include: List[ str ] = None, mime_type: str = None,
		start_time: float = None, end_time: float = None, **kwargs: Any ) -> str:
	"""Transcribe.

	Purpose:
	    Executes xAI transcription using validated audio input and model configuration.

	Args:
	    path (str): Path supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    language (str): Language supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    frequency (float): Frequency supplied to the xAI workflow.
	    presence (float): Presence supplied to the xAI workflow.
	    max_tokens (int): Max tokens supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    stream (bool): Stream supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    response_format (str): Response format supplied to the xAI workflow.
	    include (List[str]): Include supplied to the xAI workflow.
	    mime_type (str): Mime type supplied to the xAI workflow.
	    start_time (float): Start time supplied to the xAI workflow.
	    end_time (float): End time supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'path', path )
		throw_if( 'model', model )
		self.file_path = path
		self.model = model
		self.language = language
		self.prompt = prompt
		self.temperature = temperature if temperature is not None else self.temperature
		self.top_percent = top_p if top_p is not None else self.top_percent
		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_output_tokens = max_tokens if max_tokens is not None else self.max_output_tokens
		self.max_completion_tokens = self.max_output_tokens
		self.store = store if store is not None else self.store
		self.stream = stream if stream is not None else self.stream
		self.instructions = instruct if instruct is not None else self.instructions
		self.response_format = response_format
		self.include = include if include is not None else [ ]
		self.mime_type = mime_type
		self.start_time = start_time
		self.end_time = end_time
		self.extra_kwargs = kwargs or { }
		self.build_request( )
		self.execute_request( )
		return self.extract_transcript( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Transcription'
		ex.method = 'transcribe( self, path: str, model: str ) -> str'
		raise ex

Translation

Bases: Grok

Translation workflow wrapper.

Purpose

Builds translation request state from source content, language values, and provider model settings.

Attributes:

Name Type Description
client Optional[Client]

Runtime attribute used by the Translation workflow.

model Optional[str]

Runtime attribute used by the Translation workflow.

prompt Optional[str]

Runtime attribute used by the Translation workflow.

target_language Optional[str]

Runtime attribute used by the Translation workflow.

source_language Optional[str]

Runtime attribute used by the Translation workflow.

file_path Optional[str]

Runtime attribute used by the Translation workflow.

audio_file Optional[Any]

Runtime attribute used by the Translation workflow.

messages Optional[List[Any]]

Runtime attribute used by the Translation workflow.

response Optional[Any]

Runtime attribute used by the Translation workflow.

translation Optional[str]

Runtime attribute used by the Translation workflow.

request Optional[Dict[str, Any]]

Runtime attribute used by the Translation workflow.

Source code in grok.py
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
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
class Translation( Grok ):
	"""Translation workflow wrapper.

	Purpose:
	    Builds translation request state from source content, language values, and provider model settings.

	Attributes:
	    client: Runtime attribute used by the Translation workflow.
	    model: Runtime attribute used by the Translation workflow.
	    prompt: Runtime attribute used by the Translation workflow.
	    target_language: Runtime attribute used by the Translation workflow.
	    source_language: Runtime attribute used by the Translation workflow.
	    file_path: Runtime attribute used by the Translation workflow.
	    audio_file: Runtime attribute used by the Translation workflow.
	    messages: Runtime attribute used by the Translation workflow.
	    response: Runtime attribute used by the Translation workflow.
	    translation: Runtime attribute used by the Translation workflow.
	    request: Runtime attribute used by the Translation workflow.
	"""
	client: Optional[ Client ]
	model: Optional[ str ]
	prompt: Optional[ str ]
	target_language: Optional[ str ]
	source_language: Optional[ str ]
	file_path: Optional[ str ]
	audio_file: Optional[ Any ]
	messages: Optional[ List[ Any ] ]
	response: Optional[ Any ]
	translation: Optional[ str ]
	request: Optional[ Dict[ str, Any ] ]

	def __init__( self, model: str = 'grok-3-fast', temperature: float = 0.8,
			top_p: float = 0.9, frequency: float = 0.0, presence: float = 0.0,
			max_tokens: int = 10000, store: bool = True, stream: bool = False,
			instruct: str = None ):
		"""Initialize instance.

		Purpose:
		    Initializes Translation state with default configuration values and runtime attributes used by later xAI provider calls.

		Args:
		    model (str): Model supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		"""
		super( ).__init__( )
		self.api_key = os.getenv( 'XAI_API_KEY' ) or cfg.XAI_API_KEY
		self.base_url = getattr( cfg, 'XAI_BASE_URL', 'https://api.x.ai/v1' )
		self.client = None
		self.model = model
		self.temperature = temperature
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_output_tokens = max_tokens
		self.max_completion_tokens = max_tokens
		self.store = store
		self.stream = stream
		self.instructions = instruct
		self.prompt = None
		self.target_language = None
		self.source_language = None
		self.file_path = None
		self.audio_file = None
		self.messages = [ ]
		self.request = { }
		self.response = None
		self.chat = None
		self.translation = None
		self.response_format = None
		self.include = [ ]
		self.mime_type = None
		self.extra_kwargs = { }

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

		Purpose:
		    Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'grok-4',
				'grok-4-latest',
				'grok-4-fast-reasoning',
				'grok-4-fast-non-reasoning',
				'grok-3',
				'grok-3-latest',
				'grok-3-mini',
				'grok-3-fast',
				'grok-3-mini-fast',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'English',
				'Spanish',
				'French',
				'German',
				'Italian',
				'Japanese',
				'Korean',
				'Portuguese',
				'Chinese',
				'Tagalog',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'audio/wav',
				'audio/mp3',
				'audio/mpeg',
				'audio/mp4',
				'audio/m4a',
				'audio/webm',
				'audio/ogg',
				'audio/flac',
		]

	@property
	def response_format_options( self ) -> List[ str ]:
		"""Response format options.

		Purpose:
		    Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'text',
				'json',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ ]

	def build_prompt( self ) -> str:
		"""Build prompt.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'target_language', self.target_language )

			if isinstance( self.prompt, str ) and self.prompt.strip( ):
				base_prompt = self.prompt.strip( )
			else:
				base_prompt = 'Translate the spoken audio in the attached file.'

			if self.source_language and str( self.source_language ).strip( ):
				return (
						f'{base_prompt} Source language hint: {self.source_language}. '
						f'Translate the speech into {self.target_language}. '
						'Return only the translated text unless additional instructions require otherwise.'
				)

			return (
					f'{base_prompt} Translate the speech into {self.target_language}. '
					'Return only the translated text unless additional instructions require otherwise.'
			)
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Translation'
			ex.method = 'build_prompt( self )'
			raise ex

	def build_messages( self ) -> List[ Any ]:
		"""Build messages.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    List[Any]: Result produced by the xAI workflow.
		"""
		try:
			self.messages = [ ]

			if isinstance( self.instructions, str ) and self.instructions.strip( ):
				self.messages.append( system( self.instructions.strip( ) ) )

			self.messages.append( user( self.build_prompt( ) ) )
			return self.messages
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Translation'
			ex.method = 'build_messages( self )'
			raise ex

	def build_request( self ) -> Dict[ str, Any ]:
		"""Build request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'model', self.model )
			throw_if( 'file_path', self.file_path )
			throw_if( 'target_language', self.target_language )
			self.build_messages( )
			self.request = {
					'model': self.model,
					'messages': self.messages,
			}
			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Translation'
			ex.method = 'build_request( self )'
			raise ex

	def execute_request( self ) -> Any:
		"""Execute request.

		Purpose:
		    Provides execute request behavior for the Translation workflow while preserving provider request and response state.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'api_key', self.api_key )
			throw_if( 'file_path', self.file_path )
			self.client = Client( api_key=cfg.XAI_API_KEY )
			with open( self.file_path, 'rb' ) as self.audio_file:
				self.chat = self.client.chat.create( file=self.audio_file, **self.request )
				self.response = self.chat.sample( )

			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Translation'
			ex.method = 'execute_request( self )'
			raise ex

	def extract_translation( self ) -> str:
		"""Extract translation.

		Purpose:
		    Provides extract translation behavior for the Translation workflow while preserving provider request and response state.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			if self.response is None:
				return ''

			output_text = getattr( self.response, 'output_text', None )
			if isinstance( output_text, str ) and output_text.strip( ):
				self.translation = output_text.strip( )
				return self.translation

			text = getattr( self.response, 'text', None )
			if isinstance( text, str ) and text.strip( ):
				self.translation = text.strip( )
				return self.translation

			content = getattr( self.response, 'content', None )
			if isinstance( content, str ) and content.strip( ):
				self.translation = content.strip( )
				return self.translation

			self.translation = str( self.response ).strip( )
			return self.translation
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Translation'
			ex.method = 'extract_translation( self )'
			raise ex

	def translate( self, path: str, model: str = 'grok-3-fast', language: str = 'English',
			prompt: str = None, source_language: str = None, temperature: float = None,
			top_p: float = None, frequency: float = None, presence: float = None,
			max_tokens: int = None, store: bool = None, stream: bool = None,
			instruct: str = None, response_format: str = None, include: List[ str ] = None,
			mime_type: str = None, **kwargs: Any ) -> str:
		"""Translate.

		Purpose:
		    Executes xAI translation using validated source content and language settings.

		Args:
		    path (str): Path supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    language (str): Language supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    source_language (str): Source language supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    response_format (str): Response format supplied to the xAI workflow.
		    include (List[str]): Include supplied to the xAI workflow.
		    mime_type (str): Mime type supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'path', path )
			throw_if( 'model', model )
			throw_if( 'language', language )
			self.file_path = path
			self.model = model
			self.target_language = language
			self.source_language = source_language
			self.prompt = prompt
			self.temperature = temperature if temperature is not None else self.temperature
			self.top_percent = top_p if top_p is not None else self.top_percent
			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_output_tokens = max_tokens if max_tokens is not None else self.max_output_tokens
			self.max_completion_tokens = self.max_output_tokens
			self.store = store if store is not None else self.store
			self.stream = stream if stream is not None else self.stream
			self.instructions = instruct if instruct is not None else self.instructions
			self.response_format = response_format
			self.include = include if include is not None else [ ]
			self.mime_type = mime_type
			self.extra_kwargs = kwargs or { }
			self.build_request( )
			self.execute_request( )
			return self.extract_translation( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Translation'
			ex.method = 'translate( self, path: str, model: str, language: str ) -> str'
			raise ex

	def __dir__( self ) -> List[ str ] | None:
		"""Dir.

		Purpose:
		    Provides dir behavior for the Translation workflow while preserving provider request and response state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'api_key',
				'base_url',
				'client',
				'model',
				'temperature',
				'top_percent',
				'frequency_penalty',
				'presence_penalty',
				'max_output_tokens',
				'max_completion_tokens',
				'store',
				'stream',
				'instructions',
				'prompt',
				'target_language',
				'source_language',
				'file_path',
				'audio_file',
				'messages',
				'request',
				'response',
				'chat',
				'translation',
				'response_format',
				'include',
				'mime_type',
				'extra_kwargs',
				'model_options',
				'language_options',
				'format_options',
				'response_format_options',
				'include_options',
				'build_prompt',
				'build_messages',
				'build_request',
				'execute_request',
				'extract_translation',
				'translate',
		]

model_options property

model_options: List[str]

Model options.

Purpose

Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

language_options property

language_options: List[str]

Language options.

Purpose

Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

format_options property

format_options: List[str]

Format options.

Purpose

Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

response_format_options property

response_format_options: List[str]

Response format options.

Purpose

Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

include_options property

include_options: List[str]

Include options.

Purpose

Returns the configured option values exposed by the Translation workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

build_prompt

build_prompt() -> str

Build prompt.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def build_prompt( self ) -> str:
	"""Build prompt.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'target_language', self.target_language )

		if isinstance( self.prompt, str ) and self.prompt.strip( ):
			base_prompt = self.prompt.strip( )
		else:
			base_prompt = 'Translate the spoken audio in the attached file.'

		if self.source_language and str( self.source_language ).strip( ):
			return (
					f'{base_prompt} Source language hint: {self.source_language}. '
					f'Translate the speech into {self.target_language}. '
					'Return only the translated text unless additional instructions require otherwise.'
			)

		return (
				f'{base_prompt} Translate the speech into {self.target_language}. '
				'Return only the translated text unless additional instructions require otherwise.'
		)
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Translation'
		ex.method = 'build_prompt( self )'
		raise ex

build_messages

build_messages() -> List[Any]

Build messages.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
List[Any]

List[Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_messages( self ) -> List[ Any ]:
	"""Build messages.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    List[Any]: Result produced by the xAI workflow.
	"""
	try:
		self.messages = [ ]

		if isinstance( self.instructions, str ) and self.instructions.strip( ):
			self.messages.append( system( self.instructions.strip( ) ) )

		self.messages.append( user( self.build_prompt( ) ) )
		return self.messages
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Translation'
		ex.method = 'build_messages( self )'
		raise ex

build_request

build_request() -> Dict[str, Any]

Build request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_request( self ) -> Dict[ str, Any ]:
	"""Build request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'model', self.model )
		throw_if( 'file_path', self.file_path )
		throw_if( 'target_language', self.target_language )
		self.build_messages( )
		self.request = {
				'model': self.model,
				'messages': self.messages,
		}
		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Translation'
		ex.method = 'build_request( self )'
		raise ex

execute_request

execute_request() -> Any

Execute request.

Purpose

Provides execute request behavior for the Translation workflow while preserving provider request and response state.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def execute_request( self ) -> Any:
	"""Execute request.

	Purpose:
	    Provides execute request behavior for the Translation workflow while preserving provider request and response state.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'api_key', self.api_key )
		throw_if( 'file_path', self.file_path )
		self.client = Client( api_key=cfg.XAI_API_KEY )
		with open( self.file_path, 'rb' ) as self.audio_file:
			self.chat = self.client.chat.create( file=self.audio_file, **self.request )
			self.response = self.chat.sample( )

		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Translation'
		ex.method = 'execute_request( self )'
		raise ex

extract_translation

extract_translation() -> str

Extract translation.

Purpose

Provides extract translation behavior for the Translation workflow while preserving provider request and response state.

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def extract_translation( self ) -> str:
	"""Extract translation.

	Purpose:
	    Provides extract translation behavior for the Translation workflow while preserving provider request and response state.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		if self.response is None:
			return ''

		output_text = getattr( self.response, 'output_text', None )
		if isinstance( output_text, str ) and output_text.strip( ):
			self.translation = output_text.strip( )
			return self.translation

		text = getattr( self.response, 'text', None )
		if isinstance( text, str ) and text.strip( ):
			self.translation = text.strip( )
			return self.translation

		content = getattr( self.response, 'content', None )
		if isinstance( content, str ) and content.strip( ):
			self.translation = content.strip( )
			return self.translation

		self.translation = str( self.response ).strip( )
		return self.translation
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Translation'
		ex.method = 'extract_translation( self )'
		raise ex

translate

translate(
    path: str,
    model: str = "grok-3-fast",
    language: str = "English",
    prompt: str = None,
    source_language: str = None,
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    store: bool = None,
    stream: bool = None,
    instruct: str = None,
    response_format: str = None,
    include: List[str] = None,
    mime_type: str = None,
    **kwargs: Any
) -> str

Translate.

Purpose

Executes xAI translation using validated source content and language settings.

Parameters:

Name Type Description Default
path str

Path supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-3-fast'
language str

Language supplied to the xAI workflow.

'English'
prompt str

Prompt supplied to the xAI workflow.

None
source_language str

Source language supplied to the xAI workflow.

None
temperature float

Temperature supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
frequency float

Frequency supplied to the xAI workflow.

None
presence float

Presence supplied to the xAI workflow.

None
max_tokens int

Max tokens supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

None
stream bool

Stream supplied to the xAI workflow.

None
instruct str

Instruct supplied to the xAI workflow.

None
response_format str

Response format supplied to the xAI workflow.

None
include List[str]

Include supplied to the xAI workflow.

None
mime_type str

Mime type supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def translate( self, path: str, model: str = 'grok-3-fast', language: str = 'English',
		prompt: str = None, source_language: str = None, temperature: float = None,
		top_p: float = None, frequency: float = None, presence: float = None,
		max_tokens: int = None, store: bool = None, stream: bool = None,
		instruct: str = None, response_format: str = None, include: List[ str ] = None,
		mime_type: str = None, **kwargs: Any ) -> str:
	"""Translate.

	Purpose:
	    Executes xAI translation using validated source content and language settings.

	Args:
	    path (str): Path supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    language (str): Language supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    source_language (str): Source language supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    frequency (float): Frequency supplied to the xAI workflow.
	    presence (float): Presence supplied to the xAI workflow.
	    max_tokens (int): Max tokens supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    stream (bool): Stream supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    response_format (str): Response format supplied to the xAI workflow.
	    include (List[str]): Include supplied to the xAI workflow.
	    mime_type (str): Mime type supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'path', path )
		throw_if( 'model', model )
		throw_if( 'language', language )
		self.file_path = path
		self.model = model
		self.target_language = language
		self.source_language = source_language
		self.prompt = prompt
		self.temperature = temperature if temperature is not None else self.temperature
		self.top_percent = top_p if top_p is not None else self.top_percent
		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_output_tokens = max_tokens if max_tokens is not None else self.max_output_tokens
		self.max_completion_tokens = self.max_output_tokens
		self.store = store if store is not None else self.store
		self.stream = stream if stream is not None else self.stream
		self.instructions = instruct if instruct is not None else self.instructions
		self.response_format = response_format
		self.include = include if include is not None else [ ]
		self.mime_type = mime_type
		self.extra_kwargs = kwargs or { }
		self.build_request( )
		self.execute_request( )
		return self.extract_translation( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Translation'
		ex.method = 'translate( self, path: str, model: str, language: str ) -> str'
		raise ex

Images

Bases: Grok

Images workflow wrapper.

Purpose

Builds and executes xAI image-generation and image-analysis workflows while preserving prompt, model, and response state.

Attributes:

Name Type Description
model Optional[str]

Runtime attribute used by the Images workflow.

prompt Optional[str]

Runtime attribute used by the Images workflow.

aspect_ratio Optional[str]

Runtime attribute used by the Images workflow.

resolution Optional[str]

Runtime attribute used by the Images workflow.

response_format Optional[str]

Runtime attribute used by the Images workflow.

client Optional[OpenAI]

Runtime attribute used by the Images workflow.

image_path Optional[str]

Runtime attribute used by the Images workflow.

image_url Optional[str]

Runtime attribute used by the Images workflow.

detail Optional[str]

Runtime attribute used by the Images workflow.

response Optional[Any]

Runtime attribute used by the Images workflow.

request Optional[Dict[str, Any]]

Runtime attribute used by the Images workflow.

output Optional[Any]

Runtime attribute used by the Images workflow.

Source code in grok.py
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
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
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
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
class Images( Grok ):
	"""Images workflow wrapper.

	Purpose:
	    Builds and executes xAI image-generation and image-analysis workflows while preserving prompt, model, and response state.

	Attributes:
	    model: Runtime attribute used by the Images workflow.
	    prompt: Runtime attribute used by the Images workflow.
	    aspect_ratio: Runtime attribute used by the Images workflow.
	    resolution: Runtime attribute used by the Images workflow.
	    response_format: Runtime attribute used by the Images workflow.
	    client: Runtime attribute used by the Images workflow.
	    image_path: Runtime attribute used by the Images workflow.
	    image_url: Runtime attribute used by the Images workflow.
	    detail: Runtime attribute used by the Images workflow.
	    response: Runtime attribute used by the Images workflow.
	    request: Runtime attribute used by the Images workflow.
	    output: Runtime attribute used by the Images workflow.
	"""
	model: Optional[ str ]
	prompt: Optional[ str ]
	aspect_ratio: Optional[ str ]
	resolution: Optional[ str ]
	response_format: Optional[ str ]
	client: Optional[ OpenAI ]
	image_path: Optional[ str ]
	image_url: Optional[ str ]
	detail: Optional[ str ]
	response: Optional[ Any ]
	request: Optional[ Dict[ str, Any ] ]
	output: Optional[ Any ]

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

		Purpose:
		    Initializes Images state with default configuration values and runtime attributes used by later xAI provider calls.
		"""
		super( ).__init__( )
		self.api_key = os.getenv( 'XAI_API_KEY' ) or cfg.XAI_API_KEY
		self.base_url = getattr( cfg, 'XAI_BASE_URL', 'https://api.x.ai/v1' )
		self.client = None
		self.model = None
		self.prompt = None
		self.number = None
		self.aspect_ratio = None
		self.resolution = None
		self.size = None
		self.quality = None
		self.style = None
		self.detail = None
		self.response_format = None
		self.mime_type = None
		self.compression = None
		self.background = None
		self.response_modalities = None
		self.max_output_tokens = None
		self.temperature = None
		self.top_percent = None
		self.frequency_penalty = None
		self.presence_penalty = None
		self.tools = [ ]
		self.tool_choice = None
		self.include = [ ]
		self.allowed_domains = [ ]
		self.store = None
		self.stream = None
		self.is_parallel = None
		self.max_tools = None
		self.max_searches = None
		self.image_path = None
		self.image_url = None
		self.mask_path = None
		self.request = { }
		self.response = None
		self.output = None
		self.extra_body = { }
		self.extra_kwargs = { }

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ 'grok-imagine-image', 'grok-2-image-1212' ]

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'grok-4.20-reasoning',
				'grok-4.20',
				'grok-4',
				'grok-4-latest',
				'grok-4-fast-reasoning',
				'grok-4-fast-non-reasoning',
		]

	@property
	def tool_options( self ) -> List[ str ] | None:
		"""Tool options.

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [ ]

	@property
	def include_options( self ) -> List[ str ] | None:
		"""Include options.

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [ ]

	@property
	def choice_options( self ) -> List[ str ] | None:
		"""Choice options.

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [ 'auto', 'required', 'none' ]

	@property
	def aspect_options( self ) -> List[ str ]:
		"""Aspect options.

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'auto',
				'1:1',
				'3:4',
				'4:3',
				'9:16',
				'16:9',
				'2:3',
				'3:2',
				'9:19.5',
				'19.5:9',
				'9:20',
				'20:9',
				'1:2',
				'2:1',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ '1k', '2k' ]

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ 'auto', 'low', 'medium', 'high' ]

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ ]

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ ]

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ 'auto', 'low', 'high' ]

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ 'url', 'b64_json' ]

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

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ 'url', 'b64_json' ]

	@property
	def output_options( self ) -> List[ str ]:
		"""Output options.

		Purpose:
		    Returns the configured option values exposed by the Images workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [ 'url', 'b64_json' ]

	def initialize_client( self ) -> None:
		"""Initialize client.

		Purpose:
		    Provides initialize client behavior for the Images workflow while preserving provider request and response state.
		"""
		try:
			throw_if( 'api_key', self.api_key )
			throw_if( 'base_url', self.base_url )
			self.client = OpenAI( api_key=cfg.XAI_API_KEY, base_url=self.base_url )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'initialize_client( self )'
			raise ex

	def normalize_resolution( self, value: str = None ) -> str | None:
		"""Normalize resolution.

		Purpose:
		    Provides normalize resolution behavior for the Images workflow while preserving provider request and response state.

		Args:
		    value (str): Value supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			if value is None:
				return None

			resolution = str( value ).strip( ).lower( )
			if resolution in [ '1k', '2k' ]:
				return resolution

			return None
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'normalize_resolution( self, value )'
			raise ex

	def normalize_response_format( self, value: str = None ) -> str | None:
		"""Normalize response format.

		Purpose:
		    Provides normalize response format behavior for the Images workflow while preserving provider request and response state.

		Args:
		    value (str): Value supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			if value is None:
				return None

			response_format = str( value ).strip( ).lower( )
			if response_format in [ 'url', 'b64_json' ]:
				return response_format

			if response_format == 'base64':
				return 'b64_json'

			return None
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'normalize_response_format( self, value )'
			raise ex

	def encode_image_data_uri( self, image_path: str ) -> str:
		"""Encode image data uri.

		Purpose:
		    Encodes local binary content into a text representation required by xAI request payloads.

		Args:
		    image_path (str): Image path supplied to the xAI workflow.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'image_path', image_path )
			path = Path( image_path )

			if not path.exists( ):
				raise FileNotFoundError( f'Image file was not found: {image_path}' )

			suffix = path.suffix.lower( ).replace( '.', '' )
			if suffix == 'jpg':
				suffix = 'jpeg'

			if suffix not in [ 'jpeg', 'png', 'webp' ]:
				suffix = 'jpeg'

			image_bytes = path.read_bytes( )
			encoded = base64.b64encode( image_bytes ).decode( 'utf-8' )
			return f'data:image/{suffix};base64,{encoded}'
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'encode_image_data_uri( self, image_path )'
			raise ex

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

		Purpose:
		    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			if self.response is None:
				return None

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

			output = getattr( self.response, 'output', None )
			if not isinstance( output, list ):
				return None

			text_parts: List[ str ] = [ ]
			for item in output:
				if getattr( item, 'type', None ) != 'message':
					continue

				content = getattr( item, 'content', None )
				if not isinstance( content, list ):
					continue

				for block in content:
					if getattr( block, 'type', None ) == 'output_text':
						text = getattr( block, 'text', None )
						if text:
							text_parts.append( text )

			return ''.join( text_parts ).strip( ) if text_parts else None
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'get_output_text( self )'
			raise ex

	def normalize_image_result( self ) -> Any:
		"""Normalize image result.

		Purpose:
		    Provides normalize image result behavior for the Images workflow while preserving provider request and response state.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			if self.response is None:
				return None

			data = getattr( self.response, 'data', None )
			if isinstance( data, list ) and len( data ) > 0:
				results: List[ Any ] = [ ]

				for item in data:
					url = getattr( item, 'url', None )
					b64_json = getattr( item, 'b64_json', None )

					if url:
						results.append( url )
						continue

					if b64_json:
						results.append( b64_json )
						continue

					results.append( item )

				return results[ 0 ] if len( results ) == 1 else results

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

			base64_value = getattr( self.response, 'base64', None )
			if base64_value:
				return base64_value

			image_bytes = getattr( self.response, 'image', None )
			if image_bytes:
				return image_bytes

			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'normalize_image_result( self )'
			raise ex

	def build_generation_request( self ) -> Dict[ str, Any ]:
		"""Build generation request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', self.prompt )
			throw_if( 'model', self.model )
			self.request = {
					'model': self.model,
					'prompt': self.prompt,
			}
			self.extra_body = { }

			if isinstance( self.number, int ) and self.number > 0:
				self.request[ 'n' ] = self.number

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

			if self.aspect_ratio:
				self.extra_body[ 'aspect_ratio' ] = self.aspect_ratio

			if self.resolution:
				self.extra_body[ 'resolution' ] = self.resolution

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

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'build_generation_request( self )'
			raise ex

	def build_edit_request( self ) -> Dict[ str, Any ]:
		"""Build edit request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', self.prompt )
			throw_if( 'model', self.model )
			throw_if( 'image_url', self.image_url )
			self.request = {
					'model': self.model,
					'prompt': self.prompt,
					'image': {
							'type': 'image_url',
							'url': self.image_url,
					},
			}

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

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

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

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'build_edit_request( self )'
			raise ex

	def build_analysis_request( self ) -> Dict[ str, Any ]:
		"""Build analysis request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', self.prompt )
			throw_if( 'model', self.model )
			throw_if( 'image_url', self.image_url )
			self.request = {
					'model': self.model,
					'input': [
							{
									'role': 'user',
									'content': [
											{
													'type': 'input_image',
													'image_url': self.image_url,
											},
											{
													'type': 'input_text',
													'text': self.prompt,
											},
									],
							},
					],
			}

			if self.detail:
				self.request[ 'input' ][ 0 ][ 'content' ][ 0 ][ 'detail' ] = self.detail

			if isinstance( self.max_output_tokens, int ) and self.max_output_tokens > 0:
				self.request[ 'max_output_tokens' ] = self.max_output_tokens

			if self.temperature is not None:
				self.request[ 'temperature' ] = self.temperature

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

			if self.store is not None:
				self.request[ 'store' ] = self.store

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'build_analysis_request( self )'
			raise ex

	def generate( self, prompt: str, model: str = 'grok-imagine-image', number: int = None,
			size: str = None, quality: str = None, style: str = None, fmt: str = None,
			mime_type: str = None, compression: float = None, background: str = None,
			aspect_ratio: str = None, response_modalities: str = None, temperature: float = None,
			top_p: float = None, top_k: int = None, frequency: float = None, presence: float = None,
			max_tokens: int = None, instruct: str = None, tools: List[ Any ] = None,
			tool_choice: str = None, include: List[ str ] = None,
			allowed_domains: List[ str ] = None,
			store: bool = None, stream: bool = None, is_parallel: bool = None,
			max_tools: int = None,
			max_searches: int = None, grounded: bool = False, image_search: bool = False,
			response_format: str = None, **kwargs: Any ) -> Any:
		"""Generate.

		Purpose:
		    Provides generate behavior for the Images workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    number (int): Number supplied to the xAI workflow.
		    size (str): Size supplied to the xAI workflow.
		    quality (str): Quality supplied to the xAI workflow.
		    style (str): Style supplied to the xAI workflow.
		    fmt (str): Fmt supplied to the xAI workflow.
		    mime_type (str): Mime type supplied to the xAI workflow.
		    compression (float): Compression supplied to the xAI workflow.
		    background (str): Background supplied to the xAI workflow.
		    aspect_ratio (str): Aspect ratio supplied to the xAI workflow.
		    response_modalities (str): Response modalities supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    top_k (int): Top k supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    tools (List[Any]): Tools supplied to the xAI workflow.
		    tool_choice (str): Tool choice supplied to the xAI workflow.
		    include (List[str]): Include supplied to the xAI workflow.
		    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    is_parallel (bool): Is parallel supplied to the xAI workflow.
		    max_tools (int): Max tools supplied to the xAI workflow.
		    max_searches (int): Max searches supplied to the xAI workflow.
		    grounded (bool): Grounded supplied to the xAI workflow.
		    image_search (bool): Image search supplied to the xAI workflow.
		    response_format (str): Response format supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.prompt = prompt
			self.model = model
			self.number = number
			self.size = size
			self.resolution = self.normalize_resolution( size )
			self.quality = quality
			self.style = style
			self.response_format = self.normalize_response_format(
				response_format or fmt or mime_type )
			self.mime_type = mime_type
			self.compression = compression
			self.background = background
			self.aspect_ratio = aspect_ratio
			self.response_modalities = response_modalities
			self.temperature = temperature
			self.top_percent = top_p
			self.top_k = top_k
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_output_tokens = max_tokens
			self.instructions = instruct
			self.tools = tools if tools is not None else [ ]
			self.tool_choice = tool_choice
			self.include = include if include is not None else [ ]
			self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
			self.store = store
			self.stream = stream
			self.is_parallel = is_parallel
			self.max_tools = max_tools
			self.max_searches = max_searches
			self.grounded = grounded
			self.image_search = image_search
			self.extra_kwargs = kwargs or { }
			self.initialize_client( )
			self.build_generation_request( )
			self.response = self.client.images.generate( **self.request )
			self.output = self.normalize_image_result( )
			return self.output
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'generate( self, prompt: str, model: str )'
			raise ex

	def generate_image( self, prompt: str, model: str = 'grok-imagine-image',
			number: int = None, size: str = None, quality: str = None, style: str = None,
			fmt: str = None, mime_type: str = None, compression: float = None,
			background: str = None, aspect_ratio: str = None,
			response_modalities: str = None, **kwargs: Any ) -> Any:
		"""Generate image.

		Purpose:
		    Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    number (int): Number supplied to the xAI workflow.
		    size (str): Size supplied to the xAI workflow.
		    quality (str): Quality supplied to the xAI workflow.
		    style (str): Style supplied to the xAI workflow.
		    fmt (str): Fmt supplied to the xAI workflow.
		    mime_type (str): Mime type supplied to the xAI workflow.
		    compression (float): Compression supplied to the xAI workflow.
		    background (str): Background supplied to the xAI workflow.
		    aspect_ratio (str): Aspect ratio supplied to the xAI workflow.
		    response_modalities (str): Response modalities supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			return self.generate( prompt=prompt, model=model, number=number, size=size,
				quality=quality, style=style, fmt=fmt, mime_type=mime_type,
				compression=compression, background=background, aspect_ratio=aspect_ratio,
				response_modalities=response_modalities, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'generate_image( self, prompt: str, model: str )'
			raise ex

	def create( self, prompt: str, model: str = 'grok-imagine-image', resolution: str = None,
			aspect_ratio: str = None, format: str = None, number: int = None,
			quality: str = None, style: str = None, **kwargs: Any ) -> Any:
		"""Create.

		Purpose:
		    Provides create behavior for the Images workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    resolution (str): Resolution supplied to the xAI workflow.
		    aspect_ratio (str): Aspect ratio supplied to the xAI workflow.
		    format (str): Format supplied to the xAI workflow.
		    number (int): Number supplied to the xAI workflow.
		    quality (str): Quality supplied to the xAI workflow.
		    style (str): Style supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			return self.generate( prompt=prompt, model=model, number=number,
				size=resolution, quality=quality, style=style, fmt=format,
				aspect_ratio=aspect_ratio, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'create( self, prompt: str, model: str )'
			raise ex

	def create_image( self, prompt: str, model: str = 'grok-imagine-image',
			**kwargs: Any ) -> Any:
		"""Create image.

		Purpose:
		    Creates the requested xAI resource using validated names, paths, or configuration values.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			return self.generate( prompt=prompt, model=model, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'create_image( self, prompt: str, model: str )'
			raise ex

	def edit( self, image_path: str = None, prompt: str = None, model: str = 'grok-imagine-image',
			aspect_ratio: str = None, resolution: str = None, quality: str = None,
			response_format: str = None, path: str = None, mask_path: str = None, mask: str = None,
			size: str = None, fmt: str = None, mime_type: str = None, **kwargs: Any ) -> Any:
		"""Edit.

		Purpose:
		    Provides edit behavior for the Images workflow while preserving provider request and response state.

		Args:
		    image_path (str): Image path supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    aspect_ratio (str): Aspect ratio supplied to the xAI workflow.
		    resolution (str): Resolution supplied to the xAI workflow.
		    quality (str): Quality supplied to the xAI workflow.
		    response_format (str): Response format supplied to the xAI workflow.
		    path (str): Path supplied to the xAI workflow.
		    mask_path (str): Mask path supplied to the xAI workflow.
		    mask (str): Mask supplied to the xAI workflow.
		    size (str): Size supplied to the xAI workflow.
		    fmt (str): Fmt supplied to the xAI workflow.
		    mime_type (str): Mime type supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			self.image_path = image_path or path
			throw_if( 'image_path', self.image_path )
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.prompt = prompt
			self.model = model
			self.aspect_ratio = aspect_ratio
			self.resolution = self.normalize_resolution( resolution or size )
			self.quality = quality
			self.response_format = self.normalize_response_format(
				response_format or fmt or mime_type )
			self.mask_path = mask_path or mask
			self.extra_kwargs = kwargs or { }

			if str( self.image_path ).startswith( 'http://' ) or str(
					self.image_path ).startswith( 'https://' ):
				self.image_url = str( self.image_path )
			elif str( self.image_path ).startswith( 'data:image/' ):
				self.image_url = str( self.image_path )
			else:
				self.image_url = self.encode_image_data_uri( self.image_path )

			self.build_edit_request( )
			self.response = requests.post(
				url=f'{self.base_url.rstrip( "/" )}/images/edits',
				headers={
						'Authorization': f'Bearer {self.api_key}',
						'Content-Type': 'application/json',
				},
				json=self.request,
				timeout=self.timeout or 3600,
			)
			self.response.raise_for_status( )
			self.output = self.response.json( )
			return self.output
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'edit( self, image_path: str, prompt: str )'
			raise ex

	def edit_image( self, image_path: str = None, prompt: str = None,
			model: str = 'grok-imagine-image', **kwargs: Any ) -> Any:
		"""Edit image.

		Purpose:
		    Provides edit image behavior for the Images workflow while preserving provider request and response state.

		Args:
		    image_path (str): Image path supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			return self.edit( image_path=image_path, prompt=prompt, model=model, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'edit_image( self, image_path: str, prompt: str )'
			raise ex

	def modify( self, image_path: str = None, prompt: str = None,
			model: str = 'grok-imagine-image', **kwargs: Any ) -> Any:
		"""Modify.

		Purpose:
		    Provides modify behavior for the Images workflow while preserving provider request and response state.

		Args:
		    image_path (str): Image path supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			return self.edit( image_path=image_path, prompt=prompt, model=model, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'modify( self, image_path: str, prompt: str )'
			raise ex

	def generate_edit( self, image_path: str = None, prompt: str = None,
			model: str = 'grok-imagine-image', **kwargs: Any ) -> Any:
		"""Generate edit.

		Purpose:
		    Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

		Args:
		    image_path (str): Image path supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			return self.edit( image_path=image_path, prompt=prompt, model=model, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'generate_edit( self, image_path: str, prompt: str )'
			raise ex

	def analyze( self, prompt: str, image_url: str = None, model: str = 'grok-4.20-reasoning',
			max_output_tokens: int = 10000, temperature: float = None, top_p: float = None,
			detail: str = 'high', image_path: str = None, path: str = None, store: bool = False,
			**kwargs: Any ) -> str | None:
		"""Analyze.

		Purpose:
		    Provides analyze behavior for the Images workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    image_url (str): Image url supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    max_output_tokens (int): Max output tokens supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    detail (str): Detail supplied to the xAI workflow.
		    image_path (str): Image path supplied to the xAI workflow.
		    path (str): Path supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'model', model )
			self.prompt = prompt
			self.model = model
			self.image_path = image_path or path
			self.detail = detail
			self.max_output_tokens = max_output_tokens
			self.temperature = temperature
			self.top_percent = top_p
			self.store = store
			self.extra_kwargs = kwargs or { }

			if image_url:
				self.image_url = image_url
			elif self.image_path:
				self.image_url = self.encode_image_data_uri( self.image_path )
			else:
				raise ValueError( 'Either image_url, image_path, or path is required.' )

			self.initialize_client( )
			self.build_analysis_request( )
			self.response = self.client.responses.create( **self.request )
			self.output = self.get_output_text( )
			return self.output
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'analyze( self, prompt: str, image_url: str )'
			raise ex

	def analyze_image( self, prompt: str, image_url: str = None, model: str = 'grok-4.20-reasoning',
			image_path: str = None, path: str = None, **kwargs: Any ) -> str | None:
		"""Analyze image.

		Purpose:
		    Provides analyze image behavior for the Images workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    image_url (str): Image url supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    image_path (str): Image path supplied to the xAI workflow.
		    path (str): Path supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			return self.analyze( prompt=prompt, image_url=image_url, model=model,
				image_path=image_path, path=path, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'analyze_image( self, prompt: str, image_url: str )'
			raise ex

	def vision( self, prompt: str, image_url: str = None, model: str = 'grok-4.20-reasoning',
			image_path: str = None, path: str = None, **kwargs: Any ) -> str | None:
		"""Vision.

		Purpose:
		    Provides vision behavior for the Images workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    image_url (str): Image url supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    image_path (str): Image path supplied to the xAI workflow.
		    path (str): Path supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			return self.analyze( prompt=prompt, image_url=image_url, model=model,
				image_path=image_path, path=path, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'vision( self, prompt: str, image_url: str )'
			raise ex

	def describe( self, prompt: str, image_url: str = None, model: str = 'grok-4.20-reasoning',
			image_path: str = None, path: str = None, **kwargs: Any ) -> str | None:
		"""Describe.

		Purpose:
		    Provides describe behavior for the Images workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    image_url (str): Image url supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    image_path (str): Image path supplied to the xAI workflow.
		    path (str): Path supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			return self.analyze( prompt=prompt, image_url=image_url, model=model,
				image_path=image_path, path=path, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Images'
			ex.method = 'describe( self, prompt: str, image_url: str )'
			raise ex

	def __dir__( self ) -> List[ str ] | None:
		"""Dir.

		Purpose:
		    Provides dir behavior for the Images workflow while preserving provider request and response state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'api_key',
				'base_url',
				'client',
				'model',
				'prompt',
				'number',
				'aspect_ratio',
				'resolution',
				'size',
				'quality',
				'style',
				'detail',
				'response_format',
				'mime_type',
				'compression',
				'background',
				'response_modalities',
				'max_output_tokens',
				'temperature',
				'top_percent',
				'frequency_penalty',
				'presence_penalty',
				'tools',
				'tool_choice',
				'include',
				'allowed_domains',
				'store',
				'stream',
				'is_parallel',
				'max_tools',
				'max_searches',
				'image_path',
				'image_url',
				'mask_path',
				'request',
				'response',
				'output',
				'extra_body',
				'extra_kwargs',
				'model_options',
				'analysis_model_options',
				'tool_options',
				'include_options',
				'choice_options',
				'aspect_options',
				'size_options',
				'quality_options',
				'style_options',
				'backcolor_options',
				'detail_options',
				'format_options',
				'mime_options',
				'output_options',
				'initialize_client',
				'normalize_resolution',
				'normalize_response_format',
				'encode_image_data_uri',
				'get_output_text',
				'normalize_image_result',
				'build_generation_request',
				'build_edit_request',
				'build_analysis_request',
				'generate',
				'generate_image',
				'create',
				'create_image',
				'edit',
				'edit_image',
				'modify',
				'generate_edit',
				'analyze',
				'analyze_image',
				'vision',
				'describe',
		]

model_options property

model_options: List[str]

Model options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

analysis_model_options property

analysis_model_options: List[str]

Analysis model options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

tool_options property

tool_options: List[str] | None

Tool options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

include_options property

include_options: List[str] | None

Include options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

choice_options property

choice_options: List[str] | None

Choice options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str] | None

List[str] | None: Result produced by the xAI workflow.

aspect_options property

aspect_options: List[str]

Aspect options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

size_options property

size_options: List[str]

Size options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

quality_options property

quality_options: List[str]

Quality options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

style_options property

style_options: List[str]

Style options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

backcolor_options property

backcolor_options: List[str]

Backcolor options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

detail_options property

detail_options: List[str]

Detail options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

format_options property

format_options: List[str]

Format options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

mime_options property

mime_options: List[str]

Mime options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

output_options property

output_options: List[str]

Output options.

Purpose

Returns the configured option values exposed by the Images workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

initialize_client

initialize_client() -> None

Initialize client.

Purpose

Provides initialize client behavior for the Images workflow while preserving provider request and response state.

Source code in grok.py
def initialize_client( self ) -> None:
	"""Initialize client.

	Purpose:
	    Provides initialize client behavior for the Images workflow while preserving provider request and response state.
	"""
	try:
		throw_if( 'api_key', self.api_key )
		throw_if( 'base_url', self.base_url )
		self.client = OpenAI( api_key=cfg.XAI_API_KEY, base_url=self.base_url )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'initialize_client( self )'
		raise ex

normalize_resolution

normalize_resolution(value: str = None) -> str | None

Normalize resolution.

Purpose

Provides normalize resolution behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
value str

Value supplied to the xAI workflow.

None

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def normalize_resolution( self, value: str = None ) -> str | None:
	"""Normalize resolution.

	Purpose:
	    Provides normalize resolution behavior for the Images workflow while preserving provider request and response state.

	Args:
	    value (str): Value supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		if value is None:
			return None

		resolution = str( value ).strip( ).lower( )
		if resolution in [ '1k', '2k' ]:
			return resolution

		return None
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'normalize_resolution( self, value )'
		raise ex

normalize_response_format

normalize_response_format(value: str = None) -> str | None

Normalize response format.

Purpose

Provides normalize response format behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
value str

Value supplied to the xAI workflow.

None

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def normalize_response_format( self, value: str = None ) -> str | None:
	"""Normalize response format.

	Purpose:
	    Provides normalize response format behavior for the Images workflow while preserving provider request and response state.

	Args:
	    value (str): Value supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		if value is None:
			return None

		response_format = str( value ).strip( ).lower( )
		if response_format in [ 'url', 'b64_json' ]:
			return response_format

		if response_format == 'base64':
			return 'b64_json'

		return None
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'normalize_response_format( self, value )'
		raise ex

encode_image_data_uri

encode_image_data_uri(image_path: str) -> str

Encode image data uri.

Purpose

Encodes local binary content into a text representation required by xAI request payloads.

Parameters:

Name Type Description Default
image_path str

Image path supplied to the xAI workflow.

required

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def encode_image_data_uri( self, image_path: str ) -> str:
	"""Encode image data uri.

	Purpose:
	    Encodes local binary content into a text representation required by xAI request payloads.

	Args:
	    image_path (str): Image path supplied to the xAI workflow.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'image_path', image_path )
		path = Path( image_path )

		if not path.exists( ):
			raise FileNotFoundError( f'Image file was not found: {image_path}' )

		suffix = path.suffix.lower( ).replace( '.', '' )
		if suffix == 'jpg':
			suffix = 'jpeg'

		if suffix not in [ 'jpeg', 'png', 'webp' ]:
			suffix = 'jpeg'

		image_bytes = path.read_bytes( )
		encoded = base64.b64encode( image_bytes ).decode( 'utf-8' )
		return f'data:image/{suffix};base64,{encoded}'
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'encode_image_data_uri( self, image_path )'
		raise ex

get_output_text

get_output_text() -> str | None

Get output text.

Purpose

Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

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

	Purpose:
	    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		if self.response is None:
			return None

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

		output = getattr( self.response, 'output', None )
		if not isinstance( output, list ):
			return None

		text_parts: List[ str ] = [ ]
		for item in output:
			if getattr( item, 'type', None ) != 'message':
				continue

			content = getattr( item, 'content', None )
			if not isinstance( content, list ):
				continue

			for block in content:
				if getattr( block, 'type', None ) == 'output_text':
					text = getattr( block, 'text', None )
					if text:
						text_parts.append( text )

		return ''.join( text_parts ).strip( ) if text_parts else None
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'get_output_text( self )'
		raise ex

normalize_image_result

normalize_image_result() -> Any

Normalize image result.

Purpose

Provides normalize image result behavior for the Images workflow while preserving provider request and response state.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def normalize_image_result( self ) -> Any:
	"""Normalize image result.

	Purpose:
	    Provides normalize image result behavior for the Images workflow while preserving provider request and response state.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		if self.response is None:
			return None

		data = getattr( self.response, 'data', None )
		if isinstance( data, list ) and len( data ) > 0:
			results: List[ Any ] = [ ]

			for item in data:
				url = getattr( item, 'url', None )
				b64_json = getattr( item, 'b64_json', None )

				if url:
					results.append( url )
					continue

				if b64_json:
					results.append( b64_json )
					continue

				results.append( item )

			return results[ 0 ] if len( results ) == 1 else results

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

		base64_value = getattr( self.response, 'base64', None )
		if base64_value:
			return base64_value

		image_bytes = getattr( self.response, 'image', None )
		if image_bytes:
			return image_bytes

		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'normalize_image_result( self )'
		raise ex

build_generation_request

build_generation_request() -> Dict[str, Any]

Build generation request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_generation_request( self ) -> Dict[ str, Any ]:
	"""Build generation request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', self.prompt )
		throw_if( 'model', self.model )
		self.request = {
				'model': self.model,
				'prompt': self.prompt,
		}
		self.extra_body = { }

		if isinstance( self.number, int ) and self.number > 0:
			self.request[ 'n' ] = self.number

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

		if self.aspect_ratio:
			self.extra_body[ 'aspect_ratio' ] = self.aspect_ratio

		if self.resolution:
			self.extra_body[ 'resolution' ] = self.resolution

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

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'build_generation_request( self )'
		raise ex

build_edit_request

build_edit_request() -> Dict[str, Any]

Build edit request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_edit_request( self ) -> Dict[ str, Any ]:
	"""Build edit request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', self.prompt )
		throw_if( 'model', self.model )
		throw_if( 'image_url', self.image_url )
		self.request = {
				'model': self.model,
				'prompt': self.prompt,
				'image': {
						'type': 'image_url',
						'url': self.image_url,
				},
		}

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

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

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

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'build_edit_request( self )'
		raise ex

build_analysis_request

build_analysis_request() -> Dict[str, Any]

Build analysis request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_analysis_request( self ) -> Dict[ str, Any ]:
	"""Build analysis request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', self.prompt )
		throw_if( 'model', self.model )
		throw_if( 'image_url', self.image_url )
		self.request = {
				'model': self.model,
				'input': [
						{
								'role': 'user',
								'content': [
										{
												'type': 'input_image',
												'image_url': self.image_url,
										},
										{
												'type': 'input_text',
												'text': self.prompt,
										},
								],
						},
				],
		}

		if self.detail:
			self.request[ 'input' ][ 0 ][ 'content' ][ 0 ][ 'detail' ] = self.detail

		if isinstance( self.max_output_tokens, int ) and self.max_output_tokens > 0:
			self.request[ 'max_output_tokens' ] = self.max_output_tokens

		if self.temperature is not None:
			self.request[ 'temperature' ] = self.temperature

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

		if self.store is not None:
			self.request[ 'store' ] = self.store

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'build_analysis_request( self )'
		raise ex

generate

generate(
    prompt: str,
    model: str = "grok-imagine-image",
    number: int = None,
    size: str = None,
    quality: str = None,
    style: str = None,
    fmt: str = None,
    mime_type: str = None,
    compression: float = None,
    background: str = None,
    aspect_ratio: str = None,
    response_modalities: str = None,
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    instruct: str = None,
    tools: List[Any] = None,
    tool_choice: str = None,
    include: List[str] = None,
    allowed_domains: List[str] = None,
    store: bool = None,
    stream: bool = None,
    is_parallel: bool = None,
    max_tools: int = None,
    max_searches: int = None,
    grounded: bool = False,
    image_search: bool = False,
    response_format: str = None,
    **kwargs: Any
) -> Any

Generate.

Purpose

Provides generate behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-imagine-image'
number int

Number supplied to the xAI workflow.

None
size str

Size supplied to the xAI workflow.

None
quality str

Quality supplied to the xAI workflow.

None
style str

Style supplied to the xAI workflow.

None
fmt str

Fmt supplied to the xAI workflow.

None
mime_type str

Mime type supplied to the xAI workflow.

None
compression float

Compression supplied to the xAI workflow.

None
background str

Background supplied to the xAI workflow.

None
aspect_ratio str

Aspect ratio supplied to the xAI workflow.

None
response_modalities str

Response modalities supplied to the xAI workflow.

None
temperature float

Temperature supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
top_k int

Top k supplied to the xAI workflow.

None
frequency float

Frequency supplied to the xAI workflow.

None
presence float

Presence supplied to the xAI workflow.

None
max_tokens int

Max tokens supplied to the xAI workflow.

None
instruct str

Instruct supplied to the xAI workflow.

None
tools List[Any]

Tools supplied to the xAI workflow.

None
tool_choice str

Tool choice supplied to the xAI workflow.

None
include List[str]

Include supplied to the xAI workflow.

None
allowed_domains List[str]

Allowed domains supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

None
stream bool

Stream supplied to the xAI workflow.

None
is_parallel bool

Is parallel supplied to the xAI workflow.

None
max_tools int

Max tools supplied to the xAI workflow.

None
max_searches int

Max searches supplied to the xAI workflow.

None
grounded bool

Grounded supplied to the xAI workflow.

False
image_search bool

Image search supplied to the xAI workflow.

False
response_format str

Response format supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def generate( self, prompt: str, model: str = 'grok-imagine-image', number: int = None,
		size: str = None, quality: str = None, style: str = None, fmt: str = None,
		mime_type: str = None, compression: float = None, background: str = None,
		aspect_ratio: str = None, response_modalities: str = None, temperature: float = None,
		top_p: float = None, top_k: int = None, frequency: float = None, presence: float = None,
		max_tokens: int = None, instruct: str = None, tools: List[ Any ] = None,
		tool_choice: str = None, include: List[ str ] = None,
		allowed_domains: List[ str ] = None,
		store: bool = None, stream: bool = None, is_parallel: bool = None,
		max_tools: int = None,
		max_searches: int = None, grounded: bool = False, image_search: bool = False,
		response_format: str = None, **kwargs: Any ) -> Any:
	"""Generate.

	Purpose:
	    Provides generate behavior for the Images workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    number (int): Number supplied to the xAI workflow.
	    size (str): Size supplied to the xAI workflow.
	    quality (str): Quality supplied to the xAI workflow.
	    style (str): Style supplied to the xAI workflow.
	    fmt (str): Fmt supplied to the xAI workflow.
	    mime_type (str): Mime type supplied to the xAI workflow.
	    compression (float): Compression supplied to the xAI workflow.
	    background (str): Background supplied to the xAI workflow.
	    aspect_ratio (str): Aspect ratio supplied to the xAI workflow.
	    response_modalities (str): Response modalities supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    top_k (int): Top k supplied to the xAI workflow.
	    frequency (float): Frequency supplied to the xAI workflow.
	    presence (float): Presence supplied to the xAI workflow.
	    max_tokens (int): Max tokens supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    tools (List[Any]): Tools supplied to the xAI workflow.
	    tool_choice (str): Tool choice supplied to the xAI workflow.
	    include (List[str]): Include supplied to the xAI workflow.
	    allowed_domains (List[str]): Allowed domains supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    stream (bool): Stream supplied to the xAI workflow.
	    is_parallel (bool): Is parallel supplied to the xAI workflow.
	    max_tools (int): Max tools supplied to the xAI workflow.
	    max_searches (int): Max searches supplied to the xAI workflow.
	    grounded (bool): Grounded supplied to the xAI workflow.
	    image_search (bool): Image search supplied to the xAI workflow.
	    response_format (str): Response format supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.prompt = prompt
		self.model = model
		self.number = number
		self.size = size
		self.resolution = self.normalize_resolution( size )
		self.quality = quality
		self.style = style
		self.response_format = self.normalize_response_format(
			response_format or fmt or mime_type )
		self.mime_type = mime_type
		self.compression = compression
		self.background = background
		self.aspect_ratio = aspect_ratio
		self.response_modalities = response_modalities
		self.temperature = temperature
		self.top_percent = top_p
		self.top_k = top_k
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_output_tokens = max_tokens
		self.instructions = instruct
		self.tools = tools if tools is not None else [ ]
		self.tool_choice = tool_choice
		self.include = include if include is not None else [ ]
		self.allowed_domains = allowed_domains if allowed_domains is not None else [ ]
		self.store = store
		self.stream = stream
		self.is_parallel = is_parallel
		self.max_tools = max_tools
		self.max_searches = max_searches
		self.grounded = grounded
		self.image_search = image_search
		self.extra_kwargs = kwargs or { }
		self.initialize_client( )
		self.build_generation_request( )
		self.response = self.client.images.generate( **self.request )
		self.output = self.normalize_image_result( )
		return self.output
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'generate( self, prompt: str, model: str )'
		raise ex

generate_image

generate_image(
    prompt: str,
    model: str = "grok-imagine-image",
    number: int = None,
    size: str = None,
    quality: str = None,
    style: str = None,
    fmt: str = None,
    mime_type: str = None,
    compression: float = None,
    background: str = None,
    aspect_ratio: str = None,
    response_modalities: str = None,
    **kwargs: Any
) -> Any

Generate image.

Purpose

Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-imagine-image'
number int

Number supplied to the xAI workflow.

None
size str

Size supplied to the xAI workflow.

None
quality str

Quality supplied to the xAI workflow.

None
style str

Style supplied to the xAI workflow.

None
fmt str

Fmt supplied to the xAI workflow.

None
mime_type str

Mime type supplied to the xAI workflow.

None
compression float

Compression supplied to the xAI workflow.

None
background str

Background supplied to the xAI workflow.

None
aspect_ratio str

Aspect ratio supplied to the xAI workflow.

None
response_modalities str

Response modalities supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def generate_image( self, prompt: str, model: str = 'grok-imagine-image',
		number: int = None, size: str = None, quality: str = None, style: str = None,
		fmt: str = None, mime_type: str = None, compression: float = None,
		background: str = None, aspect_ratio: str = None,
		response_modalities: str = None, **kwargs: Any ) -> Any:
	"""Generate image.

	Purpose:
	    Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    number (int): Number supplied to the xAI workflow.
	    size (str): Size supplied to the xAI workflow.
	    quality (str): Quality supplied to the xAI workflow.
	    style (str): Style supplied to the xAI workflow.
	    fmt (str): Fmt supplied to the xAI workflow.
	    mime_type (str): Mime type supplied to the xAI workflow.
	    compression (float): Compression supplied to the xAI workflow.
	    background (str): Background supplied to the xAI workflow.
	    aspect_ratio (str): Aspect ratio supplied to the xAI workflow.
	    response_modalities (str): Response modalities supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		return self.generate( prompt=prompt, model=model, number=number, size=size,
			quality=quality, style=style, fmt=fmt, mime_type=mime_type,
			compression=compression, background=background, aspect_ratio=aspect_ratio,
			response_modalities=response_modalities, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'generate_image( self, prompt: str, model: str )'
		raise ex

create

create(
    prompt: str,
    model: str = "grok-imagine-image",
    resolution: str = None,
    aspect_ratio: str = None,
    format: str = None,
    number: int = None,
    quality: str = None,
    style: str = None,
    **kwargs: Any
) -> Any

Create.

Purpose

Provides create behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-imagine-image'
resolution str

Resolution supplied to the xAI workflow.

None
aspect_ratio str

Aspect ratio supplied to the xAI workflow.

None
format str

Format supplied to the xAI workflow.

None
number int

Number supplied to the xAI workflow.

None
quality str

Quality supplied to the xAI workflow.

None
style str

Style supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def create( self, prompt: str, model: str = 'grok-imagine-image', resolution: str = None,
		aspect_ratio: str = None, format: str = None, number: int = None,
		quality: str = None, style: str = None, **kwargs: Any ) -> Any:
	"""Create.

	Purpose:
	    Provides create behavior for the Images workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    resolution (str): Resolution supplied to the xAI workflow.
	    aspect_ratio (str): Aspect ratio supplied to the xAI workflow.
	    format (str): Format supplied to the xAI workflow.
	    number (int): Number supplied to the xAI workflow.
	    quality (str): Quality supplied to the xAI workflow.
	    style (str): Style supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		return self.generate( prompt=prompt, model=model, number=number,
			size=resolution, quality=quality, style=style, fmt=format,
			aspect_ratio=aspect_ratio, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'create( self, prompt: str, model: str )'
		raise ex

create_image

create_image(
    prompt: str,
    model: str = "grok-imagine-image",
    **kwargs: Any
) -> Any

Create image.

Purpose

Creates the requested xAI resource using validated names, paths, or configuration values.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-imagine-image'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def create_image( self, prompt: str, model: str = 'grok-imagine-image',
		**kwargs: Any ) -> Any:
	"""Create image.

	Purpose:
	    Creates the requested xAI resource using validated names, paths, or configuration values.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		return self.generate( prompt=prompt, model=model, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'create_image( self, prompt: str, model: str )'
		raise ex

edit

edit(
    image_path: str = None,
    prompt: str = None,
    model: str = "grok-imagine-image",
    aspect_ratio: str = None,
    resolution: str = None,
    quality: str = None,
    response_format: str = None,
    path: str = None,
    mask_path: str = None,
    mask: str = None,
    size: str = None,
    fmt: str = None,
    mime_type: str = None,
    **kwargs: Any
) -> Any

Edit.

Purpose

Provides edit behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
image_path str

Image path supplied to the xAI workflow.

None
prompt str

Prompt supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-imagine-image'
aspect_ratio str

Aspect ratio supplied to the xAI workflow.

None
resolution str

Resolution supplied to the xAI workflow.

None
quality str

Quality supplied to the xAI workflow.

None
response_format str

Response format supplied to the xAI workflow.

None
path str

Path supplied to the xAI workflow.

None
mask_path str

Mask path supplied to the xAI workflow.

None
mask str

Mask supplied to the xAI workflow.

None
size str

Size supplied to the xAI workflow.

None
fmt str

Fmt supplied to the xAI workflow.

None
mime_type str

Mime type supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def edit( self, image_path: str = None, prompt: str = None, model: str = 'grok-imagine-image',
		aspect_ratio: str = None, resolution: str = None, quality: str = None,
		response_format: str = None, path: str = None, mask_path: str = None, mask: str = None,
		size: str = None, fmt: str = None, mime_type: str = None, **kwargs: Any ) -> Any:
	"""Edit.

	Purpose:
	    Provides edit behavior for the Images workflow while preserving provider request and response state.

	Args:
	    image_path (str): Image path supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    aspect_ratio (str): Aspect ratio supplied to the xAI workflow.
	    resolution (str): Resolution supplied to the xAI workflow.
	    quality (str): Quality supplied to the xAI workflow.
	    response_format (str): Response format supplied to the xAI workflow.
	    path (str): Path supplied to the xAI workflow.
	    mask_path (str): Mask path supplied to the xAI workflow.
	    mask (str): Mask supplied to the xAI workflow.
	    size (str): Size supplied to the xAI workflow.
	    fmt (str): Fmt supplied to the xAI workflow.
	    mime_type (str): Mime type supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		self.image_path = image_path or path
		throw_if( 'image_path', self.image_path )
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.prompt = prompt
		self.model = model
		self.aspect_ratio = aspect_ratio
		self.resolution = self.normalize_resolution( resolution or size )
		self.quality = quality
		self.response_format = self.normalize_response_format(
			response_format or fmt or mime_type )
		self.mask_path = mask_path or mask
		self.extra_kwargs = kwargs or { }

		if str( self.image_path ).startswith( 'http://' ) or str(
				self.image_path ).startswith( 'https://' ):
			self.image_url = str( self.image_path )
		elif str( self.image_path ).startswith( 'data:image/' ):
			self.image_url = str( self.image_path )
		else:
			self.image_url = self.encode_image_data_uri( self.image_path )

		self.build_edit_request( )
		self.response = requests.post(
			url=f'{self.base_url.rstrip( "/" )}/images/edits',
			headers={
					'Authorization': f'Bearer {self.api_key}',
					'Content-Type': 'application/json',
			},
			json=self.request,
			timeout=self.timeout or 3600,
		)
		self.response.raise_for_status( )
		self.output = self.response.json( )
		return self.output
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'edit( self, image_path: str, prompt: str )'
		raise ex

edit_image

edit_image(
    image_path: str = None,
    prompt: str = None,
    model: str = "grok-imagine-image",
    **kwargs: Any
) -> Any

Edit image.

Purpose

Provides edit image behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
image_path str

Image path supplied to the xAI workflow.

None
prompt str

Prompt supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-imagine-image'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def edit_image( self, image_path: str = None, prompt: str = None,
		model: str = 'grok-imagine-image', **kwargs: Any ) -> Any:
	"""Edit image.

	Purpose:
	    Provides edit image behavior for the Images workflow while preserving provider request and response state.

	Args:
	    image_path (str): Image path supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		return self.edit( image_path=image_path, prompt=prompt, model=model, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'edit_image( self, image_path: str, prompt: str )'
		raise ex

modify

modify(
    image_path: str = None,
    prompt: str = None,
    model: str = "grok-imagine-image",
    **kwargs: Any
) -> Any

Modify.

Purpose

Provides modify behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
image_path str

Image path supplied to the xAI workflow.

None
prompt str

Prompt supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-imagine-image'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def modify( self, image_path: str = None, prompt: str = None,
		model: str = 'grok-imagine-image', **kwargs: Any ) -> Any:
	"""Modify.

	Purpose:
	    Provides modify behavior for the Images workflow while preserving provider request and response state.

	Args:
	    image_path (str): Image path supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		return self.edit( image_path=image_path, prompt=prompt, model=model, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'modify( self, image_path: str, prompt: str )'
		raise ex

generate_edit

generate_edit(
    image_path: str = None,
    prompt: str = None,
    model: str = "grok-imagine-image",
    **kwargs: Any
) -> Any

Generate edit.

Purpose

Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

Parameters:

Name Type Description Default
image_path str

Image path supplied to the xAI workflow.

None
prompt str

Prompt supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-imagine-image'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def generate_edit( self, image_path: str = None, prompt: str = None,
		model: str = 'grok-imagine-image', **kwargs: Any ) -> Any:
	"""Generate edit.

	Purpose:
	    Executes an xAI generation workflow using validated request settings, captures the provider response, and returns displayable output.

	Args:
	    image_path (str): Image path supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		return self.edit( image_path=image_path, prompt=prompt, model=model, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'generate_edit( self, image_path: str, prompt: str )'
		raise ex

analyze

analyze(
    prompt: str,
    image_url: str = None,
    model: str = "grok-4.20-reasoning",
    max_output_tokens: int = 10000,
    temperature: float = None,
    top_p: float = None,
    detail: str = "high",
    image_path: str = None,
    path: str = None,
    store: bool = False,
    **kwargs: Any
) -> str | None

Analyze.

Purpose

Provides analyze behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
image_url str

Image url supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-4.20-reasoning'
max_output_tokens int

Max output tokens supplied to the xAI workflow.

10000
temperature float

Temperature supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
detail str

Detail supplied to the xAI workflow.

'high'
image_path str

Image path supplied to the xAI workflow.

None
path str

Path supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

False
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def analyze( self, prompt: str, image_url: str = None, model: str = 'grok-4.20-reasoning',
		max_output_tokens: int = 10000, temperature: float = None, top_p: float = None,
		detail: str = 'high', image_path: str = None, path: str = None, store: bool = False,
		**kwargs: Any ) -> str | None:
	"""Analyze.

	Purpose:
	    Provides analyze behavior for the Images workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    image_url (str): Image url supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    max_output_tokens (int): Max output tokens supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    detail (str): Detail supplied to the xAI workflow.
	    image_path (str): Image path supplied to the xAI workflow.
	    path (str): Path supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'model', model )
		self.prompt = prompt
		self.model = model
		self.image_path = image_path or path
		self.detail = detail
		self.max_output_tokens = max_output_tokens
		self.temperature = temperature
		self.top_percent = top_p
		self.store = store
		self.extra_kwargs = kwargs or { }

		if image_url:
			self.image_url = image_url
		elif self.image_path:
			self.image_url = self.encode_image_data_uri( self.image_path )
		else:
			raise ValueError( 'Either image_url, image_path, or path is required.' )

		self.initialize_client( )
		self.build_analysis_request( )
		self.response = self.client.responses.create( **self.request )
		self.output = self.get_output_text( )
		return self.output
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'analyze( self, prompt: str, image_url: str )'
		raise ex

analyze_image

analyze_image(
    prompt: str,
    image_url: str = None,
    model: str = "grok-4.20-reasoning",
    image_path: str = None,
    path: str = None,
    **kwargs: Any
) -> str | None

Analyze image.

Purpose

Provides analyze image behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
image_url str

Image url supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-4.20-reasoning'
image_path str

Image path supplied to the xAI workflow.

None
path str

Path supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def analyze_image( self, prompt: str, image_url: str = None, model: str = 'grok-4.20-reasoning',
		image_path: str = None, path: str = None, **kwargs: Any ) -> str | None:
	"""Analyze image.

	Purpose:
	    Provides analyze image behavior for the Images workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    image_url (str): Image url supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    image_path (str): Image path supplied to the xAI workflow.
	    path (str): Path supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		return self.analyze( prompt=prompt, image_url=image_url, model=model,
			image_path=image_path, path=path, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'analyze_image( self, prompt: str, image_url: str )'
		raise ex

vision

vision(
    prompt: str,
    image_url: str = None,
    model: str = "grok-4.20-reasoning",
    image_path: str = None,
    path: str = None,
    **kwargs: Any
) -> str | None

Vision.

Purpose

Provides vision behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
image_url str

Image url supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-4.20-reasoning'
image_path str

Image path supplied to the xAI workflow.

None
path str

Path supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def vision( self, prompt: str, image_url: str = None, model: str = 'grok-4.20-reasoning',
		image_path: str = None, path: str = None, **kwargs: Any ) -> str | None:
	"""Vision.

	Purpose:
	    Provides vision behavior for the Images workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    image_url (str): Image url supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    image_path (str): Image path supplied to the xAI workflow.
	    path (str): Path supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		return self.analyze( prompt=prompt, image_url=image_url, model=model,
			image_path=image_path, path=path, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'vision( self, prompt: str, image_url: str )'
		raise ex

describe

describe(
    prompt: str,
    image_url: str = None,
    model: str = "grok-4.20-reasoning",
    image_path: str = None,
    path: str = None,
    **kwargs: Any
) -> str | None

Describe.

Purpose

Provides describe behavior for the Images workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
image_url str

Image url supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-4.20-reasoning'
image_path str

Image path supplied to the xAI workflow.

None
path str

Path supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def describe( self, prompt: str, image_url: str = None, model: str = 'grok-4.20-reasoning',
		image_path: str = None, path: str = None, **kwargs: Any ) -> str | None:
	"""Describe.

	Purpose:
	    Provides describe behavior for the Images workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    image_url (str): Image url supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    image_path (str): Image path supplied to the xAI workflow.
	    path (str): Path supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		return self.analyze( prompt=prompt, image_url=image_url, model=model,
			image_path=image_path, path=path, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Images'
		ex.method = 'describe( self, prompt: str, image_url: str )'
		raise ex

Files

Bases: Grok

Files workflow wrapper.

Purpose

Manages xAI file upload, retrieval, listing, deletion, and metadata workflows used by document and provider operations.

Attributes:

Name Type Description
client Optional[OpenAI]

Runtime attribute used by the Files workflow.

api_key Optional[str]

Runtime attribute used by the Files workflow.

base_url Optional[str]

Runtime attribute used by the Files workflow.

file_path Optional[str]

Runtime attribute used by the Files workflow.

file_name Optional[str]

Runtime attribute used by the Files workflow.

file_id Optional[str]

Runtime attribute used by the Files workflow.

file_ids Optional[List[str]]

Runtime attribute used by the Files workflow.

purpose Optional[str]

Runtime attribute used by the Files workflow.

model Optional[str]

Runtime attribute used by the Files workflow.

prompt Optional[str]

Runtime attribute used by the Files workflow.

instructions Optional[str]

Runtime attribute used by the Files workflow.

request Optional[Dict[str, Any]]

Runtime attribute used by the Files workflow.

response Optional[Any]

Runtime attribute used by the Files workflow.

content Optional[Any]

Runtime attribute used by the Files workflow.

output_text Optional[str]

Runtime attribute used by the Files workflow.

documents Optional[Dict[str, str]]

Runtime attribute used by the Files workflow.

Source code in grok.py
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
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
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
class Files( Grok ):
	"""Files workflow wrapper.

	Purpose:
	    Manages xAI file upload, retrieval, listing, deletion, and metadata workflows used by document and provider operations.

	Attributes:
	    client: Runtime attribute used by the Files workflow.
	    api_key: Runtime attribute used by the Files workflow.
	    base_url: Runtime attribute used by the Files workflow.
	    file_path: Runtime attribute used by the Files workflow.
	    file_name: Runtime attribute used by the Files workflow.
	    file_id: Runtime attribute used by the Files workflow.
	    file_ids: Runtime attribute used by the Files workflow.
	    purpose: Runtime attribute used by the Files workflow.
	    model: Runtime attribute used by the Files workflow.
	    prompt: Runtime attribute used by the Files workflow.
	    instructions: Runtime attribute used by the Files workflow.
	    request: Runtime attribute used by the Files workflow.
	    response: Runtime attribute used by the Files workflow.
	    content: Runtime attribute used by the Files workflow.
	    output_text: Runtime attribute used by the Files workflow.
	    documents: Runtime attribute used by the Files workflow.
	"""
	client: Optional[ OpenAI ]
	api_key: Optional[ str ]
	base_url: Optional[ str ]
	file_path: Optional[ str ]
	file_name: Optional[ str ]
	file_id: Optional[ str ]
	file_ids: Optional[ List[ str ] ]
	purpose: Optional[ str ]
	model: Optional[ str ]
	prompt: Optional[ str ]
	instructions: Optional[ str ]
	request: Optional[ Dict[ str, Any ] ]
	response: Optional[ Any ]
	content: Optional[ Any ]
	output_text: Optional[ str ]
	documents: Optional[ Dict[ str, str ] ]

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

		Purpose:
		    Initializes Files state with default configuration values and runtime attributes used by later xAI provider calls.
		"""
		super( ).__init__( )
		self.api_key = cfg.XAI_API_KEY
		self.base_url = cfg.XAI_BASE_URL
		self.client = None
		self.model = None
		self.instructions = None
		self.prompt = None
		self.response = None
		self.request = { }
		self.content = None
		self.output_text = None
		self.file_id = None
		self.file_ids = [ ]
		self.file_path = None
		self.file_name = None
		self.file_paths = [ ]
		self.file_names = [ ]
		self.purpose = 'assistants'
		self.response_format = None
		self.temperature = None
		self.top_percent = None
		self.frequency_penalty = None
		self.presence_penalty = None
		self.max_output_tokens = None
		self.store = None
		self.stream = None
		self.include = [ ]
		self.tools = [ ]
		self.tool_choice = None
		self.previous_id = None
		self.previous_response_id = None
		self.conversation_id = None
		self.limit = None
		self.next_token = None
		self.order = None
		self.sort_by = None
		self.filter = None
		self.team_id = None
		self.download_format = None
		self.page_number = None
		self.extra_kwargs = { }
		self.documents = {
				'AccountBalances.csv': 'file_4731bb8c-d8ff-48c0-9dae-3092fbcab214',
				'SF133.csv': 'file_41037cc2-e1f4-4cce-b25a-5c1d1f0172b2',
				'Authority.csv': 'file_cbde06d5-988b-483f-880c-441613bfe54f',
				'Outlays.csv': 'file_78479189-7d47-4edb-9abc-2931172430e9',
		}

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

		Purpose:
		    Returns the configured option values exposed by the Files workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'grok-4.20-reasoning',
				'grok-4.20',
				'grok-4',
				'grok-4-latest',
				'grok-4-fast-reasoning',
				'grok-4-fast-non-reasoning',
				'grok-code-fast-1',
				'grok-3',
				'grok-3-mini',
				'grok-3-fast',
				'grok-3-mini-fast',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Files workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'assistants',
				'batch',
				'fine-tune',
				'user_data',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Files workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'text',
				'json_object',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Files workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'code_interpreter',
		]

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

		Purpose:
		    Returns the configured option values exposed by the Files workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'code_execution_call_output',
		]

	def initialize_client( self ) -> None:
		"""Initialize client.

		Purpose:
		    Provides initialize client behavior for the Files workflow while preserving provider request and response state.
		"""
		try:
			throw_if( 'api_key', self.api_key )
			throw_if( 'base_url', self.base_url )
			self.client = OpenAI( api_key=cfg.XAI_API_KEY, base_url=self.base_url )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'initialize_client( self )'
			raise ex

	def build_headers( self ) -> Dict[ str, str ]:
		"""Build headers.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, str]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'api_key', self.api_key )
			return {
					'Authorization': f'Bearer {self.api_key}',
			}
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_headers( self )'
			raise ex

	def build_json_headers( self ) -> Dict[ str, str ]:
		"""Build json headers.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, str]: Result produced by the xAI workflow.
		"""
		try:
			headers = self.build_headers( )
			headers[ 'Content-Type' ] = 'application/json'
			return headers
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_json_headers( self )'
			raise ex

	def normalize_file_id( self, response: Any = None ) -> str | None:
		"""Normalize file id.

		Purpose:
		    Provides normalize file id behavior for the Files workflow while preserving provider request and response state.

		Args:
		    response (Any): Response supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			value = response if response is not None else self.response

			if value is None:
				return None

			if isinstance( value, dict ):
				file_id = value.get( 'id' ) or value.get( 'file_id' )
				return str( file_id ) if file_id else None

			file_id = getattr( value, 'id', None ) or getattr( value, 'file_id', None )
			return str( file_id ) if file_id else None
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'normalize_file_id( self, response )'
			raise ex

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

		Purpose:
		    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			if self.response is None:
				return None

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

			output = getattr( self.response, 'output', None )
			if not isinstance( output, list ):
				return None

			parts: List[ str ] = [ ]
			for item in output:
				if getattr( item, 'type', None ) != 'message':
					continue

				content = getattr( item, 'content', None )
				if not isinstance( content, list ):
					continue

				for block in content:
					text = getattr( block, 'text', None )
					if text:
						parts.append( text )

			self.output_text = ''.join( parts ).strip( ) if parts else None
			return self.output_text
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'get_output_text( self )'
			raise ex

	def build_upload_request( self ) -> Dict[ str, Any ]:
		"""Build upload request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'file_path', self.file_path )
			path = Path( self.file_path )

			if not path.exists( ):
				raise FileNotFoundError( f'File was not found: {self.file_path}' )

			self.file_name = self.file_name or path.name
			throw_if( 'file_name', self.file_name )
			self.request = {
					'file_path': str( path ),
					'file_name': self.file_name,
					'purpose': self.purpose,
			}
			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_upload_request( self )'
			raise ex

	def execute_upload( self ) -> Any:
		"""Execute upload.

		Purpose:
		    Provides execute upload behavior for the Files workflow while preserving provider request and response state.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			self.initialize_client( )
			throw_if( 'file_path', self.file_path )
			throw_if( 'purpose', self.purpose )
			with open( self.file_path, 'rb' ) as file_stream:
				self.response = self.client.files.create( file=file_stream, purpose=self.purpose )

			self.file_id = self.normalize_file_id( self.response )
			if self.file_id and self.file_id not in self.file_ids:
				self.file_ids.append( self.file_id )

			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'execute_upload( self )'
			raise ex

	def build_list_request( self ) -> Dict[ str, Any ]:
		"""Build list request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			self.request = { }

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

			if isinstance( self.limit, int ) and self.limit > 0:
				self.request[ 'limit' ] = self.limit

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

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

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

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

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_list_request( self )'
			raise ex

	def execute_list( self ) -> Any:
		"""Execute list.

		Purpose:
		    Provides execute list behavior for the Files workflow while preserving provider request and response state.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'base_url', self.base_url )
			response = requests.get( url=f'{self.base_url.rstrip( "/" )}/files',
				headers=self.build_headers( ), params=self.request, timeout=self.timeout or 3600 )
			response.raise_for_status( )
			self.response = response.json( )
			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'execute_list( self )'
			raise ex

	def build_retrieve_request( self ) -> Dict[ str, Any ]:
		"""Build retrieve request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'file_id', self.file_id )
			self.request = { }

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

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_retrieve_request( self )'
			raise ex

	def execute_retrieve( self ) -> Any:
		"""Execute retrieve.

		Purpose:
		    Provides execute retrieve behavior for the Files workflow while preserving provider request and response state.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'base_url', self.base_url )
			throw_if( 'file_id', self.file_id )
			response = requests.get( url=f'{self.base_url.rstrip( "/" )}/files/{self.file_id}',
				headers=self.build_headers( ), params=self.request, timeout=self.timeout or 3600 )
			response.raise_for_status( )
			self.response = response.json( )
			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'execute_retrieve( self )'
			raise ex

	def build_extract_request( self ) -> Dict[ str, Any ]:
		"""Build extract request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'file_id', self.file_id )
			self.request = { }

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

			if self.download_format:
				self.request[ 'format' ] = self.download_format

			if isinstance( self.page_number, int ) and self.page_number > 0:
				self.request[ 'page_number' ] = self.page_number

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_extract_request( self )'
			raise ex

	def execute_extract( self ) -> bytes | str | None:
		"""Execute extract.

		Purpose:
		    Provides execute extract behavior for the Files workflow while preserving provider request and response state.

		Returns:
		    bytes | str | None: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'base_url', self.base_url )
			throw_if( 'file_id', self.file_id )
			response = requests.get(
				url=f'{self.base_url.rstrip( "/" )}/files/{self.file_id}/content',
				headers=self.build_headers( ), params=self.request, timeout=self.timeout or 3600 )
			response.raise_for_status( )
			content_type = str( response.headers.get( 'content-type', '' ) ).lower( )
			if 'application/json' in content_type:
				self.content = response.json( )
				return self.content

			if self.download_format == 'DOWNLOAD_FORMAT_TEXT' or 'text/' in content_type:
				self.content = response.text
				return self.content

			self.content = response.content
			return self.content
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'execute_extract( self )'
			raise ex

	def build_delete_request( self ) -> Dict[ str, Any ]:
		"""Build delete request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'file_id', self.file_id )
			self.request = { }

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

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_delete_request( self )'
			raise ex

	def execute_delete( self ) -> Any:
		"""Execute delete.

		Purpose:
		    Provides execute delete behavior for the Files workflow while preserving provider request and response state.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'base_url', self.base_url )
			throw_if( 'file_id', self.file_id )
			response = requests.delete( url=f'{self.base_url.rstrip( "/" )}/files/{self.file_id}',
				headers=self.build_headers( ), params=self.request, timeout=self.timeout or 3600 )
			response.raise_for_status( )
			if response.content:
				try:
					self.response = response.json( )
				except Exception:
					self.response = { 'id': self.file_id, 'deleted': True }
			else:
				self.response = { 'id': self.file_id, 'deleted': True }

			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'execute_delete( self )'
			raise ex

	def build_file_input( self ) -> List[ Dict[ str, Any ] ]:
		"""Build file input.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    List[Dict[str, Any]]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', self.prompt )
			self.content = [ {
					'type': 'input_text',
					'text': self.prompt,
			}, ]

			for file_id in self.file_ids:
				if not isinstance( file_id, str ) or not file_id.strip( ):
					continue

				self.content.append( {
						'type': 'input_file',
						'file_id': file_id.strip( ),
				} )

			return self.content
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_file_input( self )'
			raise ex

	def build_file_response_request( self ) -> Dict[ str, Any ]:
		"""Build file response request.

		Purpose:
		    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'model', self.model )
			throw_if( 'prompt', self.prompt )
			if not isinstance( self.file_ids, list ) or len( self.file_ids ) == 0:
				raise ValueError( 'At least one file_id is required for a file-aware response.' )

			self.request = { 'model': self.model, 'input': [ {
					'role': 'user',
					'content': self.build_file_input( ),
			} ], }
			if self.instructions:
				self.request[ 'instructions' ] = self.instructions

			if isinstance( self.max_output_tokens, int ) and self.max_output_tokens > 0:
				self.request[ 'max_output_tokens' ] = self.max_output_tokens

			if self.temperature is not None:
				self.request[ 'temperature' ] = self.temperature

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

			if self.frequency_penalty is not None:
				self.request[ 'frequency_penalty' ] = self.frequency_penalty

			if self.presence_penalty is not None:
				self.request[ 'presence_penalty' ] = self.presence_penalty

			if self.store is not None:
				self.request[ 'store' ] = self.store

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

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

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

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

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

			if self.response_format:
				self.request[ 'text' ] = { 'format': { 'type': self.response_format, } }

			return self.request
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'build_file_response_request( self )'
			raise ex

	def execute_file_response( self ) -> str | None:
		"""Execute file response.

		Purpose:
		    Provides execute file response behavior for the Files workflow while preserving provider request and response state.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			self.initialize_client( )
			self.response = self.client.responses.create( **self.request )
			return self.get_output_text( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'execute_file_response( self )'
			raise ex

	def upload( self, filepath: str, filename: str = None, purpose: str = 'assistants',
			**kwargs: Any ) -> Any:
		"""Upload.

		Purpose:
		    Provides upload behavior for the Files workflow while preserving provider request and response state.

		Args:
		    filepath (str): Filepath supplied to the xAI workflow.
		    filename (str): Filename supplied to the xAI workflow.
		    purpose (str): Purpose supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'filepath', filepath )
			self.file_path = filepath
			self.file_name = filename
			self.purpose = purpose or 'assistants'
			self.extra_kwargs = kwargs or { }
			self.build_upload_request( )
			return self.execute_upload( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'upload( self, filepath: str, filename: str=None )'
			raise ex

	def list( self, limit: int = None, next_token: str = None, order: str = None,
			sort_by: str = None, filter: str = None, team_id: str = None, **kwargs: Any ) -> Any:
		"""List.

		Purpose:
		    Provides list behavior for the Files workflow while preserving provider request and response state.

		Args:
		    limit (int): Limit supplied to the xAI workflow.
		    next_token (str): Next token supplied to the xAI workflow.
		    order (str): Order supplied to the xAI workflow.
		    sort_by (str): Sort by supplied to the xAI workflow.
		    filter (str): Filter supplied to the xAI workflow.
		    team_id (str): Team id supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			self.limit = limit
			self.next_token = next_token
			self.order = order
			self.sort_by = sort_by
			self.filter = filter
			self.team_id = team_id
			self.extra_kwargs = kwargs or { }
			self.build_list_request( )
			return self.execute_list( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'list( self )'
			raise ex

	def list_files( self, limit: int = None, next_token: str = None, order: str = None,
			sort_by: str = None, filter: str = None, team_id: str = None, **kwargs: Any ) -> Any:
		"""List files.

		Purpose:
		    Lists xAI resources and returns normalized metadata for UI display or downstream selection.

		Args:
		    limit (int): Limit supplied to the xAI workflow.
		    next_token (str): Next token supplied to the xAI workflow.
		    order (str): Order supplied to the xAI workflow.
		    sort_by (str): Sort by supplied to the xAI workflow.
		    filter (str): Filter supplied to the xAI workflow.
		    team_id (str): Team id supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			return self.list( limit=limit, next_token=next_token, order=order,
				sort_by=sort_by, filter=filter, team_id=team_id, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'list_files( self )'
			raise ex

	def retrieve( self, file_id: str, team_id: str = None, **kwargs: Any ) -> Any:
		"""Retrieve.

		Purpose:
		    Provides retrieve behavior for the Files workflow while preserving provider request and response state.

		Args:
		    file_id (str): File id supplied to the xAI workflow.
		    team_id (str): Team id supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'file_id', file_id )
			self.file_id = file_id
			self.team_id = team_id
			self.extra_kwargs = kwargs or { }
			self.build_retrieve_request( )
			return self.execute_retrieve( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'retrieve( self, file_id: str )'
			raise ex

	def extract( self, file_id: str, format: str = None, page_number: int = None,
			team_id: str = None, **kwargs: Any ) -> bytes | str | None:
		"""Extract.

		Purpose:
		    Provides extract behavior for the Files workflow while preserving provider request and response state.

		Args:
		    file_id (str): File id supplied to the xAI workflow.
		    format (str): Format supplied to the xAI workflow.
		    page_number (int): Page number supplied to the xAI workflow.
		    team_id (str): Team id supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    bytes | str | None: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'file_id', file_id )
			self.file_id = file_id
			self.download_format = format
			self.page_number = page_number
			self.team_id = team_id
			self.extra_kwargs = kwargs or { }
			self.build_extract_request( )
			return self.execute_extract( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'extract( self, file_id: str )'
			raise ex

	def download( self, file_id: str, format: str = None, page_number: int = None,
			team_id: str = None, **kwargs: Any ) -> bytes | str | None:
		"""Download.

		Purpose:
		    Provides download behavior for the Files workflow while preserving provider request and response state.

		Args:
		    file_id (str): File id supplied to the xAI workflow.
		    format (str): Format supplied to the xAI workflow.
		    page_number (int): Page number supplied to the xAI workflow.
		    team_id (str): Team id supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    bytes | str | None: Result produced by the xAI workflow.
		"""
		try:
			return self.extract( file_id=file_id, format=format, page_number=page_number,
				team_id=team_id, **kwargs )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'download( self, file_id: str )'
			raise ex

	def delete( self, file_id: str, team_id: str = None, **kwargs: Any ) -> Any:
		"""Delete.

		Purpose:
		    Provides delete behavior for the Files workflow while preserving provider request and response state.

		Args:
		    file_id (str): File id supplied to the xAI workflow.
		    team_id (str): Team id supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'file_id', file_id )
			self.file_id = file_id
			self.team_id = team_id
			self.extra_kwargs = kwargs or { }
			self.build_delete_request( )
			return self.execute_delete( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'delete( self, file_id: str )'
			raise ex

	def summarize( self, filepath: str = None, filename: str = None, prompt: str = None,
			file_id: str = None, model: str = 'grok-4.20-reasoning', temperature: float = None,
			top_p: float = None, frequency: float = None, presence: float = None,
			max_tokens: int = None, store: bool = None, stream: bool = None,
			instruct: str = None, include: List[ str ] = None, tools: List[ Any ] = None,
			tool_choice: str = None, previous_id: str = None, conversation_id: str = None,
			purpose: str = 'assistants', **kwargs: Any ) -> str | None:
		"""Summarize.

		Purpose:
		    Provides summarize behavior for the Files workflow while preserving provider request and response state.

		Args:
		    filepath (str): Filepath supplied to the xAI workflow.
		    filename (str): Filename supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    file_id (str): File id supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    include (List[str]): Include supplied to the xAI workflow.
		    tools (List[Any]): Tools supplied to the xAI workflow.
		    tool_choice (str): Tool choice supplied to the xAI workflow.
		    previous_id (str): Previous id supplied to the xAI workflow.
		    conversation_id (str): Conversation id supplied to the xAI workflow.
		    purpose (str): Purpose supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', prompt )
			self.prompt = prompt
			self.model = model
			self.instructions = instruct
			self.temperature = temperature
			self.top_percent = top_p
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_output_tokens = max_tokens
			self.store = store
			self.stream = stream
			self.include = include if include is not None else [ ]
			self.tools = tools if tools is not None else [ ]
			self.tool_choice = tool_choice
			self.previous_id = previous_id
			self.previous_response_id = previous_id
			self.conversation_id = conversation_id
			self.extra_kwargs = kwargs or { }
			self.file_ids = [ ]

			if file_id:
				self.file_id = file_id
				self.file_ids.append( file_id )

			if filepath:
				upload_response = self.upload( filepath=filepath, filename=filename,
					purpose=purpose )
				uploaded_id = self.normalize_file_id( upload_response )
				if uploaded_id and uploaded_id not in self.file_ids:
					self.file_ids.append( uploaded_id )

			self.build_file_response_request( )
			return self.execute_file_response( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'summarize( self, filepath: str, prompt: str )'
			raise ex

	def survey( self, filepaths: List[ str ], filenames: List[ str ], prompt: str,
			model: str = 'grok-4.20-reasoning', temperature: float = None, top_p: float = None,
			frequency: float = None, presence: float = None, max_tokens: int = None,
			store: bool = None, stream: bool = None, instruct: str = None,
			purpose: str = 'assistants', **kwargs: Any ) -> str | None:
		"""Survey.

		Purpose:
		    Provides survey behavior for the Files workflow while preserving provider request and response state.

		Args:
		    filepaths (List[str]): Filepaths supplied to the xAI workflow.
		    filenames (List[str]): Filenames supplied to the xAI workflow.
		    prompt (str): Prompt supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.
		    temperature (float): Temperature supplied to the xAI workflow.
		    top_p (float): Top p supplied to the xAI workflow.
		    frequency (float): Frequency supplied to the xAI workflow.
		    presence (float): Presence supplied to the xAI workflow.
		    max_tokens (int): Max tokens supplied to the xAI workflow.
		    store (bool): Store supplied to the xAI workflow.
		    stream (bool): Stream supplied to the xAI workflow.
		    instruct (str): Instruct supplied to the xAI workflow.
		    purpose (str): Purpose supplied to the xAI workflow.
		    **kwargs: Additional keyword values supplied to the xAI workflow.

		Returns:
		    str | None: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'filepaths', filepaths )
			throw_if( 'filenames', filenames )
			throw_if( 'prompt', prompt )

			if len( filepaths ) != len( filenames ):
				raise ValueError( 'filepaths and filenames must have the same length.' )

			self.file_ids = [ ]
			for index, filepath in enumerate( filepaths ):
				upload_response = self.upload( filepath=filepath, filename=filenames[ index ],
					purpose=purpose )
				uploaded_id = self.normalize_file_id( upload_response )
				if uploaded_id and uploaded_id not in self.file_ids:
					self.file_ids.append( uploaded_id )

			self.prompt = prompt
			self.model = model
			self.instructions = instruct
			self.temperature = temperature
			self.top_percent = top_p
			self.frequency_penalty = frequency
			self.presence_penalty = presence
			self.max_output_tokens = max_tokens
			self.store = store
			self.stream = stream
			self.extra_kwargs = kwargs or { }
			self.build_file_response_request( )
			return self.execute_file_response( )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'Files'
			ex.method = 'survey( self, filepaths: List[ str ], filenames: List[ str ] )'
			raise ex

	def __dir__( self ) -> List[ str ] | None:
		"""Dir.

		Purpose:
		    Provides dir behavior for the Files workflow while preserving provider request and response state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'api_key',
				'base_url',
				'client',
				'file_path',
				'file_name',
				'file_id',
				'file_ids',
				'file_paths',
				'file_names',
				'purpose',
				'model',
				'prompt',
				'instructions',
				'response',
				'request',
				'content',
				'output_text',
				'documents',
				'response_format',
				'temperature',
				'top_percent',
				'frequency_penalty',
				'presence_penalty',
				'max_output_tokens',
				'store',
				'stream',
				'include',
				'tools',
				'tool_choice',
				'previous_id',
				'previous_response_id',
				'conversation_id',
				'limit',
				'next_token',
				'order',
				'sort_by',
				'filter',
				'team_id',
				'download_format',
				'page_number',
				'extra_kwargs',
				'model_options',
				'purpose_options',
				'format_options',
				'tool_options',
				'include_options',
				'initialize_client',
				'build_headers',
				'build_json_headers',
				'normalize_file_id',
				'get_output_text',
				'build_upload_request',
				'execute_upload',
				'build_list_request',
				'execute_list',
				'build_retrieve_request',
				'execute_retrieve',
				'build_extract_request',
				'execute_extract',
				'build_delete_request',
				'execute_delete',
				'build_file_input',
				'build_file_response_request',
				'execute_file_response',
				'upload',
				'list',
				'list_files',
				'retrieve',
				'extract',
				'download',
				'delete',
				'summarize',
				'survey',
		]

model_options property

model_options: List[str]

Model options.

Purpose

Returns the configured option values exposed by the Files workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

purpose_options property

purpose_options: List[str]

Purpose options.

Purpose

Returns the configured option values exposed by the Files workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

format_options property

format_options: List[str]

Format options.

Purpose

Returns the configured option values exposed by the Files workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

tool_options property

tool_options: List[str]

Tool options.

Purpose

Returns the configured option values exposed by the Files workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

include_options property

include_options: List[str]

Include options.

Purpose

Returns the configured option values exposed by the Files workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

initialize_client

initialize_client() -> None

Initialize client.

Purpose

Provides initialize client behavior for the Files workflow while preserving provider request and response state.

Source code in grok.py
def initialize_client( self ) -> None:
	"""Initialize client.

	Purpose:
	    Provides initialize client behavior for the Files workflow while preserving provider request and response state.
	"""
	try:
		throw_if( 'api_key', self.api_key )
		throw_if( 'base_url', self.base_url )
		self.client = OpenAI( api_key=cfg.XAI_API_KEY, base_url=self.base_url )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'initialize_client( self )'
		raise ex

build_headers

build_headers() -> Dict[str, str]

Build headers.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Result produced by the xAI workflow.

Source code in grok.py
def build_headers( self ) -> Dict[ str, str ]:
	"""Build headers.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, str]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'api_key', self.api_key )
		return {
				'Authorization': f'Bearer {self.api_key}',
		}
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_headers( self )'
		raise ex

build_json_headers

build_json_headers() -> Dict[str, str]

Build json headers.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Result produced by the xAI workflow.

Source code in grok.py
def build_json_headers( self ) -> Dict[ str, str ]:
	"""Build json headers.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, str]: Result produced by the xAI workflow.
	"""
	try:
		headers = self.build_headers( )
		headers[ 'Content-Type' ] = 'application/json'
		return headers
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_json_headers( self )'
		raise ex

normalize_file_id

normalize_file_id(response: Any = None) -> str | None

Normalize file id.

Purpose

Provides normalize file id behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
response Any

Response supplied to the xAI workflow.

None

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def normalize_file_id( self, response: Any = None ) -> str | None:
	"""Normalize file id.

	Purpose:
	    Provides normalize file id behavior for the Files workflow while preserving provider request and response state.

	Args:
	    response (Any): Response supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		value = response if response is not None else self.response

		if value is None:
			return None

		if isinstance( value, dict ):
			file_id = value.get( 'id' ) or value.get( 'file_id' )
			return str( file_id ) if file_id else None

		file_id = getattr( value, 'id', None ) or getattr( value, 'file_id', None )
		return str( file_id ) if file_id else None
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'normalize_file_id( self, response )'
		raise ex

get_output_text

get_output_text() -> str | None

Get output text.

Purpose

Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

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

	Purpose:
	    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		if self.response is None:
			return None

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

		output = getattr( self.response, 'output', None )
		if not isinstance( output, list ):
			return None

		parts: List[ str ] = [ ]
		for item in output:
			if getattr( item, 'type', None ) != 'message':
				continue

			content = getattr( item, 'content', None )
			if not isinstance( content, list ):
				continue

			for block in content:
				text = getattr( block, 'text', None )
				if text:
					parts.append( text )

		self.output_text = ''.join( parts ).strip( ) if parts else None
		return self.output_text
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'get_output_text( self )'
		raise ex

build_upload_request

build_upload_request() -> Dict[str, Any]

Build upload request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_upload_request( self ) -> Dict[ str, Any ]:
	"""Build upload request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'file_path', self.file_path )
		path = Path( self.file_path )

		if not path.exists( ):
			raise FileNotFoundError( f'File was not found: {self.file_path}' )

		self.file_name = self.file_name or path.name
		throw_if( 'file_name', self.file_name )
		self.request = {
				'file_path': str( path ),
				'file_name': self.file_name,
				'purpose': self.purpose,
		}
		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_upload_request( self )'
		raise ex

execute_upload

execute_upload() -> Any

Execute upload.

Purpose

Provides execute upload behavior for the Files workflow while preserving provider request and response state.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def execute_upload( self ) -> Any:
	"""Execute upload.

	Purpose:
	    Provides execute upload behavior for the Files workflow while preserving provider request and response state.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		self.initialize_client( )
		throw_if( 'file_path', self.file_path )
		throw_if( 'purpose', self.purpose )
		with open( self.file_path, 'rb' ) as file_stream:
			self.response = self.client.files.create( file=file_stream, purpose=self.purpose )

		self.file_id = self.normalize_file_id( self.response )
		if self.file_id and self.file_id not in self.file_ids:
			self.file_ids.append( self.file_id )

		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'execute_upload( self )'
		raise ex

build_list_request

build_list_request() -> Dict[str, Any]

Build list request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_list_request( self ) -> Dict[ str, Any ]:
	"""Build list request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		self.request = { }

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

		if isinstance( self.limit, int ) and self.limit > 0:
			self.request[ 'limit' ] = self.limit

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

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

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

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

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_list_request( self )'
		raise ex

execute_list

execute_list() -> Any

Execute list.

Purpose

Provides execute list behavior for the Files workflow while preserving provider request and response state.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def execute_list( self ) -> Any:
	"""Execute list.

	Purpose:
	    Provides execute list behavior for the Files workflow while preserving provider request and response state.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'base_url', self.base_url )
		response = requests.get( url=f'{self.base_url.rstrip( "/" )}/files',
			headers=self.build_headers( ), params=self.request, timeout=self.timeout or 3600 )
		response.raise_for_status( )
		self.response = response.json( )
		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'execute_list( self )'
		raise ex

build_retrieve_request

build_retrieve_request() -> Dict[str, Any]

Build retrieve request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_retrieve_request( self ) -> Dict[ str, Any ]:
	"""Build retrieve request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'file_id', self.file_id )
		self.request = { }

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

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_retrieve_request( self )'
		raise ex

execute_retrieve

execute_retrieve() -> Any

Execute retrieve.

Purpose

Provides execute retrieve behavior for the Files workflow while preserving provider request and response state.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def execute_retrieve( self ) -> Any:
	"""Execute retrieve.

	Purpose:
	    Provides execute retrieve behavior for the Files workflow while preserving provider request and response state.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'base_url', self.base_url )
		throw_if( 'file_id', self.file_id )
		response = requests.get( url=f'{self.base_url.rstrip( "/" )}/files/{self.file_id}',
			headers=self.build_headers( ), params=self.request, timeout=self.timeout or 3600 )
		response.raise_for_status( )
		self.response = response.json( )
		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'execute_retrieve( self )'
		raise ex

build_extract_request

build_extract_request() -> Dict[str, Any]

Build extract request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_extract_request( self ) -> Dict[ str, Any ]:
	"""Build extract request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'file_id', self.file_id )
		self.request = { }

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

		if self.download_format:
			self.request[ 'format' ] = self.download_format

		if isinstance( self.page_number, int ) and self.page_number > 0:
			self.request[ 'page_number' ] = self.page_number

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_extract_request( self )'
		raise ex

execute_extract

execute_extract() -> bytes | str | None

Execute extract.

Purpose

Provides execute extract behavior for the Files workflow while preserving provider request and response state.

Returns:

Type Description
bytes | str | None

bytes | str | None: Result produced by the xAI workflow.

Source code in grok.py
def execute_extract( self ) -> bytes | str | None:
	"""Execute extract.

	Purpose:
	    Provides execute extract behavior for the Files workflow while preserving provider request and response state.

	Returns:
	    bytes | str | None: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'base_url', self.base_url )
		throw_if( 'file_id', self.file_id )
		response = requests.get(
			url=f'{self.base_url.rstrip( "/" )}/files/{self.file_id}/content',
			headers=self.build_headers( ), params=self.request, timeout=self.timeout or 3600 )
		response.raise_for_status( )
		content_type = str( response.headers.get( 'content-type', '' ) ).lower( )
		if 'application/json' in content_type:
			self.content = response.json( )
			return self.content

		if self.download_format == 'DOWNLOAD_FORMAT_TEXT' or 'text/' in content_type:
			self.content = response.text
			return self.content

		self.content = response.content
		return self.content
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'execute_extract( self )'
		raise ex

build_delete_request

build_delete_request() -> Dict[str, Any]

Build delete request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_delete_request( self ) -> Dict[ str, Any ]:
	"""Build delete request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'file_id', self.file_id )
		self.request = { }

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

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_delete_request( self )'
		raise ex

execute_delete

execute_delete() -> Any

Execute delete.

Purpose

Provides execute delete behavior for the Files workflow while preserving provider request and response state.

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def execute_delete( self ) -> Any:
	"""Execute delete.

	Purpose:
	    Provides execute delete behavior for the Files workflow while preserving provider request and response state.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'base_url', self.base_url )
		throw_if( 'file_id', self.file_id )
		response = requests.delete( url=f'{self.base_url.rstrip( "/" )}/files/{self.file_id}',
			headers=self.build_headers( ), params=self.request, timeout=self.timeout or 3600 )
		response.raise_for_status( )
		if response.content:
			try:
				self.response = response.json( )
			except Exception:
				self.response = { 'id': self.file_id, 'deleted': True }
		else:
			self.response = { 'id': self.file_id, 'deleted': True }

		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'execute_delete( self )'
		raise ex

build_file_input

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

Build file input.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Result produced by the xAI workflow.

Source code in grok.py
def build_file_input( self ) -> List[ Dict[ str, Any ] ]:
	"""Build file input.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    List[Dict[str, Any]]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', self.prompt )
		self.content = [ {
				'type': 'input_text',
				'text': self.prompt,
		}, ]

		for file_id in self.file_ids:
			if not isinstance( file_id, str ) or not file_id.strip( ):
				continue

			self.content.append( {
					'type': 'input_file',
					'file_id': file_id.strip( ),
			} )

		return self.content
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_file_input( self )'
		raise ex

build_file_response_request

build_file_response_request() -> Dict[str, Any]

Build file response request.

Purpose

Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def build_file_response_request( self ) -> Dict[ str, Any ]:
	"""Build file response request.

	Purpose:
	    Builds normalized xAI request configuration from validated inputs and stores the resulting state on the instance for provider execution.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'model', self.model )
		throw_if( 'prompt', self.prompt )
		if not isinstance( self.file_ids, list ) or len( self.file_ids ) == 0:
			raise ValueError( 'At least one file_id is required for a file-aware response.' )

		self.request = { 'model': self.model, 'input': [ {
				'role': 'user',
				'content': self.build_file_input( ),
		} ], }
		if self.instructions:
			self.request[ 'instructions' ] = self.instructions

		if isinstance( self.max_output_tokens, int ) and self.max_output_tokens > 0:
			self.request[ 'max_output_tokens' ] = self.max_output_tokens

		if self.temperature is not None:
			self.request[ 'temperature' ] = self.temperature

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

		if self.frequency_penalty is not None:
			self.request[ 'frequency_penalty' ] = self.frequency_penalty

		if self.presence_penalty is not None:
			self.request[ 'presence_penalty' ] = self.presence_penalty

		if self.store is not None:
			self.request[ 'store' ] = self.store

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

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

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

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

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

		if self.response_format:
			self.request[ 'text' ] = { 'format': { 'type': self.response_format, } }

		return self.request
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'build_file_response_request( self )'
		raise ex

execute_file_response

execute_file_response() -> str | None

Execute file response.

Purpose

Provides execute file response behavior for the Files workflow while preserving provider request and response state.

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def execute_file_response( self ) -> str | None:
	"""Execute file response.

	Purpose:
	    Provides execute file response behavior for the Files workflow while preserving provider request and response state.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		self.initialize_client( )
		self.response = self.client.responses.create( **self.request )
		return self.get_output_text( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'execute_file_response( self )'
		raise ex

upload

upload(
    filepath: str,
    filename: str = None,
    purpose: str = "assistants",
    **kwargs: Any
) -> Any

Upload.

Purpose

Provides upload behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
filepath str

Filepath supplied to the xAI workflow.

required
filename str

Filename supplied to the xAI workflow.

None
purpose str

Purpose supplied to the xAI workflow.

'assistants'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def upload( self, filepath: str, filename: str = None, purpose: str = 'assistants',
		**kwargs: Any ) -> Any:
	"""Upload.

	Purpose:
	    Provides upload behavior for the Files workflow while preserving provider request and response state.

	Args:
	    filepath (str): Filepath supplied to the xAI workflow.
	    filename (str): Filename supplied to the xAI workflow.
	    purpose (str): Purpose supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'filepath', filepath )
		self.file_path = filepath
		self.file_name = filename
		self.purpose = purpose or 'assistants'
		self.extra_kwargs = kwargs or { }
		self.build_upload_request( )
		return self.execute_upload( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'upload( self, filepath: str, filename: str=None )'
		raise ex

list

list(
    limit: int = None,
    next_token: str = None,
    order: str = None,
    sort_by: str = None,
    filter: str = None,
    team_id: str = None,
    **kwargs: Any
) -> Any

List.

Purpose

Provides list behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
limit int

Limit supplied to the xAI workflow.

None
next_token str

Next token supplied to the xAI workflow.

None
order str

Order supplied to the xAI workflow.

None
sort_by str

Sort by supplied to the xAI workflow.

None
filter str

Filter supplied to the xAI workflow.

None
team_id str

Team id supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def list( self, limit: int = None, next_token: str = None, order: str = None,
		sort_by: str = None, filter: str = None, team_id: str = None, **kwargs: Any ) -> Any:
	"""List.

	Purpose:
	    Provides list behavior for the Files workflow while preserving provider request and response state.

	Args:
	    limit (int): Limit supplied to the xAI workflow.
	    next_token (str): Next token supplied to the xAI workflow.
	    order (str): Order supplied to the xAI workflow.
	    sort_by (str): Sort by supplied to the xAI workflow.
	    filter (str): Filter supplied to the xAI workflow.
	    team_id (str): Team id supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		self.limit = limit
		self.next_token = next_token
		self.order = order
		self.sort_by = sort_by
		self.filter = filter
		self.team_id = team_id
		self.extra_kwargs = kwargs or { }
		self.build_list_request( )
		return self.execute_list( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'list( self )'
		raise ex

list_files

list_files(
    limit: int = None,
    next_token: str = None,
    order: str = None,
    sort_by: str = None,
    filter: str = None,
    team_id: str = None,
    **kwargs: Any
) -> Any

List files.

Purpose

Lists xAI resources and returns normalized metadata for UI display or downstream selection.

Parameters:

Name Type Description Default
limit int

Limit supplied to the xAI workflow.

None
next_token str

Next token supplied to the xAI workflow.

None
order str

Order supplied to the xAI workflow.

None
sort_by str

Sort by supplied to the xAI workflow.

None
filter str

Filter supplied to the xAI workflow.

None
team_id str

Team id supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def list_files( self, limit: int = None, next_token: str = None, order: str = None,
		sort_by: str = None, filter: str = None, team_id: str = None, **kwargs: Any ) -> Any:
	"""List files.

	Purpose:
	    Lists xAI resources and returns normalized metadata for UI display or downstream selection.

	Args:
	    limit (int): Limit supplied to the xAI workflow.
	    next_token (str): Next token supplied to the xAI workflow.
	    order (str): Order supplied to the xAI workflow.
	    sort_by (str): Sort by supplied to the xAI workflow.
	    filter (str): Filter supplied to the xAI workflow.
	    team_id (str): Team id supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		return self.list( limit=limit, next_token=next_token, order=order,
			sort_by=sort_by, filter=filter, team_id=team_id, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'list_files( self )'
		raise ex

retrieve

retrieve(
    file_id: str, team_id: str = None, **kwargs: Any
) -> Any

Retrieve.

Purpose

Provides retrieve behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
file_id str

File id supplied to the xAI workflow.

required
team_id str

Team id supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def retrieve( self, file_id: str, team_id: str = None, **kwargs: Any ) -> Any:
	"""Retrieve.

	Purpose:
	    Provides retrieve behavior for the Files workflow while preserving provider request and response state.

	Args:
	    file_id (str): File id supplied to the xAI workflow.
	    team_id (str): Team id supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'file_id', file_id )
		self.file_id = file_id
		self.team_id = team_id
		self.extra_kwargs = kwargs or { }
		self.build_retrieve_request( )
		return self.execute_retrieve( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'retrieve( self, file_id: str )'
		raise ex

extract

extract(
    file_id: str,
    format: str = None,
    page_number: int = None,
    team_id: str = None,
    **kwargs: Any
) -> bytes | str | None

Extract.

Purpose

Provides extract behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
file_id str

File id supplied to the xAI workflow.

required
format str

Format supplied to the xAI workflow.

None
page_number int

Page number supplied to the xAI workflow.

None
team_id str

Team id supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
bytes | str | None

bytes | str | None: Result produced by the xAI workflow.

Source code in grok.py
def extract( self, file_id: str, format: str = None, page_number: int = None,
		team_id: str = None, **kwargs: Any ) -> bytes | str | None:
	"""Extract.

	Purpose:
	    Provides extract behavior for the Files workflow while preserving provider request and response state.

	Args:
	    file_id (str): File id supplied to the xAI workflow.
	    format (str): Format supplied to the xAI workflow.
	    page_number (int): Page number supplied to the xAI workflow.
	    team_id (str): Team id supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    bytes | str | None: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'file_id', file_id )
		self.file_id = file_id
		self.download_format = format
		self.page_number = page_number
		self.team_id = team_id
		self.extra_kwargs = kwargs or { }
		self.build_extract_request( )
		return self.execute_extract( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'extract( self, file_id: str )'
		raise ex

download

download(
    file_id: str,
    format: str = None,
    page_number: int = None,
    team_id: str = None,
    **kwargs: Any
) -> bytes | str | None

Download.

Purpose

Provides download behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
file_id str

File id supplied to the xAI workflow.

required
format str

Format supplied to the xAI workflow.

None
page_number int

Page number supplied to the xAI workflow.

None
team_id str

Team id supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
bytes | str | None

bytes | str | None: Result produced by the xAI workflow.

Source code in grok.py
def download( self, file_id: str, format: str = None, page_number: int = None,
		team_id: str = None, **kwargs: Any ) -> bytes | str | None:
	"""Download.

	Purpose:
	    Provides download behavior for the Files workflow while preserving provider request and response state.

	Args:
	    file_id (str): File id supplied to the xAI workflow.
	    format (str): Format supplied to the xAI workflow.
	    page_number (int): Page number supplied to the xAI workflow.
	    team_id (str): Team id supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    bytes | str | None: Result produced by the xAI workflow.
	"""
	try:
		return self.extract( file_id=file_id, format=format, page_number=page_number,
			team_id=team_id, **kwargs )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'download( self, file_id: str )'
		raise ex

delete

delete(
    file_id: str, team_id: str = None, **kwargs: Any
) -> Any

Delete.

Purpose

Provides delete behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
file_id str

File id supplied to the xAI workflow.

required
team_id str

Team id supplied to the xAI workflow.

None
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def delete( self, file_id: str, team_id: str = None, **kwargs: Any ) -> Any:
	"""Delete.

	Purpose:
	    Provides delete behavior for the Files workflow while preserving provider request and response state.

	Args:
	    file_id (str): File id supplied to the xAI workflow.
	    team_id (str): Team id supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'file_id', file_id )
		self.file_id = file_id
		self.team_id = team_id
		self.extra_kwargs = kwargs or { }
		self.build_delete_request( )
		return self.execute_delete( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'delete( self, file_id: str )'
		raise ex

summarize

summarize(
    filepath: str = None,
    filename: str = None,
    prompt: str = None,
    file_id: str = None,
    model: str = "grok-4.20-reasoning",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    store: bool = None,
    stream: bool = None,
    instruct: str = None,
    include: List[str] = None,
    tools: List[Any] = None,
    tool_choice: str = None,
    previous_id: str = None,
    conversation_id: str = None,
    purpose: str = "assistants",
    **kwargs: Any
) -> str | None

Summarize.

Purpose

Provides summarize behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
filepath str

Filepath supplied to the xAI workflow.

None
filename str

Filename supplied to the xAI workflow.

None
prompt str

Prompt supplied to the xAI workflow.

None
file_id str

File id supplied to the xAI workflow.

None
model str

Model supplied to the xAI workflow.

'grok-4.20-reasoning'
temperature float

Temperature supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
frequency float

Frequency supplied to the xAI workflow.

None
presence float

Presence supplied to the xAI workflow.

None
max_tokens int

Max tokens supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

None
stream bool

Stream supplied to the xAI workflow.

None
instruct str

Instruct supplied to the xAI workflow.

None
include List[str]

Include supplied to the xAI workflow.

None
tools List[Any]

Tools supplied to the xAI workflow.

None
tool_choice str

Tool choice supplied to the xAI workflow.

None
previous_id str

Previous id supplied to the xAI workflow.

None
conversation_id str

Conversation id supplied to the xAI workflow.

None
purpose str

Purpose supplied to the xAI workflow.

'assistants'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def summarize( self, filepath: str = None, filename: str = None, prompt: str = None,
		file_id: str = None, model: str = 'grok-4.20-reasoning', temperature: float = None,
		top_p: float = None, frequency: float = None, presence: float = None,
		max_tokens: int = None, store: bool = None, stream: bool = None,
		instruct: str = None, include: List[ str ] = None, tools: List[ Any ] = None,
		tool_choice: str = None, previous_id: str = None, conversation_id: str = None,
		purpose: str = 'assistants', **kwargs: Any ) -> str | None:
	"""Summarize.

	Purpose:
	    Provides summarize behavior for the Files workflow while preserving provider request and response state.

	Args:
	    filepath (str): Filepath supplied to the xAI workflow.
	    filename (str): Filename supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    file_id (str): File id supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    frequency (float): Frequency supplied to the xAI workflow.
	    presence (float): Presence supplied to the xAI workflow.
	    max_tokens (int): Max tokens supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    stream (bool): Stream supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    include (List[str]): Include supplied to the xAI workflow.
	    tools (List[Any]): Tools supplied to the xAI workflow.
	    tool_choice (str): Tool choice supplied to the xAI workflow.
	    previous_id (str): Previous id supplied to the xAI workflow.
	    conversation_id (str): Conversation id supplied to the xAI workflow.
	    purpose (str): Purpose supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', prompt )
		self.prompt = prompt
		self.model = model
		self.instructions = instruct
		self.temperature = temperature
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_output_tokens = max_tokens
		self.store = store
		self.stream = stream
		self.include = include if include is not None else [ ]
		self.tools = tools if tools is not None else [ ]
		self.tool_choice = tool_choice
		self.previous_id = previous_id
		self.previous_response_id = previous_id
		self.conversation_id = conversation_id
		self.extra_kwargs = kwargs or { }
		self.file_ids = [ ]

		if file_id:
			self.file_id = file_id
			self.file_ids.append( file_id )

		if filepath:
			upload_response = self.upload( filepath=filepath, filename=filename,
				purpose=purpose )
			uploaded_id = self.normalize_file_id( upload_response )
			if uploaded_id and uploaded_id not in self.file_ids:
				self.file_ids.append( uploaded_id )

		self.build_file_response_request( )
		return self.execute_file_response( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'summarize( self, filepath: str, prompt: str )'
		raise ex

survey

survey(
    filepaths: List[str],
    filenames: List[str],
    prompt: str,
    model: str = "grok-4.20-reasoning",
    temperature: float = None,
    top_p: float = None,
    frequency: float = None,
    presence: float = None,
    max_tokens: int = None,
    store: bool = None,
    stream: bool = None,
    instruct: str = None,
    purpose: str = "assistants",
    **kwargs: Any
) -> str | None

Survey.

Purpose

Provides survey behavior for the Files workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
filepaths List[str]

Filepaths supplied to the xAI workflow.

required
filenames List[str]

Filenames supplied to the xAI workflow.

required
prompt str

Prompt supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-4.20-reasoning'
temperature float

Temperature supplied to the xAI workflow.

None
top_p float

Top p supplied to the xAI workflow.

None
frequency float

Frequency supplied to the xAI workflow.

None
presence float

Presence supplied to the xAI workflow.

None
max_tokens int

Max tokens supplied to the xAI workflow.

None
store bool

Store supplied to the xAI workflow.

None
stream bool

Stream supplied to the xAI workflow.

None
instruct str

Instruct supplied to the xAI workflow.

None
purpose str

Purpose supplied to the xAI workflow.

'assistants'
**kwargs Any

Additional keyword values supplied to the xAI workflow.

{}

Returns:

Type Description
str | None

str | None: Result produced by the xAI workflow.

Source code in grok.py
def survey( self, filepaths: List[ str ], filenames: List[ str ], prompt: str,
		model: str = 'grok-4.20-reasoning', temperature: float = None, top_p: float = None,
		frequency: float = None, presence: float = None, max_tokens: int = None,
		store: bool = None, stream: bool = None, instruct: str = None,
		purpose: str = 'assistants', **kwargs: Any ) -> str | None:
	"""Survey.

	Purpose:
	    Provides survey behavior for the Files workflow while preserving provider request and response state.

	Args:
	    filepaths (List[str]): Filepaths supplied to the xAI workflow.
	    filenames (List[str]): Filenames supplied to the xAI workflow.
	    prompt (str): Prompt supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.
	    temperature (float): Temperature supplied to the xAI workflow.
	    top_p (float): Top p supplied to the xAI workflow.
	    frequency (float): Frequency supplied to the xAI workflow.
	    presence (float): Presence supplied to the xAI workflow.
	    max_tokens (int): Max tokens supplied to the xAI workflow.
	    store (bool): Store supplied to the xAI workflow.
	    stream (bool): Stream supplied to the xAI workflow.
	    instruct (str): Instruct supplied to the xAI workflow.
	    purpose (str): Purpose supplied to the xAI workflow.
	    **kwargs: Additional keyword values supplied to the xAI workflow.

	Returns:
	    str | None: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'filepaths', filepaths )
		throw_if( 'filenames', filenames )
		throw_if( 'prompt', prompt )

		if len( filepaths ) != len( filenames ):
			raise ValueError( 'filepaths and filenames must have the same length.' )

		self.file_ids = [ ]
		for index, filepath in enumerate( filepaths ):
			upload_response = self.upload( filepath=filepath, filename=filenames[ index ],
				purpose=purpose )
			uploaded_id = self.normalize_file_id( upload_response )
			if uploaded_id and uploaded_id not in self.file_ids:
				self.file_ids.append( uploaded_id )

		self.prompt = prompt
		self.model = model
		self.instructions = instruct
		self.temperature = temperature
		self.top_percent = top_p
		self.frequency_penalty = frequency
		self.presence_penalty = presence
		self.max_output_tokens = max_tokens
		self.store = store
		self.stream = stream
		self.extra_kwargs = kwargs or { }
		self.build_file_response_request( )
		return self.execute_file_response( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'Files'
		ex.method = 'survey( self, filepaths: List[ str ], filenames: List[ str ] )'
		raise ex

VectorStores

Bases: Grok

VectorStores workflow wrapper.

Purpose

Manages xAI collection and vector-store style operations used to connect documents to retrieval-enabled workflows.

Attributes:

Name Type Description
client Optional[Client]

Runtime attribute used by the VectorStores workflow.

model Optional[str]

Runtime attribute used by the VectorStores workflow.

prompt Optional[str]

Runtime attribute used by the VectorStores workflow.

response_format Optional[str]

Runtime attribute used by the VectorStores workflow.

number Optional[int]

Runtime attribute used by the VectorStores workflow.

content Optional[str]

Runtime attribute used by the VectorStores workflow.

name Optional[str]

Runtime attribute used by the VectorStores workflow.

file_path Optional[str]

Runtime attribute used by the VectorStores workflow.

file_name Optional[str]

Runtime attribute used by the VectorStores workflow.

file_ids Optional[List[str]]

Runtime attribute used by the VectorStores workflow.

store_ids Optional[List[str]]

Runtime attribute used by the VectorStores workflow.

store_id Optional[str]

Runtime attribute used by the VectorStores workflow.

collection_ids Optional[List[str]]

Runtime attribute used by the VectorStores workflow.

collection_id Optional[str]

Runtime attribute used by the VectorStores workflow.

documents Optional[Dict[str, str]]

Runtime attribute used by the VectorStores workflow.

collections Optional[Dict[str, str]]

Runtime attribute used by the VectorStores workflow.

response Optional[Any]

Runtime attribute used by the VectorStores workflow.

Source code in grok.py
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
class VectorStores( Grok ):
	"""VectorStores workflow wrapper.

	Purpose:
	    Manages xAI collection and vector-store style operations used to connect documents to retrieval-enabled workflows.

	Attributes:
	    client: Runtime attribute used by the VectorStores workflow.
	    model: Runtime attribute used by the VectorStores workflow.
	    prompt: Runtime attribute used by the VectorStores workflow.
	    response_format: Runtime attribute used by the VectorStores workflow.
	    number: Runtime attribute used by the VectorStores workflow.
	    content: Runtime attribute used by the VectorStores workflow.
	    name: Runtime attribute used by the VectorStores workflow.
	    file_path: Runtime attribute used by the VectorStores workflow.
	    file_name: Runtime attribute used by the VectorStores workflow.
	    file_ids: Runtime attribute used by the VectorStores workflow.
	    store_ids: Runtime attribute used by the VectorStores workflow.
	    store_id: Runtime attribute used by the VectorStores workflow.
	    collection_ids: Runtime attribute used by the VectorStores workflow.
	    collection_id: Runtime attribute used by the VectorStores workflow.
	    documents: Runtime attribute used by the VectorStores workflow.
	    collections: Runtime attribute used by the VectorStores workflow.
	    response: Runtime attribute used by the VectorStores workflow.
	"""
	client: Optional[ Client ]
	model: Optional[ str ]
	prompt: Optional[ str ]
	response_format: Optional[ str ]
	number: Optional[ int ]
	content: Optional[ str ]
	name: Optional[ str ]
	file_path: Optional[ str ]
	file_name: Optional[ str ]
	file_ids: Optional[ List[ str ] ]
	store_ids: Optional[ List[ str ] ]
	store_id: Optional[ str ]
	collection_ids: Optional[ List[ str ] ]
	collection_id: Optional[ str ]
	documents: Optional[ Dict[ str, str ] ]
	collections: Optional[ Dict[ str, str ] ]
	response: Optional[ Any ]

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

		Purpose:
		    Initializes VectorStores state with default configuration values and runtime attributes used by later xAI provider calls.
		"""
		super( ).__init__( )
		self.api_key = cfg.XAI_API_KEY
		self.base_url = cfg.XAI_BASE_URL
		self.client = Client( api_key=cfg.XAI_API_KEY )
		self.model = None
		self.prompt = None
		self.response_format = None
		self.number = None
		self.content = None
		self.name = None
		self.response = None
		self.file_ids = [ ]
		self.store_ids = [ ]
		self.collection_ids = [ ]
		self.file_path = None
		self.file_name = None
		self.store_id = None
		self.collection_id = None
		default_collections = {
				'Federal Financial Regulations': 'collection_9195d847-03a1-443c-9240-294c64dd01e2',
				'Federal Financial Data': 'collection_e28cdcc2-a9e5-430a-bdf5-94fbaf44b6a4',
				'Explanatory Statements': 'collection_41dc3374-24d0-4692-819c-59e3d7b11b93',
				'Public Laws': 'collection_c1d0b83e-2f59-4f10-9cf7-51392b490fee'
		}
		configured_collections = getattr( cfg, 'GROK_COLLECTIONS', None )
		self.collections = configured_collections if isinstance( configured_collections,
			dict ) else default_collections

		default_documents = {
				'Outlays.csv': 'file_b0a448b3-904a-40c7-bae1-64df657fde1c',
				'Authority.csv': 'file_c6ad236f-0c52-45f4-8883-d3be032d07c2',
				'Balances.csv': 'file_0f63d120-406f-49e6-97e5-7855f2cb26b5'
		}
		configured_documents = getattr( cfg, 'GROK_DOCUMENTS', None )
		self.documents = configured_documents if isinstance( configured_documents,
			dict ) else default_documents

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

		Purpose:
		    Returns the configured option values exposed by the VectorStores workflow selector without mutating provider state.

		Returns:
		    List[str]: Result produced by the xAI workflow.
		"""
		return [
				'grok-4',
				'grok-4-0709',
				'grok-4-latest',
				'grok-4-1-fast',
				'grok-4-1-fast-reasoning',
				'grok-4-1-fast-reasoning-latest',
				'grok-4-1-fast-non-reasoning',
				'grok-4-1-fast-non-reasoning-latest',
				'grok-4-fast',
				'grok-4-fast-reasoning',
				'grok-4-fast-reasoning-latest',
				'grok-4-fast-non-reasoning',
				'grok-4-fast-non-reasoning-latest',
				'grok-code-fast-1',
				'grok-3',
				'grok-3-latest',
				'grok-3-mini',
				'grok-3-fast',
				'grok-3-fast-latest',
				'grok-3-mini-fast',
				'grok-3-mini-fast-latest',
		]

	def get_collection_id( self, store_id: str ) -> str:
		"""Get collection id.

		Purpose:
		    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

		Args:
		    store_id (str): Store id supplied to the xAI workflow.

		Returns:
		    str: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'store_id', store_id )
			value = str( store_id ).strip( )

			if value in self.collections:
				return self.collections[ value ]

			if ' — ' in value:
				return value.split( ' — ' )[ -1 ].strip( )

			return value
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'get_collection_id( self, store_id: str ) -> str'
			raise ex

	def get_collection_rows( self ) -> List[ Dict[ str, Any ] ]:
		"""Get collection rows.

		Purpose:
		    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

		Returns:
		    List[Dict[str, Any]]: Result produced by the xAI workflow.
		"""
		try:
			rows = [ ]
			for name, collection_id in self.collections.items( ):
				rows.append(
					{
							'id': collection_id,
							'name': name,
							'display_name': name,
							'description': '',
							'status': 'configured',
							'file_counts': '',
							'usage_bytes': '',
							'collection_id': collection_id,
							'collection_name': name,
							'collection_description': '',
					}
				)

			return rows
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'get_collection_rows( self ) -> List[ Dict[ str, Any ] ]'
			raise ex

	def get_text_output( self, response: Any ) -> Any:
		"""Get text output.

		Purpose:
		    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

		Args:
		    response (Any): Response supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			if response is None:
				return None

			output_text = getattr( response, 'output_text', None )
			if output_text:
				return output_text

			text = getattr( response, 'text', None )
			if text:
				return text

			if isinstance( response, dict ):
				output_text = response.get( 'output_text' ) or response.get( 'text' )
				if output_text:
					return output_text

			return response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'get_text_output( self, response: Any ) -> Any'
			raise ex

	def raise_management_required( self, operation: str ) -> None:
		"""Raise management required.

		Purpose:
		    Provides raise management required behavior for the VectorStores workflow while preserving provider request and response state.

		Args:
		    operation (str): Operation supplied to the xAI workflow.
		"""
		raise NotImplementedError(
			f'Grok VectorStores.{operation} requires xAI collection-management capability. '
			f'This wrapper is currently configured with XAI_API_KEY only. Use configured '
			f'collections for search, or add the required management credential/path before '
			f'enabling remote collection management.'
		)

	def create( self, name: str, model: str = None ) -> Any:
		"""Create.

		Purpose:
		    Provides create behavior for the VectorStores workflow while preserving provider request and response state.

		Args:
		    name (str): Name supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'name', name )
			self.name = name
			self.file_name = name
			self.model = model
			self.raise_management_required( 'create' )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'create( self, name: str, model: str=None ) -> Any'
			raise ex

	def list( self ) -> List[ Dict[ str, Any ] ]:
		"""List.

		Purpose:
		    Provides list behavior for the VectorStores workflow while preserving provider request and response state.

		Returns:
		    List[Dict[str, Any]]: Result produced by the xAI workflow.
		"""
		try:
			self.response = self.get_collection_rows( )
			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'list( self ) -> List[ Dict[ str, Any ] ]'
			raise ex

	def retrieve( self, store_id: str ) -> Dict[ str, Any ]:
		"""Retrieve.

		Purpose:
		    Provides retrieve behavior for the VectorStores workflow while preserving provider request and response state.

		Args:
		    store_id (str): Store id supplied to the xAI workflow.

		Returns:
		    Dict[str, Any]: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'store_id', store_id )
			self.store_id = store_id
			self.collection_id = self.get_collection_id( self.store_id )
			display_name = ''
			for name, collection_id in self.collections.items( ):
				if collection_id == self.collection_id:
					display_name = name
					break

			self.response = {
					'id': self.collection_id,
					'name': display_name or self.collection_id,
					'display_name': display_name or self.collection_id,
					'description': '',
					'status': 'configured',
					'file_counts': '',
					'usage_bytes': '',
					'collection_id': self.collection_id,
					'collection_name': display_name or self.collection_id,
					'collection_description': '',
			}
			return self.response
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'retrieve( self, store_id: str ) -> Dict[ str, Any ]'
			raise ex

	def search( self, prompt: str, store_id: str, model: str = 'grok-4-fast' ) -> Any:
		"""Search.

		Purpose:
		    Provides search behavior for the VectorStores workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    store_id (str): Store id supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'store_id', store_id )
			self.prompt = prompt
			self.model = model
			self.store_id = store_id
			self.collection_id = self.get_collection_id( self.store_id )
			self.store_ids = [ self.collection_id ]
			self.collection_ids = [ self.collection_id ]
			self.response = self.client.collections.search( query=self.prompt,
				collection_ids=self.collection_ids )
			return self.get_text_output( self.response )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'search( self, prompt: str, store_id: str, model: str ) -> Any'
			raise ex

	def survey( self, prompt: str, store_ids: List[ str ], model: str = 'grok-4-fast' ) -> Any:
		"""Survey.

		Purpose:
		    Provides survey behavior for the VectorStores workflow while preserving provider request and response state.

		Args:
		    prompt (str): Prompt supplied to the xAI workflow.
		    store_ids (List[str]): Store ids supplied to the xAI workflow.
		    model (str): Model supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'prompt', prompt )
			throw_if( 'store_ids', store_ids )
			self.prompt = prompt
			self.model = model
			self.store_ids = store_ids
			self.collection_ids = [
					self.get_collection_id( store_id )
					for store_id in self.store_ids
			]
			self.response = self.client.collections.search( query=self.prompt,
				collection_ids=self.collection_ids )
			return self.get_text_output( self.response )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'survey( self, prompt: str, store_ids: List[ str ], model: str ) -> Any'
			raise ex

	def update( self, store_id: str, filepath: str = None, filename: str = None ) -> Any:
		"""Update.

		Purpose:
		    Provides update behavior for the VectorStores workflow while preserving provider request and response state.

		Args:
		    store_id (str): Store id supplied to the xAI workflow.
		    filepath (str): Filepath supplied to the xAI workflow.
		    filename (str): Filename supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'store_id', store_id )
			self.store_id = store_id
			self.collection_id = self.get_collection_id( self.store_id )
			self.file_path = filepath
			self.file_name = filename
			self.raise_management_required( 'update' )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'update( self, store_id: str, filepath: str=None, filename: str=None ) -> Any'
			raise ex

	def delete( self, store_id: str ) -> Any:
		"""Delete.

		Purpose:
		    Provides delete behavior for the VectorStores workflow while preserving provider request and response state.

		Args:
		    store_id (str): Store id supplied to the xAI workflow.

		Returns:
		    Any: Result produced by the xAI workflow.
		"""
		try:
			throw_if( 'store_id', store_id )
			self.store_id = store_id
			self.collection_id = self.get_collection_id( self.store_id )
			self.raise_management_required( 'delete' )
		except Exception as e:
			ex = Error( e )
			ex.module = 'grok'
			ex.cause = 'VectorStores'
			ex.method = 'delete( self, store_id: str ) -> Any'
			raise ex

	def __dir__( self ) -> List[ str ] | None:
		"""Dir.

		Purpose:
		    Provides dir behavior for the VectorStores workflow while preserving provider request and response state.

		Returns:
		    List[str] | None: Result produced by the xAI workflow.
		"""
		return [
				'client',
				'file_path',
				'file_name',
				'response',
				'model',
				'prompt',
				'response_format',
				'number',
				'content',
				'name',
				'file_ids',
				'store_ids',
				'store_id',
				'collection_ids',
				'collection_id',
				'documents',
				'collections',
				'model_options',
				'get_collection_id',
				'get_collection_rows',
				'get_text_output',
				'raise_management_required',
				'create',
				'list',
				'retrieve',
				'search',
				'survey',
				'update',
				'delete',
		]

model_options property

model_options: List[str]

Model options.

Purpose

Returns the configured option values exposed by the VectorStores workflow selector without mutating provider state.

Returns:

Type Description
List[str]

List[str]: Result produced by the xAI workflow.

get_collection_id

get_collection_id(store_id: str) -> str

Get collection id.

Purpose

Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

Parameters:

Name Type Description Default
store_id str

Store id supplied to the xAI workflow.

required

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def get_collection_id( self, store_id: str ) -> str:
	"""Get collection id.

	Purpose:
	    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

	Args:
	    store_id (str): Store id supplied to the xAI workflow.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'store_id', store_id )
		value = str( store_id ).strip( )

		if value in self.collections:
			return self.collections[ value ]

		if ' — ' in value:
			return value.split( ' — ' )[ -1 ].strip( )

		return value
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'get_collection_id( self, store_id: str ) -> str'
		raise ex

get_collection_rows

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

Get collection rows.

Purpose

Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Result produced by the xAI workflow.

Source code in grok.py
def get_collection_rows( self ) -> List[ Dict[ str, Any ] ]:
	"""Get collection rows.

	Purpose:
	    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

	Returns:
	    List[Dict[str, Any]]: Result produced by the xAI workflow.
	"""
	try:
		rows = [ ]
		for name, collection_id in self.collections.items( ):
			rows.append(
				{
						'id': collection_id,
						'name': name,
						'display_name': name,
						'description': '',
						'status': 'configured',
						'file_counts': '',
						'usage_bytes': '',
						'collection_id': collection_id,
						'collection_name': name,
						'collection_description': '',
				}
			)

		return rows
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'get_collection_rows( self ) -> List[ Dict[ str, Any ] ]'
		raise ex

get_text_output

get_text_output(response: Any) -> Any

Get text output.

Purpose

Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

Parameters:

Name Type Description Default
response Any

Response supplied to the xAI workflow.

required

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def get_text_output( self, response: Any ) -> Any:
	"""Get text output.

	Purpose:
	    Retrieves normalized xAI provider state or response data for display, reuse, or downstream request construction.

	Args:
	    response (Any): Response supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		if response is None:
			return None

		output_text = getattr( response, 'output_text', None )
		if output_text:
			return output_text

		text = getattr( response, 'text', None )
		if text:
			return text

		if isinstance( response, dict ):
			output_text = response.get( 'output_text' ) or response.get( 'text' )
			if output_text:
				return output_text

		return response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'get_text_output( self, response: Any ) -> Any'
		raise ex

raise_management_required

raise_management_required(operation: str) -> None

Raise management required.

Purpose

Provides raise management required behavior for the VectorStores workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
operation str

Operation supplied to the xAI workflow.

required
Source code in grok.py
def raise_management_required( self, operation: str ) -> None:
	"""Raise management required.

	Purpose:
	    Provides raise management required behavior for the VectorStores workflow while preserving provider request and response state.

	Args:
	    operation (str): Operation supplied to the xAI workflow.
	"""
	raise NotImplementedError(
		f'Grok VectorStores.{operation} requires xAI collection-management capability. '
		f'This wrapper is currently configured with XAI_API_KEY only. Use configured '
		f'collections for search, or add the required management credential/path before '
		f'enabling remote collection management.'
	)

create

create(name: str, model: str = None) -> Any

Create.

Purpose

Provides create behavior for the VectorStores workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
name str

Name supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

None

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def create( self, name: str, model: str = None ) -> Any:
	"""Create.

	Purpose:
	    Provides create behavior for the VectorStores workflow while preserving provider request and response state.

	Args:
	    name (str): Name supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'name', name )
		self.name = name
		self.file_name = name
		self.model = model
		self.raise_management_required( 'create' )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'create( self, name: str, model: str=None ) -> Any'
		raise ex

list

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

List.

Purpose

Provides list behavior for the VectorStores workflow while preserving provider request and response state.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Result produced by the xAI workflow.

Source code in grok.py
def list( self ) -> List[ Dict[ str, Any ] ]:
	"""List.

	Purpose:
	    Provides list behavior for the VectorStores workflow while preserving provider request and response state.

	Returns:
	    List[Dict[str, Any]]: Result produced by the xAI workflow.
	"""
	try:
		self.response = self.get_collection_rows( )
		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'list( self ) -> List[ Dict[ str, Any ] ]'
		raise ex

retrieve

retrieve(store_id: str) -> Dict[str, Any]

Retrieve.

Purpose

Provides retrieve behavior for the VectorStores workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
store_id str

Store id supplied to the xAI workflow.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Result produced by the xAI workflow.

Source code in grok.py
def retrieve( self, store_id: str ) -> Dict[ str, Any ]:
	"""Retrieve.

	Purpose:
	    Provides retrieve behavior for the VectorStores workflow while preserving provider request and response state.

	Args:
	    store_id (str): Store id supplied to the xAI workflow.

	Returns:
	    Dict[str, Any]: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'store_id', store_id )
		self.store_id = store_id
		self.collection_id = self.get_collection_id( self.store_id )
		display_name = ''
		for name, collection_id in self.collections.items( ):
			if collection_id == self.collection_id:
				display_name = name
				break

		self.response = {
				'id': self.collection_id,
				'name': display_name or self.collection_id,
				'display_name': display_name or self.collection_id,
				'description': '',
				'status': 'configured',
				'file_counts': '',
				'usage_bytes': '',
				'collection_id': self.collection_id,
				'collection_name': display_name or self.collection_id,
				'collection_description': '',
		}
		return self.response
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'retrieve( self, store_id: str ) -> Dict[ str, Any ]'
		raise ex

search

search(
    prompt: str, store_id: str, model: str = "grok-4-fast"
) -> Any

Search.

Purpose

Provides search behavior for the VectorStores workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
store_id str

Store id supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-4-fast'

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def search( self, prompt: str, store_id: str, model: str = 'grok-4-fast' ) -> Any:
	"""Search.

	Purpose:
	    Provides search behavior for the VectorStores workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    store_id (str): Store id supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'store_id', store_id )
		self.prompt = prompt
		self.model = model
		self.store_id = store_id
		self.collection_id = self.get_collection_id( self.store_id )
		self.store_ids = [ self.collection_id ]
		self.collection_ids = [ self.collection_id ]
		self.response = self.client.collections.search( query=self.prompt,
			collection_ids=self.collection_ids )
		return self.get_text_output( self.response )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'search( self, prompt: str, store_id: str, model: str ) -> Any'
		raise ex

survey

survey(
    prompt: str,
    store_ids: List[str],
    model: str = "grok-4-fast",
) -> Any

Survey.

Purpose

Provides survey behavior for the VectorStores workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
prompt str

Prompt supplied to the xAI workflow.

required
store_ids List[str]

Store ids supplied to the xAI workflow.

required
model str

Model supplied to the xAI workflow.

'grok-4-fast'

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def survey( self, prompt: str, store_ids: List[ str ], model: str = 'grok-4-fast' ) -> Any:
	"""Survey.

	Purpose:
	    Provides survey behavior for the VectorStores workflow while preserving provider request and response state.

	Args:
	    prompt (str): Prompt supplied to the xAI workflow.
	    store_ids (List[str]): Store ids supplied to the xAI workflow.
	    model (str): Model supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'prompt', prompt )
		throw_if( 'store_ids', store_ids )
		self.prompt = prompt
		self.model = model
		self.store_ids = store_ids
		self.collection_ids = [
				self.get_collection_id( store_id )
				for store_id in self.store_ids
		]
		self.response = self.client.collections.search( query=self.prompt,
			collection_ids=self.collection_ids )
		return self.get_text_output( self.response )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'survey( self, prompt: str, store_ids: List[ str ], model: str ) -> Any'
		raise ex

update

update(
    store_id: str,
    filepath: str = None,
    filename: str = None,
) -> Any

Update.

Purpose

Provides update behavior for the VectorStores workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
store_id str

Store id supplied to the xAI workflow.

required
filepath str

Filepath supplied to the xAI workflow.

None
filename str

Filename supplied to the xAI workflow.

None

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def update( self, store_id: str, filepath: str = None, filename: str = None ) -> Any:
	"""Update.

	Purpose:
	    Provides update behavior for the VectorStores workflow while preserving provider request and response state.

	Args:
	    store_id (str): Store id supplied to the xAI workflow.
	    filepath (str): Filepath supplied to the xAI workflow.
	    filename (str): Filename supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'store_id', store_id )
		self.store_id = store_id
		self.collection_id = self.get_collection_id( self.store_id )
		self.file_path = filepath
		self.file_name = filename
		self.raise_management_required( 'update' )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'update( self, store_id: str, filepath: str=None, filename: str=None ) -> Any'
		raise ex

delete

delete(store_id: str) -> Any

Delete.

Purpose

Provides delete behavior for the VectorStores workflow while preserving provider request and response state.

Parameters:

Name Type Description Default
store_id str

Store id supplied to the xAI workflow.

required

Returns:

Name Type Description
Any Any

Result produced by the xAI workflow.

Source code in grok.py
def delete( self, store_id: str ) -> Any:
	"""Delete.

	Purpose:
	    Provides delete behavior for the VectorStores workflow while preserving provider request and response state.

	Args:
	    store_id (str): Store id supplied to the xAI workflow.

	Returns:
	    Any: Result produced by the xAI workflow.
	"""
	try:
		throw_if( 'store_id', store_id )
		self.store_id = store_id
		self.collection_id = self.get_collection_id( self.store_id )
		self.raise_management_required( 'delete' )
	except Exception as e:
		ex = Error( e )
		ex.module = 'grok'
		ex.cause = 'VectorStores'
		ex.method = 'delete( self, store_id: str ) -> Any'
		raise ex

encode_image

encode_image(image_path: str) -> str

Encode image.

Purpose

Encodes local binary content into a text representation required by xAI request payloads.

Parameters:

Name Type Description Default
image_path str

Image path supplied to the xAI workflow.

required

Returns:

Name Type Description
str str

Result produced by the xAI workflow.

Source code in grok.py
def encode_image( image_path: str ) -> str:
	"""Encode image.

	Purpose:
	    Encodes local binary content into a text representation required by xAI request payloads.

	Args:
	    image_path (str): Image path supplied to the xAI workflow.

	Returns:
	    str: Result produced by the xAI workflow.
	"""
	with open( image_path, "rb" ) as image_file:
		return base64.b64encode( image_file.read( ) ).decode( 'utf-8' )

throw_if

throw_if(name: str, value: object) -> None

Throw if.

Purpose

Validates required values before provider request construction.

Parameters:

Name Type Description Default
name str

Name supplied to the xAI workflow.

required
value object

Value supplied to the xAI workflow.

required
Source code in grok.py
def throw_if( name: str, value: object ) -> None:
	"""Throw if.

	Purpose:
	    Validates required values before provider request construction.

	Args:
	    name (str): Name supplied to the xAI workflow.
	    value (object): Value supplied to the xAI workflow.
	"""
	if value is None:
		raise ValueError( f'Argument "{name}" cannot be None.' )

	if isinstance( value, str ) and not value.strip( ):
		raise ValueError( f'Argument "{name}" cannot be empty.' )