Deprecation Warning / How To Change Code?

Hello - i currently have this working assistant solution - but not i get several deprecation wargning:

C:\DEVNEU\Fiverr2025\TRY\seagullandshark\test.py:68: DeprecationWarning: The Assistants API is deprecated in favor of the Responses API
thread = client.beta.threads.create()
Preparing question
C:\DEVNEU\Fiverr2025\TRY\seagullandshark\test.py:70: DeprecationWarning: The Assistants API is deprecated in favor of the Responses API
results = client.beta.threads.messages.create(
Running for answer
C:\DEVNEU\Fiverr2025\TRY\seagullandshark\test.py:76: DeprecationWarning: The Assistants API is deprecated in favor of the Responses API
run = client.beta.threads.runs.create (
C:\DEVNEU\Fiverr2025\TRY\seagullandshark\test.py:81: DeprecationWarning: The Assistants API is deprecated in favor of the Responses API
run = client.beta.threads.runs.retrieve (
C:\DEVNEU\Fiverr2025\TRY\seagullandshark\test.py:87: DeprecationWarning: The Assistants API is deprecated in favor of the Responses API
results = client.beta.threads.messages.list(

Find attached the code which i am using:

import os, sys
import time
from dotenv import load_dotenv
from openai import OpenAI
from pydantic import BaseModel
import json
from typing import List

path = os.path.abspath(os.path.dirname(sys.argv[0]))

class ArticleSummary(BaseModel):
buyerName: str
purchasePercentInterest: str
purchasePrice: str

class Messages(BaseModel):
messages: List[ArticleSummary]

fn = os.path.join(path, “.env”)
load_dotenv(fn)
CHATGPT_API_KEY = os.environ.get(“CHATGPT_API_KEY”)
client = OpenAI(api_key = CHATGPT_API_KEY)

fn = os.path.join(path, “prompt.txt”)
with open(fn, encoding=“utf-8”, errors=“ignore”) as f:
lines = f.read().splitlines()
questionParse = “\n”.join(lines)

vector_store = client.vector_stores.create(name=“File”)
pdf1 = os.path.join(path, “inpPA.pdf”)
pdf2 = os.path.join(path, “inpPQ.pdf”)

file_paths = [pdf1, pdf2]
file_streams = [open(path, “rb”) for path in file_paths]
file_batch = client.vector_stores.file_batches.upload_and_poll(
vector_store_id=vector_store.id, files=file_streams
)
print(file_batch.status)
print(file_batch.file_counts)

print(f"Preparing assistant for file")
assistant = client.beta.assistants.create(
name=“Document Analyse Assistant”,
instructions=“You are a machine learning researcher, answer questions about the provided pdf
file”,
model = “gpt-4o”,
tools = [{“type”: “file_search”}],
response_format={
“type”: “json_schema”,
“json_schema”: {
“name”: “test_schema”,
“schema”: Messages.model_json_schema()
}
}
)
assistant = client.beta.assistants.update(
assistant_id=assistant.id,
tool_resources={“file_search”: {“vector_store_ids”: [vector_store.id]}},
)

print(f"Preparing thread")
thread = client.beta.threads.create()
print(f"Preparing question")
results = client.beta.threads.messages.create(
thread_id = thread.id,
role = “user”,
content = questionParse
)

print(f"Running for answer")
run = client.beta.threads.runs.create (
thread_id = thread.id,
assistant_id = assistant.id
)

while run.status not in [“completed”, “failed”]:
run = client.beta.threads.runs.retrieve (
thread_id = thread.id,
run_id = run.id
)

if run.status == “completed”:
results = client.beta.threads.messages.list(
thread_id=thread.id
)
resultAnswer = results.data[0].content[0].text.value

try:
resultAnswer = json.loads(resultAnswer)
except:
print(f"No output - try again…")
time.sleep(3)

with open(‘data.json’, ‘w’, encoding=‘utf-8’) as f:
json.dump(resultAnswer, f, ensure_ascii=False, indent=4)
print(resultAnswer)

if run.status == “failed”:
print(run.last_error.code)
print(run.last_error.message)

How can i change this code so its running with the new version from openai without deprecation warnings.

1 Like

What is deprecated is the Assistants endpoint itself. It will be shut off in 2026: no more threads, no more runs, no more assistant instructions to call upon, no history of what was ever discussed. Updated is moving your application to Chat Completions (write your own function that uses OpenAI’s search endpoint) or Responses (use the internal tool for search similarly). Each have a significantly different pattern of usage from Assistants.

Hopefully a lesson in not using cloud-based server-side data products out of your control, period.


What you see is a “warning”. To quiet the code in the short term, you could stop warnings, stop the category of warning, but we’ll go beyond and stop exactly and only that message. Add to your imports and immediately after:

import warnings

warnings.filterwarnings(
    "ignore",
    category=DeprecationWarning,
    message=r"^The Assistants API is deprecated in favor of the Responses API"
)
1 Like

ok i see - thanks
So its currently not possible to change the code any way to have the same funcionality but without deprecation warnings?

I provided exactly how to “change the code” and not see warnings.

You would not want to alter the OpenAI library, as it often needs to be updated, and it is plastered with dozens of deprecations decorators that directly issue the warning..

You can use the last version to not spit out warnings to the channel:

pip install "openai==1.82.1"

You can also not use the SDK library at all, and make RESTful calls, and not have this nasty bloat messing with you, period.

Here’s code that doesn’t use the library, uploads a local file to code interpreter (find it in the script) - and then demonstrates that Assistants sucks by not putting your file in the mount point with your file name.

Summary
import os
import json
import time
import httpx

API_BASE = "https://api.openai.com/v1"
API_KEY = os.environ.get("OPENAI_API_KEY")

if not API_KEY:
    raise RuntimeError("OPENAI_API_KEY environment variable is not set")

def print_http_error(prefix, err: httpx.HTTPStatusError):
    try:
        body = err.response.text
    except Exception:
        body = "<no body>"
    print(f"{prefix}\nHTTP {err.response.status_code}\n{body}")

def main():
    file_id = None
    assistant_id = None
    thread_id = None

    # Only assistants endpoints need this header
    assistants_beta_hdr = {"OpenAI-Beta": "assistants=v2"}

    try:
        with httpx.Client(
            base_url=API_BASE,
            headers={"Authorization": f"Bearer {API_KEY}"},
            timeout=60.0,
            follow_redirects=True,
        ) as client:
            # Step 1: Upload the File (multipart/form-data)
            file_path = "mydata.json"  # Replace with your actual file path
            with open(file_path, "rb") as f:
                resp = client.post(
                    "/files",
                    data={"purpose": "assistants"},
                    files={"file": (os.path.basename(file_path), f, "application/json")},
                )
            resp.raise_for_status()
            uploaded_file = resp.json()
            file_id = uploaded_file["id"]
            print(f"Uploaded File ID: {file_id}")

            # Step 2: Create the Assistant
            payload = {
                "instructions": "You are an AI programming assistant.",
                "name": "example_coder",
                "model": "gpt-4.1",
                "tools": [{"type": "code_interpreter"}],
                "tool_resources": {
                    "code_interpreter": {
                        "file_ids": [file_id]
                    }
                },
            }
            resp = client.post("/assistants", headers=assistants_beta_hdr, json=payload)
            resp.raise_for_status()
            assistant = resp.json()
            assistant_id = assistant["id"]
            print(f"Created Assistant ID: {assistant_id}")

            # Step 3: Create a Thread with a User Message
            content = (
                "List files uploaded to your mount point, by ID and original name.\n"
                "Your goal is to give the user-friendly file name, not a system-assigned ID"
            )
            resp = client.post(
                "/threads",
                headers=assistants_beta_hdr,
                json={"messages": [{"role": "user", "content": content}]},
            )
            resp.raise_for_status()
            thread = resp.json()
            thread_id = thread["id"]
            print(f"Created Thread ID: {thread_id}")

            # Step 4: Create a message in the thread
            resp = client.post(
                f"/threads/{thread_id}/messages",
                headers=assistants_beta_hdr,
                json={"role": "user", "content": content},
            )
            resp.raise_for_status()
            message = resp.json()  # not used, but validates success

            # Step 5: Create a Run and poll until completed
            resp = client.post(
                f"/threads/{thread_id}/runs",
                headers=assistants_beta_hdr,
                json={"assistant_id": assistant_id},
            )
            resp.raise_for_status()
            run = resp.json()
            run_id = run["id"]

            # Polling loop
            while True:
                time.sleep(2)  # 2000 ms
                r = client.get(
                    f"/threads/{thread_id}/runs/{run_id}",
                    headers=assistants_beta_hdr,
                )
                r.raise_for_status()
                run_status = r.json()
                status = run_status.get("status")
                if status in ("completed", "failed", "cancelled", "expired"):
                    break

            if status != "completed":
                raise RuntimeError(f"Run ended with status: {status}")

            # Step 6: Fetch the latest message from this run
            resp = client.get(
                f"/threads/{thread_id}/messages",
                headers=assistants_beta_hdr,
                params={"limit": 1, "run_id": run_id},
            )
            resp.raise_for_status()
            thread_messages = resp.json()
            print(thread_messages.get("data"))

    except httpx.HTTPStatusError as e:
        print_http_error("HTTP request failed", e)
    except Exception as e:
        print(f"code failed\n{e}")
    finally:
        # Cleanup
        with httpx.Client(
            base_url=API_BASE,
            headers={"Authorization": f"Bearer {API_KEY}"},
            timeout=60.0,
            follow_redirects=True,
        ) as client:
            # Best-effort deletes (ignore failures)
            if thread_id:
                try:
                    r = client.delete(f"/threads/{thread_id}", headers={"OpenAI-Beta": "assistants=v2"})
                    r.raise_for_status()
                    print("Deleted Thread.")
                except httpx.HTTPStatusError as e:
                    print_http_error("Failed to delete thread", e)
            if assistant_id:
                try:
                    r = client.delete(f"/assistants/{assistant_id}", headers={"OpenAI-Beta": "assistants=v2"})
                    r.raise_for_status()
                    print("Deleted Assistant.")
                except httpx.HTTPStatusError as e:
                    print_http_error("Failed to delete assistant", e)
            if file_id:
                try:
                    r = client.delete(f"/files/{file_id}")
                    r.raise_for_status()
                    print("Deleted File.")
                except httpx.HTTPStatusError as e:
                    print_http_error("Failed to delete file", e)

if __name__ == "__main__":
    main()

You can continue using Assistants until it is shut off - and the API library is giving you fair warning.

1 Like

Thanks a lot for detailed explanation - i think i understand more or less.