0Pricing
Prompt Engineering & LLM Optimization for Developers · บทเรียน

การโต้ตอบกับ API ของ LLM (OpenAI, Anthropic)

ทำความเข้าใจวิธีโต้ตอบกับผู้ให้บริการ LLM ชั้นนำอย่าง OpenAI และ Anthropic ผ่าน API อย่างเป็นทางการด้วยโปรแกรม

การโต้ตอบกับ API ของ LLM (OpenAI, Anthropic) เป็นบทเรียน Prompt Engineering & LLM Optimization for Developers ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Prompt Engineering & LLM Optimization for Developers และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Prompt Engineering & LLM Optimization for Developers มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Use LLM APIs?

Large Language Models (LLMs) like those from OpenAI and Anthropic are incredibly powerful. To use them in your own apps, you need to interact with their Application Programming Interfaces (APIs).

An API acts like a messenger, allowing your code to send requests to the LLM and receive its responses. This enables you to build dynamic, AI-powered features into your applications.

API Keys: Your Access Pass

To use an LLM API, you need an API key. Think of it as a password that authenticates your requests and links them to your account for billing.

  • Get your key: Sign up on OpenAI or Anthropic's platform and generate an API key.
  • Keep it secret: Never hardcode your API key directly in your code. Store it securely, ideally as an environment variable.
  • Environment variables: These are system-wide variables that your program can access without the key being visible in the code itself.

OpenAI API: Initial Setup

Let's start with OpenAI. First, you'll need to install their official Python client library. Then, set up your API key for authentication.

Run this in your terminal:

pip install openai

Then, in your Python script, you'll typically set the API key like this (before making calls):

import os
# It's best practice to load from an environment variable
# e.g., export OPENAI_API_KEY='sk-your-key-here'

# This line is usually enough if OPENAI_API_KEY is set
# The client automatically picks it up.
# If you need to set it manually in code (NOT recommended for production):
# from openai import OpenAI
# client = OpenAI(api_key="YOUR_ACTUAL_API_KEY")

print("OpenAI client library installed and ready!")
print("Ensure OPENAI_API_KEY is set as an environment variable.")

OpenAI API: First Chat Completion

The core of OpenAI's API for conversation is the Chat Completions endpoint. You send a list of 'messages' and the model responds with the next message in the conversation.

Try running this simple example:

from openai import OpenAI
import os

# Initialize the client. It will automatically pick up OPENAI_API_KEY
# from your environment variables if it's set.
client = OpenAI()

def get_completion(prompt_text):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": prompt_text}
        ],
        temperature=0.7,
        max_tokens=50
    )
    return response.choices[0].message.content

if __name__ == "__main__":
    # Make sure you have your OPENAI_API_KEY set as an environment variable
    # before running this code.
    if "OPENAI_API_KEY" not in os.environ:
        print("Error: OPENAI_API_KEY environment variable not set.")
        print("Please set it before running this script.")
    else:
        user_prompt = "What is the capital of France?"
        print(f"User: {user_prompt}")
        llm_response = get_completion(user_prompt)
        print(f"LLM: {llm_response}")

OpenAI: Key Parameters

When making an OpenAI API call, these parameters are crucial:

  • model: Specifies which LLM to use (e.g., "gpt-3.5-turbo", "gpt-4"). Different models have different capabilities and costs.
  • messages: A list of message objects defining the conversation history. Each object has a "role" and "content".
  • temperature: Controls the randomness of the output. Higher values (e.g., 0.8) make the output more creative; lower values (e.g., 0.2) make it more focused and deterministic.
  • max_tokens: The maximum number of tokens (words/pieces of words) the model should generate in its response.

OpenAI: Understanding Message Roles

The messages parameter in OpenAI's API uses specific roles to guide the conversation flow:

  • system: Sets the overall behavior or persona of the assistant.
  • user: Represents the user's input to the assistant.
  • assistant: Represents the assistant's previous responses.

Including past assistant messages helps the model maintain context.

from openai import OpenAI
import os

client = OpenAI()

def get_contextual_completion(messages_list):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=messages_list,
        temperature=0.7,
        max_tokens=70
    )
    return response.choices[0].message.content

if __name__ == "__main__":
    if "OPENAI_API_KEY" not in os.environ:
        print("Error: OPENAI_API_KEY environment variable not set.")
        print("Please set it before running this script.")
    else:
        conversation_history = [
            {"role": "system", "content": "You are a helpful assistant that provides short, factual answers."},
            {"role": "user", "content": "What is the capital of Japan?"},
            {"role": "assistant", "content": "The capital of Japan is Tokyo."},
            {"role": "user", "content": "And of Germany?"}
        ]
        print("Current conversation:")
        for msg in conversation_history:
            print(f"{msg['role'].capitalize()}: {msg['content']}")

        llm_response = get_contextual_completion(conversation_history)
        print(f"Assistant: {llm_response}")

