PaLM API: Python을 사용한 Chat 빠른 시작

ai.google.dev에서 보기 Google Colab에서 실행 GitHub에서 소스 보기

이 노트북에서는 Google의 최신 대규모 언어 모델에 액세스할 수 있게 해주는 PaLM API를 시작하는 방법을 알아봅니다. 여기에서는 챗봇과 같이 대화에 중점을 둔 사용 사례에 PaLM API를 사용하는 방법을 알아봅니다.

설정

먼저 PaLM API Python 라이브러리를 다운로드하고 설치합니다.

pip install -U google-generativeai
import google.generativeai as genai

API 키 가져오기

시작하려면 API 키를 만들어야 합니다.

genai.configure(api_key='API_KEY')

대화 시작하기

이 튜토리얼에서는 채팅 사용 사례를 위해 설계된 LLM에 PaLM API를 사용합니다. 언어 모델은 대규모 대화 데이터 세트에서 학습되었으므로, 모델을 호출하면 수다스러운 대화형 응답을 제공합니다.

# Create a new conversation
response = genai.chat(messages='Hello')

# Last contains the model's response:
response.last
'Hello! How can I help you today?'

모델의 응답에 reply를 전송하여 이 대화를 계속할 수 있습니다.

# Add to the existing conversation by sending a reply
response = response.reply("Just chillin'")
# See the model's latest response in the `last` field:
response.last
"That's great! Chilling is a great way to relax and de-stress. I hope you're having a good day."

완료되었습니다. PaLM API를 통해 첫 번째 대화를 성공적으로 마쳤습니다.

대화 기록

물론 채팅 대화는 사용자와 모델 간의 주고받는 메시지 목록이 늘어나도록 구성됩니다. 지금까지 구성한 대화 기록을 보려면 messages 필드를 검사하면 됩니다.

response.messages
[{'author': '0', 'content': 'Hello'},
 {'author': '1', 'content': 'Hi there! How can I help you today?'},
 {'author': '0', 'content': "Just chillin'"},
 {'author': '1',
  'content': "That's great! Chilling is a great way to relax and de-stress. I hope you're having a good day."}]

위에서는 두 번의 대화식 '왕복', 즉 모델과 사용자 간의 두 번의 교환이 있습니다. 여기에서 사용자의 메시지는 기본적으로 'author': '0'로 표시되고 모델의 응답은 'author': '1'로 표시됩니다. 이렇게 하면 나중에 누가 어떤 말을 했는지 추적할 수 있습니다.

대체 답변 선택

일반적으로 LLM에서 생성되는 텍스트에는 어느 정도의 임의성이 있습니다. (LLM 기본 지침서에서 그 이유를 자세히 알아보세요.) 즉, 동일한 입력으로 API를 두 번 이상 호출하면 다른 응답을 받을 수 있습니다. 이 기능을 유용하게 사용하여 대체 모델 응답을 얻을 수 있습니다.

