Main Package API¶
The main openaivec package provides the core classes for AI-powered data processing.
Configuration¶
Client and model configuration helpers. These are the canonical entry point for setting up OpenAI / Azure OpenAI credentials, Fabric built-in models, and model names. Configuration is shared within the current Python process; Spark executors require their own setup. See the authentication guide.
openaivec.setup_fabric ¶
setup_fabric(
*,
responses_model: str = "gpt-5.1",
embeddings_model: str = "text-embedding-ada-002",
api_version: str = "2025-04-01-preview",
) -> None
Use Fabric's built-in models with runtime-managed authentication.
Explicitly replaces the default sync and async clients and model names for the current Python process. No Azure OpenAI resource, API key, or service principal secret is required. HTTP clients are created lazily. The async API requires the corresponding helper in the Fabric runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
responses_model
|
str
|
Built-in response model. Defaults to |
'gpt-5.1'
|
embeddings_model
|
str
|
Built-in embedding model. Defaults to
|
'text-embedding-ada-002'
|
api_version
|
str
|
Fabric-supported Azure OpenAI API version. Defaults
to |
'2025-04-01-preview'
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Not running in a supported Fabric notebook runtime. |
ValueError
|
A model name or API version is empty. |
Example
import openaivec openaivec.setup_fabric() # doctest: +SKIP
Notes
Built-in models are a preview feature billed to Fabric capacity. This configures the notebook driver, not Spark executor authentication. Close resolved clients before replacing them with another setup.
Source code in src/openaivec/_provider.py
openaivec.set_client ¶
Register a custom OpenAI client.
Future schema inference resolves its provider again with the new client. Caller-owned clients are never closed by this function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
OpenAI
|
A pre-configured |
required |
Source code in src/openaivec/_provider.py
openaivec.get_client ¶
Get the currently registered OpenAI client.
Returns:
| Name | Type | Description |
|---|---|---|
OpenAI |
OpenAI
|
The registered client instance. |
openaivec.set_async_client ¶
Register a custom AsyncOpenAI client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncOpenAI
|
A pre-configured |
required |
Source code in src/openaivec/_provider.py
openaivec.get_async_client ¶
Get the currently registered AsyncOpenAI client.
Returns:
| Name | Type | Description |
|---|---|---|
AsyncOpenAI |
AsyncOpenAI
|
The registered async client instance. |
openaivec.set_responses_model ¶
Override the model used for text responses.
Future schema inference resolves its provider again with the new model. Existing response wrappers and UDFs retain their configured model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Model or deployment name (e.g. |
required |
Source code in src/openaivec/_provider.py
openaivec.get_responses_model ¶
Get the currently registered model name for text responses.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The model name. |
openaivec.set_embeddings_model ¶
Override the model used for text embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Model or deployment name (e.g. |
required |
Source code in src/openaivec/_provider.py
openaivec.get_embeddings_model ¶
Get the currently registered model name for text embeddings.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The model name. |
Core Classes¶
All core functionality is accessible through the main package imports:
openaivec.BatchResponses
dataclass
¶
BatchResponses(
client: OpenAI,
model_name: str,
system_message: str,
response_format: type[ResponseFormat] = str,
cache: BatchCache[str, ResponseFormat | None] = (
lambda: BatchCache(
batch_size=None,
max_cache_size=DEFAULT_MANAGED_CACHE_SIZE,
)
)(),
api_kwargs: dict[str, Any] = dict(),
max_validation_retries: int = 3,
multimodal: bool = False,
retry_policy: RetryPolicy | None = None,
limits: ResponseLimits = ResponseLimits(),
)
Bases: Generic[ResponseFormat]
Stateless façade that turns OpenAI's JSON‑mode API into a batched API.
This wrapper allows you to submit multiple user prompts in one JSON‑mode request and receive the answers in the original order.
Example
Attributes:
| Name | Type | Description |
|---|---|---|
client |
OpenAI
|
Initialised OpenAI client. |
model_name |
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
system_message |
str
|
System prompt prepended to every request. |
response_format |
type[ResponseFormat]
|
Expected Pydantic model class or |
cache |
BatchCache[str, ResponseFormat | None]
|
Order-preserving batching
proxy with de-duplication and caching. Library-managed instances use
bounded retention by default. Caller-provided caches must accept
|
max_validation_retries |
int
|
Number of retries when structured output fails local schema validation. |
retry_policy |
RetryPolicy | None
|
Transport limits. |
Notes
Internally the work is delegated to two helpers:
_predict_chunk– fragments the workload and restores ordering._request_llm– issues OpenAI API calls and retries with validation feedback when needed.
Methods:¶
of
classmethod
¶
of(
client: OpenAI,
model_name: str,
system_message: str,
response_format: type[ResponseFormat] = str,
batch_size: int | None = None,
max_validation_retries: int = 3,
multimodal: bool = False,
*,
limits: ResponseLimits | None = None,
retry_policy: RetryPolicy | None = None,
**api_kwargs,
) -> BatchResponses
Factory constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
OpenAI
|
OpenAI client. |
required |
model_name
|
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
required |
system_message
|
str
|
System prompt for the model. |
required |
response_format
|
type[ResponseFormat]
|
Expected output type. Defaults to |
str
|
batch_size
|
int | None
|
Max unique prompts per API call. Defaults to None (automatic batch size optimization). Set to a positive integer for fixed batch size. |
None
|
max_validation_retries
|
int
|
Retry count when structured output fails local schema validation. Defaults to 3. |
3
|
multimodal
|
bool
|
When |
False
|
limits
|
ResponseLimits | None
|
Text request context and item limits. |
None
|
retry_policy
|
RetryPolicy | None
|
Transport limits. |
None
|
**api_kwargs
|
Additional OpenAI API parameters (temperature, top_p, etc.). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
BatchResponses |
BatchResponses
|
Configured instance backed by a batching proxy. |
Source code in src/openaivec/_responses.py
of_task
classmethod
¶
of_task(
client: OpenAI,
model_name: str,
task: PreparedTask[ResponseFormat],
batch_size: int | None = None,
max_validation_retries: int = 3,
multimodal: bool = False,
*,
limits: ResponseLimits | None = None,
retry_policy: RetryPolicy | None = None,
**api_kwargs,
) -> BatchResponses
Factory from a PreparedTask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
OpenAI
|
OpenAI client. |
required |
model_name
|
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
required |
task
|
PreparedTask
|
Prepared task with instructions and response format. |
required |
batch_size
|
int | None
|
Max unique prompts per API call. Defaults to None (automatic batch size optimization). Set to a positive integer for fixed batch size. |
None
|
max_validation_retries
|
int
|
Retry count when structured output fails local schema validation. Defaults to 3. |
3
|
multimodal
|
bool
|
When |
False
|
limits
|
ResponseLimits | None
|
Text request context and item limits. |
None
|
retry_policy
|
RetryPolicy | None
|
Transport limits. |
None
|
**api_kwargs
|
Additional OpenAI API parameters forwarded to the Responses API. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
BatchResponses |
BatchResponses
|
Configured instance backed by a batching proxy. |
Source code in src/openaivec/_responses.py
parse ¶
Batched predict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
list[str]
|
Prompts that require responses. Duplicates are de‑duplicated. |
required |
Returns:
| Type | Description |
|---|---|
list[ResponseFormat | None]
|
list[ResponseFormat | None]: Assistant responses aligned to |
Source code in src/openaivec/_responses.py
openaivec.AsyncBatchResponses
dataclass
¶
AsyncBatchResponses(
client: AsyncOpenAI,
model_name: str,
system_message: str,
response_format: type[ResponseFormat] = str,
cache: AsyncBatchCache[str, ResponseFormat | None] = (
lambda: AsyncBatchCache(
batch_size=None,
max_concurrency=8,
max_cache_size=DEFAULT_MANAGED_CACHE_SIZE,
)
)(),
api_kwargs: dict[str, Any] = dict(),
max_validation_retries: int = 3,
multimodal: bool = False,
retry_policy: RetryPolicy | None = None,
limits: ResponseLimits = ResponseLimits(),
)
Bases: Generic[ResponseFormat]
Stateless façade that turns OpenAI's JSON-mode API into a batched API (Async version).
This wrapper allows you to submit multiple user prompts in one JSON-mode request and receive the answers in the original order asynchronously. It also controls the maximum number of concurrent requests to the OpenAI API.
Example
import asyncio
from openai import AsyncOpenAI
from openaivec import AsyncBatchResponses
openai_async_client = AsyncOpenAI() # initialize your client
vector_llm = AsyncBatchResponses.of(
client=openai_async_client,
model_name="gpt-6-luna",
system_message="You are a helpful assistant.",
batch_size=64,
max_concurrency=5,
reasoning={"effort": "none"},
)
questions = [
"What is the capital of France?",
"Explain quantum physics simply.",
]
async def main():
answers = await vector_llm.parse(questions)
print(answers)
asyncio.run(main())
Attributes:
| Name | Type | Description |
|---|---|---|
client |
AsyncOpenAI
|
Initialised OpenAI async client. |
model_name |
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
system_message |
str
|
System prompt prepended to every request. |
response_format |
type[ResponseFormat]
|
Expected Pydantic model class or |
cache |
AsyncBatchCache[str, ResponseFormat | None]
|
Async batching proxy
with de-duplication and concurrency control. Library-managed
instances use bounded retention by default. Caller-provided caches
must accept |
max_validation_retries |
int
|
Number of retries when structured output fails local schema validation. |
retry_policy |
RetryPolicy | None
|
Transport limits. |
Methods:¶
of
classmethod
¶
of(
client: AsyncOpenAI,
model_name: str,
system_message: str,
response_format: type[ResponseFormat] = str,
batch_size: int | None = None,
max_concurrency: int = 8,
max_validation_retries: int = 3,
multimodal: bool = False,
*,
limits: ResponseLimits | None = None,
retry_policy: RetryPolicy | None = None,
**api_kwargs,
) -> AsyncBatchResponses
Factory constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncOpenAI
|
OpenAI async client. |
required |
model_name
|
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
required |
system_message
|
str
|
System prompt. |
required |
response_format
|
type[ResponseFormat]
|
Expected output type. Defaults to |
str
|
batch_size
|
int | None
|
Max unique prompts per API call. Defaults to None (automatic batch size optimization). Set to a positive integer for fixed batch size. |
None
|
max_concurrency
|
int
|
Max concurrent API calls. Defaults to 8. |
8
|
max_validation_retries
|
int
|
Retry count when structured output fails local schema validation. Defaults to 3. |
3
|
multimodal
|
bool
|
When |
False
|
limits
|
ResponseLimits | None
|
Text request context and item limits. |
None
|
retry_policy
|
RetryPolicy | None
|
Transport limits. |
None
|
**api_kwargs
|
Additional OpenAI API parameters (temperature, top_p, etc.). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
AsyncBatchResponses |
AsyncBatchResponses
|
Configured instance backed by an async batching proxy. |
Source code in src/openaivec/_responses.py
of_task
classmethod
¶
of_task(
client: AsyncOpenAI,
model_name: str,
task: PreparedTask[ResponseFormat],
batch_size: int | None = None,
max_concurrency: int = 8,
max_validation_retries: int = 3,
multimodal: bool = False,
*,
limits: ResponseLimits | None = None,
retry_policy: RetryPolicy | None = None,
**api_kwargs,
) -> AsyncBatchResponses
Factory from a PreparedTask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncOpenAI
|
OpenAI async client. |
required |
model_name
|
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
required |
task
|
PreparedTask
|
Prepared task with instructions and response format. |
required |
batch_size
|
int | None
|
Max unique prompts per API call. Defaults to None (automatic batch size optimization). Set to a positive integer for fixed batch size. |
None
|
max_concurrency
|
int
|
Max concurrent API calls. Defaults to 8. |
8
|
max_validation_retries
|
int
|
Retry count when structured output fails local schema validation. Defaults to 3. |
3
|
multimodal
|
bool
|
When |
False
|
limits
|
ResponseLimits | None
|
Text request context and item limits. |
None
|
retry_policy
|
RetryPolicy | None
|
Transport limits. |
None
|
**api_kwargs
|
Additional OpenAI API parameters forwarded to the Responses API. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
AsyncBatchResponses |
AsyncBatchResponses
|
Configured instance backed by an async batching proxy. |
Source code in src/openaivec/_responses.py
parse
async
¶
Batched predict (async).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
list[str]
|
Prompts that require responses. Duplicates are de‑duplicated. |
required |
Returns:
| Type | Description |
|---|---|
list[ResponseFormat | None]
|
list[ResponseFormat | None]: Assistant responses aligned to |
Source code in src/openaivec/_responses.py
Responses request budgets¶
Text Responses requests are planned against a conservative 128,000-token
context estimate and 128 items per request, independently of cache
batch_size. Each request includes the serialized input envelope, vectorized
instructions, generated structured-output schema, 256 expected output tokens
per item, and a 256-token validation-feedback allowance when retries are on.
batch_size=None remains adaptive; fixed sizes and nonpositive sizes also
respect the request budget. An oversized single text input raises ValueError
before any requests for that cache chunk are sent. Results preserve IDs, order,
and cache deduplication across request splits.
Check the actual context window and output requirements of your model or Azure deployment. The default is not model metadata and token counts are estimates, not a guarantee against server-side request limits. Override the limits and tokenizer when deployment metadata is unavailable:
from openaivec import BatchResponses, ResponseLimits
responses = BatchResponses.of(
client,
"my-deployment",
"Summarize each item.",
batch_size=64,
limits=ResponseLimits(
max_request_tokens=32000,
max_inputs=32,
expected_output_tokens_per_item=512,
encoding_name="o200k_base",
),
)
The same limits option works on AsyncBatchResponses.of, both of_task
factories, and direct constructors. max_output_tokens (if supplied to the
API) is also reserved when larger than the per-item allowance. The planner
applies only to batched text inputs, not individual multimodal requests.
Multimodal files and URLs¶
Set multimodal=True to classify local images and binary documents, or image
and document URLs, by their file extension. Signed URL query parameters are
preserved in the request but are not used to classify the media type. Audio
(.mp3 and .wav) is rejected by the Responses API wrapper.
Local text files are read into the text batch; images are inlined. Local
binary documents are uploaded to the Files API as temporary,
request-owned files and deleted when the request finishes, including failed
requests. Validation correction attempts reuse the same upload before it is
deleted. The caller remains responsible for any files uploaded directly
through the OpenAI client or through the internal builder's standalone
build() method. The cache identifies local files by their contents as well
as path, so a changed file does not reuse an earlier result.
openaivec.ResponseLimits
dataclass
¶
ResponseLimits(
max_request_tokens: int = 128000,
max_inputs: int = 128,
expected_output_tokens_per_item: int = 256,
validation_feedback_tokens: int = 256,
encoding_name: str | None = None,
)
Estimated per-request context budget for batched text Responses.
max_request_tokens is the model/deployment context limit, not an API
parameter. Override it and encoding_name for custom Azure deployments.
Output and validation allowances are estimates; choose values appropriate
for the task and model. A correction whose actual feedback exceeds the
configured budget fails before a request is sent. Multimodal requests use
a separate path.
openaivec.BatchEmbeddings
dataclass
¶
BatchEmbeddings(
client: OpenAI,
model_name: str,
cache: BatchCache[str, NDArray[float32]] = (
lambda: BatchCache(
batch_size=None,
max_cache_size=DEFAULT_MANAGED_CACHE_SIZE,
)
)(),
api_kwargs: dict[str, Any] = dict(),
limits: EmbeddingLimits = EmbeddingLimits(),
retry_policy: RetryPolicy | None = None,
)
Thin wrapper around the OpenAI embeddings endpoint (synchronous).
By default, requests are limited to 2,048 inputs and 300,000 total tokens, even
with automatic or nonpositive batch sizes. Empty inputs and inputs over
8,192 tokens are rejected before sending the affected cache batch. Text
is never truncated. Deployment aliases use the cl100k_base tokenizer
shared by the supported OpenAI embedding models. Supply limits to
override these provider defaults.
Attributes:
| Name | Type | Description |
|---|---|---|
client |
OpenAI
|
Configured OpenAI client. |
model_name |
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name
(e.g., |
cache |
BatchCache[str, NDArray[float32]]
|
Batching proxy for ordered, cached mapping. Library-managed instances use bounded retention by default. |
api_kwargs |
dict[str, Any]
|
Additional OpenAI API parameters stored at initialization. |
limits |
EmbeddingLimits
|
Provider request limits, independent of cache batch size. |
retry_policy |
RetryPolicy | None
|
Transport limits. |
Methods:¶
of
classmethod
¶
of(
client: OpenAI,
model_name: str,
batch_size: int | None = None,
*,
limits: EmbeddingLimits | None = None,
retry_policy: RetryPolicy | None = None,
**api_kwargs,
) -> BatchEmbeddings
Factory constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
OpenAI
|
OpenAI client. |
required |
model_name
|
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
required |
batch_size
|
int | None
|
Max unique inputs per API call. Defaults to None (automatic batch size optimization). Set to a positive integer for fixed batch size. |
None
|
limits
|
EmbeddingLimits | None
|
Provider-specific hard limits. None uses OpenAI defaults. |
None
|
retry_policy
|
RetryPolicy | None
|
Transport limits. |
None
|
**api_kwargs
|
Additional OpenAI API parameters (e.g., dimensions for text-embedding-3 models). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
BatchEmbeddings |
BatchEmbeddings
|
Configured instance backed by a batching proxy. |
Source code in src/openaivec/_embeddings.py
create ¶
Generate embeddings for inputs using cached, ordered batching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
list[str]
|
Input strings. Duplicates allowed. |
required |
Returns:
| Type | Description |
|---|---|
list[NDArray[float32]]
|
list[NDArray[np.float32]]: Embedding vectors aligned to |
Source code in src/openaivec/_embeddings.py
openaivec.AsyncBatchEmbeddings
dataclass
¶
AsyncBatchEmbeddings(
client: AsyncOpenAI,
model_name: str,
cache: AsyncBatchCache[str, NDArray[float32]] = (
lambda: AsyncBatchCache(
batch_size=None,
max_concurrency=8,
max_cache_size=DEFAULT_MANAGED_CACHE_SIZE,
)
)(),
api_kwargs: dict[str, Any] = dict(),
limits: EmbeddingLimits = EmbeddingLimits(),
retry_policy: RetryPolicy | None = None,
)
Thin wrapper around the OpenAI embeddings endpoint (asynchronous).
This class provides an asynchronous interface for generating embeddings using OpenAI models. It manages concurrency, handles rate limits automatically, and efficiently processes batches of inputs, including de-duplication.
Request limits and input validation match BatchEmbeddings. Splitting
a cache batch does not increase concurrency; subrequests run sequentially
within the existing cache worker.
Example
import asyncio
import numpy as np
from openai import AsyncOpenAI
from openaivec import AsyncBatchEmbeddings
# Assuming openai_async_client is an initialized AsyncOpenAI client
openai_async_client = AsyncOpenAI() # Replace with your actual client initialization
embedder = AsyncBatchEmbeddings.of(
client=openai_async_client,
model_name="text-embedding-3-small",
batch_size=128,
max_concurrency=8,
)
texts = ["This is the first document.", "This is the second document.", "This is the first document."]
# Asynchronous call
async def main():
embeddings = await embedder.create(texts)
# embeddings will be a list of numpy arrays (float32)
# The embedding for the third text will be identical to the first
# due to automatic de-duplication.
print(f"Generated {len(embeddings)} embeddings.")
print(f"Shape of first embedding: {embeddings[0].shape}")
assert np.array_equal(embeddings[0], embeddings[2])
# Run the async function
asyncio.run(main())
Attributes:
| Name | Type | Description |
|---|---|---|
client |
AsyncOpenAI
|
Configured OpenAI async client. |
model_name |
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
cache |
AsyncBatchCache[str, NDArray[float32]]
|
Async batching proxy. Library-managed instances use bounded retention by default. |
api_kwargs |
dict
|
Additional OpenAI API parameters stored at initialization. |
limits |
EmbeddingLimits
|
Provider request limits, independent of cache batch size. |
retry_policy |
RetryPolicy | None
|
Transport limits. |
Methods:¶
of
classmethod
¶
of(
client: AsyncOpenAI,
model_name: str,
batch_size: int | None = None,
max_concurrency: int = 8,
*,
limits: EmbeddingLimits | None = None,
retry_policy: RetryPolicy | None = None,
**api_kwargs,
) -> AsyncBatchEmbeddings
Factory constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncOpenAI
|
OpenAI async client. |
required |
model_name
|
str
|
For Azure OpenAI, use your deployment name. For OpenAI, use the model name. |
required |
batch_size
|
int | None
|
Max unique inputs per API call. Defaults to None (automatic batch size optimization). Set to a positive integer for fixed batch size. |
None
|
max_concurrency
|
int
|
Max concurrent API calls. Defaults to 8. |
8
|
limits
|
EmbeddingLimits | None
|
Provider-specific hard limits. None uses OpenAI defaults. |
None
|
retry_policy
|
RetryPolicy | None
|
Transport limits. |
None
|
**api_kwargs
|
Additional OpenAI API parameters (e.g., dimensions for text-embedding-3 models). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
AsyncBatchEmbeddings |
AsyncBatchEmbeddings
|
Configured instance with an async batching proxy. |
Source code in src/openaivec/_embeddings.py
create
async
¶
Generate embeddings for inputs using proxy batching (async).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
list[str]
|
Input strings. Duplicates allowed. |
required |
Returns:
| Type | Description |
|---|---|
list[NDArray[float32]]
|
list[NDArray[np.float32]]: Embedding vectors aligned to |
Source code in src/openaivec/_embeddings.py
Prompt Building¶
openaivec.FewShotPromptBuilder ¶
Builder for creating few-shot prompts with validation.
Usage
builder = (FewShotPromptBuilder() .purpose("Your task description") .example("input1", "output1") # At least one required .example("input2", "output2") .build())
Note
Both .purpose() and at least one .example() call are required before calling .build(), .improve(), or .get_object().
Initialize an empty FewShotPromptBuilder.
Note
You must call .purpose() and at least one .example() before building.
Source code in src/openaivec/_prompt.py
Methods:¶
of
classmethod
¶
Create a builder pre‑populated with an existing prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
FewShotPrompt
|
The prompt to start from. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FewShotPromptBuilder |
FewShotPromptBuilder
|
A new builder instance. |
Source code in src/openaivec/_prompt.py
of_empty
classmethod
¶
Create a builder.
Returns:
| Name | Type | Description |
|---|---|---|
FewShotPromptBuilder |
FewShotPromptBuilder
|
A new builder instance with an empty prompt. |
purpose ¶
Set the purpose of the prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
purpose
|
str
|
A concise statement describing the prompt’s goal. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FewShotPromptBuilder |
FewShotPromptBuilder
|
The current builder instance (for chaining). |
Source code in src/openaivec/_prompt.py
caution ¶
Append a cautionary note to the prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
caution
|
str
|
A caution or edge‑case description. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FewShotPromptBuilder |
FewShotPromptBuilder
|
The current builder instance. |
Source code in src/openaivec/_prompt.py
example ¶
Add a single input/output example.
At least one example is required before calling .build(), .improve(), or .get_object().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_value
|
str | BaseModel
|
Example input; if a Pydantic model is provided it is serialised to JSON. |
required |
output_value
|
str | BaseModel
|
Expected output; serialised if needed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FewShotPromptBuilder |
FewShotPromptBuilder
|
The current builder instance. |
Source code in src/openaivec/_prompt.py
improve ¶
improve(
client: OpenAI | None = None,
model_name: str | None = None,
**api_kwargs,
) -> FewShotPromptBuilder
Iteratively refine the prompt using an LLM.
The method calls a single LLM request that returns multiple editing steps and stores each step for inspection.
When client is None, automatically creates a client using environment variables:
- For OpenAI: OPENAI_API_KEY
- For Azure OpenAI: AZURE_OPENAI_BASE_URL with AZURE_OPENAI_API_KEY
or Entra ID (DefaultAzureCredential)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
OpenAI | None
|
Configured OpenAI client. If None, uses DI container with environment variables. |
None
|
model_name
|
str | None
|
Model identifier. If None, uses default |
None
|
**api_kwargs
|
Additional OpenAI API parameters (temperature, top_p, etc.). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
FewShotPromptBuilder |
FewShotPromptBuilder
|
The current builder instance containing the refined prompt and iteration history. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the prompt is not valid (missing purpose or examples). |
Source code in src/openaivec/_prompt.py
explain ¶
Pretty‑print the diff of each improvement iteration.
Returns:
| Name | Type | Description |
|---|---|---|
FewShotPromptBuilder |
FewShotPromptBuilder
|
The current builder instance. |
Source code in src/openaivec/_prompt.py
get_object ¶
Return the underlying FewShotPrompt object.
Returns:
| Name | Type | Description |
|---|---|---|
FewShotPrompt |
FewShotPrompt
|
The validated prompt object. |
build ¶
Build and return the prompt as XML.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
XML representation of the prompt. |
build_json ¶
Build and return the prompt as a JSON string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Keyword arguments forwarded to Pydantic's |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
JSON representation of the prompt. |
Source code in src/openaivec/_prompt.py
build_xml ¶
Alias for meth:
build for explicit XML generation.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
XML representation of the prompt. |