# Python: open-weight 모델로 연결한 OpenAI SDK

> 공식 openai 패키지로 Python에서 open-weight LLM을 호출하세요: 단일 호출, 동시성 제한이 있는 async 배치, 스트리밍, 그리고 요청별 비용까지.

- URL: https://llmwithcrypto.com/ko/docs/python/
- 마지막 업데이트: 2026-10-23
- 발행자: LLMwithCrypto (https://llmwithcrypto.com)

공식 `openai` 패키지는 그대로 동작합니다. 클라이언트를 만들 때 저희 base URL과 본인의 키를 전달하세요. 모델 이름을 제외하면 코드의 나머지는 모두 그대로입니다.

**빠른 답변 — Python에서 LLMwithCrypto은 어떻게 호출하나요?**

`pip install openai`로 공식 패키지를 설치한 다음, `base_url="https://llmwithcrypto.com/api/v1"`와 `LLMWITHCRYPTO_API_KEY`의 키로 클라이언트를 만드세요. **LLMwithCrypto**는 OpenAI API처럼 `client.chat.completions.create()`에 응답하며, `deepseek-v4-pro`이나 `gpt-oss-120b` 같은 12개의 open-weight 모델을 지원합니다. 스트리밍, async, tool call은 2026년 10월 23일 문서 기준으로 평소처럼 동작합니다.

## 필요한 것

| 속성 | 값 |
| --- | --- |
| Python | 3.9 이상 |
| 패키지 | `openai` (공식), 크레딧 호출에는 `requests` |
| Base URL | `https://llmwithcrypto.com/api/v1` |
| Key | 코드가 아니라 환경 변수 `LLMWITHCRYPTO_API_KEY`에 넣으세요 |
| 모델 id | [models 페이지](https://llmwithcrypto.com/ko/models/)에서 또는 `client.models.list()`에서 |

## 요청 하나는 어떻게 보내나요?

클라이언트는 한 번 만들어 재사용하세요. 호출 사이에 연결을 열어 둡니다. 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`와 함께 사용하고, 세마포어로 동시에 실행되는 요청 수를 제한하세요. 넷이 안전한 시작점이며, rate limit 아래에 머무는 선에서 늘리세요. 모든 계정에는 분당 요청 및 토큰 한도가 있으며 대시보드에 표시됩니다. 지원팀에 요청하면 한도를 올릴 수 있습니다.

*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`를 넘기고 chunk를 순회하세요. 각 chunk는 `delta.content`에 담긴 텍스트 조각을 운반합니다. `stream_options={"include_usage": True}`을 사용하면 마지막 chunk가 토큰 수를 담습니다. [streaming 페이지](https://llmwithcrypto.com/ko/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")

```

## 요청 하나에 비용이 얼마인지 어떻게 알 수 있나요?

`usage` 수에 모델의 백만 토큰당 가격을 곱하세요. 2026년 10월 23일 기준으로 DeepSeek V4 Pro는 입력 백만 토큰당 $1.254, 출력 백만 토큰당 $3.762입니다. 예제는 이 두 숫자를 하드코딩하므로, 가격이 바뀌면 [pricing 페이지](https://llmwithcrypto.com/ko/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. **클라이언트.** `base_url`을 추가하고, `OpenAI()` 또는 `AsyncOpenAI()`을 생성하는 곳에서 `LLMWITHCRYPTO_API_KEY`로부터 키를 읽으세요.
2. **모델 이름.** 모든 `gpt-…` 이름을 [models 페이지](https://llmwithcrypto.com/ko/models/)의 id로 바꾸세요. 프로젝트 전체를 검색하세요. 모델 이름은 config 파일, prompt, 테스트에 숨어 있습니다.
3. **의존하는 기능.** Chat, streaming, system prompt는 어디서나 동작합니다. Tool calling과 JSON 출력은 모델에 따라 다르므로, 선택한 모델에 대해 기존 테스트를 실행하세요.

나머지는 그대로 둡니다. prompt, 재시도 로직, `choices`과 `usage` 파싱입니다. [switching 가이드](https://llmwithcrypto.com/ko/guides/switch-openai-sdk-to-open-models/)에서 세부 사항을 안내합니다.

## 키는 어디에 두어야 하나요?

환경 변수에 두고, 절대 코드에 두지 마세요. 로컬에서는 앱이 불러오고 `.gitignore`에 나열된 `.env` 파일이면 충분하고, 프로덕션에서는 호스트나 CI의 secret store를 사용하세요. 앱이나 서비스마다 고유한 키를 부여해, 다른 것을 멈추지 않고 하나를 폐기할 수 있게 하세요. 앱, 에이전트, 팀원마다 API 키를 하나씩 만들고, 대시보드에서 다른 키는 건드리지 않고 원하는 키만 폐기할 수 있습니다.

## Python: 자주 묻는 질문

### SDK가 자체적으로 재시도하나요?

네, `openai` 패키지는 일부 오류를 기본적으로 두 번 재시도합니다(`max_retries`). [errors 페이지](https://llmwithcrypto.com/ko/docs/errors/)에 재시도할 가치가 있는 오류가 나열되어 있습니다.

### 기존 OpenAI 코드를 계속 써도 되나요?

네. API는 OpenAI chat completions 형식을 따릅니다. OpenAI SDK, LangChain 또는 OpenAI 호환 도구의 base URL을 우리 base URL로 지정하고 키를 넣은 뒤 모델 이름만 바꾸면 됩니다. [switching 가이드](https://llmwithcrypto.com/ko/guides/switch-openai-sdk-to-open-models/)에 확인할 항목이 나열되어 있습니다.

### 어떤 Python 프레임워크가 동작하나요?

OpenAI 호환 base URL을 받는 것이면 무엇이든 동작합니다. [LangChain 페이지](https://llmwithcrypto.com/ko/docs/langchain/)에서 LangChain과 LlamaIndex를 보여줍니다.

---

LLMwithCrypto: LLMwithCrypto는 오픈 웨이트 모델을 위한 OpenAI 호환 LLM API입니다 — 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 — 충전해 둔 암호화폐 잔액에서 토큰 단위로 결제하며, 공개 호스트 가격 중앙값보다 5% 저렴합니다. KYC 없이: 신분증도, 셀피도, 서류도 필요하지 않습니다. 프롬프트와 출력은 저장되지 않습니다.