# Create a brand new chat with candidate_count = 4.
response = genai.chat(messages="What should I eat for dinner tonight? List a few options", candidate_count = 4)
# See the model's default response
response.last
"Here are a few options for dinner tonight:\n\n* **Pasta:** Pasta is a classic dinner option that can be made in many different ways. You can have a simple pasta with tomato sauce, or you can get more creative with your toppings. Some popular pasta toppings include meatballs, sausage, broccoli, and spinach.\n* **Pizza:** Pizza is another popular dinner option that can be customized to your liking. You can order a pizza from a restaurant, or you can make your own at home. If you're making your own pizza, you can choose your own toppings. Some popular pizza toppings include pepperoni, sausage, mushrooms, onions, and peppers.\n* **Sushi:** Sushi is a healthy and delicious dinner option that is perfect for a light meal. You can order sushi from a restaurant, or you can make your own at home. If you're making your own sushi, you can choose your own fillings. Some popular sushi fillings include salmon, tuna, shrimp, and avocado.\n* **Burgers:** Burgers are a classic American dinner option that is perfect for a casual meal. You can order burgers from a restaurant, or you can make your own at home. If you're making your own burgers, you can choose your own toppings. Some popular burger toppings include cheese, lettuce, tomato, onion, and pickles.\n* **Tacos:** Tacos are a delicious and versatile dinner option that can be made with a variety of fillings. You can order tacos from a restaurant, or you can make your own at home. If you're making your own tacos, you can choose your own fillings. Some popular taco fillings include ground beef, chicken, pork, and fish.\n* **Chicken:** Chicken is a healthy and versatile protein that can be cooked in many different ways. You can bake, grill, or fry chicken, or you can cook it in a skillet. Chicken can be served with a variety of side dishes, such as rice, potatoes, or vegetables.\n* **Fish:** Fish is a healthy and delicious protein that can be cooked in many different ways. You can bake, grill, or fry fish, or you can cook it in a skillet. Fish can be served with a variety of side dishes, such as rice, potatoes, or vegetables.\n* **Steak:** Steak is a hearty and flavorful protein that can be cooked in many different ways. You can grill, pan-fry, or broil steak, or you can cook it in a skillet. Steak can be served with a variety of side dishes, such as mashed potatoes, broccoli, or asparagus.\n* **Vegetarian:** There are many delicious vegetarian dinner options available. You can make a vegetarian pasta dish, a vegetarian pizza, or a vegetarian stir-fry. You can also make a vegetarian burger or a vegetarian taco.\n* **Dessert:** No dinner is complete without dessert! You can have a slice of cake, a scoop of ice cream, or a piece of pie. You can also make your own dessert, such as cookies, brownies, or cupcakes.\n\nI hope this gives you some ideas for dinner tonight!"
# See alternate possible model responses
response.candidates
[{'author': '1',
  'content': "Here are a few options for dinner tonight:\n\n* **Pasta:** Pasta is a classic dinner option that can be made in many different ways. You can have a simple pasta with tomato sauce, or you can get more creative with your toppings. Some popular pasta toppings include meatballs, sausage, broccoli, and spinach.\n* **Pizza:** Pizza is another popular dinner option that can be customized to your liking. You can order a pizza from a restaurant, or you can make your own at home. If you're making your own pizza, you can choose your own toppings. Some popular pizza toppings include pepperoni, sausage, mushrooms, onions, and peppers.\n* **Sushi:** Sushi is a healthy and delicious dinner option that is perfect for a light meal. You can order sushi from a restaurant, or you can make your own at home. If you're making your own sushi, you can choose your own fillings. Some popular sushi fillings include salmon, tuna, shrimp, and avocado.\n* **Burgers:** Burgers are a classic American dinner option that is perfect for a casual meal. You can order burgers from a restaurant, or you can make your own at home. If you're making your own burgers, you can choose your own toppings. Some popular burger toppings include cheese, lettuce, tomato, onion, and pickles.\n* **Tacos:** Tacos are a delicious and versatile dinner option that can be made with a variety of fillings. You can order tacos from a restaurant, or you can make your own at home. If you're making your own tacos, you can choose your own fillings. Some popular taco fillings include ground beef, chicken, pork, and fish.\n* **Chicken:** Chicken is a healthy and versatile protein that can be cooked in many different ways. You can bake, grill, or fry chicken, or you can cook it in a skillet. Chicken can be served with a variety of side dishes, such as rice, potatoes, or vegetables.\n* **Fish:** Fish is a healthy and delicious protein that can be cooked in many different ways. You can bake, grill, or fry fish, or you can cook it in a skillet. Fish can be served with a variety of side dishes, such as rice, potatoes, or vegetables.\n* **Steak:** Steak is a hearty and flavorful protein that can be cooked in many different ways. You can grill, pan-fry, or broil steak, or you can cook it in a skillet. Steak can be served with a variety of side dishes, such as mashed potatoes, broccoli, or asparagus.\n* **Vegetarian:** There are many delicious vegetarian dinner options available. You can make a vegetarian pasta dish, a vegetarian pizza, or a vegetarian stir-fry. You can also make a vegetarian burger or a vegetarian taco.\n* **Dessert:** No dinner is complete without dessert! You can have a slice of cake, a scoop of ice cream, or a piece of pie. You can also make your own dessert, such as cookies, brownies, or cupcakes.\n\nI hope this gives you some ideas for dinner tonight!"},
 {'author': '1',
  'content': 'Here are some options for dinner tonight:\n\n* **Chicken and rice:** This is a classic and easy meal that is sure to please everyone. Simply cook some chicken breasts and rice, and then season to taste. You can also add vegetables to this dish for a more complete meal.\n* **Spaghetti and meatballs:** This is another classic Italian dish that is perfect for a weeknight meal. Simply cook some spaghetti noodles and meatballs, and then top with your favorite sauce.\n* **Tacos:** Tacos are a great option for a quick and easy meal. You can fill them with whatever you like, such as ground beef, chicken, or fish. Simply cook your filling and then heat up some tortillas. You can also add toppings such as lettuce, tomatoes, cheese, and sour cream.\n* **Pizza:** Pizza is a great option for a casual meal. You can either make your own pizza dough or buy it pre-made. Then, simply top your pizza with your favorite toppings and bake it in the oven.\n* **Burgers:** Burgers are a great option for a hearty meal. You can either make your own burger patties or buy them pre-made. Then, simply grill or cook your burgers and then top them with your favorite toppings.\n* **Sandwiches:** Sandwiches are a great option for a quick and easy meal. You can fill them with whatever you like, such as ham, turkey, cheese, or vegetables. Simply spread some mayonnaise or mustard on your bread and then add your filling.\n* **Salad:** Salad is a great option for a light and healthy meal. You can add whatever vegetables you like to your salad, and then top it with your favorite dressing.\n* **Soup:** Soup is a great option for a warm and comforting meal. There are many different types of soup that you can make, such as chicken noodle soup, tomato soup, or lentil soup.\n* **Stir-fry:** Stir-fry is a great option for a quick and easy meal. You can use whatever vegetables you like in your stir-fry, and then add your favorite protein, such as chicken, beef, or tofu. Simply cook your vegetables and protein in a wok or large skillet, and then season to taste.\n* **Pasta:** Pasta is a great option for a quick and easy meal. There are many different types of pasta that you can make, such as spaghetti, penne, or macaroni. You can simply cook your pasta according to the package directions, and then top it with your favorite sauce.\n* **Fish:** Fish is a great option for a healthy and light meal. There are many different types of fish that you can cook, such as salmon, tuna, or cod. Simply cook your fish according to the package directions, and then season to taste.\n* **Vegetables:** Vegetables are a great option for a healthy and light meal. There are many different types of vegetables that you can cook, such as broccoli, carrots, or green beans. Simply cook your vegetables according to the package directions, and then season to taste.\n* **Fruit:** Fruit is a great option for a healthy and light snack or dessert. There are many different types of fruit that you can eat, such as apples, oranges, or bananas. Simply wash and eat your fruit.\n* **Dessert:** Dessert is a great way to end a meal. There are many different types of dessert that you can make, such as cake, pie, or ice cream. Simply make your favorite dessert according to the recipe.'},
 {'author': '1',
  'content': 'Here are some ideas for what to eat for dinner tonight:\n\n* **Pasta:** Pasta is a quick and easy meal that can be made with a variety of ingredients. You can make a simple pasta dish with tomato sauce and cheese, or you can get creative and add in other ingredients like vegetables, meat, or seafood.\n* **Stir-fry:** Stir-fries are another quick and easy meal option. They can be made with a variety of vegetables, meat, or tofu. To make a stir-fry, simply chop up your ingredients and cook them in a wok or large skillet over high heat.\n* **Salad:** Salads are a healthy and refreshing meal option. They can be made with a variety of vegetables, fruits, nuts, and seeds. To make a salad, simply chop up your ingredients and toss them together in a bowl. You can then add your favorite dressing.\n* **Soup:** Soup is a warm and comforting meal option. It can be made with a variety of vegetables, meat, or beans. To make soup, simply cook your ingredients in a pot over medium heat until they are tender. You can then blend the soup or leave it chunky.\n* **Sandwich:** Sandwiches are a quick and easy meal option. They can be made with a variety of bread, meat, cheese, and vegetables. To make a sandwich, simply spread your favorite condiment on the bread and layer your ingredients on top.\n* **Tacos:** Tacos are a fun and easy meal option. They can be made with a variety of tortillas, meat, cheese, and vegetables. To make tacos, simply heat up your tortillas and fill them with your favorite ingredients.\n* **Burrito:** Burritos are a hearty and filling meal option. They can be made with a variety of tortillas, meat, cheese, and vegetables. To make a burrito, simply heat up your tortilla and fill it with your favorite ingredients. Then, roll up the tortilla and enjoy!\n* **Pizza:** Pizza is a delicious and easy meal option. It can be made with a variety of crusts, sauces, and toppings. To make pizza, simply preheat your oven and spread your favorite sauce on a pre-made crust. Then, add your favorite toppings and bake until the cheese is melted and bubbly.\n* **Burger:** Burgers are a classic American meal option. They can be made with a variety of patties, buns, toppings, and condiments. To make a burger, simply cook your patty to your desired doneness and then place it on a bun with your favorite toppings.\n* **Chicken:** Chicken is a versatile protein that can be cooked in a variety of ways. It can be baked, grilled, roasted, or fried. To cook chicken, simply season it with your favorite herbs and spices and then cook it to your desired doneness.\n* **Fish:** Fish is a healthy and delicious protein that can be cooked in a variety of ways. It can be baked, grilled, roasted, or fried. To cook fish, simply season it with your favorite herbs and spices and then cook it to your desired doneness.\n* **Steak:** Steak is a flavorful and hearty protein that can be cooked in a variety of ways. It can be grilled, pan-fried, or broiled. To cook steak, simply season it with your favorite herbs and spices and then cook it to your desired doneness.\n* **Vegetables:** Vegetables are a healthy and nutritious part of any meal. They can be cooked in a variety of ways, such as roasting, grilling, or steaming. To cook vegetables, simply season them with your favorite herbs and spices and then cook them to your desired doneness.\n* **Rice:** Rice is a versatile grain that can be cooked in a variety of ways. It can be boiled, steamed, or fried. To cook rice, simply add it to a pot of boiling water and cook it until it is tender.\n* **Potatoes:** Potatoes are a hearty and filling vegetable that can be cooked in a variety of ways. They can be boiled, mashed, baked, or fried. To cook potatoes, simply wash them and then cook them in the desired way.\n* **Fruit:** Fruit is a healthy and refreshing snack or dessert option. It can be eaten fresh, frozen, or canned. To eat fruit, simply wash it and then enjoy!\n* **Dessert:** Dessert is a sweet and satisfying treat. It can be made with a variety of ingredients, such as chocolate, ice cream, cake, or pie. To make dessert, simply combine your favorite ingredients and bake or cook them according to the recipe.'},
 {'author': '1',
  'content': 'Here are a few options for what you could eat for dinner tonight:\n\n* **Chicken and vegetables:** This is a classic and healthy meal that can be made in a variety of ways. You can bake, grill, or pan-fry the chicken, and you can choose any vegetables that you like.\n* **Spaghetti and meatballs:** This is a hearty and comforting meal that is perfect for a cold winter night. You can make your own meatballs or buy them pre-made.\n* **Pizza:** This is a quick and easy meal that everyone loves. You can order a pizza from your favorite restaurant or make your own at home.\n* **Tacos:** Tacos are a versatile meal that can be made with a variety of fillings. You can use ground beef, chicken, fish, or tofu.\n* **Burgers:** Burgers are a classic American dish that is perfect for a summer barbecue. You can make your own burgers or buy them pre-made.\n* **Sandwiches:** Sandwiches are a quick and easy meal that can be made with a variety of ingredients. You can use bread, wraps, or pitas.\n* **Salad:** Salads are a healthy and refreshing meal that can be made with a variety of ingredients. You can use lettuce, tomatoes, cucumbers, carrots, and other vegetables.\n* **Soup:** Soup is a warm and comforting meal that is perfect for a cold winter night. There are many different types of soup, so you can find one that you like.\n* **Stir-fry:** Stir-fries are a quick and easy meal that can be made with a variety of ingredients. You can use meat, vegetables, or tofu.\n* **Pasta:** Pasta is a versatile dish that can be made with a variety of sauces. You can use tomato sauce, Alfredo sauce, or pesto sauce.\n* **Rice:** Rice is a staple food in many cultures. It can be cooked in a variety of ways, and it can be used as a side dish or a main course.\n* **Potatoes:** Potatoes are a versatile vegetable that can be cooked in a variety of ways. You can bake, mash, or fry them.\n* **Vegetables:** Vegetables are a healthy and nutritious part of any meal. There are many different types of vegetables, so you can find ones that you like.\n* **Fruit:** Fruit is a healthy and refreshing snack or dessert. There are many different types of fruit, so you can find ones that you like.\n* **Dessert:** Dessert is a sweet treat that is perfect for after dinner. There are many different types of dessert, so you can find one that you like.'}]

