API Reference¶
Core modes are the recommended default. Legacy provider-specific modes still work but are deprecated and will show warnings. See the Mode Migration Guide for details.
Core Clients¶
The main client classes for interacting with LLM providers.
Source code in instructor/core/client.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
handle_kwargs(kwargs) ¶
Handle and process keyword arguments for the API call.
This method merges the provided kwargs with the default kwargs stored in the instance. It ensures that any kwargs passed to the method call take precedence over the default ones.
Source code in instructor/core/client.py
Bases: Instructor
Source code in instructor/core/client.py
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 | |
Source code in instructor/core/client.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
Client Creation¶
Functions to create Instructor clients from various providers.
Create an Instructor client from a model string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | Union[str, KnownModelName] | String in format "provider/model-name" (e.g., "openai/gpt-4", "anthropic/claude-3-sonnet", "google/gemini-pro") | required |
async_client | bool | Whether to return an async client | False |
cache | BaseCache | None | Optional cache adapter (e.g., | None |
mode | Union[Mode, None] | Override the default mode for the provider. If not specified, uses the recommended default mode for each provider. | None |
**kwargs | Any | Additional arguments passed to the provider client functions. This includes the cache parameter and any provider-specific options. | {} |
Returns:
| Type | Description |
|---|---|
Union[Instructor, AsyncInstructor] | Instructor or AsyncInstructor instance |
Raises:
| Type | Description |
|---|---|
ValueError | If provider is not supported or model string is invalid |
ImportError | If required package for provider is not installed |
Examples:
>>> import instructor
>>> from instructor.cache import AutoCache
>>>
>>> # Basic usage
>>> client = instructor.from_provider("openai/gpt-4")
>>> client = instructor.from_provider("anthropic/claude-3-sonnet")
>>>
>>> # With caching
>>> cache = AutoCache(maxsize=1000)
>>> client = instructor.from_provider("openai/gpt-4", cache=cache)
>>>
>>> # Async clients
>>> async_client = instructor.from_provider("openai/gpt-4", async_client=True)
Source code in instructor/auto_client.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
Source code in instructor/core/client.py
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 | |
Source code in instructor/core/client.py
DSL Components¶
Domain-specific language components for advanced patterns and data handling.
Backwards compatibility module for instructor.dsl.validators.
This module provides lazy imports to avoid circular import issues.
__getattr__(name) ¶
Lazy import to avoid circular dependencies.
Source code in instructor/dsl/validators.py
IterableBase ¶
Source code in instructor/dsl/iterable.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
tasks_from_mistral_chunks(json_chunks, **kwargs) async classmethod ¶
Process streaming chunks from Mistral and VertexAI.
Handles the specific JSON format used by these providers when streaming.
Source code in instructor/dsl/iterable.py
Partial ¶
Bases: Generic[T_Model]
Generate a new class which has PartialBase as a base class.
Notes
This will enable partial validation of the model while streaming.
Example
Partial[SomeModel]
Source code in instructor/dsl/partial.py
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 | |
__class_getitem__(wrapped_class) ¶
Convert model to one that inherits from PartialBase.
We don't make the fields optional at this point, we just wrap them with Partial so the names of the nested models will be Partial{ModelName}. We want the output of model_json_schema() to reflect the name change, but everything else should be the same as the original model. During validation, we'll generate a true partial model to support partially defined fields.
Source code in instructor/dsl/partial.py
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 | |
__init_subclass__(*args, **kwargs) ¶
Cannot subclass.
Raises:
| Type | Description |
|---|---|
TypeError | Subclassing not allowed. |
__new__(*args, **kwargs) ¶
Cannot instantiate.
Raises:
| Type | Description |
|---|---|
TypeError | Direct instantiation not allowed. |
Source code in instructor/dsl/partial.py
PartialBase ¶
Bases: Generic[T_Model]
Source code in instructor/dsl/partial.py
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 | |
extract_json(completion, mode) staticmethod ¶
Extract JSON chunks from various LLM provider streaming responses.
Each provider has a different structure for streaming responses that needs specific handling to extract the relevant JSON data.
Source code in instructor/dsl/partial.py
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 | |
get_partial_model() cached classmethod ¶
Return a partial model for holding incomplete streaming data.
With completeness-based validation, we use model_construct() to build partial objects without validation. This method creates a model with all fields optional and stores a reference to the original model for validation when JSON is complete.
Source code in instructor/dsl/partial.py
PartialLiteralMixin ¶
DEPRECATED: This mixin is no longer necessary.
With completeness-based validation, Literal and Enum types are handled automatically during streaming: - Incomplete JSON: no validation runs, partial values are stored as-is - Complete JSON: full validation against original model
You can safely remove this mixin from your models.
Source code in instructor/dsl/partial.py
process_potential_object(potential_object, partial_mode, partial_model, **kwargs) ¶
Process a potential JSON object using completeness-based validation.
- If JSON is complete (closed braces/brackets): validate against original model
- If JSON is incomplete: build partial object using model_construct (no validation)
Note: Pydantic v2.10+ has experimental_allow_partial but it doesn't support BaseModel constraints during partial validation (only TypedDict). If Pydantic adds BaseModel support in the future, this could potentially be simplified. See: https://docs.pydantic.dev/latest/concepts/partial_validation/
Source code in instructor/dsl/partial.py
MaybeBase ¶
Bases: BaseModel, Generic[T]
Extract a result from a model, if any, otherwise set the error and message fields.
Source code in instructor/dsl/maybe.py
Maybe(model) ¶
Create a Maybe model for a given Pydantic model. This allows you to return a model that includes fields for result, error, and message for sitatations where the data may not be present in the context.
Usage¶
from pydantic import BaseModel, Field
from instructor import Maybe
class User(BaseModel):
name: str = Field(description="The name of the person")
age: int = Field(description="The age of the person")
role: str = Field(description="The role of the person")
MaybeUser = Maybe(User)
Result¶
class MaybeUser(BaseModel):
result: Optional[User]
error: bool = Field(default=False)
message: Optional[str]
def __bool__(self):
return self.result is not None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | Type[BaseModel] | The Pydantic model to wrap with Maybe. | required |
Returns:
| Name | Type | Description |
|---|---|---|
MaybeModel | Type[BaseModel] | A new Pydantic model that includes fields for |
Source code in instructor/dsl/maybe.py
CitationMixin ¶
Bases: BaseModel
Helpful mixing that can use validation_context={"context": context} in from_response to find the span of the substring_phrase in the context.
Usage¶
from pydantic import BaseModel, Field
from instructor import CitationMixin
class User(BaseModel):
name: str = Field(description="The name of the person")
age: int = Field(description="The age of the person")
role: str = Field(description="The role of the person")
context = "Betty was a student. Jason was a student. Jason is 20 years old"
user = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": "Extract jason from {context}",
},
response_model=User,
validation_context={"context": context},
]
)
for quote in user.substring_quotes:
assert quote in context
print(user.model_dump())
Result¶
{
"name": "Jason Liu",
"age": 20,
"role": "student",
"substring_quotes": [
"Jason was a student",
"Jason is 20 years old",
]
}
Source code in instructor/dsl/citation.py
validate_sources(info) ¶
For each substring_phrase, find the span of the substring_phrase in the context. If the span is not found, remove the substring_phrase from the list.
Source code in instructor/dsl/citation.py
Function Calls & Schema¶
Classes and functions for defining and working with function call schemas.
Backwards compatibility module for instructor.function_calls.
This module re-exports everything from instructor.processing.function_calls for backwards compatibility.
ConfigurationError ¶
Bases: InstructorError
Exception raised for configuration-related errors.
This exception occurs when there are issues with how Instructor is configured or initialized, such as: - Missing required dependencies - Invalid parameters - Incompatible settings - Improper client initialization
Common Scenarios
- Missing provider SDK (e.g., anthropic package not installed)
- Invalid model string format in from_provider()
- Incompatible parameter combinations
- Invalid max_retries configuration
Examples:
try:
# Missing provider SDK
client = instructor.from_provider("anthropic/claude-3")
except ConfigurationError as e:
print(f"Configuration issue: {e}")
# e.g., "The anthropic package is required..."
try:
# Invalid model string
client = instructor.from_provider("invalid-format")
except ConfigurationError as e:
print(f"Configuration issue: {e}")
# e.g., "Model string must be in format 'provider/model-name'"
Source code in instructor/core/exceptions.py
IncompleteOutputException ¶
Bases: InstructorError
Exception raised when LLM output is truncated due to token limits.
This exception occurs when the LLM hits the max_tokens limit before completing its response. This is particularly common with: - Large structured outputs - Very detailed responses - Low max_tokens settings
Attributes:
| Name | Type | Description |
|---|---|---|
last_completion | The partial/incomplete response from the LLM before truncation occurred |
Common Solutions
- Increase max_tokens in your request
- Simplify your response model
- Use streaming with Partial models to get incomplete data
- Break down complex extractions into smaller tasks
Examples:
try:
response = client.chat.completions.create(
response_model=DetailedReport,
max_tokens=100, # Too low
...
)
except IncompleteOutputException as e:
print(f"Output truncated. Partial data: {e.last_completion}")
# Retry with higher max_tokens
response = client.chat.completions.create(
response_model=DetailedReport,
max_tokens=2000,
...
)
See Also
- instructor.dsl.Partial: For handling partial/incomplete responses
Source code in instructor/core/exceptions.py
Mode ¶
Bases: Enum
Mode enumeration for patching LLM API clients.
Each mode determines how the library formats and structures requests to different provider APIs and how it processes their responses.
Source code in instructor/mode.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
json_modes() classmethod ¶
Returns a set of all JSON-based modes.
Source code in instructor/mode.py
tool_modes() classmethod ¶
Returns a set of all tool-based modes.
Source code in instructor/mode.py
warn_mode_functions_deprecation() classmethod ¶
Warn about FUNCTIONS mode deprecation.
Shows the warning only once per session to avoid spamming logs with the same message.
Source code in instructor/mode.py
OpenAISchema ¶
Bases: BaseModel
Source code in instructor/processing/function_calls.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
from_response(completion, validation_context=None, strict=None, mode=Mode.TOOLS) classmethod ¶
Execute the function from the response of an openai chat completion
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completion | ChatCompletion | The response from an openai chat completion | required |
strict | bool | Whether to use strict json parsing | None |
mode | Mode | The openai completion mode | TOOLS |
Returns:
| Name | Type | Description |
|---|---|---|
cls | OpenAISchema | An instance of the class |
Source code in instructor/processing/function_calls.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
openai_schema() ¶
Return the schema in the format of OpenAI's schema as jsonschema
Note
Its important to add a docstring to describe how to best use this class, it will be included in the description attribute and be part of the prompt.
Returns:
| Name | Type | Description |
|---|---|---|
model_json_schema | dict | A dictionary in the format of OpenAI's schema as jsonschema |
Source code in instructor/processing/function_calls.py
parse_cohere_tools(completion, validation_context=None, strict=None) classmethod ¶
Parse Cohere tools response.
Supports: - V1 native tool calls: completion.tool_calls[0].parameters - V2 native tool calls: completion.message.tool_calls[0].function.arguments (JSON string) - V1 text-based: completion.text (prompt-based approach) - V2 text-based: completion.message.content[].text (prompt-based approach)
Source code in instructor/processing/function_calls.py
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 | |
parse_json(completion, validation_context=None, strict=None) classmethod ¶
Parse JSON mode responses using the optimized extraction and validation.
Source code in instructor/processing/function_calls.py
ResponseParsingError ¶
Bases: ValueError, InstructorError
Exception raised when unable to parse the LLM response.
This exception occurs when the LLM's raw response cannot be parsed into the expected format. Common scenarios include: - Malformed JSON in JSON mode - Missing required fields in the response - Unexpected response structure - Invalid tool call format
Note: This exception inherits from both ValueError and InstructorError to maintain backwards compatibility with code that catches ValueError.
Attributes:
| Name | Type | Description |
|---|---|---|
mode | The mode being used when parsing failed | |
raw_response | The raw response that failed to parse (if available) |
Examples:
try:
response = client.chat.completions.create(
response_model=User,
mode=instructor.Mode.JSON,
...
)
except ResponseParsingError as e:
print(f"Failed to parse response in {e.mode} mode")
print(f"Raw response: {e.raw_response}")
# May indicate the model doesn't support this mode well
Backwards compatible with ValueError:
try:
response = client.chat.completions.create(...)
except ValueError as e:
# Still catches ResponseParsingError
print(f"Parsing error: {e}")
Source code in instructor/core/exceptions.py
classproperty ¶
Bases: Generic[R_co]
Descriptor for class-level properties.
Examples:
Source code in instructor/utils/core.py
extract_json_from_codeblock(content) ¶
Extract JSON from a string that may contain extra text.
The function looks for the first '{' and the last '}' in the string and returns the content between them, inclusive. If no braces are found, the original string is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content | str | The string that may contain JSON | required |
Returns:
| Type | Description |
|---|---|
str | The extracted JSON string |
Source code in instructor/utils/core.py
generate_anthropic_schema(model) cached ¶
Generate Anthropic tool schema from a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[BaseModel] | A Pydantic BaseModel subclass | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | A dictionary in the format of Anthropic's tool schema |
Source code in instructor/processing/schema.py
generate_gemini_schema(model) cached ¶
Generate Gemini function schema from a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[BaseModel] | A Pydantic BaseModel subclass | required |
Returns:
| Type | Description |
|---|---|
Any | A Gemini FunctionDeclaration object |
Note
This function is deprecated. The google-generativeai library is being replaced by google-genai.
Source code in instructor/processing/schema.py
generate_openai_schema(model) cached ¶
Generate OpenAI function schema from a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[BaseModel] | A Pydantic BaseModel subclass | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | A dictionary in the format of OpenAI's function schema |
Note
The model's docstring will be used for the function description. Parameter descriptions from the docstring will enrich field descriptions.
Source code in instructor/processing/schema.py
openai_schema(cls) ¶
Wrap a Pydantic model class to add OpenAISchema functionality.
Source code in instructor/processing/function_calls.py
Bases: BaseModel
Source code in instructor/processing/function_calls.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
from_response(completion, validation_context=None, strict=None, mode=Mode.TOOLS) classmethod ¶
Execute the function from the response of an openai chat completion
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
completion | ChatCompletion | The response from an openai chat completion | required |
strict | bool | Whether to use strict json parsing | None |
mode | Mode | The openai completion mode | TOOLS |
Returns:
| Name | Type | Description |
|---|---|---|
cls | OpenAISchema | An instance of the class |
Source code in instructor/processing/function_calls.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
openai_schema() ¶
Return the schema in the format of OpenAI's schema as jsonschema
Note
Its important to add a docstring to describe how to best use this class, it will be included in the description attribute and be part of the prompt.
Returns:
| Name | Type | Description |
|---|---|---|
model_json_schema | dict | A dictionary in the format of OpenAI's schema as jsonschema |
Source code in instructor/processing/function_calls.py
parse_cohere_tools(completion, validation_context=None, strict=None) classmethod ¶
Parse Cohere tools response.
Supports: - V1 native tool calls: completion.tool_calls[0].parameters - V2 native tool calls: completion.message.tool_calls[0].function.arguments (JSON string) - V1 text-based: completion.text (prompt-based approach) - V2 text-based: completion.message.content[].text (prompt-based approach)
Source code in instructor/processing/function_calls.py
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 | |
parse_json(completion, validation_context=None, strict=None) classmethod ¶
Parse JSON mode responses using the optimized extraction and validation.
Source code in instructor/processing/function_calls.py
Wrap a Pydantic model class to add OpenAISchema functionality.
Source code in instructor/processing/function_calls.py
Generate OpenAI function schema from a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[BaseModel] | A Pydantic BaseModel subclass | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | A dictionary in the format of OpenAI's function schema |
Note
The model's docstring will be used for the function description. Parameter descriptions from the docstring will enrich field descriptions.
Source code in instructor/processing/schema.py
Generate Anthropic tool schema from a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[BaseModel] | A Pydantic BaseModel subclass | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | A dictionary in the format of Anthropic's tool schema |
Source code in instructor/processing/schema.py
Generate Gemini function schema from a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model | type[BaseModel] | A Pydantic BaseModel subclass | required |
Returns:
| Type | Description |
|---|---|
Any | A Gemini FunctionDeclaration object |
Note
This function is deprecated. The google-generativeai library is being replaced by google-genai.
Source code in instructor/processing/schema.py
Validation¶
Validation utilities for LLM outputs and async validation support.
Validation components for instructor.
AsyncValidationError ¶
Bases: ValueError, InstructorError
Exception raised during async validation.
This exception is used specifically for errors that occur during asynchronous validation operations. It inherits from both ValueError and InstructorError to maintain compatibility with existing code.
Attributes:
| Name | Type | Description |
|---|---|---|
errors | list[ValueError] | List of ValueError instances from failed validations |
Examples:
from instructor.validation import async_field_validator
class Model(BaseModel):
urls: list[str]
@async_field_validator('urls')
async def validate_urls(cls, v):
# Async validation logic
...
try:
response = await client.chat.completions.create(
response_model=Model,
...
)
except AsyncValidationError as e:
print(f"Async validation failed: {e.errors}")
Source code in instructor/core/exceptions.py
Validator ¶
Bases: OpenAISchema
Validate if an attribute is correct and if not, return a new value with an error message
Source code in instructor/processing/validators.py
llm_validator(statement, client, allow_override=False, model='gpt-3.5-turbo', temperature=0) ¶
Create a validator that uses the LLM to validate an attribute
Usage¶
from instructor import llm_validator
from pydantic import BaseModel, Field, field_validator
class User(BaseModel):
name: str = Annotated[str, llm_validator("The name must be a full name all lowercase")
age: int = Field(description="The age of the person")
try:
user = User(name="Jason Liu", age=20)
except ValidationError as e:
print(e)
1 validation error for User
name
The name is valid but not all lowercase (type=value_error.llm_validator)
Note that there, the error message is written by the LLM, and the error type is value_error.llm_validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statement | str | The statement to validate | required |
model | str | The LLM to use for validation (default: "gpt-4o-mini") | 'gpt-3.5-turbo' |
temperature | float | The temperature to use for the LLM (default: 0) | 0 |
client | OpenAI | The OpenAI client to use (default: None) | required |
Source code in instructor/validation/llm_validators.py
openai_moderation(client) ¶
Validates a message using OpenAI moderation model.
Should only be used for monitoring inputs and outputs of OpenAI APIs Other use cases are disallowed as per: https://platform.openai.com/docs/guides/moderation/overview
Example:
from instructor import OpenAIModeration
class Response(BaseModel):
message: Annotated[str, AfterValidator(OpenAIModeration(openai_client=client))]
Response(message="I hate you")
ValidationError: 1 validation error for Response
message
Value error, `I hate you.` was flagged for ['harassment'] [type=value_error, input_value='I hate you.', input_type=str]
client (OpenAI): The OpenAI client to use, must be sync (default: None)
Source code in instructor/validation/llm_validators.py
Create a validator that uses the LLM to validate an attribute
Usage¶
from instructor import llm_validator
from pydantic import BaseModel, Field, field_validator
class User(BaseModel):
name: str = Annotated[str, llm_validator("The name must be a full name all lowercase")
age: int = Field(description="The age of the person")
try:
user = User(name="Jason Liu", age=20)
except ValidationError as e:
print(e)
1 validation error for User
name
The name is valid but not all lowercase (type=value_error.llm_validator)
Note that there, the error message is written by the LLM, and the error type is value_error.llm_validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statement | str | The statement to validate | required |
model | str | The LLM to use for validation (default: "gpt-4o-mini") | 'gpt-3.5-turbo' |
temperature | float | The temperature to use for the LLM (default: 0) | 0 |
client | OpenAI | The OpenAI client to use (default: None) | required |
Source code in instructor/validation/llm_validators.py
Validates a message using OpenAI moderation model.
Should only be used for monitoring inputs and outputs of OpenAI APIs Other use cases are disallowed as per: https://platform.openai.com/docs/guides/moderation/overview
Example:
from instructor import OpenAIModeration
class Response(BaseModel):
message: Annotated[str, AfterValidator(OpenAIModeration(openai_client=client))]
Response(message="I hate you")
ValidationError: 1 validation error for Response
message
Value error, `I hate you.` was flagged for ['harassment'] [type=value_error, input_value='I hate you.', input_type=str]
client (OpenAI): The OpenAI client to use, must be sync (default: None)
Source code in instructor/validation/llm_validators.py
Batch Processing¶
Batch processing utilities for handling multiple requests efficiently.
Unified Batch Processing API for Multiple Providers
This module provides a unified interface for batch processing across OpenAI and Anthropic providers. The API uses a Maybe/Result-like pattern with custom_id tracking for type-safe handling of batch results.
Supported Providers: - OpenAI: 50% cost savings on batch requests - Anthropic: 50% cost savings on batch requests (Message Batches API)
Features: - Type-safe Maybe/Result pattern for handling successes and errors - Custom ID tracking for correlating results to original requests - Unified interface across all providers - Helper functions for filtering and extracting results
Example usage
from instructor.batch import BatchProcessor, filter_successful, extract_results from pydantic import BaseModel
class User(BaseModel): name: str age: int
processor = BatchProcessor("openai/gpt-4o-mini", User) batch_id = processor.submit_batch("requests.jsonl")
Results are BatchSuccess[T] | BatchError union types¶
all_results = processor.retrieve_results(batch_id) successful_results = filter_successful(all_results) extracted_users = extract_results(all_results)
Documentation: - OpenAI Batch API: https://platform.openai.com/docs/guides/batch - Anthropic Message Batches: https://docs.anthropic.com/en/api/creating-message-batches
BatchError ¶
Bases: BaseModel
Error information for failed batch requests
Source code in instructor/batch/models.py
BatchErrorInfo ¶
BatchFiles ¶
Bases: BaseModel
File references for batch job
Source code in instructor/batch/models.py
BatchJob ¶
Legacy BatchJob class for backward compatibility
Source code in instructor/batch/__init__.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
parse_from_string(content, response_model) classmethod ¶
Enhanced parser that works with all providers using JSON schema
Source code in instructor/batch/__init__.py
BatchJobInfo ¶
Bases: BaseModel
Enhanced unified batch job information with comprehensive provider support
Source code in instructor/batch/models.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
from_anthropic(batch_data) classmethod ¶
Create from Anthropic batch response
Source code in instructor/batch/models.py
from_openai(batch_data) classmethod ¶
Create from OpenAI batch response
Source code in instructor/batch/models.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
BatchProcessor ¶
Bases: Generic[T]
Unified batch processor that works across all providers
Source code in instructor/batch/processor.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
cancel_batch(batch_id) ¶
Cancel a batch job
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_id | str | The batch job ID to cancel | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | Dict containing the cancelled batch information |
Source code in instructor/batch/processor.py
create_batch_from_messages(messages_list, file_path=None, max_tokens=1000, temperature=0.1) ¶
Create batch file from list of message conversations
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages_list | list[list[dict[str, Any]]] | List of message conversations, each as a list of message dicts | required |
file_path | str | None | Path to save the batch request file. If None, returns BytesIO buffer | None |
max_tokens | int | None | Maximum tokens per request | 1000 |
temperature | float | None | Temperature for generation | 0.1 |
Returns:
| Type | Description |
|---|---|
str | BytesIO | The file path where the batch was saved, or BytesIO buffer if file_path is None |
Source code in instructor/batch/processor.py
delete_batch(batch_id) ¶
Delete a batch job (only available for completed batches)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_id | str | The batch job ID to delete | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | Dict containing the deletion confirmation |
Source code in instructor/batch/processor.py
get_batch_status(batch_id) ¶
get_results(batch_id, file_path=None) ¶
Get batch results, optionally saving raw results to a file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_id | str | The batch job ID | required |
file_path | str | None | Optional file path to save raw results. If provided, raw results will be saved to this file. If not provided, results are only kept in memory. | None |
Returns:
| Type | Description |
|---|---|
list[BatchResult] | List of BatchResult objects (BatchSuccess[T] or BatchError) |
Source code in instructor/batch/processor.py
list_batches(limit=10) ¶
List batch jobs for the current provider
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit | int | Maximum number of batch jobs to return | 10 |
Returns:
| Type | Description |
|---|---|
list[BatchJobInfo] | List of BatchJobInfo objects with normalized batch information |
Source code in instructor/batch/processor.py
parse_results(results_content) ¶
Parse batch results from content string into Maybe-like results with custom_id tracking
Source code in instructor/batch/processor.py
retrieve_results(batch_id) ¶
Retrieve and parse batch results from the provider
submit_batch(file_path_or_buffer, metadata=None, **kwargs) ¶
Submit batch job to the provider and return job ID
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path_or_buffer | str | BytesIO | Path to the batch request file or BytesIO buffer | required |
metadata | dict[str, Any] | None | Optional metadata to attach to the batch job | None |
**kwargs | Additional provider-specific arguments | {} |
Source code in instructor/batch/processor.py
BatchRequest ¶
Bases: BaseModel, Generic[T]
Unified batch request that works across all providers using JSON schema
Source code in instructor/batch/request.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
get_json_schema() ¶
save_to_file(file_path_or_buffer, provider) ¶
Save batch request to file or BytesIO buffer in provider-specific format
Source code in instructor/batch/request.py
to_anthropic_format() ¶
Convert to Anthropic batch format with JSON schema
Source code in instructor/batch/request.py
to_openai_format() ¶
Convert to OpenAI batch format with JSON schema
Source code in instructor/batch/request.py
BatchRequestCounts ¶
Bases: BaseModel
Unified request counts across providers
Source code in instructor/batch/models.py
BatchStatus ¶
Bases: str, Enum
Normalized batch status across providers
Source code in instructor/batch/models.py
BatchSuccess ¶
Bases: BaseModel, Generic[T]
Successful batch result with custom_id
Source code in instructor/batch/models.py
BatchTimestamps ¶
Bases: BaseModel
Comprehensive timestamp tracking
Source code in instructor/batch/models.py
extract_results(results) ¶
filter_errors(results) ¶
filter_successful(results) ¶
get_results_by_custom_id(results) ¶
Bases: Generic[T]
Unified batch processor that works across all providers
Source code in instructor/batch/processor.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
cancel_batch(batch_id) ¶
Cancel a batch job
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_id | str | The batch job ID to cancel | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | Dict containing the cancelled batch information |
Source code in instructor/batch/processor.py
create_batch_from_messages(messages_list, file_path=None, max_tokens=1000, temperature=0.1) ¶
Create batch file from list of message conversations
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages_list | list[list[dict[str, Any]]] | List of message conversations, each as a list of message dicts | required |
file_path | str | None | Path to save the batch request file. If None, returns BytesIO buffer | None |
max_tokens | int | None | Maximum tokens per request | 1000 |
temperature | float | None | Temperature for generation | 0.1 |
Returns:
| Type | Description |
|---|---|
str | BytesIO | The file path where the batch was saved, or BytesIO buffer if file_path is None |
Source code in instructor/batch/processor.py
delete_batch(batch_id) ¶
Delete a batch job (only available for completed batches)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_id | str | The batch job ID to delete | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | Dict containing the deletion confirmation |
Source code in instructor/batch/processor.py
get_batch_status(batch_id) ¶
get_results(batch_id, file_path=None) ¶
Get batch results, optionally saving raw results to a file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_id | str | The batch job ID | required |
file_path | str | None | Optional file path to save raw results. If provided, raw results will be saved to this file. If not provided, results are only kept in memory. | None |
Returns:
| Type | Description |
|---|---|
list[BatchResult] | List of BatchResult objects (BatchSuccess[T] or BatchError) |
Source code in instructor/batch/processor.py
list_batches(limit=10) ¶
List batch jobs for the current provider
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit | int | Maximum number of batch jobs to return | 10 |
Returns:
| Type | Description |
|---|---|
list[BatchJobInfo] | List of BatchJobInfo objects with normalized batch information |
Source code in instructor/batch/processor.py
parse_results(results_content) ¶
Parse batch results from content string into Maybe-like results with custom_id tracking
Source code in instructor/batch/processor.py
retrieve_results(batch_id) ¶
Retrieve and parse batch results from the provider
submit_batch(file_path_or_buffer, metadata=None, **kwargs) ¶
Submit batch job to the provider and return job ID
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path_or_buffer | str | BytesIO | Path to the batch request file or BytesIO buffer | required |
metadata | dict[str, Any] | None | Optional metadata to attach to the batch job | None |
**kwargs | Additional provider-specific arguments | {} |
Source code in instructor/batch/processor.py
Bases: BaseModel, Generic[T]
Unified batch request that works across all providers using JSON schema
Source code in instructor/batch/request.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
get_json_schema() ¶
save_to_file(file_path_or_buffer, provider) ¶
Save batch request to file or BytesIO buffer in provider-specific format
Source code in instructor/batch/request.py
to_anthropic_format() ¶
Convert to Anthropic batch format with JSON schema
Source code in instructor/batch/request.py
to_openai_format() ¶
Convert to OpenAI batch format with JSON schema
Source code in instructor/batch/request.py
Legacy BatchJob class for backward compatibility
Source code in instructor/batch/__init__.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
parse_from_string(content, response_model) classmethod ¶
Enhanced parser that works with all providers using JSON schema
Source code in instructor/batch/__init__.py
Distillation¶
Tools for distillation and fine-tuning workflows.
Instructions ¶
Source code in instructor/distil.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
__init__(name=None, id=None, log_handlers=None, finetune_format=FinetuneFormat.MESSAGES, indent=2, include_code_body=False, openai_client=None) ¶
Instructions for distillation and dispatch.
:param name: Name of the instructions. :param id: ID of the instructions. :param log_handlers: List of log handlers to use. :param finetune_format: Format to use for finetuning. :param indent: Indentation to use for finetuning. :param include_code_body: Whether to include the code body in the finetuning.
Source code in instructor/distil.py
distil(*args, name=None, mode='distil', model='gpt-3.5-turbo', fine_tune_format=None) ¶
Decorator to track the function call and response, supports distillation and dispatch modes.
If used without arguments, it must be used as a decorator.
:Example:
@distil def my_function() -> MyModel: return MyModel()
@distil(name="my_function") def my_function() -> MyModel: return MyModel()
:param fn: Function to track. :param name: Name of the function to track. Defaults to the function name. :param mode: Mode to use for distillation. Defaults to "distil".
Source code in instructor/distil.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
track(fn, args, kwargs, resp, name=None, finetune_format=FinetuneFormat.MESSAGES) ¶
Track the function call and response in a log file, later used for finetuning.
:param fn: Function to track. :param args: Arguments passed to the function. :param kwargs: Keyword arguments passed to the function. :param resp: Response returned by the function. :param name: Name of the function to track. Defaults to the function name. :param finetune_format: Format to use for finetuning. Defaults to "raw".
Source code in instructor/distil.py
format_function(func) cached ¶
Format a function as a string with docstring and body.
Source code in instructor/distil.py
get_signature_from_fn(fn) ¶
Get the function signature as a string.
:Example:
def my_function(a: int, b: int) -> int: return a + b
get_signature_from_fn(my_function) "def my_function(a: int, b: int) -> int"
:param fn: Function to get the signature for. :return: Function signature as a string.
Source code in instructor/distil.py
is_return_type_base_model_or_instance(func) ¶
Check if the return type of a function is a pydantic BaseModel or an instance of it.
:param func: Function to check. :return: True if the return type is a pydantic BaseModel or an instance of it.
Source code in instructor/distil.py
Source code in instructor/distil.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
__init__(name=None, id=None, log_handlers=None, finetune_format=FinetuneFormat.MESSAGES, indent=2, include_code_body=False, openai_client=None) ¶
Instructions for distillation and dispatch.
:param name: Name of the instructions. :param id: ID of the instructions. :param log_handlers: List of log handlers to use. :param finetune_format: Format to use for finetuning. :param indent: Indentation to use for finetuning. :param include_code_body: Whether to include the code body in the finetuning.
Source code in instructor/distil.py
distil(*args, name=None, mode='distil', model='gpt-3.5-turbo', fine_tune_format=None) ¶
Decorator to track the function call and response, supports distillation and dispatch modes.
If used without arguments, it must be used as a decorator.
:Example:
@distil def my_function() -> MyModel: return MyModel()
@distil(name="my_function") def my_function() -> MyModel: return MyModel()
:param fn: Function to track. :param name: Name of the function to track. Defaults to the function name. :param mode: Mode to use for distillation. Defaults to "distil".
Source code in instructor/distil.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
track(fn, args, kwargs, resp, name=None, finetune_format=FinetuneFormat.MESSAGES) ¶
Track the function call and response in a log file, later used for finetuning.
:param fn: Function to track. :param args: Arguments passed to the function. :param kwargs: Keyword arguments passed to the function. :param resp: Response returned by the function. :param name: Name of the function to track. Defaults to the function name. :param finetune_format: Format to use for finetuning. Defaults to "raw".
Source code in instructor/distil.py
Multimodal¶
Support for image and audio content in LLM requests.
Audio ¶
Bases: BaseModel
Represents an audio that can be loaded from a URL or file path.
Source code in instructor/processing/multimodal.py
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 | |
autodetect(source) classmethod ¶
Attempt to autodetect an audio from a source string or Path.
Source code in instructor/processing/multimodal.py
autodetect_safely(source) classmethod ¶
Safely attempt to autodetect an audio from a source string or path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | Union[str, path] | The source string or path. | required |
Returns: An Audio if the source is detected to be a valid audio, otherwise the source itself as a string.
Source code in instructor/processing/multimodal.py
from_gs_url(data_uri, timeout=30) classmethod ¶
Create an Audio instance from a Google Cloud Storage URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_uri | str | GCS URL starting with gs:// | required |
timeout | int | Request timeout in seconds (default: 30) | 30 |
Source code in instructor/processing/multimodal.py
from_path(path) classmethod ¶
Create an Audio instance from a file path.
Source code in instructor/processing/multimodal.py
from_url(url) classmethod ¶
Create an Audio instance from a URL.
Source code in instructor/processing/multimodal.py
to_genai() ¶
Convert the Audio instance to Google GenAI's API format.
Source code in instructor/processing/multimodal.py
to_openai(mode) ¶
Convert the Audio instance to OpenAI's API format.
Source code in instructor/processing/multimodal.py
Image ¶
Bases: BaseModel
Source code in instructor/processing/multimodal.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
autodetect(source) classmethod ¶
Attempt to autodetect an image from a source string or Path.
Source code in instructor/processing/multimodal.py
autodetect_safely(source) classmethod ¶
Safely attempt to autodetect an image from a source string or path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | Union[str, path] | The source string or path. | required |
Returns: An Image if the source is detected to be a valid image, otherwise the source itself as a string.
Source code in instructor/processing/multimodal.py
from_gs_url(data_uri, timeout=30) classmethod ¶
Create an Image instance from a Google Cloud Storage URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_uri | str | GCS URL starting with gs:// | required |
timeout | int | Request timeout in seconds (default: 30) | 30 |
Source code in instructor/processing/multimodal.py
to_genai() ¶
Convert the Image instance to Google GenAI's API format.
Source code in instructor/processing/multimodal.py
url_to_base64(url) cached staticmethod ¶
Cachable helper method for getting image url and encoding to base64.
Source code in instructor/processing/multimodal.py
ImageWithCacheControl ¶
Bases: Image
Image with Anthropic prompt caching support.
Source code in instructor/processing/multimodal.py
to_anthropic() ¶
Override Anthropic return with cache_control.
PDF ¶
Bases: BaseModel
Source code in instructor/processing/multimodal.py
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 | |
autodetect(source) classmethod ¶
Attempt to autodetect a PDF from a source string or Path. Args: source (Union[str,path]): The source string or path. Returns: A PDF if the source is detected to be a valid PDF. Raises: ValueError: If the source is not detected to be a valid PDF.
Source code in instructor/processing/multimodal.py
autodetect_safely(source) classmethod ¶
Safely attempt to autodetect a PDF from a source string or path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | Union[str, path] | The source string or path. | required |
Returns: A PDF if the source is detected to be a valid PDF, otherwise the source itself as a string.
Source code in instructor/processing/multimodal.py
from_gs_url(data_uri, timeout=30) classmethod ¶
Create a PDF instance from a Google Cloud Storage URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_uri | str | GCS URL starting with gs:// | required |
timeout | int | Request timeout in seconds (default: 30) | 30 |
Source code in instructor/processing/multimodal.py
to_anthropic() ¶
Convert to Anthropic's document format.
Source code in instructor/processing/multimodal.py
to_bedrock(name=None) ¶
Convert to Bedrock's document format.
Source code in instructor/processing/multimodal.py
to_openai(mode) ¶
Convert to OpenAI's document format.
Source code in instructor/processing/multimodal.py
PDFWithCacheControl ¶
PDFWithGenaiFile ¶
Bases: PDF
Source code in instructor/processing/multimodal.py
from_existing_genai_file(file_name) classmethod ¶
Create a new PDFWithGenaiFile from a file URL.
Source code in instructor/processing/multimodal.py
from_new_genai_file(file_path, retry_delay=10, max_retries=20) classmethod ¶
Create a new PDFWithGenaiFile from a file path.
Source code in instructor/processing/multimodal.py
autodetect_media(source) ¶
Autodetect images, audio, or PDFs from a given source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path | Image | Audio | PDF | URL, file path, Path, or data URI to inspect. | required |
Returns:
| Type | Description |
|---|---|
Image | Audio | PDF | str | The detected :class: |
Image | Audio | PDF | str | If detection fails, the original source is returned. |
Source code in instructor/processing/multimodal.py
convert_contents(contents, mode) ¶
Convert content items to the appropriate format based on the specified mode.
Source code in instructor/processing/multimodal.py
convert_messages(messages, mode, autodetect_images=False) ¶
Convert messages to the appropriate format based on the specified mode.
Source code in instructor/processing/multimodal.py
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 | |
extract_genai_multimodal_content(contents, autodetect_images=True) ¶
Convert Typed Contents to the appropriate format for Google GenAI.
Source code in instructor/processing/multimodal.py
Bases: BaseModel
Source code in instructor/processing/multimodal.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
autodetect(source) classmethod ¶
Attempt to autodetect an image from a source string or Path.
Source code in instructor/processing/multimodal.py
autodetect_safely(source) classmethod ¶
Safely attempt to autodetect an image from a source string or path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | Union[str, path] | The source string or path. | required |
Returns: An Image if the source is detected to be a valid image, otherwise the source itself as a string.
Source code in instructor/processing/multimodal.py
from_gs_url(data_uri, timeout=30) classmethod ¶
Create an Image instance from a Google Cloud Storage URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_uri | str | GCS URL starting with gs:// | required |
timeout | int | Request timeout in seconds (default: 30) | 30 |
Source code in instructor/processing/multimodal.py
to_genai() ¶
Convert the Image instance to Google GenAI's API format.
Source code in instructor/processing/multimodal.py
url_to_base64(url) cached staticmethod ¶
Cachable helper method for getting image url and encoding to base64.
Source code in instructor/processing/multimodal.py
Bases: BaseModel
Represents an audio that can be loaded from a URL or file path.
Source code in instructor/processing/multimodal.py
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 | |
autodetect(source) classmethod ¶
Attempt to autodetect an audio from a source string or Path.
Source code in instructor/processing/multimodal.py
autodetect_safely(source) classmethod ¶
Safely attempt to autodetect an audio from a source string or path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | Union[str, path] | The source string or path. | required |
Returns: An Audio if the source is detected to be a valid audio, otherwise the source itself as a string.
Source code in instructor/processing/multimodal.py
from_gs_url(data_uri, timeout=30) classmethod ¶
Create an Audio instance from a Google Cloud Storage URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_uri | str | GCS URL starting with gs:// | required |
timeout | int | Request timeout in seconds (default: 30) | 30 |
Source code in instructor/processing/multimodal.py
from_path(path) classmethod ¶
Create an Audio instance from a file path.
Source code in instructor/processing/multimodal.py
from_url(url) classmethod ¶
Create an Audio instance from a URL.
Source code in instructor/processing/multimodal.py
to_genai() ¶
Convert the Audio instance to Google GenAI's API format.
Source code in instructor/processing/multimodal.py
to_openai(mode) ¶
Convert the Audio instance to OpenAI's API format.
Source code in instructor/processing/multimodal.py
Mode & Provider¶
Enumerations for modes and providers.
Bases: Enum
Mode enumeration for patching LLM API clients.
Each mode determines how the library formats and structures requests to different provider APIs and how it processes their responses.
Source code in instructor/mode.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
json_modes() classmethod ¶
Returns a set of all JSON-based modes.
Source code in instructor/mode.py
tool_modes() classmethod ¶
Returns a set of all tool-based modes.
Source code in instructor/mode.py
warn_mode_functions_deprecation() classmethod ¶
Warn about FUNCTIONS mode deprecation.
Shows the warning only once per session to avoid spamming logs with the same message.
Source code in instructor/mode.py
Bases: Enum
Source code in instructor/utils/providers.py
Exceptions¶
Exception classes for error handling.
AsyncValidationError ¶
Bases: ValueError, InstructorError
Exception raised during async validation.
This exception is used specifically for errors that occur during asynchronous validation operations. It inherits from both ValueError and InstructorError to maintain compatibility with existing code.
Attributes:
| Name | Type | Description |
|---|---|---|
errors | list[ValueError] | List of ValueError instances from failed validations |
Examples:
from instructor.validation import async_field_validator
class Model(BaseModel):
urls: list[str]
@async_field_validator('urls')
async def validate_urls(cls, v):
# Async validation logic
...
try:
response = await client.chat.completions.create(
response_model=Model,
...
)
except AsyncValidationError as e:
print(f"Async validation failed: {e.errors}")
Source code in instructor/core/exceptions.py
ClientError ¶
Bases: InstructorError
Exception raised for client initialization or usage errors.
This exception covers errors related to improper client usage or initialization that don't fit other categories.
Common Scenarios
- Passing invalid client object to from_* functions
- Missing required client configuration
- Attempting operations on improperly initialized clients
Examples:
try:
# Invalid client type
client = instructor.from_openai("not_a_client")
except ClientError as e:
print(f"Client error: {e}")
Source code in instructor/core/exceptions.py
ConfigurationError ¶
Bases: InstructorError
Exception raised for configuration-related errors.
This exception occurs when there are issues with how Instructor is configured or initialized, such as: - Missing required dependencies - Invalid parameters - Incompatible settings - Improper client initialization
Common Scenarios
- Missing provider SDK (e.g., anthropic package not installed)
- Invalid model string format in from_provider()
- Incompatible parameter combinations
- Invalid max_retries configuration
Examples:
try:
# Missing provider SDK
client = instructor.from_provider("anthropic/claude-3")
except ConfigurationError as e:
print(f"Configuration issue: {e}")
# e.g., "The anthropic package is required..."
try:
# Invalid model string
client = instructor.from_provider("invalid-format")
except ConfigurationError as e:
print(f"Configuration issue: {e}")
# e.g., "Model string must be in format 'provider/model-name'"
Source code in instructor/core/exceptions.py
FailedAttempt ¶
Bases: NamedTuple
Represents a single failed retry attempt.
This immutable tuple stores information about a failed attempt during the retry process, allowing users to inspect what went wrong across multiple retry attempts.
Attributes:
| Name | Type | Description |
|---|---|---|
attempt_number | int | The sequential number of this attempt (1-indexed) |
exception | Exception | The exception that caused this attempt to fail |
completion | Any | None | Optional partial completion data from the LLM before the failure occurred. This can be useful for debugging or implementing custom recovery logic. |
Examples:
from instructor.core.exceptions import InstructorRetryException
try:
response = client.chat.completions.create(...)
except InstructorRetryException as e:
for attempt in e.failed_attempts:
print(f"Attempt {attempt.attempt_number} failed:")
print(f" Error: {attempt.exception}")
print(f" Partial data: {attempt.completion}")
Source code in instructor/core/exceptions.py
IncompleteOutputException ¶
Bases: InstructorError
Exception raised when LLM output is truncated due to token limits.
This exception occurs when the LLM hits the max_tokens limit before completing its response. This is particularly common with: - Large structured outputs - Very detailed responses - Low max_tokens settings
Attributes:
| Name | Type | Description |
|---|---|---|
last_completion | The partial/incomplete response from the LLM before truncation occurred |
Common Solutions
- Increase max_tokens in your request
- Simplify your response model
- Use streaming with Partial models to get incomplete data
- Break down complex extractions into smaller tasks
Examples:
try:
response = client.chat.completions.create(
response_model=DetailedReport,
max_tokens=100, # Too low
...
)
except IncompleteOutputException as e:
print(f"Output truncated. Partial data: {e.last_completion}")
# Retry with higher max_tokens
response = client.chat.completions.create(
response_model=DetailedReport,
max_tokens=2000,
...
)
See Also
- instructor.dsl.Partial: For handling partial/incomplete responses
Source code in instructor/core/exceptions.py
InstructorError ¶
Bases: Exception
Base exception for all Instructor-specific errors.
This is the root exception class for the Instructor library. All custom exceptions in Instructor inherit from this class, allowing you to catch any Instructor-related error with a single except clause.
Attributes:
| Name | Type | Description |
|---|---|---|
failed_attempts | list[FailedAttempt] | None | Optional list of FailedAttempt objects tracking retry attempts that failed before this exception was raised. Each attempt includes the attempt number, exception, and partial completion data. |
Examples:
Catch all Instructor errors:
try:
response = client.chat.completions.create(...)
except InstructorError as e:
logger.error(f"Instructor error: {e}")
# Handle any Instructor-specific error
Create error from another exception:
See Also
- FailedAttempt: NamedTuple containing retry attempt information
- InstructorRetryException: Raised when retries are exhausted
Source code in instructor/core/exceptions.py
from_exception(exception, failed_attempts=None) classmethod ¶
Create an InstructorError from another exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exception | Exception | The original exception to wrap | required |
failed_attempts | list[FailedAttempt] | None | Optional list of failed retry attempts | None |
Returns:
| Type | Description |
|---|---|
| A new instance of this exception class with the message from | |
| the original exception |
Source code in instructor/core/exceptions.py
InstructorRetryException ¶
Bases: InstructorError
Exception raised when all retry attempts have been exhausted.
This exception is raised after the maximum number of retries has been reached without successfully validating the LLM response. It contains detailed information about all failed attempts, making it useful for debugging and implementing custom recovery logic.
Attributes:
| Name | Type | Description |
|---|---|---|
last_completion | The final (unsuccessful) completion from the LLM | |
messages | The conversation history sent to the LLM (deprecated, use create_kwargs instead) | |
n_attempts | The total number of attempts made | |
total_usage | The cumulative token usage across all attempts | |
create_kwargs | The parameters used in the create() call, including model, messages, temperature, etc. | |
failed_attempts | list[FailedAttempt] | None | List of FailedAttempt objects with details about each failed retry |
Common Causes
- Response model too strict for the LLM's capabilities
- Ambiguous or contradictory requirements
- LLM model not powerful enough for the task
- Insufficient context or examples in the prompt
Examples:
try:
response = client.chat.completions.create(
response_model=StrictModel,
max_retries=3,
...
)
except InstructorRetryException as e:
print(f"Failed after {e.n_attempts} attempts")
print(f"Total tokens used: {e.total_usage}")
print(f"Model used: {e.create_kwargs.get('model')}")
# Inspect failed attempts
for attempt in e.failed_attempts:
print(f"Attempt {attempt.attempt_number}: {attempt.exception}")
# Implement fallback strategy
response = fallback_handler(e.last_completion)
See Also
- FailedAttempt: Contains details about each retry attempt
- ValidationError: Raised when response validation fails
Source code in instructor/core/exceptions.py
ModeError ¶
Bases: InstructorError
Exception raised when an invalid mode is used for a provider.
Different LLM providers support different modes (e.g., TOOLS, JSON, FUNCTIONS). This exception is raised when you try to use a mode that isn't supported by the current provider.
Attributes:
| Name | Type | Description |
|---|---|---|
mode | The invalid mode that was attempted | |
provider | The provider name | |
valid_modes | List of modes supported by this provider |
Examples:
try:
client = instructor.from_openai(
openai_client,
mode=instructor.Mode.ANTHROPIC_TOOLS # Wrong for OpenAI
)
except ModeError as e:
print(f"Invalid mode '{e.mode}' for {e.provider}")
print(f"Use one of: {', '.join(e.valid_modes)}")
# Retry with valid mode
client = instructor.from_openai(
openai_client,
mode=instructor.Mode.TOOLS
)
See Also
- instructor.Mode: Enum of all available modes
Source code in instructor/core/exceptions.py
MultimodalError ¶
Bases: ValueError, InstructorError
Exception raised for multimodal content processing errors.
This exception is raised when there are issues processing multimodal content (images, audio, PDFs, etc.), such as: - Unsupported file formats - File not found - Invalid base64 encoding - Provider doesn't support multimodal content
Note: This exception inherits from both ValueError and InstructorError to maintain backwards compatibility with code that catches ValueError.
Attributes:
| Name | Type | Description |
|---|---|---|
content_type | The type of content that failed (e.g., 'image', 'audio', 'pdf') | |
file_path | The file path if applicable |
Examples:
from instructor import Image
try:
response = client.chat.completions.create(
response_model=Analysis,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Analyze this image"},
Image.from_path("/invalid/path.jpg")
]
}]
)
except MultimodalError as e:
print(f"Multimodal error with {e.content_type}: {e}")
if e.file_path:
print(f"File path: {e.file_path}")
Backwards compatible with ValueError:
try:
img = Image.from_path("/path/to/image.jpg")
except ValueError as e:
# Still catches MultimodalError
print(f"Image error: {e}")
Source code in instructor/core/exceptions.py
ProviderError ¶
Bases: InstructorError
Exception raised for provider-specific errors.
This exception is used to wrap errors specific to LLM providers (OpenAI, Anthropic, etc.) and provides context about which provider caused the error.
Attributes:
| Name | Type | Description |
|---|---|---|
provider | The name of the provider that raised the error (e.g., "openai", "anthropic", "gemini") |
Common Causes
- API authentication failures
- Rate limiting
- Invalid model names
- Provider-specific API errors
- Network connectivity issues
Examples:
try:
client = instructor.from_openai(openai_client)
response = client.chat.completions.create(...)
except ProviderError as e:
print(f"Provider {e.provider} error: {e}")
# Implement provider-specific error handling
if e.provider == "openai":
# Handle OpenAI-specific errors
pass
Source code in instructor/core/exceptions.py
ResponseParsingError ¶
Bases: ValueError, InstructorError
Exception raised when unable to parse the LLM response.
This exception occurs when the LLM's raw response cannot be parsed into the expected format. Common scenarios include: - Malformed JSON in JSON mode - Missing required fields in the response - Unexpected response structure - Invalid tool call format
Note: This exception inherits from both ValueError and InstructorError to maintain backwards compatibility with code that catches ValueError.
Attributes:
| Name | Type | Description |
|---|---|---|
mode | The mode being used when parsing failed | |
raw_response | The raw response that failed to parse (if available) |
Examples:
try:
response = client.chat.completions.create(
response_model=User,
mode=instructor.Mode.JSON,
...
)
except ResponseParsingError as e:
print(f"Failed to parse response in {e.mode} mode")
print(f"Raw response: {e.raw_response}")
# May indicate the model doesn't support this mode well
Backwards compatible with ValueError:
try:
response = client.chat.completions.create(...)
except ValueError as e:
# Still catches ResponseParsingError
print(f"Parsing error: {e}")
Source code in instructor/core/exceptions.py
ValidationError ¶
Bases: InstructorError
Exception raised when LLM response validation fails.
This exception occurs when the LLM's response doesn't meet the validation requirements defined in your Pydantic model, such as: - Field validation failures - Type mismatches - Custom validator failures - Missing required fields
Note: This is distinct from Pydantic's ValidationError and provides Instructor-specific context through the failed_attempts attribute.
Examples:
from pydantic import BaseModel, field_validator
class User(BaseModel):
age: int
@field_validator('age')
def age_must_be_positive(cls, v):
if v < 0:
raise ValueError('Age must be positive')
return v
try:
response = client.chat.completions.create(
response_model=User,
...
)
except ValidationError as e:
print(f"Validation failed: {e}")
# Validation errors are automatically retried
See Also
- InstructorRetryException: Raised when validation fails repeatedly
Source code in instructor/core/exceptions.py
Hooks¶
Event hooks system for monitoring and intercepting LLM interactions.
CompletionErrorHandler ¶
CompletionKwargsHandler ¶
CompletionResponseHandler ¶
Hooks ¶
Hooks class for handling and emitting events related to completion processes.
This class provides a mechanism to register event handlers and emit events for various stages of the completion process.
Source code in instructor/core/hooks.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
__add__(other) ¶
Combine two Hooks instances into a new one.
This creates a new Hooks instance that contains all handlers from both the current instance and the other instance. Handlers are combined by appending the other's handlers after the current instance's handlers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Hooks | Another Hooks instance to combine with this one. | required |
Returns:
| Type | Description |
|---|---|
Hooks | A new Hooks instance containing all handlers from both instances. |
Example
hooks1 = Hooks() hooks2 = Hooks() hooks1.on("completion:kwargs", lambda **kw: print("Hook 1")) hooks2.on("completion:kwargs", lambda **kw: print("Hook 2")) combined = hooks1 + hooks2 combined.emit_completion_arguments() # Prints both "Hook 1" and "Hook 2"
Source code in instructor/core/hooks.py
__iadd__(other) ¶
Add another Hooks instance to this one in-place.
This modifies the current instance by adding all handlers from the other instance. The other instance's handlers are appended after the current instance's handlers for each event type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Hooks | Another Hooks instance to add to this one. | required |
Returns:
| Type | Description |
|---|---|
Hooks | This Hooks instance (for method chaining). |
Example
hooks1 = Hooks() hooks2 = Hooks() hooks1.on("completion:kwargs", lambda **kw: print("Hook 1")) hooks2.on("completion:kwargs", lambda **kw: print("Hook 2")) hooks1 += hooks2 hooks1.emit_completion_arguments() # Prints both "Hook 1" and "Hook 2"
Source code in instructor/core/hooks.py
__init__() ¶
clear(hook_name=None) ¶
Clear handlers for a specific event or all events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookNameType | None | The name of the event to clear handlers for. If None, all handlers are cleared. | None |
Source code in instructor/core/hooks.py
combine(*hooks_instances) classmethod ¶
Combine multiple Hooks instances into a new one.
This class method creates a new Hooks instance that contains all handlers from all provided instances. Handlers are combined in the order of the provided instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*hooks_instances | Hooks | Variable number of Hooks instances to combine. | () |
Returns:
| Type | Description |
|---|---|
Hooks | A new Hooks instance containing all handlers from all instances. |
Example
hooks1 = Hooks() hooks2 = Hooks() hooks3 = Hooks() hooks1.on("completion:kwargs", lambda **kw: print("Hook 1")) hooks2.on("completion:kwargs", lambda **kw: print("Hook 2")) hooks3.on("completion:kwargs", lambda **kw: print("Hook 3")) combined = Hooks.combine(hooks1, hooks2, hooks3) combined.emit_completion_arguments() # Prints all three hooks
Source code in instructor/core/hooks.py
copy() ¶
Create a deep copy of this Hooks instance.
Returns:
| Type | Description |
|---|---|
Hooks | A new Hooks instance with all the same handlers. |
Example
original = Hooks() original.on("completion:kwargs", lambda **kw: print("Hook")) copy = original.copy() copy.emit_completion_arguments() # Prints "Hook"
Source code in instructor/core/hooks.py
emit(hook_name, *args, **kwargs) ¶
Generic method to emit events for any hook type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookName | The hook to emit | required |
*args | Any | Positional arguments to pass to handlers | () |
**kwargs | Any | Keyword arguments to pass to handlers | {} |
Source code in instructor/core/hooks.py
emit_completion_arguments(*args, **kwargs) ¶
Emit a completion arguments event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args | Any | Positional arguments to pass to handlers | () |
**kwargs | Any | Keyword arguments to pass to handlers | {} |
Source code in instructor/core/hooks.py
emit_completion_error(error) ¶
Emit a completion error event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error | Exception | The exception to pass to handlers | required |
emit_completion_last_attempt(error) ¶
Emit a completion last attempt event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error | Exception | The exception to pass to handlers | required |
emit_completion_response(response) ¶
Emit a completion response event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response | Any | The completion response to pass to handlers | required |
emit_parse_error(error) ¶
Emit a parse error event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error | Exception | The exception to pass to handlers | required |
get_hook_name(hook_name) ¶
Convert a string hook name to its corresponding enum value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookNameType | Either a HookName enum value or string representation. | required |
Returns:
| Type | Description |
|---|---|
HookName | The corresponding HookName enum value. |
Raises:
| Type | Description |
|---|---|
ValueError | If the string doesn't match any HookName enum value. |
Source code in instructor/core/hooks.py
off(hook_name, handler) ¶
Remove a specific handler from an event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookNameType | The name of the hook. | required |
handler | HandlerType | The handler to remove. | required |
Source code in instructor/core/hooks.py
on(hook_name, handler) ¶
Register an event handler for a specific event.
This method allows you to attach a handler function to a specific event. When the event is emitted, all registered handlers for that event will be called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookNameType | The event to listen for. This can be either a HookName enum value or a string representation of the event name. | required |
handler | HandlerType | The function to be called when the event is emitted. | required |
Raises:
| Type | Description |
|---|---|
ValueError | If the hook_name is not a valid HookName enum or string representation. |
Example
def on_completion_kwargs(*args: Any, **kwargs: Any) -> None: ... print(f"Completion kwargs: {args}, {kwargs}") hooks = Hooks() hooks.on(HookName.COMPLETION_KWARGS, on_completion_kwargs) hooks.emit_completion_arguments(model="gpt-3.5-turbo", temperature=0.7) Completion kwargs: (), {'model': 'gpt-3.5-turbo', 'temperature': 0.7}
Source code in instructor/core/hooks.py
Hooks class for handling and emitting events related to completion processes.
This class provides a mechanism to register event handlers and emit events for various stages of the completion process.
Source code in instructor/core/hooks.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
__add__(other) ¶
Combine two Hooks instances into a new one.
This creates a new Hooks instance that contains all handlers from both the current instance and the other instance. Handlers are combined by appending the other's handlers after the current instance's handlers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Hooks | Another Hooks instance to combine with this one. | required |
Returns:
| Type | Description |
|---|---|
Hooks | A new Hooks instance containing all handlers from both instances. |
Example
hooks1 = Hooks() hooks2 = Hooks() hooks1.on("completion:kwargs", lambda **kw: print("Hook 1")) hooks2.on("completion:kwargs", lambda **kw: print("Hook 2")) combined = hooks1 + hooks2 combined.emit_completion_arguments() # Prints both "Hook 1" and "Hook 2"
Source code in instructor/core/hooks.py
__iadd__(other) ¶
Add another Hooks instance to this one in-place.
This modifies the current instance by adding all handlers from the other instance. The other instance's handlers are appended after the current instance's handlers for each event type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | Hooks | Another Hooks instance to add to this one. | required |
Returns:
| Type | Description |
|---|---|
Hooks | This Hooks instance (for method chaining). |
Example
hooks1 = Hooks() hooks2 = Hooks() hooks1.on("completion:kwargs", lambda **kw: print("Hook 1")) hooks2.on("completion:kwargs", lambda **kw: print("Hook 2")) hooks1 += hooks2 hooks1.emit_completion_arguments() # Prints both "Hook 1" and "Hook 2"
Source code in instructor/core/hooks.py
__init__() ¶
clear(hook_name=None) ¶
Clear handlers for a specific event or all events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookNameType | None | The name of the event to clear handlers for. If None, all handlers are cleared. | None |
Source code in instructor/core/hooks.py
combine(*hooks_instances) classmethod ¶
Combine multiple Hooks instances into a new one.
This class method creates a new Hooks instance that contains all handlers from all provided instances. Handlers are combined in the order of the provided instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*hooks_instances | Hooks | Variable number of Hooks instances to combine. | () |
Returns:
| Type | Description |
|---|---|
Hooks | A new Hooks instance containing all handlers from all instances. |
Example
hooks1 = Hooks() hooks2 = Hooks() hooks3 = Hooks() hooks1.on("completion:kwargs", lambda **kw: print("Hook 1")) hooks2.on("completion:kwargs", lambda **kw: print("Hook 2")) hooks3.on("completion:kwargs", lambda **kw: print("Hook 3")) combined = Hooks.combine(hooks1, hooks2, hooks3) combined.emit_completion_arguments() # Prints all three hooks
Source code in instructor/core/hooks.py
copy() ¶
Create a deep copy of this Hooks instance.
Returns:
| Type | Description |
|---|---|
Hooks | A new Hooks instance with all the same handlers. |
Example
original = Hooks() original.on("completion:kwargs", lambda **kw: print("Hook")) copy = original.copy() copy.emit_completion_arguments() # Prints "Hook"
Source code in instructor/core/hooks.py
emit(hook_name, *args, **kwargs) ¶
Generic method to emit events for any hook type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookName | The hook to emit | required |
*args | Any | Positional arguments to pass to handlers | () |
**kwargs | Any | Keyword arguments to pass to handlers | {} |
Source code in instructor/core/hooks.py
emit_completion_arguments(*args, **kwargs) ¶
Emit a completion arguments event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args | Any | Positional arguments to pass to handlers | () |
**kwargs | Any | Keyword arguments to pass to handlers | {} |
Source code in instructor/core/hooks.py
emit_completion_error(error) ¶
Emit a completion error event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error | Exception | The exception to pass to handlers | required |
emit_completion_last_attempt(error) ¶
Emit a completion last attempt event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error | Exception | The exception to pass to handlers | required |
emit_completion_response(response) ¶
Emit a completion response event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response | Any | The completion response to pass to handlers | required |
emit_parse_error(error) ¶
Emit a parse error event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error | Exception | The exception to pass to handlers | required |
get_hook_name(hook_name) ¶
Convert a string hook name to its corresponding enum value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookNameType | Either a HookName enum value or string representation. | required |
Returns:
| Type | Description |
|---|---|
HookName | The corresponding HookName enum value. |
Raises:
| Type | Description |
|---|---|
ValueError | If the string doesn't match any HookName enum value. |
Source code in instructor/core/hooks.py
off(hook_name, handler) ¶
Remove a specific handler from an event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookNameType | The name of the hook. | required |
handler | HandlerType | The handler to remove. | required |
Source code in instructor/core/hooks.py
on(hook_name, handler) ¶
Register an event handler for a specific event.
This method allows you to attach a handler function to a specific event. When the event is emitted, all registered handlers for that event will be called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_name | HookNameType | The event to listen for. This can be either a HookName enum value or a string representation of the event name. | required |
handler | HandlerType | The function to be called when the event is emitted. | required |
Raises:
| Type | Description |
|---|---|
ValueError | If the hook_name is not a valid HookName enum or string representation. |
Example
def on_completion_kwargs(*args: Any, **kwargs: Any) -> None: ... print(f"Completion kwargs: {args}, {kwargs}") hooks = Hooks() hooks.on(HookName.COMPLETION_KWARGS, on_completion_kwargs) hooks.emit_completion_arguments(model="gpt-3.5-turbo", temperature=0.7) Completion kwargs: (), {'model': 'gpt-3.5-turbo', 'temperature': 0.7}
Source code in instructor/core/hooks.py
Patch Functions¶
Decorators for patching LLM client methods.
apatch(client, mode=Mode.TOOLS) ¶
No longer necessary, use patch instead.
Patch the client.chat.completions.create method
Enables the following features:
response_modelparameter to parse the response from OpenAI's APImax_retriesparameter to retry the function if the response is not validvalidation_contextparameter to validate the response using the pydantic modelstrictparameter to use strict json parsing
Source code in instructor/core/patch.py
handle_context(context=None, validation_context=None) ¶
Handle the context and validation_context parameters. If both are provided, raise an error. If validation_context is provided, issue a deprecation warning and use it as context. If neither is provided, return None.
Source code in instructor/core/patch.py
patch(client=None, create=None, mode=Mode.TOOLS) ¶
Patch the client.chat.completions.create method
Enables the following features:
response_modelparameter to parse the response from OpenAI's APImax_retriesparameter to retry the function if the response is not validvalidation_contextparameter to validate the response using the pydantic modelstrictparameter to use strict json parsinghooksparameter to hook into the completion process
Source code in instructor/core/patch.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 | |
Backwards compatibility module for instructor.patch.
This module provides lazy imports to maintain backwards compatibility.
__getattr__(name) ¶
Lazy import to provide backward compatibility for patch imports.
Source code in instructor/patch.py
No longer necessary, use patch instead.
Patch the client.chat.completions.create method
Enables the following features:
response_modelparameter to parse the response from OpenAI's APImax_retriesparameter to retry the function if the response is not validvalidation_contextparameter to validate the response using the pydantic modelstrictparameter to use strict json parsing