Skip to content

Examples Catalog

Below is a list of examples for prefect-openai.

Completion Module

Interpret the exception raised from a flow.

import httpx
from prefect import flow
from prefect_openai.completion import interpret_exception

@flow
@interpret_exception("COMPLETION_MODEL_BLOCK_NAME_PLACEHOLDER")
def example_flow():
    resp = httpx.get("https://httpbin.org/status/403")
    resp.raise_for_status()

example_flow()

Use a unique prefix and include the last line of the traceback in the prompt.

import httpx
from prefect import flow
from prefect_openai.completion import interpret_exception

@flow
@interpret_exception(
    "COMPLETION_MODEL_BLOCK_NAME_PLACEHOLDER",
    prompt_prefix="Offer a solution:",
    traceback_tail=1,
)
def example_flow():
    resp = httpx.get("https://httpbin.org/status/403")
    resp.raise_for_status()

example_flow()
Create an OpenAI Completion given a prompt:
from prefect import flow
from prefect_openai import CompletionModel, OpenAICredentials

@flow(log_prints=True)
def my_ai_bot(model_name: str = "text-davinci-003")
    credentials = OpenAICredentials.load("my-openai-creds")

    completion_model = CompletionModel(
        openai_credentials=credentials,
    )

    for prompt in ["hi!", "what is the meaning of life?"]:
        completion = completion_model.submit_prompt(prompt)
        print(completion.choices[0].text)

Credentials Module

Load a configured block:

from prefect_openai import OpenAICredentials

credentials = OpenAICredentials.load("BLOCK_NAME")

Get the OpenAPI client:

from prefect_openai import OpenAICredentials

credentials = OpenAICredentials.load("BLOCK_NAME")
client = credentials.get_client()

Image Module

Create an OpenAI Image given a prompt:

from prefect_openai import ImageModel

image_model = ImageModel.load("BLOCK_NAME")
image_model.submit_prompt(prompt="A prompt for an image.")