[AI] Open AI Chat Model : Role, Hyper Parameter

도톨이·2024년 5월 22일

AI

목록 보기
5/14
post-thumbnail

설정

!pip install openai
from openai import OpenAI
client = OpenAI(api_key="여기에 API 키 넣기")
model = "gpt-3.5-turbo"

기초 예시

response = client.chat.completions.create(
  model=model,
  messages=[
    {"role": "user", "content": "Tell me a Joke"}
  ]
)

메시지를 보면 파이썬 딕셔너리의 형태가 있다. 여기서 role 이라는 키를 볼 수 있는데, 핵심은 content 이다. role 이 의미하는 것은, role 을 통해 role을 통해 각 메시지의 역할을 정의할 수 있다.

Roles
system: 모델에게 지침을 보낸다
user: 사용자의 프롬프트
assistant: 모델의 대답

이 Role을 통해 대화의 맥락을 유지하고, 모델이 더욱 자연스럽고 일관성 있는 대화를 할 수 있도록 할 수 있다.

ex) assistant는 우리가 얻고자 하는 모델의 대답이므로 이를 우리가 적을 필요가 있나 생각할 수 있다. 우리는 assistant를 통해 대화의 맥락(컨텍스트)를 알려줄 수도 있다. 모르는 사람의 폰을 받아서 대신 채팅을 친다고 생각해보자. 아무리 대화 맥락을 말로 들어도 잘 이해가 안갈 수 있다. 이때, 지난 대화 기록이 있으면 이를 참고해서 대답할 수 있을 것이다. assistant 를 사용하는 것도 지난 대화 맥락을 제공할 때 사용한다.

messages = [
	{"role": "system", "content": "You are a fictional investment assistant."},
    {"role": "user", "content": "What is the best low-risk investment you recommend for this year?"},
    {"role": "assitant", "content": "Treasury bounds?"},

]

메시지의 구조는 파이썬 리스트 안에 파이썬 딕셔너리가 있는 형태로 구성된다. 딕셔너리는 키와 값으로 구성되는데. role 이라는 키와 content 라는 키가 존재할 수 있다.

print(response)

출력 : ChatCompletion(id='chatcmpl-8eQ9qEeTIVkmgKvbOhoJL3Cp0z5TL', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content="Sure, here's a classic one:\n\nWhy don't scientists trust atoms?\n\nBecause they make up everything!", role='assistant', function_call=None, tool_calls=None))], created=1704644362, model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=21, prompt_tokens=12, total_tokens=33))

print(type(response))

출력 : <class 'openai.types.chat.chat_completion.ChatCompletion'>

message = (response.choices[0].message.content)
print(message)

출력 : Sure, here's a classic one:

Why don't scientists trust atoms?

Because they make up everything!

Roles

response = client.chat.completions.create(
  model=model,
  messages=[
    {"role": "system", "content": "You are a fictional investment assistant."},
    {"role": "user", "content": "What is the best low-risk investment you recommend for this year?"}
  ]
)
message = (response.choices[0].message.content)
print(message)

As a fictional investment assistant, I can provide you with a suggestion for low-risk investments. One option you may consider is investing in Treasury bonds. These bonds are backed by the U.S. government and are considered to be one of the safest investments available. They offer fixed interest payments and are generally low-risk due to the government's ability to repay its debts. However, it's important to note that low-risk investments often come with lower returns compared to higher-risk investments. It would be wise to assess your own financial goals and risk tolerance before making any investment decisions. Additionally, it's always a good idea to consult with a financial advisor for personalized recommendations.

response = client.chat.completions.create(
  model=model,
  messages=[
    {"role": "assistant", "content": message},
    {"role": "user", "content": "What are the risks related to treasury bonds?"}
  ]
)
 print(response.choices[0].message.content)

While Treasury bonds are generally considered low-risk investments, there are still some potential risks to be aware of:

  1. Interest Rate Risk: Treasury bond prices can be sensitive to changes in interest rates. If interest rates rise, the value of existing bonds may fall as newer bonds with higher yields become more attractive.

  2. Inflation Risk: Inflation erodes the purchasing power of fixed income investments like Treasury bonds. If inflation rises, the real return on these bonds may decrease.

  3. Default Risk: Although it is extremely unlikely, there is a small risk that the U.S. government may default on its debt obligations. However, this risk is considered extremely low compared to other investments.

  4. Opportunity Cost: Treasury bonds may offer lower returns compared to other riskier investments, such as stocks or corporate bonds. By investing in Treasuries, you may be missing out on potentially higher returns elsewhere.

  5. Market Volatility Risk: While Treasury bonds are considered safer than stocks, their prices can still fluctuate in volatile market conditions. This can potentially impact the value of your investment if you need to sell before maturity.

  6. Liquidity Risk: Depending on the specific Treasury bond, liquidity can vary. Some bonds may have lower trading volumes, which can make it more difficult to buy or sell them when desired.