Anthropic API: Initial Setup

Now let's look at Anthropic's Claude models. Similar to OpenAI, you'll install their client library and set your API key.

Run this in your terminal:

pip install anthropic

Then, prepare your Python script:

import os
# It's best practice to load from an environment variable
# e.g., export ANTHROPIC_API_KEY='sk-ant-your-key-here'

# The client automatically picks it up if ANTHROPIC_API_KEY is set.
# If you need to set it manually in code (NOT recommended for production):
# from anthropic import Anthropic
# client = Anthropic(api_key="YOUR_ACTUAL_ANTHROPIC_API_KEY")

print("Anthropic client library installed and ready!")
print("Ensure ANTHROPIC_API_KEY is set as an environment variable.")

Anthropic API: First Messages Call

Anthropic's main API for conversational models is called the Messages API. It also uses a list of messages, but with slightly different role names and structure compared to OpenAI.

Run this example to see it in action:

from anthropic import Anthropic
import os

# Initialize the client. It will automatically pick up ANTHROPIC_API_KEY
# from your environment variables if it's set.
client = Anthropic()

def get_claude_completion(prompt_text):
    response = client.messages.create(
        model="claude-3-haiku-20240307", # A fast, cheaper Claude model
        max_tokens=50,
        temperature=0.7,
        messages=[
            {"role": "user", "content": prompt_text}
        ]
    )
    return response.content[0].text

if __name__ == "__main__":
    # Make sure you have your ANTHROPIC_API_KEY set as an environment variable
    # before running this code.
    if "ANTHROPIC_API_KEY" not in os.environ:
        print("Error: ANTHROPIC_API_KEY environment variable not set.")
        print("Please set it before running this script.")
    else:
        user_prompt = "Tell me a very short fun fact about space."
        print(f"User: {user_prompt}")
        claude_response = get_claude_completion(user_prompt)
        print(f"Claude: {claude_response}")

Anthropic: Key Parameters & Roles

Anthropic's Messages API shares similarities with OpenAI but has some distinctions:

  • model: Specifies the Claude model (e.g., "claude-3-haiku-20240307", "claude-3-opus-20240229").
  • messages: A list of message objects. Each message must alternate between "user" and "assistant" roles. Unlike OpenAI, Anthropic does not have a distinct "system" role; system instructions are included in the first "user" message or a dedicated "system" parameter.
  • max_tokens: The maximum number of tokens Claude should generate.
  • temperature: Controls creativity, similar to OpenAI.

API Interaction Check

You've learned the basics of interacting with both OpenAI and Anthropic APIs. Let's test your understanding!

Recap: Connecting to LLMs

In this lesson, you've taken your first steps into programmatic interaction with LLMs!

  • We understood the importance of LLM APIs for building AI-powered applications.
  • You learned how to securely handle API keys using environment variables.
  • We explored setting up and making basic chat completion calls with both OpenAI's and Anthropic's Python client libraries.
  • You now understand key parameters like model, messages, temperature, and max_tokens for both platforms.

This knowledge is foundational for integrating powerful LLMs into your developer workflows!

คำถามที่พบบ่อย

บทเรียน “การโต้ตอบกับ API ของ LLM (OpenAI, Anthropic)” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การโต้ตอบกับ API ของ LLM (OpenAI, Anthropic)” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Prompt Engineering & LLM Optimization for Developers ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Prompt Engineering & LLM Optimization for Developers มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การโต้ตอบกับ API ของ LLM (OpenAI, Anthropic)”

ทำความเข้าใจวิธีโต้ตอบกับผู้ให้บริการ LLM ชั้นนำอย่าง OpenAI และ Anthropic ผ่าน API อย่างเป็นทางการด้วยโปรแกรม คุณปฏิบัติ Prompt Engineering & LLM Optimization for Developers ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Prompt Engineering & LLM Optimization for Developers หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Prompt Engineering & LLM Optimization for Developers บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การโต้ตอบกับ API ของ LLM (OpenAI, Anthropic)” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Prompt Engineering & LLM Optimization for Developers นี้ได้ไหม

ได้ บทเรียน Prompt Engineering & LLM Optimization for Developers ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การโต้ตอบกับ API ของ LLM (OpenAI, Anthropic)
  2. พื้นฐาน LangChain และ LlamaIndex
  3. การจัดการและการกำหนดเวอร์ชันพรอมต์
  4. พื้นฐานการสร้างแบบเสริมด้วยการค้นคืน (RAG)
← กลับไปที่ Prompt Engineering & LLM Optimization for Developers