Pandas Extension¶
openaivec.pandas_ext ¶
Pandas Series / DataFrame extension for OpenAI.
Setup¶
from openai import OpenAI
from openaivec import pandas_ext
# Set up the OpenAI client to use with pandas_ext
# Option 1: Use an existing client instance
# pandas_ext.use(OpenAI())
# Option 2: Use environment variables (OPENAI_API_KEY or Azure variables)
# (No explicit setup needed if variables are set)
# Option 3: Provide API key directly
pandas_ext.use_openai("YOUR_API_KEY")
# Option 4: Use Azure OpenAI credentials
# pandas_ext.use_azure_openai(
# api_key="YOUR_AZURE_KEY",
# endpoint="YOUR_AZURE_ENDPOINT",
# api_version="YOUR_API_VERSION"
# )
# Set up the model_name for responses and embeddings (optional, defaults shown)
pandas_ext.responses_model("gpt-4o-mini")
pandas_ext.embeddings_model("text-embedding-3-small")
This module provides .ai
and .aio
accessors for pandas Series and DataFrames
to easily interact with OpenAI APIs for tasks like generating responses or embeddings.
OpenAIVecSeriesAccessor ¶
pandas Series accessor (.ai
) that adds OpenAI helpers.
Source code in src/openaivec/pandas_ext.py
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 |
|
responses ¶
responses(
instructions: str,
response_format: Type[T] = str,
batch_size: int = 128,
temperature: float = 0.0,
top_p: float = 1.0,
) -> pd.Series
Call an LLM once for every Series element.
Example
This method returns a Series of strings, each containing the assistant's response to the corresponding input. The model used is set by theresponses_model
function.
The default model is gpt-4o-mini
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
instructions
|
str
|
System prompt prepended to every user message. |
required |
response_format
|
Type[T]
|
Pydantic model or built‑in
type the assistant should return. Defaults to |
str
|
batch_size
|
int
|
Number of prompts grouped into a single
request. Defaults to |
128
|
temperature
|
float
|
Sampling temperature. Defaults to |
0.0
|
top_p
|
float
|
Nucleus sampling parameter. Defaults to |
1.0
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Series whose values are instances of |
Source code in src/openaivec/pandas_ext.py
task ¶
Execute a prepared task on every Series element.
This method applies a pre-configured task to each element in the Series, using the task's instructions and response format to generate structured responses from the language model.
Example
This method returns a Series containing the task results for each corresponding input element, following the task's defined structure.Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
PreparedTask
|
A pre-configured task containing instructions, response format, and other parameters for processing the inputs. |
required |
batch_size
|
int
|
Number of prompts grouped into a single request to optimize API usage. Defaults to 128. |
128
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Series whose values are instances of the task's response format, aligned with the original Series index. |
Source code in src/openaivec/pandas_ext.py
embeddings ¶
Compute OpenAI embeddings for every Series element.
Example
This method returns a Series of numpy arrays, each containing the embedding vector for the corresponding input. The embedding model is set by theembeddings_model
function.
The default embedding model is text-embedding-3-small
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size
|
int
|
Number of inputs grouped into a
single request. Defaults to |
128
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Series whose values are |
Source code in src/openaivec/pandas_ext.py
count_tokens ¶
Count tiktoken
tokens per row.
Example
This method uses thetiktoken
library to count tokens based on the
model name set by responses_model
.
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Token counts for each element. |
Source code in src/openaivec/pandas_ext.py
extract ¶
Expand a Series of Pydantic models/dicts into columns.
Example
This method returns a DataFrame with the same index as the Series, where each column corresponds to a key in the dictionaries. If the Series has a name, extracted columns are prefixed with it.Returns:
Type | Description |
---|---|
DataFrame
|
pandas.DataFrame: Expanded representation. |
Source code in src/openaivec/pandas_ext.py
OpenAIVecDataFrameAccessor ¶
pandas DataFrame accessor (.ai
) that adds OpenAI helpers.
Source code in src/openaivec/pandas_ext.py
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 |
|
extract ¶
Flatten one column of Pydantic models/dicts into top‑level columns.
Example
This method returns a DataFrame with the same index as the original, where each column corresponds to a key in the dictionaries. The source column is dropped.Parameters:
Name | Type | Description | Default |
---|---|---|---|
column
|
str
|
Column to expand. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
pandas.DataFrame: Original DataFrame with the extracted columns; the source column is dropped. |
Source code in src/openaivec/pandas_ext.py
responses ¶
responses(
instructions: str,
response_format: Type[T] = str,
batch_size: int = 128,
temperature: float = 0.0,
top_p: float = 1.0,
) -> pd.Series
Generate a response for each row after serialising it to JSON.
Example
df = pd.DataFrame([
{"name": "cat", "legs": 4},
{"name": "dog", "legs": 4},
{"name": "elephant", "legs": 4},
])
df.ai.responses("what is the animal's name?")
responses_model
function.
The default model is gpt-4o-mini
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
instructions
|
str
|
System prompt for the assistant. |
required |
response_format
|
Type[T]
|
Desired Python type of the
responses. Defaults to |
str
|
batch_size
|
int
|
Number of requests sent in one batch.
Defaults to |
128
|
temperature
|
float
|
Sampling temperature. Defaults to |
0.0
|
top_p
|
float
|
Nucleus sampling parameter. Defaults to |
1.0
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Responses aligned with the DataFrame’s original index. |
Source code in src/openaivec/pandas_ext.py
task ¶
Execute a prepared task on each DataFrame row after serialising it to JSON.
This method applies a pre-configured task to each row in the DataFrame, using the task's instructions and response format to generate structured responses from the language model. Each row is serialised to JSON before being processed by the task.
Example
This method returns a Series containing the task results for each corresponding row, following the task's defined structure.Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
PreparedTask
|
A pre-configured task containing instructions, response format, and other parameters for processing the inputs. |
required |
batch_size
|
int
|
Number of requests sent in one batch to optimize API usage. Defaults to 128. |
128
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Series whose values are instances of the task's response format, aligned with the DataFrame's original index. |
Source code in src/openaivec/pandas_ext.py
AsyncOpenAIVecSeriesAccessor ¶
pandas Series accessor (.aio
) that adds OpenAI helpers.
Source code in src/openaivec/pandas_ext.py
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 |
|
responses
async
¶
responses(
instructions: str,
response_format: Type[T] = str,
batch_size: int = 128,
temperature: float = 0.0,
top_p: float = 1.0,
max_concurrency: int = 8,
) -> pd.Series
Call an LLM once for every Series element (asynchronously).
Example
animals = pd.Series(["cat", "dog", "elephant"])
# Must be awaited
results = await animals.aio.responses("translate to French")
responses_model
function.
The default model is gpt-4o-mini
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
instructions
|
str
|
System prompt prepended to every user message. |
required |
response_format
|
Type[T]
|
Pydantic model or built‑in
type the assistant should return. Defaults to |
str
|
batch_size
|
int
|
Number of prompts grouped into a single
request. Defaults to |
128
|
temperature
|
float
|
Sampling temperature. Defaults to |
0.0
|
top_p
|
float
|
Nucleus sampling parameter. Defaults to |
1.0
|
max_concurrency
|
int
|
Maximum number of concurrent
requests. Defaults to |
8
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Series whose values are instances of |
Note
This is an asynchronous method and must be awaited.
Source code in src/openaivec/pandas_ext.py
embeddings
async
¶
Compute OpenAI embeddings for every Series element (asynchronously).
Example
animals = pd.Series(["cat", "dog", "elephant"])
# Must be awaited
embeddings = await animals.aio.embeddings()
embeddings_model
function.
The default embedding model is text-embedding-3-small
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size
|
int
|
Number of inputs grouped into a
single request. Defaults to |
128
|
max_concurrency
|
int
|
Maximum number of concurrent
requests. Defaults to |
8
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Series whose values are |
Note
This is an asynchronous method and must be awaited.
Source code in src/openaivec/pandas_ext.py
task
async
¶
Execute a prepared task on every Series element (asynchronously).
This method applies a pre-configured task to each element in the Series, using the task's instructions and response format to generate structured responses from the language model.
Example
This method returns a Series containing the task results for each corresponding input element, following the task's defined structure.Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
PreparedTask
|
A pre-configured task containing instructions, response format, and other parameters for processing the inputs. |
required |
batch_size
|
int
|
Number of prompts grouped into a single request to optimize API usage. Defaults to 128. |
128
|
max_concurrency
|
int
|
Maximum number of concurrent requests. Defaults to 8. |
8
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Series whose values are instances of the task's response format, aligned with the original Series index. |
Note
This is an asynchronous method and must be awaited.
Source code in src/openaivec/pandas_ext.py
AsyncOpenAIVecDataFrameAccessor ¶
pandas DataFrame accessor (.aio
) that adds OpenAI helpers.
Source code in src/openaivec/pandas_ext.py
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 |
|
responses
async
¶
responses(
instructions: str,
response_format: Type[T] = str,
batch_size: int = 128,
temperature: float = 0.0,
top_p: float = 1.0,
max_concurrency: int = 8,
) -> pd.Series
Generate a response for each row after serialising it to JSON (asynchronously).
Example
df = pd.DataFrame([
{"name": "cat", "legs": 4},
{"name": "dog", "legs": 4},
{"name": "elephant", "legs": 4},
])
# Must be awaited
results = await df.aio.responses("what is the animal's name?")
responses_model
function.
The default model is gpt-4o-mini
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
instructions
|
str
|
System prompt for the assistant. |
required |
response_format
|
Type[T]
|
Desired Python type of the
responses. Defaults to |
str
|
batch_size
|
int
|
Number of requests sent in one batch.
Defaults to |
128
|
temperature
|
float
|
Sampling temperature. Defaults to |
0.0
|
top_p
|
float
|
Nucleus sampling parameter. Defaults to |
1.0
|
max_concurrency
|
int
|
Maximum number of concurrent
requests. Defaults to |
8
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Responses aligned with the DataFrame’s original index. |
Note
This is an asynchronous method and must be awaited.
Source code in src/openaivec/pandas_ext.py
task
async
¶
Execute a prepared task on each DataFrame row after serialising it to JSON (asynchronously).
This method applies a pre-configured task to each row in the DataFrame, using the task's instructions and response format to generate structured responses from the language model. Each row is serialised to JSON before being processed by the task.
Example
from openaivec.task.model import PreparedTask
# Assume you have a prepared task for data analysis
analysis_task = PreparedTask(...)
df = pd.DataFrame([
{"name": "cat", "legs": 4},
{"name": "dog", "legs": 4},
{"name": "elephant", "legs": 4},
])
# Must be awaited
results = await df.aio.task(analysis_task)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
PreparedTask
|
A pre-configured task containing instructions, response format, and other parameters for processing the inputs. |
required |
batch_size
|
int
|
Number of requests sent in one batch to optimize API usage. Defaults to 128. |
128
|
max_concurrency
|
int
|
Maximum number of concurrent requests. Defaults to 8. |
8
|
Returns:
Type | Description |
---|---|
Series
|
pandas.Series: Series whose values are instances of the task's response format, aligned with the DataFrame's original index. |
Note
This is an asynchronous method and must be awaited.
Source code in src/openaivec/pandas_ext.py
pipe
async
¶
Apply a function to the DataFrame, supporting both synchronous and asynchronous functions.
This method allows chaining operations on the DataFrame, similar to pandas' pipe
method,
but with support for asynchronous functions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable[[DataFrame], Awaitable[T] | T]
|
A function that takes a DataFrame as input and returns either a result or an awaitable result. |
required |
Returns:
Name | Type | Description |
---|---|---|
T |
T
|
The result of applying the function, either directly or after awaiting it. |
Note
This is an asynchronous method and must be awaited if the function returns an awaitable.
Source code in src/openaivec/pandas_ext.py
assign
async
¶
Asynchronously assign new columns to the DataFrame, evaluating sequentially.
This method extends pandas' assign
method by supporting asynchronous
functions as column values and evaluating assignments sequentially, allowing
later assignments to refer to columns created earlier in the same call.
For each key-value pair in kwargs
:
- If the value is a callable, it is invoked with the current state of the DataFrame
(including columns created in previous steps of this assign
call).
If the result is awaitable, it is awaited; otherwise, it is used directly.
- If the value is not callable, it is assigned directly to the new column.
Example
async def compute_column(df):
# Simulate an asynchronous computation
await asyncio.sleep(1)
return df["existing_column"] * 2
async def use_new_column(df):
# Access the column created in the previous step
await asyncio.sleep(1)
return df["new_column"] + 5
df = pd.DataFrame({"existing_column": [1, 2, 3]})
# Must be awaited
df = await df.aio.assign(
new_column=compute_column,
another_column=use_new_column
)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs
|
Any
|
Any. Column names as keys and either static values or callables (synchronous or asynchronous) as values. |
{}
|
Returns:
Type | Description |
---|---|
DataFrame
|
pandas.DataFrame: A new DataFrame with the assigned columns. |
Note
This is an asynchronous method and must be awaited.
Source code in src/openaivec/pandas_ext.py
use ¶
Register a custom OpenAI‑compatible client.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
client
|
OpenAI
|
A pre‑configured |
required |
Source code in src/openaivec/pandas_ext.py
use_async ¶
Register a custom asynchronous OpenAI‑compatible client.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
client
|
AsyncOpenAI
|
A pre‑configured |
required |
Source code in src/openaivec/pandas_ext.py
use_openai ¶
Create and register a default openai.OpenAI
client.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
api_key
|
str
|
Value forwarded to the |
required |
Source code in src/openaivec/pandas_ext.py
use_azure_openai ¶
Create and register an openai.AzureOpenAI
client.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
api_key
|
str
|
Azure OpenAI subscription key. |
required |
endpoint
|
str
|
Resource endpoint, e.g.
|
required |
api_version
|
str
|
REST API version such as |
required |
Source code in src/openaivec/pandas_ext.py
responses_model ¶
Override the model used for text responses.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Model name as listed in the OpenAI API
(for example, |
required |
Source code in src/openaivec/pandas_ext.py
embeddings_model ¶
Override the model used for text embeddings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Embedding model name, e.g. |
required |