OpenAI API,랭체인 완벽 활용법 1/10
OPENAI 사용하기 위한 개발환경 구축해보자.
여기서는 Windows PC에 파이썬, VSCode 사용한다.
텍스트 생성
이미지 생성(DALL-E)
인간의 음성 인식(Whisper)
텍스트를 음성으로 전환(TTS)
다양한 챗봇 기능(Assistant)
https://platform.openai.com/api-keys
notepad에 openai api를 적어 놓는다.
1
https://www.python.org/downloads/
C:\0ai\ch02>python -V
Python 3.13.1
2
# 가상환경 만들기
C:\0ai\ch02>python -m venv py_env
C:\0ai\ch02\py_env\Scripts>activate.bat
(py_env) C:\0ai\ch02\py_env\Scripts>deactivate
4
참고
https://brunch.co.kr/@topasvga/4180
1
https://code.visualstudio.com/
2
# 확장 프로그램 설치
python
Jupyter
3
# VSCODE
View > Command Palette > Create : New Jupyter Notebook
4
# 프로젝트 폴터 생성하기 - command 창
ch03
5
# 명령 프롬프트 cmd
# 가상환경 생성하기
C:\0ai\07-ai\ch03\>python -m venv ch03_env
C:\0ai\07-ai\ch03\ch03_env\Scripts>activate.bat
https://platform.openai.com/playground/chat?models=gpt-4o
피자 만드는법 알려줘
1
폴더 생성
2
예제코드 다운 로드
3장
https://wikibook.co.kr/llm-projects/
3
# command 창
(ch03_env) C:\0ai\07-ai\ch03>pip install openai
4
# VSCODE
File- open folder 열기
5
import openai
# API 키 지정하여 클라이언트 선언하기
OPENAI_API_KEY="sk-proj-0sylvk4-YahjUPaGQA"
client = openai.OpenAI(api_key = OPENAI_API_KEY)
# client = openai.OpenAI(api_key = "f11c0a2670a80ee8cbef23d7fa7b")
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Tell me how to make a pizza"}])
print(response)
print(response.choices[0].message.content)
To make a pizza, you will need the following ingredients: - Pizza dough - Tomato sauce - Cheese - Toppings of your choice (such as pepperoni, mushrooms, bell peppers, onions, etc.) Here are the steps to make a pizza: 1. Preheat your oven to the temperature specified on the pizza dough packaging. 2. Roll out the pizza dough on a floured surface to your desired thickness. 3. Spread a layer of tomato sauce evenly over the dough, leaving a little space around the edges for the crust. 4. Sprinkle cheese over the sauce, and then add your desired toppings. 5. Place the pizza on a baking sheet or pizza stone and bake in the preheated oven for the amount of time specified on the dough packaging, usually around 10-15 minutes. 6. Once the pizza is cooked through and the cheese is melted and bubbly, carefully remove it from the oven. 7. Let the pizza cool for a few minutes before slicing and serving. Enjoy your homemade pizza!
6
사용 요금 계산
print(response.usage)
CompletionUsage(completion_tokens=356, prompt_tokens=14, total_tokens=370, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)
response.usage.prompt_tokens
total_bill_USD = (response.usage.completion_tokens*0.002 +response.usage.prompt_tokens*0.001)/1000
# 23.11.27 기준 환율 1USD = 1304.84 KRW
total_bill_KRW = total_bill_USD*1304.84
print("총 소모 비용 : {} 원".format(total_bill_KRW))
총 소모 비용 : 0.56630056 원
7
# 역할 부여하기
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You must only answer users' questions in English. This must be honored. You must only answer in English."},
{"role": "user", "content": "2020년 월드시리즈에서는 누가 우승했어?"}
]
)
print(response.choices[0].message.content)
The Los Angeles Dodgers won the 2020 World Series.
스트림릿으로 프론트앤드 만들기
1
pip install streamlit
(ch03_env) C:\0ai\07-ai\ch03\openai-api-tutorial-main (1)\openai-api-tutorial-main\ch03>streamlit run ch03_streamlit_example.py
2
email : 그냥 enter
3
# 파이썬 설치시 방화벽 허용 필요
4
# 실습1
5
# 실습2
# 코드에 따로 API 를 입력할 필요 없다.
VSCODE > Terminal
ch03_summerize_text.py
##### 기본 정보 불러오기 ####
# Streamlit 패키지 추가
import streamlit as st
# OpenAI 패키기 추가
import openai
##### 기능 구현 함수 #####
def askGpt(prompt,apikey):
client = openai.OpenAI(api_key = apikey)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}])
gptResponse = response.choices[0].message.content
return gptResponse
##### 메인 함수 #####
def main():
st.set_page_config(page_title="요약 프로그램")
# session state 초기화
if "OPENAI_API" not in st.session_state:
st.session_state["OPENAI_API"] = ""
# 사이드바
with st.sidebar:
# Open AI API 키 입력받기
open_apikey = st.text_input(label='OPENAI API 키', placeholder='Enter Your API Key', value='',type='password')
# 입력받은 API 키 표시
if open_apikey:
st.session_state["OPENAI_API"] = open_apikey
st.markdown('---')
st.header("�요약 프로그램")
st.markdown('---')
text = st.text_area("요약 할 글을 입력하세요")
if st.button("요약"):
prompt = f'''
**Instructions** :
- You are an expert assistant that summarizes text into **Korean language**.
- Your task is to summarize the **text** sentences in **Korean language**.
- Your summaries should include the following :
- Omit duplicate content, but increase the summary weight of duplicate content.
- Summarize by emphasizing concepts and arguments rather than case evidence.
- Summarize in 3 lines.
- Use the format of a bullet point.
-text : {text}
'''
st.info(askGpt(prompt,st.session_state["OPENAI_API"]))
if __name__=="__main__":
main()
PS C:\0ai\07-ai\ch03> streamlit run .\ch03_summerize_text.py
#실습2
같이 보면 좋을 자료
https://brunch.co.kr/@topasvga/4180
다음
https://brunch.co.kr/@topasvga/4156