On the journey of

[AWS 사전공인교육] 5. AWS에서 ChatGPT 서비스 구현하기 (1) 본문

Experiences & Study/AWS

[AWS 사전공인교육] 5. AWS에서 ChatGPT 서비스 구현하기 (1)

dlrpskdi 2023. 10. 13. 17:57

5-1. Lambda ChatGPT

 

먼저 ChatGPT를 구현해보기 위해서는 OpenAI 상의 API Key가 필요하다. 그러므로 아래 링크에 접속해 본인의 고유한 API를 발급받은 후, 이를 복사해두자. (재발급이 되긴 하지만 귀찮으니까...)

 https://platform.openai.com/account/api-keys 

 

OpenAI Platform

Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform.

platform.openai.com

여기서 왼쪽 카테고리의 API Keys 접속 - Create new secret Key 클릭하면 됨!

다시 코드로 돌아와서, OpenAI Library가 필요하므로 pip install 하기 위해 zip 으로 업로드하여 Lambda Function 생성.

  • zip 파일 생성 전에 3rd part library 를 zip파일 안에 포함 시킴
    • 터미널에서 위 코드의 경로에서
    • pip3 install openai -t 로 진행
  • lambda_function.py 생성
    • 코드는 아래와 같다. 
import openai

openai.api_key = ":+:+:+:+: Your OpenAI API KEY :+:+:+:+:"


def lambda_handler(event, context):
    q = event.get('queryStringParameters', {}).get('prompt', '')

    status_code = 200
    return_message = ''
    try:
        if q:
            response = openai.Completion.create(
                model='text-davinci-003',
                prompt=q,
                temperature=0,
                max_tokens=100,
                top_p=1,
            )
            # print(response)
            print(response.choices[0].text.strip())
            return_message = response.choices[0].text.strip()
            
        else:
            status_code = 500
            return_message = 'prompt 파라메터가 필요합니다.'
    except e:
        status_code = 500
        return_message = str(e)
        
    return {
        'statusCode': status_code,
        'body': {
            'message': return_message
        }
    }
  • zip 파일로 압축
  • zip -r aws-lambda-test.zip 으로 압축 진행
  • 윈도우는 탐색기에서 압축, 또는 zip 바이너리 다운로드
  • aws-lambda-test.zip 파일이 생성된 것을 확인할 수 있다. 

Lambda Function 에 업로드

Lambda 에서 함수를 생성하고 위에서 생성한 zip 파일 업로드

  • 소스에서 openai.api_key 를 본인의 open ai key 로 입력 후 테스트

구성

함수 URL > 생성

실행

  1. 테스트로 실행
  2. 함수 URL 을 만들어서 실행

html 파일을 생성해서 javascript 로 호출하기

  • simple code
<html>
    <head>

    </head>
    <body>
        <input type="text" id="query" value="" /><button type="button" onclick="javascript:send_query()">Send</button>
        <div id="list">

        </div>
    </body>

    <script>
        var listDiv = document.getElementById('list');
        var textInput = document.getElementById("query");
        function append_list(textList){
            textList.forEach((element, index) => {
                let newDiv = document.createElement('div');
                newDiv.textContent = element;
                newDiv.classList.add('text'+index);
                listDiv.appendChild(newDiv);
            });
        }

        async function send_query(){
            
            let query = textInput.value;
            textInput.value = '';

            const response = await fetch('https://:+:+:your_lambda_url:+:+:.ap-northeast-2.on.aws/?prompt='+encodeURIComponent(query));
            const data = await response.json();
            console.log(data.message);
            append_list(['나:'+query, 'GPT:'+data.message]);
        }
    </script>
    <style>
        .text1 {
            color: green;
        }
        .text2 {
            color: blue;
            font-weight: bold;
        }
    </style>
</html>

5-2. Cloud9 GPT 번역기

: 위 5-1 절차를 모두 마쳤다면, 이제 Cloud9 환경 활용해 GPT 번역기 구현 실습을 해보자.

Main.py
import openai
import streamlit as st

api_key = st.text_input('openai api key')
if api_key:
    openai.api_key = api_key

lang_list = ('영어', '중국어', '일본어', '아랍어', '한국어')

st.header('번역기')

col1, col2 = st.columns(2)
result = ''
with col1:
    option = st.selectbox('Lang', lang_list)
    q = st.text_area('From')
    if q:

				# :+:+:+:+: prompt format 을 만들어보세요 :+:+:+:+:
				# option = 영어, 중국어.. 중 하나 
				# q = 입력 문구
        prompt = q # <- 코드를 수정하세요

        response = openai.Completion.create(
            model='text-davinci-003',
            prompt=prompt,
            temperature=0,
            max_tokens=100,
            top_p=1,
        )
        print(response.choices[0].text.strip())
        result = response.choices[0].text.strip()

with col2:
    st.text_area('To', value=result)

위와 같이 main.py를 작성했다면?

  1. Cloud9 으로 이동하여
  2. 환경 생성을 하고, 
  3. 필요한 라이브러리 설치한다. 이번에는 streamlit을 설치했다 : pip install openai streamlit 
  4. 필요한 추가 코딩(streamlit design) 진행한다.
    1. https://nowolver.tistory.com/179   
    2. https://nowolver.tistory.com/185   
 

[AWS 사전공인교육] Streamlit 활용하기 (1)

Streamlit은 Google Colab, Jupyter notebook 등 파이썬 언어를 지원하는 곳 어디에서나 활용이 가능한 시각화 툴이다. 분석 툴이 아니기 때문에, 프론트 지식이 어느 정도는 뒷받침되어야 한다고 생각함 (

nowolver.tistory.com

 

[AWS 사전공인교육] Streamlit 활용하기 (2)

요 이틀간...갑자기 조회수가 치솟아서 좀 무섭다 ,,, 뭘...검색하고 오는 거지...? 여튼 AWS Streamlit 활용교육 기록 2차 :) 9. 위젯 9.1. st.checkbox – 체크박스 import streamlit as st ## Checkbox if st.checkbox("Show/

nowolver.tistory.com

5. streamlit run main.py 를 통해 실행하면 된다. 

6. 네트워크 설정 (port 8501) 까지 완료하면, streamlit site가 새로 켜지는 것을 확인할 수 있다. 

 

다른 실습은 다음 포스팅에서 .... ✨