{ "cells": [ { "cell_type": "markdown", "id": "3e777354", "metadata": {}, "source": [ "# Working with OpenAI in Pixeltable\n", "\n", "Pixeltable's OpenAI integration enables you to access OpenAI models via the OpenAI API.\n", "\n", "### Prerequisites\n", "\n", "- An OpenAI account with an API key (https://openai.com/index/openai-api/)\n", "\n", "### Important notes\n", "\n", "- OpenAI usage may incur costs based on your OpenAI plan.\n", "- Be mindful of sensitive data and consider security measures when integrating with external services." ] }, { "cell_type": "markdown", "id": "8b2e6912-e936-4c3a-84a2-ba99950c9493", "metadata": {}, "source": [ "First you'll need to install required libraries and enter your OpenAI API key." ] }, { "cell_type": "code", "execution_count": 1, "id": "d5288926-c278-4cbc-815c-cbc0433bbf49", "metadata": {}, "outputs": [], "source": [ "%pip install -qU pixeltable openai" ] }, { "cell_type": "code", "execution_count": 2, "id": "385f6831-f029-42bb-99f1-652a809ffc6e", "metadata": {}, "outputs": [], "source": [ "import getpass\n", "import os\n", "\n", "if 'OPENAI_API_KEY' not in os.environ:\n", " os.environ['OPENAI_API_KEY'] = getpass.getpass(\n", " 'Enter your OpenAI API key:'\n", " )" ] }, { "cell_type": "markdown", "id": "azure-openai", "metadata": {}, "source": [ "## Azure OpenAI\n", "\n", "The same functions call Azure OpenAI. `OPENAI_API_KEY` is the Azure key, and `OPENAI_BASE_URL` is the resource endpoint, passed through as the client's `base_url`. `OPENAI_API_VERSION` is sent as the `api-version` query parameter; for the `/openai/v1/` endpoint use `preview` or `latest`. The `model` argument is the deployment name on that resource.\n", "\n", "```python\n", "import os\n", "\n", "os.environ['OPENAI_API_KEY'] = '...' # Azure OpenAI key\n", "os.environ['OPENAI_BASE_URL'] = 'https://YOUR_RESOURCE.openai.azure.com/openai/v1/'\n", "os.environ['OPENAI_API_VERSION'] = 'preview'\n", "```\n", "\n", "`chat_completions(..., model='your-deployment')` then uses that client. The examples below are the same call, with an OpenAI model name or an Azure deployment name." ] }, { "cell_type": "markdown", "id": "8d3dd131-22de-496c-9f02-ffd4515c20d3", "metadata": {}, "source": [ "Now let's create a Pixeltable directory to hold the tables for our demo." ] }, { "cell_type": "code", "execution_count": 3, "id": "9bdc613f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created directory 'openai_demo'.\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pixeltable as pxt\n", "\n", "# Remove the 'openai_demo' directory and its contents, if it exists\n", "pxt.drop_dir('openai_demo', force=True)\n", "pxt.create_dir('openai_demo')" ] }, { "cell_type": "markdown", "id": "02f8595f-fb03-419f-9440-ee2ae784fd20", "metadata": {}, "source": [ "## Chat completions\n", "\n", "Create a Table: In Pixeltable, create a table with columns to represent your input data and the columns where you want to store the results from OpenAI." ] }, { "cell_type": "code", "execution_count": 4, "id": "342407c1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created table 'chat'.\n", "Added 0 column values with 0 errors in 0.00 s\n" ] }, { "data": { "text/plain": [ "No rows affected." ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from pixeltable.functions import openai\n", "\n", "# Create a table in Pixeltable and add a computed column that calls OpenAI\n", "\n", "t = pxt.create_table('openai_demo/chat', {'input': pxt.String})\n", "\n", "messages = [{'role': 'user', 'content': t.input}]\n", "t.add_computed_column(\n", " output=openai.chat_completions(\n", " messages=messages,\n", " model='gpt-4o-mini',\n", " model_kwargs={\n", " # Optional dict with parameters for the OpenAI API\n", " 'max_tokens': 300,\n", " 'top_p': 0.9,\n", " 'temperature': 0.7,\n", " },\n", " )\n", ")" ] }, { "cell_type": "code", "execution_count": 5, "id": "c5f0b862", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Added 0 column values with 0 errors in 0.00 s\n" ] }, { "data": { "text/plain": [ "No rows affected." ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Parse the response into a new column\n", "t.add_computed_column(response=t.output.choices[0].message.content)" ] }, { "cell_type": "code", "execution_count": 6, "id": "15c9bc76-1b28-4d17-9a2d-339968f90786", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Inserted 1 row with 0 errors in 1.68 s (0.60 rows/s)\n" ] }, { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
inputresponse
How many islands are in the Aleutian island chain?The Aleutian Islands chain consists of around 300 islands. This archipelago stretches over 1,200 miles (1,900 kilometers) from the southwestern tip of the Alaska Peninsula to the easternmost island, Attu, near the boundary of the Bering Sea and the Bering Strait. The islands are part of the U.S. state of Alaska and are known for their rugged terrain and diverse ecosystems.
" ], "text/plain": [ " input \\\n", "0 How many islands are in the Aleutian island ch... \n", "\n", " response \n", "0 The Aleutian Islands chain consists of around ... " ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Start a conversation\n", "t.insert(\n", " [{'input': 'How many islands are in the Aleutian island chain?'}]\n", ")\n", "t.select(t.input, t.response).head()" ] }, { "cell_type": "markdown", "id": "557b41ec", "metadata": {}, "source": [ "## Responses API\n", "\n", "The [Responses API](https://developers.openai.com/api/docs/api-reference/responses) is OpenAI's recommended API for new projects. It offers built-in tools (web search, file search, code interpreter), improved reasoning model performance, lower costs, and cleaner semantics compared to Chat Completions.\n", "\n", "Key benefits:\n", "\n", "- **`instructions` parameter**: Cleanly separates system-level guidance from user input\n", "- **Built-in tools**: Use `web_search`, `file_search`, `code_interpreter` natively\n", "- **Multi-turn via `previous_response_id`**: Simpler conversation state management" ] }, { "cell_type": "code", "execution_count": 7, "id": "fa0acba3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created table 'responses'.\n", "Added 0 column values with 0 errors in 0.01 s\n", "Added 0 column values with 0 errors in 0.00 s\n" ] }, { "data": { "text/plain": [ "No rows affected." ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a table and add a computed column using the Responses API\n", "\n", "resp_t = pxt.create_table('openai_demo/responses', {'input': pxt.String})\n", "\n", "messages = [{'role': 'user', 'content': resp_t.input}]\n", "resp_t.add_computed_column(\n", " output=openai.responses(\n", " input=messages,\n", " model='gpt-4o-mini',\n", " model_kwargs={\n", " 'instructions': 'You are a helpful assistant. Be concise.',\n", " 'temperature': 0.7,\n", " 'max_output_tokens': 300,\n", " },\n", " )\n", ")\n", "\n", "# The response text is the first content part of the first output item\n", "resp_t.add_computed_column(\n", " response=resp_t.output.output[0].content[0].text\n", ")" ] }, { "cell_type": "code", "execution_count": 8, "id": "3aa731b5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Inserted 1 row with 0 errors in 1.93 s (0.52 rows/s)\n" ] }, { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
inputresponse
What are the three largest moons of Jupiter?The three largest moons of Jupiter are:\n", "\n", "1. Ganymede\n", "2. Callisto\n", "3. Io\n", "\n", "These moons are known as the Galilean moons, named after Galileo Galilei, who discovered them in 1610.
" ], "text/plain": [ " input \\\n", "0 What are the three largest moons of Jupiter? \n", "\n", " response \n", "0 The three largest moons of Jupiter are:\\n\\n1. ... " ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Insert data and view results\n", "resp_t.insert([{'input': 'What are the three largest moons of Jupiter?'}])\n", "resp_t.select(resp_t.input, resp_t.response).head()" ] }, { "cell_type": "markdown", "id": "1e234455", "metadata": {}, "source": [ "## Decisions\n", "\n", "The [Decisions API](https://developers.openai.com/api/docs/guides/decisions) answers predicate, choice, and score questions about a text or image input. Each answer is a probability, a choice, or a score instead of generated text. `decisions()` requires `openai>=3.32`.\n", "\n", "This example checks food-delivery complaints against the customer's photo. A `reply_prompt()` UDF returns `None` unless the photo supports the complaint, and a `None` input skips the `responses()` call, so only supported complaints get a drafted reply." ] }, { "cell_type": "code", "execution_count": 9, "id": "5aefab31", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created table 'complaints'.\n", "Added 0 column values with 0 errors in 0.01 s\n", "Added 0 column values with 0 errors in 0.00 s\n", "Added 0 column values with 0 errors in 0.00 s\n", "Added 0 column values with 0 errors in 0.01 s\n", "Added 0 column values with 0 errors in 0.01 s\n", "Added 0 column values with 0 errors in 0.01 s\n" ] }, { "data": { "text/plain": [ "No rows affected." ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "@pxt.udf\n", "def reply_prompt(complaint: str, supported: float | None) -> list | None:\n", " if supported is None or supported < 0.5:\n", " return None\n", " return [\n", " {\n", " 'role': 'user',\n", " 'content': f'Draft a two-sentence apology with a refund for: {complaint}',\n", " }\n", " ]\n", "\n", "\n", "dec_t = pxt.create_table(\n", " 'openai_demo/complaints',\n", " {'complaint': pxt.String, 'photo': pxt.Image},\n", ")\n", "messages = [\n", " {\n", " 'role': 'user',\n", " 'content': [\n", " {'type': 'input_text', 'text': dec_t.complaint},\n", " {'type': 'input_image', 'image_url': dec_t.photo},\n", " ],\n", " }\n", "]\n", "questions = [\n", " {\n", " 'type': 'predicate',\n", " 'name': 'supported',\n", " 'instructions': \"Does the photo support the customer's complaint?\",\n", " },\n", " {\n", " 'type': 'choice',\n", " 'name': 'issue',\n", " 'instructions': 'What is the complaint about?',\n", " 'choices': [\n", " {'value': 'missing item'},\n", " {'value': 'unwanted item'},\n", " {'value': 'food quality'},\n", " {'value': 'other'},\n", " ],\n", " },\n", " {\n", " 'type': 'score',\n", " 'name': 'urgency',\n", " 'instructions': 'How upset is the customer?',\n", " 'levels': [\n", " {'label': 'calm'},\n", " {'label': 'annoyed'},\n", " {'label': 'angry'},\n", " ],\n", " },\n", "]\n", "dec_t.add_computed_column(\n", " triage=openai.decisions(\n", " messages, questions=questions, model='gpt-6-luna'\n", " )\n", ")\n", "dec_t.add_computed_column(supported=dec_t.triage.answers[0].probability)\n", "dec_t.add_computed_column(issue=dec_t.triage.answers[1].choice)\n", "dec_t.add_computed_column(urgency=dec_t.triage.answers[2].score)\n", "dec_t.add_computed_column(\n", " reply=openai.responses(\n", " reply_prompt(dec_t.complaint, dec_t.supported),\n", " model='gpt-4o-mini',\n", " )\n", ")\n", "dec_t.add_computed_column(\n", " reply_text=dec_t.reply.output[0].content[0].text\n", ")" ] }, { "cell_type": "code", "execution_count": 10, "id": "a3610796", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Inserted 2 rows with 0 errors in 2.04 s (0.98 rows/s)\n" ] }, { "data": { "text/plain": [ "2 rows inserted." ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "photo_url = 'https://raw.githubusercontent.com/pixeltable/pixeltable/release/docs/resources/images/000000000009.jpg'\n", "dec_t.insert(\n", " [\n", " {\n", " 'complaint': 'I asked for no fruit, but the box came with oranges and pineapple. Not happy.',\n", " 'photo': photo_url,\n", " },\n", " {\n", " 'complaint': 'My order is missing the broccoli I paid for!',\n", " 'photo': photo_url,\n", " },\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 11, "id": "cd76279b", "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
complaintissuesupportedurgencyreply_text
My order is missing the broccoli I paid for!missing item0.1.NaN
I asked for no fruit, but the box came with oranges and pineapple. Not happy.unwanted item0.691.I sincerely apologize for the oversight in your order, as we understand how important it is to receive exactly what you requested. We will process a full refund for your purchase and ensure that your preferences are better accommodated in the future.
" ], "text/plain": [ " complaint issue \\\n", "0 My order is missing the broccoli I paid for! missing item \n", "1 I asked for no fruit, but the box came with or... unwanted item \n", "\n", " supported urgency reply_text \n", "0 0.00 1.0 NaN \n", "1 0.69 1.0 I sincerely apologize for the oversight in you... " ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dec_t.order_by(dec_t.urgency, asc=False).select(\n", " dec_t.complaint,\n", " dec_t.issue,\n", " dec_t.supported,\n", " dec_t.urgency,\n", " dec_t.reply_text,\n", ").collect()" ] }, { "cell_type": "markdown", "id": "f285bcef-eba6-4d0c-9f7d-950fb467eb21", "metadata": {}, "source": [ "## Embeddings\n", "\n", "Note: OpenAI Embeddings API is not available with free tier API keys" ] }, { "cell_type": "code", "execution_count": 12, "id": "edf544a9-35cc-4e40-bd56-1b76226d046e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created table 'embeddings'.\n", "Added 0 column values with 0 errors in 0.00 s\n" ] }, { "data": { "text/plain": [ "No rows affected." ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "emb_t = pxt.create_table('openai_demo/embeddings', {'input': pxt.String})\n", "emb_t.add_computed_column(\n", " embedding=openai.embeddings(\n", " input=emb_t.input, model='text-embedding-3-small'\n", " )\n", ")" ] }, { "cell_type": "code", "execution_count": 13, "id": "16e38191-0a08-457b-a202-6b2d0bcab892", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Inserted 1 row with 0 errors in 0.58 s (1.72 rows/s)\n" ] }, { "data": { "text/plain": [ "1 row inserted." ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "emb_t.insert(\n", " [{'input': 'OpenAI provides a variety of embeddings models.'}]\n", ")" ] }, { "cell_type": "code", "execution_count": 14, "id": "5bf1cc4d-fd13-497e-a7fb-2ce78e3ee2e8", "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
inputembedding
OpenAI provides a variety of embeddings models.[-0.023 -0.045  0.069 -0.017 -0.008 -0.027 ...  0.009  0.005  0.021  0.018 -0.012 -0.008]
" ], "text/plain": [ " input \\\n", "0 OpenAI provides a variety of embeddings models. \n", "\n", " embedding \n", "0 [-0.022873, -0.044708, 0.068848, -0.016922, -0... " ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "emb_t.head()" ] }, { "cell_type": "markdown", "id": "069cb1eb-2f5c-4843-9645-a79d410d8bf4", "metadata": {}, "source": [ "## Image generations" ] }, { "cell_type": "code", "execution_count": 15, "id": "24970bff-013f-4b5b-844d-764f1b5465d6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created table 'images'.\n", "Added 0 column values with 0 errors in 0.00 s\n" ] }, { "data": { "text/plain": [ "No rows affected." ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "image_t = pxt.create_table('openai_demo/images', {'input': pxt.String})\n", "image_t.add_computed_column(\n", " img=openai.image_generations(image_t.input, model='gpt-image-2')\n", ")" ] }, { "cell_type": "code", "execution_count": 16, "id": "5f7f1b29-2963-4d73-b1b6-f7168f5d0a73", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Inserted 1 row with 0 errors in 19.41 s (0.05 rows/s)\n" ] }, { "data": { "text/plain": [ "1 row inserted." ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "image_t.insert(\n", " [\n", " {\n", " 'input': 'A giant Pixel floating in the open ocean in a sea of data'\n", " }\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 17, "id": "60c6e39b-b0b2-4087-a82a-3d8033f29e90", "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
table 'openai_demo/images'
\n", "\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Column NameTypeSourceComputed WithComment
inputStringimages
imgJson[{'created': Int, 'data': Json[(Image, ...)], 'usage': Json[{'input_tokens': Int, 'input_tokens_details': Json[{'image_tokens': Int, 'text_tokens': Int}], 'output_tokens': Int, 'total_tokens': Int, 'output_tokens_details': Json[{'image_tokens': Int, 'text_tokens': Int}] | None}] | None, 'background': String | None, 'output_format': String | None, 'quality': String | None, 'size': String | None, 'safety_identifier': String | None}, optional_keys=['safety_identifier']]imagesimage_generations(input, model='gpt-image-2')
\n" ], "text/plain": [ "table 'openai_demo/images'\n", "\n", " Column Name Type Source Computed With Comment\n", "------------------------------------------------------------------------------------------------------------------------------\n", " input String images \n", " img Json[{'created': Int, 'data': Json[(Image, ...... images image_generations(input, model='gpt-image-2') " ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "image_t" ] }, { "cell_type": "code", "execution_count": 18, "id": "c1b86b7b-2a95-447f-b847-63226278de93", "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
inputimg
A giant Pixel floating in the open ocean in a sea of data{"data": [<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1327x1185 at 0x311E19730>], "size": "1327x1185", "usage": {"input_tokens": 19, "total_tokens": 220, "output_tokens": 201, "input_tokens_details": {"text_tokens": 19, "image_tokens": 0}, "output_tokens_details": {"text_tokens": 0, "image_tokens": 201}}, "created": 1793198539, "quality": "low", "background": "opaque", "output_format": "png", "safety_identifier": null}
" ], "text/plain": [ " input \\\n", "0 A giant Pixel floating in the open ocean in a ... \n", "\n", " img \n", "0 {'data': [