커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
코드가 실행이 안됩니다.
AI 종합반 v0
3주차
북마크
조*권
댓글
3
추천
0
조회수
34
조회수
34
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.


이전에 질문했는데 api키와 organization을 지정해도 코드실행이 안되네요



스파르타 즉문즉답




import openai
import gradio as gr


# OpenAI API 키 설정
openai.organization ="org-Spartacodingclub"
openai.api_key = "sk-" # 여기에 실제 API 키를 입력하세요


# 챗봇에 채팅이 입력되면 이 함수를 호출합니다.
def predict(message, history):
    # OpenAI API에 전달할 메시지 형식을 준비합니다.
    # 이 리스트는 사용자와 챗봇 간의 대화 기록을 저장합니다.
    history_openai_format = []


    # 기존의 대화 기록을 OpenAI API가 이해할 수 있는 형식으로 변환합니다.
    for human, assistant in history:
        # 사용자의 메시지를 추가합니다.
        history_openai_format.append({"role": "user", "content": human})
        # 챗봇의 응답을 추가합니다.
        history_openai_format.append({"role": "assistant", "content": assistant})


    # 가장 최근에 입력된 사용자의 메시지를 추가합니다.
    history_openai_format.append({"role": "user", "content": message})


    # OpenAI API를 호출하여 응답을 받습니다.
    # model: 사용할 모델의 이름
    # messages: 대화 기록
    # temperature: 모델의 응답을 얼마나 다양하게 할지 결정하는 값 (0~1)
    # stream: 응답을 스트리밍 형태로 받을 것인지 여부
    response = openai.ChatCompletion.create(
        model='gpt-3.5-turbo',
        messages=[{"role": "system", "content": "당신은 웨이트 트레이닝 전문가입니다. 웨이트 트레이닝 외의 질문에는 답변하지 마세요."}, *history_openai_format],
        temperature=0,
        stream=True
    )


    # 응답을 처리합니다.
    # 이 변수는 챗봇의 응답을 임시로 저장합니다.
    partial_message = ""


    # API 응답에서 각 부분을 처리합니다.
    print(response)
    for chunk in response:
        # 응답의 'delta' 부분에 실제 챗봇의 대화 내용이 있습니다.
        # 이 부분을 추출하여 임시 메시지에 추가합니다.
        if len(chunk['choices'][0]['delta']) != 0:
            partial_message += chunk['choices'][0]['delta']['content']
            # 완성된 메시지를 반환합니다.
            yield partial_message


# 챗봇 UI 설정
gr.ChatInterface(
    fn=predict,
    textbox=gr.Textbox(placeholder="말걸어주세요..", container=False, scale=7),
    examples=[["안녕"], ["인공지능 공부 어떻게 해?"], ["다이어트 꿀팁좀"]]
).queue().launch(share=True, debug=True)


Colab notebook detected. This cell will run indefinitely so that you can see errors and logs. To turn off, set debug=False in launch().
Running on public URL: https://569e5b5d90a8895091.gradio.live

This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)


Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/gradio/queueing.py", line 456, in call_prediction
    output = await route_utils.call_process_api(
  File "/usr/local/lib/python3.10/dist-packages/gradio/route_utils.py", line 232, in call_process_api
    output = await app.get_blocks().process_api(
  File "/usr/local/lib/python3.10/dist-packages/gradio/blocks.py", line 1522, in process_api
    result = await self.call_function(
  File "/usr/local/lib/python3.10/dist-packages/gradio/blocks.py", line 1156, in call_function
    prediction = await utils.async_iteration(iterator)
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 514, in async_iteration
    return await iterator.__anext__()
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 635, in asyncgen_wrapper
    async for response in f(*args, **kwargs):
  File "/usr/local/lib/python3.10/dist-packages/gradio/chat_interface.py", line 441, in _stream_fn
    first_response = await async_iteration(generator)
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 514, in async_iteration
    return await iterator.__anext__()
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 507, in __anext__
    return await anyio.to_thread.run_sync(
  File "/usr/local/lib/python3.10/dist-packages/anyio/to_thread.py", line 33, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
  File "/usr/local/lib/python3.10/dist-packages/anyio/_backends/_asyncio.py", line 877, in run_sync_in_worker_thread
    return await future
  File "/usr/local/lib/python3.10/dist-packages/anyio/_backends/_asyncio.py", line 807, in run
    result = context.run(func, *args)
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 490, in run_sync_iterator_async
    return next(iterator)
  File "<ipython-input-3-b675f57f2483>", line 29, in predict
    response = openai.ChatCompletion.create(
  File "/usr/local/lib/python3.10/dist-packages/openai/_utils/_proxy.py", line 22, in __getattr__
    return getattr(self.__get_proxied__(), attr)
  File "/usr/local/lib/python3.10/dist-packages/openai/_utils/_proxy.py", line 43, in __get_proxied__
    return self.__load__()
  File "/usr/local/lib/python3.10/dist-packages/openai/lib/_old_api.py", line 33, in __load__
    raise APIRemovedInV1(symbol=self._symbol)
openai.lib._old_api.APIRemovedInV1: 

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface. 

Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/gradio/queueing.py", line 456, in call_prediction
    output = await route_utils.call_process_api(
  File "/usr/local/lib/python3.10/dist-packages/gradio/route_utils.py", line 232, in call_process_api
    output = await app.get_blocks().process_api(
  File "/usr/local/lib/python3.10/dist-packages/gradio/blocks.py", line 1522, in process_api
    result = await self.call_function(
  File "/usr/local/lib/python3.10/dist-packages/gradio/blocks.py", line 1156, in call_function
    prediction = await utils.async_iteration(iterator)
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 514, in async_iteration
    return await iterator.__anext__()
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 635, in asyncgen_wrapper
    async for response in f(*args, **kwargs):
  File "/usr/local/lib/python3.10/dist-packages/gradio/chat_interface.py", line 441, in _stream_fn
    first_response = await async_iteration(generator)
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 514, in async_iteration
    return await iterator.__anext__()
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 507, in __anext__
    return await anyio.to_thread.run_sync(
  File "/usr/local/lib/python3.10/dist-packages/anyio/to_thread.py", line 33, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
  File "/usr/local/lib/python3.10/dist-packages/anyio/_backends/_asyncio.py", line 877, in run_sync_in_worker_thread
    return await future
  File "/usr/local/lib/python3.10/dist-packages/anyio/_backends/_asyncio.py", line 807, in run
    result = context.run(func, *args)
  File "/usr/local/lib/python3.10/dist-packages/gradio/utils.py", line 490, in run_sync_iterator_async
    return next(iterator)
  File "<ipython-input-3-b675f57f2483>", line 29, in predict
    response = openai.ChatCompletion.create(
  File "/usr/local/lib/python3.10/dist-packages/openai/_utils/_proxy.py", line 22, in __getattr__
    return getattr(self.__get_proxied__(), attr)
  File "/usr/local/lib/python3.10/dist-packages/openai/_utils/_proxy.py", line 43, in __get_proxied__
    return self.__load__()
  File "/usr/local/lib/python3.10/dist-packages/openai/lib/_old_api.py", line 33, in __load__
    raise APIRemovedInV1(symbol=self._symbol)
openai.lib._old_api.APIRemovedInV1: 

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface. 

Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/gradio/queueing.py", line 501, in process_events
    response = await self.call_prediction(awake_events, batch)
  File "/usr/local/lib/python3.10/dist-packages/gradio/queueing.py", line 465, in call_prediction
    raise Exception(str(error) if show_error else None) from error

Exception: None



취소
 공유
취소
댓글 0
댓글 알림
나의얼굴