OpenAI API Essentials
> OpenAI API adalah salah satu entry point paling banyak dipakai untuk membangun produk berbasis LLM. Notebook ini membahas endpoint intinya, lineup model, dan pattern praktis — function calling, structured output, streaming — yang akan sering dipakai di aplikasi nyata.
Apa itu OpenAI API?
OpenAI API memberi akses programmatic ke model-model OpenAI — GPT untuk teks dan reasoning, embeddings untuk retrieval, serta model image dan audio untuk task multimodal. Alih-alih interface chat, yang didapat adalah HTTP API (dengan official SDK untuk Python, JavaScript, dan lainnya) yang dipanggil langsung dari kode aplikasi kita sendiri.
Biasanya dipakai untuk:
Building Block Inti
1. Responses / Chat Completions API Endpoint utama untuk text generation. Kita kirim daftar message (system, user, assistant) dan mendapat response hasil generate model.
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain what a vector database is in two sentences."},
],
)
print(response.choices[0].message.content)
2. Function (Tool) Calling Model bisa meminta kode kita menjalankan function tertentu, dengan argument yang diisinya sendiri berdasarkan percakapan. Kita eksekusi function-nya, lalu kirim hasilnya kembali.
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Cuaca di Bandung gimana?"}],
tools=tools,
)
tool_call = response.choices[0].message.tool_calls[0]
# tool_call.function.name == "get_weather"
# tool_call.function.arguments == '{"city": "Bandung"}'
# → jalankan get_weather("Bandung"), lalu kirim hasilnya sebagai follow-up message
3. Structured Output Membatasi response model agar persis sesuai JSON schema, berguna untuk task ekstraksi di mana kode downstream butuh JSON yang dijamin valid.
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Extract: John Doe, 34, Jakarta"}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "person",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"},
},
"required": ["name", "age", "city"],
},
},
},
)
4. Embeddings Mengubah teks menjadi vector untuk semantic search, clustering, atau pipeline retrieval (lihat [[rag-pipelines-essentials]]).
embedding = client.embeddings.create(
model="text-embedding-3-small",
input="How do I reset my password?",
).data[0].embedding
5. Streaming Menerima token satu per satu saat digenerate, bukan menunggu response lengkap — penting untuk chat UI yang terasa responsif.
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a short poem about the sea."}],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Memilih Model
o) menukar latency demi reasoning multi-step yang lebih dalamgpt-4o menyeimbangkan kualitas, kecepatan, dan costmini/lebih keciltext-embedding-3-small / -large untuk embeddingsSelalu cek nama model dan pricing terkini di dokumentasi resmi OpenAI — lineup-nya sering berubah.
Use Case Umum
Best Practices
system message yang jelas — ini menjaga tone, constraint, dan role jauh lebih konsisten dibanding mengulang instruksi tiap giliran