커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
조언 주신 대로 코드 변경을 했는데 여전히 API 오류가 뜹니다
나만의 ChatGPT 서비스 만들기 v0
기타
북마크
우*아
댓글
7
추천
0
조회수
21
조회수
21
답변 완료

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

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



이전에 해결법 주신대로 코드 변경을 해 보았으나 같은 에러 메세지가 나오고 있습니다

이런 경우 API 키를 새로 받아서 코드를 다시 짜야 하는지 여쭤 보고자 합니다

다만 터미널 에서는 에러가 뜨지 않았습니다


아울러 보안상 문제로 제 실제 api key 가 아닌

openai.api_key = os.getenv("my api is here!" 으로 작성 한 점 참고 부탁 드립니다



스파르타 즉문즉답




작성한 코드 및 에러 메세지

오류 import streamlit as st
import openai
import os
from PIL import Image



openai.api_key = os.getenv("my api is here!")



def chatbot_response(user_input):
    try:
        response = openai.chat.completions.create(
            model="gpt-4o",  
            messages=[
                {"role": "system", "content": "너는 사용자가 입력한 꿈 내용을 분석하고 그에 따른 심리 상태를 해석한 후 해결책을 알려주는 역할이야. 채팅이 끝나면 그림을 그려서 사용자에게 보여줘야 해."},
                {"role": "user", "content": user_input}
            ],
            temperature=0.7,  
            max_tokens=1500,  
        )
        return response.choices[0].message['content']
    except Exception as e:
        st.write(f"Chatbot Error: {e}")
        return "지금은 일하고 싶지 않나봐요 :( 좀 이따 다시 와주세요!"


def generate_image(prompt):
    try:
        response = openai.Image.create(
            prompt=prompt,
            n=1,
            size="1024x1024"
        )
        image_url = response['data'][0]['url']
        return image_url
    except Exception as e:
        st.write(f"Image Generation Error: {e}")
        return None



st.set_page_config(layout="wide")



if "chat_history" not in st.session_state:
    st.session_state.chat_history = []  



if "page" not in st.session_state:
    st.session_state.page = "조고예몽 메인"


if "button_clicked" not in st.session_state:
    st.session_state.button_clicked = False



def select_page(page_name):
    st.session_state.page = page_name
    
col1, col_space, col2 = st.columns([1, 1.5, 2.2])



with col1:
    st.markdown('<div class="image-wrapper">', unsafe_allow_html=True)
    image_path = "images/zogoemong.jpg"
    image = Image.open(image_path)
    st.image(image, caption=" ", use_column_width=False, width=400)
    st.markdown('</div>', unsafe_allow_html=True)


    st.markdown('<br><br><br>', unsafe_allow_html=True)
    st.header("조고예몽 메인&nbsp;&nbsp;🐈", divider="violet")
    st.markdown("made by. jia_2024")



with col2:
    st.write("**조고예몽에 어서오세요**")
    st.image("images/채팅창.jpg", width=500, caption=" ")


    message = st.empty()


    def display_chat_history():
        with message.container():
            for chat in st.session_state.chat_history:
                st.write(chat)


    if "conversation_started" not in st.session_state:
        st.session_state.conversation_started = True
        st.write("**[달래]** 안녕👋 밤 새 잘 잤어?")
    
    display_chat_history()  



    if not st.session_state.button_clicked:
        col_btn1, col_btn2 = st.columns([0.5, 0.5])


        with col_btn1:
            if st.button("응! 정말 개운하게 잘 잤어 🌞", key="button1"):
                st.session_state.chat_history.append("**[사용자]** 응! 정말 개운하게 잘 잤어 🌞")
                st.session_state.chat_history.append("**[달래]** 다행이다! 잘 잔 만큼 좋은 꿈도 풀어줘야 의미가 있는 법!")
                st.session_state.chat_history.append("**[달래]** 아래 채팅창에 꿈 내용을 적어서 나에게 줘")
                st.session_state.button_clicked = True



        with col_btn2:
            if st.button("아니 너무 피곤해 죽을거 같아 😴", key="button2"):
                st.session_state.chat_history.append("**[사용자]** 아니 너무 피곤해 죽을거 같아 😴")
                st.session_state.chat_history.append("**[달래]** 에구, 왜 잠을 못 잤을까?")
                st.session_state.chat_history.append("**[달래]** 좀 더 나은 하루가 될 수 있도록 내가 도와 주려고 해")
                st.session_state.chat_history.append("**[달래]** 아래 채팅창에 꿈 내용을 적어서 나에게 줘")
                st.session_state.button_clicked = True



    user_input = st.text_input("메시지 입력", key="chat_input", placeholder="꿈 내용을 적어주세요...")
    send_button = st.button("보내기", key="send_button")



    if send_button and user_input.strip():
        st.session_state.chat_history.append(f"**[사용자]** {user_input}")


        chatbot_reply = chatbot_response(user_input)
        st.session_state.chat_history.append(f"**[달래]** {chatbot_reply}")


        image_prompt = f"꿈 내용에 기반한 이미지: {user_input}" 
        image_url = generate_image(image_prompt)
        
        if image_url:
            st.session_state.chat_history.append(f"**[달래]** [이미지 보기]({image_url})")
            st.session_state.chat_history.append("**[달래]** 오늘 너의 꿈일기를 그려 봤어. 오늘도 좋은 하루 되길 바랄게!")
        else:
            st.session_state.chat_history.append("**[달래]** 이미지를 생성하려는데 귀찮아서 엎었어요.")


        display_chat_history()


Chatbot Error: module 'openai' has no attribute 'chat'

Image Generation Error: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details.




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