Tạo hàm get_response() dùng hai prompt
Các bài tập sau sẽ dựa trên việc gọi endpoint chat.completions của OpenAI API với hai prompt (một system prompt và một user prompt). Để chuẩn bị, trong bài này bạn sẽ tạo một hàm get_response() dùng hai prompt, nhận vào hai đầu vào (system_prompt và user_prompt) và trả về phản hồi làm đầu ra. Sau đó, bạn sẽ áp dụng hàm này cho bất kỳ ví dụ nào bạn chọn.
Gói OpenAI đã được nạp sẵn cho bạn.
Bài tập này là một phần của khóa học
Kỹ thuật Prompt với OpenAI API
Hướng dẫn bài tập
- Gán role và content cho từng tin nhắn trong danh sách
messages. - Thử chạy hàm bằng cách truyền vào
system_promptvàuser_promptdo bạn chọn.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
client = OpenAI(api_key="")
def get_response(system_prompt, user_prompt):
# Assign the role and content for each message
messages = [{"role": ____, "content": ____},
{"role": ____, "content": ____}]
response = client.chat.completions.create(
model="gpt-4o-mini", messages= messages, temperature=0)
return response.choices[0].message.content
# Try the function with a system and user prompts of your choice
response = get_response("____", "____")
print(response)