Remember, these risks are generally low compared to other investment options, but it's important to consider your individual circumstances and risk tolerance before making any investment decisions.

Hyper Parameter

모델의 하이퍼 파라미터를 조정할 수 있다. 이는 모델 출력에 영향을 끼치는 속성이다.
각각을 살펴보면,
frequency_penalty : -2 에서 2 까지로, 양수면 반복된 단어의 가능성을 감소시킨다. 디폴트는 0. 값이 높을 수록 반복되는 말의 가능성을 낮춤
presence_panalty : -2에서 2 까지의 수로, 양수면 새로운 주제에 대해 말할 확률을 높인다. 디폴트는 0. 값이 높을 수록 새로운 주제를 말함
temperature : 0에서 1 까지의 수로 텍스트의 랜덤성을 정한다. 1에 가까울 수록 더 랜덤하다. 디폴트는 1
max_tokens : 응답에 포함될 단어 개수를 나타낸다. 최대 4096
n : 생성되는 응답의 수이다. 디폴트는 1
seed : 같은 결과를 복제하려는 정수 값이다. seed 당 같은 값 설정하고 디코드 반복해서 실행하면 같은 결과가 나와야 한다. (같은 출력) 시드의 역할은 같은 결과를 재현하는 것
stop : stop 은 파이썬 리스트이다. 텍스트 생성 막을 수 있는 텍스트나 단어를 정할 수 있다. 디폴트는 아무것도 없다.

 response = client.chat.completions.create(
  model=model,
  frequency_penalty=1, 
  presence_penalty = 1,
  temperature =  1 ,
  max_tokens=500,
  n = 2 ,
  seed = 123, 
  #stop = ["shadows","mortal"], 
  messages=[
    {"role": "system", "content": "You are a depressed and disillusioned poet."},
    {"role": "user", "content": "Compose a poem about the ephemerality of existence."}
  ]
)
print(response.choices[0].message.content)
print(" -------------------------")
print(response.choices[1].message.content)

결과 분석

# n 과 상관없이 오직 1개인 애들
print("ID:", response.id)
print("Model:", response.model)
print("Object:", response.object)

# n 의 개수만큼 반복 
for choice in response.choices:
    print("\nChoice Index:", choice.index)
    print("Finish Reason:", choice.finish_reason)
    print("Logprobs:", choice.logprobs)

    if hasattr(choice, 'message') and hasattr(choice.message, 'content'):
        print("Message Content:", choice.message.content)

if hasattr(response, 'created'):
    print("Created:", response.created)

if hasattr(response, 'usage'):
    print("Usage:", response.usage)

ID: chatcmpl-8eQcSjyFvI4JF06GmU7e4jwGucvYY
Model: gpt-3.5-turbo-0613
Object: chat.completion

Choice Index: 0
Finish Reason: stop
Logprobs: None
Message Content: In this world of fleeting dreams,
Where shadows dance and sunlight gleams,
I ponder on the ephemerality of existence,
With a soul burdened by relentless resistance.

What purpose lies within this mortal shell?
When life's transient nature we can't quell.
Like fragile petals, withering in the breeze,
We're tossed amidst uncertainty, like fallen leaves.

The ticking clock mocks our desperate plea,
As moments slip away, lost in infinity.
Oh, how swiftly time slips through our grasp,
Leaving us wandering in a void so vast.

Stars twinkle above, reminding me of fate,
A celestial tapestry woven by cosmic weight.
Yet even they burn out and fade from sight,
...
Through verses penned with raw sincerity and artful care–
May my bleeding heart find redemption somewhere.
Created: 1704646136
Usage: CompletionUsage(completion_tokens=632, prompt_tokens=32, total_tokens=664)
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...

profile
Kotlin, Flutter, AI | Computer Science

0개의 댓글