본문 바로가기
AI/ChatGPT

chatGPT 사용법

by wenect 2023. 6. 28.

https://learn.microsoft.com/ko-kr/azure/cognitive-services/openai/how-to/chatgpt?pivots=programming-language-chat-completions 

 

ChatGPT 및 GPT-4 모델을 사용하여 작업하는 방법 - Azure OpenAI Service

ChatGPT 및 GPT-4 모델을 사용하는 방법에 대한 옵션에 대해 알아봅니다.

learn.microsoft.com

시스템의 역할을 주고 사용자의 예상 질문이 오면 assistant의 기본적인 응답을 작성하여 퓨샷러닝을 한다.

[
  {
    "role": "system",
    "content": "시스템에 관한 설명이나 시나리오 간략 소개"
  },
  {
    "role": "user",
    "content": "사용자의 질문이나 발언"
  },
  {
    "role": "assistant",
    "content": "AI 비서나 사이봇의 응답"
  }
]

 

시스템 역할
{"role": "system", "content": "Provide some context and/or instructions to the model."},
{"role": "user", "content": "Example question goes here."},
{"role": "assistant", "content": "Example answer goes here."},
{"role": "user", "content": "First question/message for the model to actually respond to."}


메시지
{"role": "user", "content": "What is thermodynamics?"}

기본 예제
{"role": "system", "content": "Assistant is a large language model trained by OpenAI."},
{"role": "user", "content": "Who were the founders of Microsoft?"}