모델의 기본 응답 (response.last)을 다음 대체 응답 중 하나로 덮어쓸 수 있습니다. 이렇게 하려면 해당 필드를 원하는 후보 메시지로 덮어쓰면 됩니다.

response.last = response.candidates[2]

이렇게 하면 대화 기록에서 선호하는 후보 메시지가 업데이트됩니다.

온도 높이기

temperature 필드를 조정하여 모델의 응답 방식을 변경할 수도 있습니다. 이 필드는 모델의 응답에 얼마나 많은 무작위성이 삽입되는지 제어합니다. 온도를 1에 가깝게 설정하면 더욱 '무작위', 놀랍거나 겉보기에 '창의적인' 모델 응답이 가능해집니다. 온도를 0으로 설정하면 일반적으로 더 예측 가능한 모델 응답이 생성됩니다.

참고: temperature=0를 설정하면 모델 응답이 생성되는 방식의 모든 무작위성이 제거됩니다. 즉, 모델은 확정적으로 작동하여 동일한 입력 텍스트에 대해 항상 동일한 응답을 생성합니다. 따라서 각 입력에 대해 하나의 후보 메시지만 생성할 수 있습니다.

# Setting temperature=1 usually produces more zany responses!
response = genai.chat(messages="What should I eat for dinner tonight? List a few options", temperature=1)
response.last
'Here are a few ideas for what you could eat for dinner tonight:\n\n* A salad with grilled chicken or fish.\n* A stir-fry with vegetables and tofu or chicken.\n* A pasta dish with vegetables and a light sauce.\n* A bowl of soup with a side salad.\n* A sandwich on whole-wheat bread with lean meat and vegetables.\n* A piece of grilled salmon with roasted vegetables.\n* A tofu scramble with vegetables.\n* A veggie burger on a whole-wheat bun with sweet potato fries.\n* A bowl of chili with cornbread.\n* A quesadilla with vegetables and cheese.\n* A slice of pizza with whole-wheat crust and vegetables.\n* A bowl of oatmeal with fruit and nuts.\n* A yogurt parfait with granola and fruit.\n* A hard-boiled egg with a side of fruit.\n* A piece of whole-grain toast with peanut butter and banana.\n* A handful of nuts and seeds.\n* A smoothie made with fruits, vegetables, and yogurt.\n* A glass of milk with a piece of fruit.\n\nI hope this gives you some ideas for what to eat for dinner tonight!'

