openai / openai-python

The official Python library for the OpenAI API
https://pypi.org/project/openai/
Apache License 2.0
22.66k stars 3.16k forks source link

Assistant access doesn't work without OPENAI_API_KEY env variable, preventing from accessing assistants in different projects. #1513

Closed hedb closed 3 months ago

hedb commented 3 months ago

Confirm this is an issue with the Python library and not an underlying OpenAI API

Describe the bug

Assistant access doesn't work without OPENAI_API_KEY env variable, preventing from accessing assistants in different projects.

Why is it needed? I have two assistant that i need to access from slack bot they are located in different projects

I can't rely on the environment variable - as the api_key needed is different.

To Reproduce

  1. Create an assistant
  2. fill the details
  3. run the code snippet

Code snippets

import os
import openai
from retrying import retry

def should_reject(run_status):
    return run_status.status != "completed"

@retry(retry_on_result=should_reject, stop_max_attempt_number=20, wait_fixed=3000)
def retrieve_run_status(thread_id, run_id):
    return openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id)

def monitor_thread_status(thread_id, run_id):
    run_status = retrieve_run_status(thread_id, run_id)
    return run_status

def access_the_assistant(api_key):

    question = "What can you help with?"
    project_id = 'proj_..........'
    assistant_id = 'asst_...........'

    client = openai.OpenAI(project=project_id, api_key=api_key)

    the_thread = client.beta.threads.create()
    thread_id = the_thread.id

    _ = client.beta.threads.messages.create(
        thread_id, role="user", content=question
    )
    run = client.beta.threads.runs.create(
        thread_id=thread_id, assistant_id=assistant_id
    )

    run_status = retrieve_run_status(thread_id, run.id)

    thread_messages = client.beta.threads.messages.list(
        thread_id,
    )
    return ( str (thread_messages.data) )

def main():
    #load the api key
    api_key = os.getenv("OPENAI_API_KEY")

    # if uncommented fix the issue - caches the api_key
    # ret = access_the_assistant(api_key)
    # print(ret)

    del os.environ['OPENAI_API_KEY']

    ret = access_the_assistant(api_key)
    print(ret)

if __name__ == "__main__":
    main()

OS

Mac

Python version

3.9

Library version

1.35.7

RobertCraigie commented 3 months ago

Assistant access doesn't work without OPENAI_API_KEY env variable

what do you mean by "doesn't work", does it crash? if so can you share a stack trace?

hedb commented 3 months ago

My bug I used : return openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id) instead of return client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id)

which caused a mess