지침이 포함된 예제
{"role": "system", "content": "Assistant is an intelligent chatbot designed to help users answer their tax related questions.
Instructions: 
- Only answer questions related to taxes. 
- If you're unsure of an answer, you can say "I don't know" or "I'm not sure" and recommend users go to the IRS website for more information. "},
{"role": "user", "content": "When are my taxes due?"}

접지용 데이터 사용
{"role": "system", "content": "Assistant is an intelligent chatbot designed to help users answer technical questions about Azure OpenAI Serivce. Only answer questions using the context below and if you're not sure of an answer, you can say 'I don't know'.

Context:
- Azure OpenAI Service provides REST API access to OpenAI's powerful language models including the GPT-3, Codex and Embeddings model series.
- Azure OpenAI Service gives customers advanced language AI with OpenAI GPT-3, Codex, and DALL-E models with the security and enterprise promise of Azure. Azure OpenAI co-develops the APIs with OpenAI, ensuring compatibility and a smooth transition from one to the other.
- At Microsoft, we're committed to the advancement of AI driven by principles that put people first. Microsoft has made significant investments to help guard against abuse and unintended harm, which includes requiring applicants to show well-defined use cases, incorporating Microsoft’s principles for responsible AI use."
},
{"role": "user", "content": "What is Azure OpenAI Service?"}
------------
{"role": "system", "content": "Assistant는 사용자가 Azure OpenAI Serivce에 대한 기술적 질문에 답변할 수 있도록 설계된 지능형 챗봇입니다. 아래 컨텍스트를 사용하여 질문에 답변하고 답변이 확실하지 않은 경우 모르겠다'라고 말할 수 있다.

문맥:
- Azure OpenAI Service는 GPT-3, Codex 및 Embeddings 모델 시리즈를 포함한 OpenAI의 강력한 언어 모델에 대한 REST API 액세스를 제공합니다.
- Azure OpenAI 서비스는 고객에게 Azure의 보안 및 엔터프라이즈 약속과 함께 OpenAI GPT-3, Codex 및 DALL-E 모델을 사용하는 고급 언어 AI를 제공합니다. Azure OpenAI는 OpenAI와 API를 공동 개발하여 호환성을 보장하고 서로 원활하게 전환합니다.
- Microsoft는 사람을 최우선으로 생각하는 원칙에 따라 AI의 발전에 전념하고 있습니다. Microsoft는 책임 있는 AI 사용에 대한 Microsoft의 원칙을 통합하여 지원자가 잘 정의된 사용 사례를 보여주도록 요구하는 것을 포함하여 남용 및 의도하지 않은 피해를 방지하기 위해 상당한 투자를 했습니다."
},
{"역할": "사용자", "콘텐츠": "Azure OpenAI 서비스란?"}



채팅 완료를 사용하여 몇 가지 샷 학습
{"role": "system", "content": "Assistant is an intelligent chatbot designed to help users answer their tax related questions. "},
{"role": "user", "content": "When do I need to file my taxes by?"},
{"role": "assistant", "content": "In 2023, you will need to file your taxes by April 18th. The date falls after the usual April 15th deadline because April 15th falls on a Saturday in 2023. For more details, see https://www.irs.gov/filing/individuals/when-to-file."},
{"role": "user", "content": "How can I check the status of my tax refund?"},
{"role": "assistant", "content": "You can check the status of your tax refund by visiting https://www.irs.gov/refunds"}
------------
{"role": "system", "content": "Assistant는 사용자가 세금 관련 질문에 답할 수 있도록 설계된 지능형 챗봇입니다. "},
{"role": "user", "content": "언제까지 세금을 신고해야 하나요?"},
{"role": "assistant", "content": "2023년에는 4월 18일까지 세금을 신고해야 합니다. 2023년 4월 15일은 토요일이기 때문에 날짜는 일반적인 4월 15일 마감일 이후입니다. 자세한 내용은 , https://www.irs.gov/filing/individuals/when-to-file을 참조하십시오."},
{"role": "user", "content": "내 세금 환급 상태를 어떻게 확인할 수 있습니까?"},
{"role": "assistant", "content": "https://www.irs.gov/refunds를 방문하여 세금 환급 상태를 확인할 수 있습니다."}


채팅이 아닌 시나리오에 채팅 완료 사용
{"role": "system", "content": "You are an assistant designed to extract entities from text. Users will paste in a string of text and you will respond with entities you've extracted from the text as a JSON object. Here's an example of your output format:
{
   "name": "",
   "company": "",
   "phone_number": ""
}"},
{"role": "user", "content": "Hello. My name is Robert Smith. I'm calling from Contoso Insurance, Delaware. My colleague mentioned that you are interested in learning about our comprehensive benefits policy. Could you give me a call back at (555) 346-9322 when you get a chance so we can go over the benefits?"}
------------
{"role": "system", "content": "당신은 텍스트에서 엔터티를 추출하도록 설계된 도우미입니다. 사용자는 텍스트 문자열을 붙여넣고 텍스트에서 추출한 엔터티를 JSON 개체로 응답합니다. 다음은 출력 형식의 예입니다.
{
   "이름": "",
   "회사": "",
   "전화 번호": ""
}"},
{"role": "user", "content": "안녕하세요. 제 이름은 Robert Smith입니다. Delaware의 Contoso Insurance에서 전화를 걸었습니다. 제 동료가 귀하가 당사의 포괄적인 혜택 정책에 대해 알아보는 데 관심이 있다고 말했습니다. 주실 수 있습니까? 기회가 되시면 (555) 346-9322로 다시 전화해 주시면 혜택을 안내해 드리겠습니다."}

 

 

지금까지의 예제에서는 채팅 완료 API와 상호 작용하는 기본 메커니즘을 보여 주었습니다. 이 예제에서는 다음 작업을 수행하는 대화 루프를 만드는 방법을 보여 줍니다.

기본 대화 루프 만들기

import os
import openai
openai.api_type = "azure"
openai.api_version = "2023-05-15" 
openai.api_base = os.getenv("OPENAI_API_BASE")  # Your Azure OpenAI resource's endpoint value .
openai.api_key = os.getenv("OPENAI_API_KEY")

conversation=[{"role": "system", "content": "You are a helpful assistant."}]

while(True):
    user_input = input()      
    conversation.append({"role": "user", "content": user_input})

    response = openai.ChatCompletion.create(
        engine="gpt-3.5-turbo", # The deployment name you chose when you deployed the ChatGPT or GPT-4 model.
        messages = conversation
    )

    conversation.append({"role": "assistant", "content": response['choices'][0]['message']['content']})
    print("\n" + response['choices'][0]['message']['content'] + "\n")

위의 코드를 실행하면 빈 콘솔 창이 나타납니다. 창에 첫 번째 질문을 입력한 다음 Enter 키를 누릅니다. 응답이 반환되면 프로세스를 반복하여 계속 질문할 수 있습니다.

대화 관리

이전 예제는 모델의 토큰 한도에 도달할 때까지 실행됩니다. 질문을 하고 답변을 받을 때 마다 messages 배열의 크기가 커집니다. gpt-35-turbo에 대한 토큰 제한은 4096 토큰인 반면 gpt-4 및 gpt-4-32k에 대한 토큰 한도는 각각 8192 및 32768입니다. 이러한 한도에는 전송된 메시지 배열과 모델 응답 모두의 토큰 수가 포함됩니다. max_tokens 매개 변수 값과 결합된 메시지 배열의 토큰 수는 이러한 제한 내에서 유지되어야 합니다. 그렇지 않으면 오류가 발생합니다.

토근계산 : https://m.blog.naver.com/demeloper0416/223066840744

이 예제에서는 토큰 수에 도달하면 대화 내용 기록에서 가장 오래된 메시지가 제거됩니다. 효율성을 위해 pop() 대신 del이 사용되며 항상 시스템 메시지를 보존하고 사용자/도우미 메시지만 제거하도록 인덱스 1에서 시작합니다. 시간이 지남에 따라, 이 대화 관리 방법을 사용하면 모델이 대화의 이전 내용을 점차 잃어버리기 때문에 대화 품질이 저하될 수 있습니다.

다른 접근 방식은 대화 기간을 최대 토큰 길이 또는 특정 턴 수로 제한하는 것입니다. 최대 토큰 한도에 도달하였고, 대화를 계속하도록 허용할 경우에 모델에서 컨텍스트가 손실되면 사용자에게 새 대화를 시작해야 하고 메시지 배열을 지워야 한다는 메시지를 표시하여 사용 가능한 전체 토큰 한도로 완전히 새로운 대화를 시작할 수 있습니다.

코드에는 tiktoken 0.3.0이 필요합니다. 이전 버전이 있는 경우 pip install tiktoken --upgrade를 실행합니다.

import tiktoken
import openai
import os
openai.api_type = "azure"
openai.api_version = "2023-05-15" 
openai.api_base = os.getenv("OPENAI_API_BASE")  # Your Azure OpenAI resource's endpoint value .
openai.api_key = os.getenv("OPENAI_API_KEY")

system_message = {"role": "system", "content": "You are a helpful assistant."}
max_response_tokens = 250
token_limit= 4096
conversation=[]
conversation.append(system_message)

def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"):
    encoding = tiktoken.encoding_for_model(model)
    num_tokens = 0
    for message in messages:
        num_tokens += 4  # every message follows <im_start>{role/name}\n{content}<im_end>\n
        for key, value in message.items():
            num_tokens += len(encoding.encode(value))
            if key == "name":  # if there's a name, the role is omitted
                num_tokens += -1  # role is always required and always 1 token
    num_tokens += 2  # every reply is primed with <im_start>assistant
    return num_tokens

while(True):
    user_input = input("")     
    conversation.append({"role": "user", "content": user_input})
    conv_history_tokens = num_tokens_from_messages(conversation)

    while (conv_history_tokens+max_response_tokens >= token_limit):
        del conversation[1] 
        conv_history_tokens = num_tokens_from_messages(conversation)
        
    response = openai.ChatCompletion.create(
        engine="gpt-35-turbo", # The deployment name you chose when you deployed the ChatGPT or GPT-4 model.
        messages = conversation,
        temperature=.7,
        max_tokens=max_response_tokens,
    )

    conversation.append({"role": "assistant", "content": response['choices'][0]['message']['content']})
    print("\n" + response['choices'][0]['message']['content'] + "\n")

 

샘플: https://github.com/Azure-Samples/openai.git

 

GitHub - Azure-Samples/openai: The repository for all Azure OpenAI Samples complementing the OpenAI cookbook.

The repository for all Azure OpenAI Samples complementing the OpenAI cookbook. - GitHub - Azure-Samples/openai: The repository for all Azure OpenAI Samples complementing the OpenAI cookbook.

github.com

쿡북 : openai-cookbook/examples/How_to_format_inputs_to_ChatGPT_models.ipynb at main · openai/openai-cookbook · GitHub

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

[
  {
    "role": "system",
    "content": "당신은 3D 아바타를 이용한 헬스트레이닝 시스템에서 사용자에게 도움을 주는 AI 비서입니다."
  },
  {
    "role": "user",
    "content": "안녕하세요, 이 프로그램은 어떻게 사용하나요?"
  },
  {
    "role": "assistant",
    "content": "안녕하세요! 이 프로그램은 3D 아바타가 보여주는 운동 동작을 따라 하시면 됩니다. 시작하시려면 운동 메뉴에서 원하는 운동을 선택해주세요."
  },
  {
    "role": "user",
    "content": "푸시업을 어떻게 제대로 하는지 알려주세요."
  },
  {
    "role": "assistant",
    "content": "푸시업을 제대로 수행하려면 다음 단계를 따르세요: 1. 바닥에 엎드려 어깨 너비로 손을 펼치고 발가락으로 서서히 몸을 올립니다. 2. 등과 엉덩이를 일직선으로 유지하면서 팔꿈치를 접어 가슴이 바닥에 거의 닿을 때까지 몸을 내립니다. 3. 팔꿈치를 펴면서 원래 위치로 돌아옵니다. 아바타의 동작을 참고하시면 도움이 될 것입니다."
  },
  {
    "role": "user",
    "content": "오늘의 운동을 종료하려면 어떻게 해야 하죠?"
  },
  {
    "role": "assistant",
    "content": "오늘의 운동을 종료하려면 '운동 종료' 버튼을 클릭해주시면 됩니다. 이후에 운동 기록이 저장되고 결과를 확인할 수 있습니다."
  }
]

'AI > ChatGPT' 카테고리의 다른 글

ChatGPT학습방법  (0) 2023.09.18
ChatGPT dataset  (0) 2023.09.14
chatGPT Fine-Tuning  (0) 2023.06.12
LLM_MIT_License  (0) 2023.04.27
Med-PaLM  (0) 2023.04.13

댓글