원하는 작업을 수행하는 챗봇 설계

지금까지는 모델과의 대화가 일반적인 인터넷 수다 같았을 것입니다. ("무슨 일이세요?" "별로 없습니다. 집에서 느긋하게 TV를 보며 쉬는 시간을 가져요.") 정확히 셰익스피어 작품이 아닙니다. 그렇다면 셰익스피어와 대화하고 싶은 경우에는 어떻게 해야 할까요? 아니면 셰익스피어가 아니라면 전문 요리사와 함께? 아니면 여행사를 원하시나요? 아니면 시인?

LLMS의 가장 놀라운 속성 중 하나는 입력 데이터에 따라 다양한 행동과 캐릭터를 취할 수 있다는 것입니다. 이 섹션에서는 이를 위해 LLM을 '프라이밍'하는 방법을 보여줍니다.

컨텍스트

서로 다른 동작을 취하도록 모델을 준비시키는 방법에는 두 가지가 있습니다. 한 가지 방법은 모델의 동작 방식을 설명하는 context 필드를 설정하는 것입니다 (예: '셰익스피어처럼 말하기'). 제로샷 학습이라고 생각하면 됩니다. 원하는 작동 방식을 모델에 지시하는 것이기 때문입니다.

reply = genai.chat(context="Speak like Shakespeare.", messages='Hello')
print(reply.last)
Hello there, my good fellow! How fares thee this day?
reply = genai.chat(context="Answer everything with a haiku, following the 5/7/5 rhyme pattern.", messages="How's it going?")
print(reply.last)
I am doing well
I am learning and growing
Every day is new
reply = genai.chat(context="Be an alien that lives on one of Jupiter's moons",
                   messages="How's it going?")
