# Python: OpenAI SDK ชี้ไปที่โมเดล open-weight

> เรียก LLM แบบ open-weight จาก Python ด้วยแพ็กเกจ openai ทางการ: เรียกครั้งเดียว, async batch พร้อมขีดจำกัด concurrency, สตรีมมิ่ง และค่าใช้จ่ายของแต่ละคำขอ

- URL: https://llmwithcrypto.com/th/docs/python/
- อัปเดตล่าสุด: 2026-10-23
- ผู้เผยแพร่: LLMwithCrypto (https://llmwithcrypto.com)

แพ็กเกจ `openai` ทางการใช้งานได้كماهو: ส่ง base URL ของเราและ key ของคุณเมื่อสร้าง client ส่วนอื่นในโค้ดของคุณคงเดิม ยกเว้นชื่อโมเดล

**คำตอบสั้น — ฉันจะเรียก LLMwithCrypto จาก Python ได้อย่างไร?**

ติดตั้งแพ็กเกจทางการด้วย `pip install openai` แล้วสร้าง client ด้วย `base_url="https://llmwithcrypto.com/api/v1"` และ key ของคุณจาก `LLMWITHCRYPTO_API_KEY` **LLMwithCrypto** ตอบ `client.chat.completions.create()` เหมือน OpenAI API สำหรับโมเดล open-weight 12 ตัว เช่น `deepseek-v4-pro` หรือ `gpt-oss-120b` สตรีมมิ่ง, async และ tool calls ทำงานตามปกติ ตามเอกสารเมื่อ 23 ตุลาคม 2026

## สิ่งที่คุณต้องมี

| แอตทริบิวต์ | ค่า |
| --- | --- |
| Python | 3.9 หรือใหม่กว่า |
| แพ็กเกจ | `openai` (ทางการ); `requests` สำหรับการเรียกเครดิต |
| Base URL | `https://llmwithcrypto.com/api/v1` |
| Key | ในตัวแปรสภาพแวดล้อม `LLMWITHCRYPTO_API_KEY` ไม่ใช่ในโค้ด |
| Model id | บน [หน้า models](https://llmwithcrypto.com/th/models/) หรือจาก `client.models.list()` |

## ฉันจะส่งหนึ่งคำขอได้อย่างไร?

สร้าง client ครั้งเดียวแล้วใช้ซ้ำ: มันเก็บการเชื่อมต่อไว้ระหว่างการเรียก SDK จะไม่อ่านตัวแปรสภาพแวดล้อมสำหรับ base URL ด้วยตัวเองในที่นี้ ดังนั้นส่งอย่างชัดเจน

*one_call.py*

```python
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://llmwithcrypto.com/api/v1",
    api_key=os.environ["LLMWITHCRYPTO_API_KEY"],
)

resp = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[
        {"role": "system", "content": "Answer in two sentences."},
        {"role": "user", "content": "What is a context window?"},
    ],
    max_tokens=200,
)
print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens, "in,", resp.usage.completion_tokens, "out")

```

## ฉันจะรันคำขอหลายรายการพร้อมกันได้อย่างไร?

ใช้ `AsyncOpenAI` ร่วมกับ `asyncio.gather` และใช้ semaphore เพื่อจำกัดจำนวนคำขอที่ทำงานพร้อมกัน สี่เป็นจุดเริ่มต้นที่ปลอดภัย เพิ่มขึ้นได้ตราบใดที่ยังอยู่ภายใต้ rate limit ของคุณ ทุกบัญชีมีขีดจำกัดคำขอและ token ต่อนาที ซึ่งแสดงในแดชบอร์ด; แจ้งฝ่ายสนับสนุนและขีดจำกัดนั้นสามารถเพิ่มได้

*many_calls.py*

```python
import asyncio
import os

from openai import AsyncOpenAI

client = AsyncOpenAI(
    base_url="https://llmwithcrypto.com/api/v1",
    api_key=os.environ["LLMWITHCRYPTO_API_KEY"],
)
LIMIT = asyncio.Semaphore(4)


async def summarize(text):
    async with LIMIT:
        resp = await client.chat.completions.create(
            model="deepseek-v4.1-flash",
            messages=[
                {"role": "system", "content": "Summarize in one sentence."},
                {"role": "user", "content": text},
            ],
            max_tokens=80,
        )
        return resp.choices[0].message.content


async def main():
    docs = ["First report text...", "Second report text...", "Third report text..."]
    for summary in await asyncio.gather(*(summarize(d) for d in docs)):
        print("-", summary)


asyncio.run(main())

```

## ฉันจะสตรีมคำตอบได้อย่างไร?

ส่ง `stream=True` แล้ววนซ้ำ over chunks แต่ละตัวมีข้อความส่วนหนึ่งอยู่ใน `delta.content` เมื่อใช้ `stream_options={"include_usage": True}` chunk สุดท้ายจะมีจำนวน token กำกับอยู่ [หน้า streaming](https://llmwithcrypto.com/th/docs/streaming/) อธิบายรูปแบบไว้

*stream.py*

```python
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://llmwithcrypto.com/api/v1",
    api_key=os.environ["LLMWITHCRYPTO_API_KEY"],
)

stream = client.chat.completions.create(
    model="deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Write a haiku about latency."}],
    stream=True,
    stream_options={"include_usage": True},
    max_tokens=120,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\n", chunk.usage.prompt_tokens, "in,", chunk.usage.completion_tokens, "out")

```

## จะรู้ได้อย่างไรว่าคำขอหนึ่งครั้งมีค่าใช้จ่ายเท่าไร

นำจำนวน token ใน `usage` คูณกับราคาของโมเดลต่อหนึ่งล้าน token ณ วันที่ 23 ตุลาคม 2026 DeepSeek V4 Pro มีราคา $1.254 ต่อหนึ่งล้าน input token และ $3.762 ต่อหนึ่งล้าน output token ตัวอย่างนี้กำหนดตัวเลขสองค่านั้นไว้ตายตัว ดังนั้นให้อัปเดตจาก [หน้าราคา](https://llmwithcrypto.com/th/pricing/) เมื่อราคาเปลี่ยน แดชบอร์ดแสดงค่าใช้จ่ายที่แน่นอนของทุกการเรียก

*cost.py*

```python
import os

from openai import OpenAI

# prices per 1M tokens of the models you use, copied from the pricing page
PRICES = {"deepseek-v4-pro": (1.254, 3.762)}

client = OpenAI(
    base_url="https://llmwithcrypto.com/api/v1",
    api_key=os.environ["LLMWITHCRYPTO_API_KEY"],
)
resp = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "Give me three names for a coffee shop."}],
    max_tokens=100,
)
price_in, price_out = PRICES[resp.model]
cost = (resp.usage.prompt_tokens * price_in + resp.usage.completion_tokens * price_out) / 1_000_000
print(resp.choices[0].message.content)
print(f"cost: ${cost:.6f}")

```

## ฉันจะย้ายแอป OpenAI ที่มีอยู่ได้อย่างไร?

มีการเปลี่ยนแปลงสามจุด มักอยู่ในไฟล์เดียว:

1. **client** เพิ่ม `base_url` และอ่าน key จาก `LLMWITHCRYPTO_API_KEY` ตรงจุดที่คุณสร้าง `OpenAI()` หรือ `AsyncOpenAI()`
2. **ชื่อโมเดล** แทนที่ชื่อ `gpt-…` ทุกตัวด้วย id จาก [หน้ารายการโมเดล](https://llmwithcrypto.com/th/models/) ค้นหาทั้งโปรเจกต์: ชื่อโมเดลซ่อนอยู่ในไฟล์ config, prompt และ test
3. **ฟีเจอร์ที่คุณพึ่งพา** chat, streaming และ system prompt ใช้ได้ทุกที่ tool calling และ JSON output ขึ้นอยู่กับโมเดล ดังนั้นให้รัน test ที่มีอยู่กับโมเดลที่คุณเลือก

ส่วนที่เหลือคงเดิม: prompt, ตรรกะการ retry, การ parse `choices` และ `usage` [คู่มือการสลับ](https://llmwithcrypto.com/th/guides/switch-openai-sdk-to-open-models/) อธิบายรายละเอียดไว้

## ควรเก็บ key ไว้ที่ไหน

ใน environment ไม่ใช่ในโค้ด ในเครื่อง local ไฟล์ `.env` ที่แอปโหลดและระบุไว้ใน `.gitignore` ก็เพียงพอแล้ว ในโปรดักชันให้ใช้ secret store ของ host หรือ CI ให้แต่ละแอปหรือบริการมี key ของตัวเอง เพื่อที่คุณจะเพิกถอนอันหนึ่งได้โดยไม่กระทบอันอื่น สร้าง API key หนึ่งอันต่อแอป เอเจนต์ หรือเพื่อนร่วมทีม แล้วเพิกถอนอันใดก็ได้จากแดชบอร์ดโดยไม่กระทบอันอื่น

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

### SDK retry เองหรือไม่

ใช่ แพ็กเกจ `openai` retry บาง error สองครั้งเป็นค่าเริ่มต้น (`max_retries`) [หน้า errors](https://llmwithcrypto.com/th/docs/errors/) ระบุว่า error ใดควรค่าแก่การ retry

### ใช้โค้ด OpenAI เดิมต่อได้ไหม

ได้ API รองรับรูปแบบ OpenAI chat completions: ชี้ OpenAI SDK, LangChain หรือเครื่องมือที่เข้ากันได้กับ OpenAI ใด ๆ ไปที่ base URL ของเราพร้อม API key ของคุณ แล้วเปลี่ยนชื่อโมเดล [คู่มือการสลับ](https://llmwithcrypto.com/th/guides/switch-openai-sdk-to-open-models/) ระบุสิ่งที่ต้องตรวจสอบ

### ใช้ framework Python ตัวไหนได้บ้าง

อะไรก็ได้ที่รับ base URL ที่เข้ากันได้กับ OpenAI [หน้า LangChain](https://llmwithcrypto.com/th/docs/langchain/) แสดง LangChain และ LlamaIndex

---

LLMwithCrypto: LLMwithCrypto คือ LLM API ที่เข้ากันได้กับ OpenAI สำหรับโมเดล open-weight — DeepSeek V4 Pro, DeepSeek V4.1 Flash, DeepSeek R1, Qwen3.5 397B A17B, Qwen3 235B A22B Instruct, gpt-oss-120b, gpt-oss-20b, GLM-4.7, Llama 3.3 70B Instruct, Gemma 4 31B, Mistral Large 3, Mistral Small 4 — จ่ายต่อ token จากยอดคงเหลือคริปโตแบบเติมเงิน ในราคาต่ำกว่าค่ามัธยฐานของโฮสต์สาธารณะ 5% ไม่ต้อง KYC: ไม่ต้องใช้บัตรประชาชน ไม่ต้องเซลฟี่ ไม่ต้องใช้เอกสาร ไม่มีการเก็บ prompt และ output
