Intro.
프로젝트의 핵심 기능이라고 할 수 있는 AI 서비스를 구현하기에 앞서 어떤 LLM을 사용하면 좋을지 선택하기 위해 가장 먼저 ChatGPT API를 사용해보았다.
패키지 설치
pip install openai
API Key 발급
OpenAI 로그인을 한뒤 [api-keys]에서 발급 받을 수 있다.
https://platform.openai.com/api-keys
환경변수 설정하기
- API KEY와 같은 외부에 알려지면 안되는 정보는 환경변수로 관리해줘야한다.
- 또한 별도의 파일에 빼서 관리하는 것이기 때문에 재사용하기에도 좋다.
- OpenAI도 이를 권장하고 있다.
- OpenAI는 그중에서도 1번을 권장하고 있지만 나는 2번으로 해봤다.
- .env 파일을 생성해 API_KEY를 넣어줬다.
※ 깃허브에 레포지토리를 올릴 때 이 정보가 올라가면 안되므로 .gitignore 파일에 .env를 추가해줘야 한다.
from dotenv import load_dotenv
load_dotenv()
# client = OpenAI(
# api_key=os.environ.get("OPENAI_API_KEY"),
# )
client = OpenAI()
- 다음과 같이 불러올 수 있다.
💡 그러나 ChatGPT API는 key값의 변수명을 .env에 OPENAI_API_KEY로 지정시 생략이 가능하다.
API Request 하기
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
{"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
]
)
print(completion.choices[0].message.content)
In the realm of code, a concept profound,
Recursion dances, swirling around.
An elegant cycle, a mystical flow,
Unraveling layers, like the petals of a rose.
A function calling itself, again and again,
A loop of sorcery, a magical chain.
Reducing problems to smaller parts,
Like a dance of light in the dark.
Base case, the anchor in this recursive sea,
A moment of clarity, where the loop breaks free.
Each repetition a step towards the end,
A recursive journey, a path to transcend.
In programming's world, recursion's embrace,
A concept so wondrous, a puzzle we chase.
Traversing the depths of a problem's core,
Recursion whispers, "Just recurse more."
지금까지 ChatGPT API를 사용하는 기본적인 방법을 알아봤다.
참고:https://platform.openai.com/docs/quickstart?context=python
'생성형 AI' 카테고리의 다른 글
Gemini API, LLama API로 깃허브 리포지토리 요약하기 (0) | 2024.04.05 |
---|---|
Github Repository정보 ChatGpt API로 요약하기 (0) | 2024.04.04 |
Github API 사용하기 (0) | 2024.03.31 |