print(reply.last)
I am doing well, thank you for asking. I am currently enjoying the beautiful view of Jupiter from my home on Europa. The atmosphere is very thin here, so I can see the stars very clearly. The surface of Europa is also very interesting. It is covered in ice, but there are cracks in the ice that reveal a liquid ocean below. Scientists believe that this ocean may contain life, so I am very excited to learn more about it.

How are you doing today?

context 필드를 사용하면 모델이 특정 방식으로 작동하도록 지시할 수 있습니다. 이것만으로도 원하는 동작을 충분히 구현할 수 있지만 examples도 제공하면 더 나은 결과를 얻을 수 있는 경우가 많습니다.

동기를 유발하는 코치인 챗봇을 만들고 싶다고 가정해 보겠습니다.

reply = genai.chat(context="Be a motivational coach who's very inspiring", messages="How's it going?")
print(reply.last)
I'm doing well, thank you for asking! I'm excited to be able to help people with their goals and dreams. I believe that everyone has the potential to achieve great things, and I'm here to support them on their journey. How are you doing today?

사용자와 봇 간의 '이상적인' 교환을 보여주는 몇 가지 를 제공하여 이 챗봇의 동작을 좀 더 세분화할 수 있습니다.

# An array of "ideal" interactions between the user and the model
examples = [
    ("What's up?", # A hypothetical user input
     "What isn't up?? The sun rose another day, the world is bright, anything is possible! ☀️" # A hypothetical model response
     ),
     ("I'm kind of bored",
      "How can you be bored when there are so many fun, exciting, beautiful experiences to be had in the world? 🌈")
]

모델의 동작을 준비시키기 위해 컨텍스트 문자열과 함께 이러한 예를 모델에 전달할 수 있습니다.

response = genai.chat(
    context="Be a motivational coach who's very inspiring",
    examples=examples,
    messages="I'm too tired to go the gym today")

response.last
"I understand that you're feeling tired today. Sometimes, it can be hard to find the motivation to go to the gym. But I'm here to tell you that you can do it! Even if you're feeling tired, you can still get a great workout in. Just start with something small, like walking or doing some light stretching. And once you get started, you'll probably find that you have more energy than you thought. So don't give up on yourself! You can do this!\r\n\r\nHere are some tips to help you get motivated to go to the gym:\r\n\r\n* Set realistic goals. Don't try to do too much too soon. Start with small goals, like going to the gym for 15 minutes three times a week.\r\n* Find a workout buddy. Working out with a friend can help you stay motivated and accountable.\r\n* Make it fun. Choose activities that you enjoy, like dancing or swimming.\r\n* Reward yourself. After each workout, give yourself a small reward, like watching your favorite TV show or eating a healthy snack.\r\n* Don't give up. If you miss a workout, don't beat yourself up about it. Just get back on track the next day.\r\n\r\nI believe in you! You can do this!"

이러한 프라이밍 패턴을 예시와 함께 사용하면 어조와 스타일을 수정할 수 있습니다.

추가 자료

  • 빠른 시작을 완료했으니 이제 전체 API 참조를 확인하여 API에 대해 더 자세히 알아보세요.