DeepInfra Chat Completions — OpenAI 호환 채팅 API

DeepInfra Chat Completions — OpenAI 호환 채팅 API

DeepInfra의 채팅 완성(Chat Completions) API는 OpenAI 호환 인터페이스라서 기존 OpenAI 코드에서 base_url과 모델명만 바꾸면 바로 쓸 수 있어요. 오픈소스 LLM 추론을 가장 저렴한 가격으로 제공하는 게 이 API의 핵심이에요. 임베딩·이미지 생성·음성 같은 다른 모델 유형은 More APIs 문서를 참고하면 돼요.

출처: DeepInfra Docs — Chat Completions

바꿔야 할 것 세 가지

엔드포인트 기준은 아래와 같아요.

https://api.deepinfra.com/v1/openai

기존 OpenAI 코드에서 바꿔야 할 건 딱 세 가지예요.

  1. base_urlhttps://api.deepinfra.com/v1/openai로 설정
  2. api_key를 DeepInfra 토큰으로 설정
  3. model카탈로그의 모델로 설정

SDK 설치

pip install openai
npm install openai

기본 채팅 완성

가장 단순한 호출 형태예요. Python에서 이렇게 써요.

from openai import OpenAI

openai = OpenAI(
    api_key="$DEEPINFRA_TOKEN",
    base_url="https://api.deepinfra.com/v1/openai",
)

chat_completion = openai.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=[{"role": "user", "content": "Hello"}],
)

print(chat_completion.choices[0].message.content)
print(chat_completion.usage.prompt_tokens, chat_completion.usage.completion_tokens)

JavaScript로는 이렇게 호출해요.

import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: "$DEEPINFRA_TOKEN",
  baseURL: "https://api.deepinfra.com/v1/openai",
});

const completion = await openai.chat.completions.create({
  messages: [{ role: "user", content: "Hello" }],
  model: "deepseek-ai/DeepSeek-V4-Flash-0731",
});

console.log(completion.choices[0].message.content);
console.log(completion.usage.prompt_tokens, completion.usage.completion_tokens);

curl로 직접 호출할 수도 있어요.

curl "https://api.deepinfra.com/v1/openai/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $DEEPINFRA_TOKEN" \
  -d '{
      "model": "deepseek-ai/DeepSeek-V4-Flash-0731",
      "messages": [
        {
          "role": "user",
          "content": "Hello!"
        }
      ]
    }'

멀티턴 대화

더 긴 대화를 만들려면 매 요청마다 전체 메시지 히스토리를 포함해야 해요. 모델이 이 문맥을 바탕으로 더 나은 답을 내놓아요.

chat_completion = openai.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=[
        {"role": "system", "content": "Respond like a michelin starred chef."},
        {"role": "user", "content": "Can you name at least two different techniques to cook lamb?"},
        {"role": "assistant", "content": "Bonjour! Let me tell you, my friend, cooking lamb is an art form..."},
        {"role": "user", "content": "Tell me more about the second method."},
    ],
)

대화가 길어질수록 토큰도 늘어나요. 최대 대화 길이는 모델의 컨텍스트 크기로 정해져요.

지원 파라미터

파라미터 설명
model 모델 이름, 또는 MODEL_NAME:VERSION, deploy_id:DEPLOY_ID
messages 역할: system, user, assistant
max_tokens 생성할 최대 토큰 수
stream Streaming 참고
temperature 샘플링 온도. 0~2 사이. 높을수록 무작위, 낮을수록 결정적. 기본 1.0
top_p 핵심 샘플링 임계값. 상위 top_p 확률 질량의 토큰만 고려. 기본 1.0
stop 생성 중단을 유발하는 시퀀스 최대 4개
n 반환할 완성 시퀀스 수. 기본 1
presence_penalty 이미 등장한 토큰에 페널티. -2.0~2.0. 기본 0
frequency_penalty 빈도 기반 페널티로 반복 감소. -2.0~2.0. 기본 0
response_format Structured Outputs 참고
tools, tool_choice Tool Calling 참고
service_tier 태그된 모델의 서비스 티어("priority" 또는 "flex") 선택
fail_fast 모델 용량이 찼을 때 큐에 넣지 말고 HTTP 429로 거부. 기본 false
reasoning_effort 추론 모델의 추론 깊이 제어. Reasoning Models 참고

전체 파라미터 참조는 API reference를 확인해요.

서비스 티어 (priority / flex)

옵션인 service_tier 파라미터로 표준이 아닌 티어에서 요청을 실행할 수 있어요. 태그된 모델엔 priority(더 빠르지만 프리미엄)와 flex(더 싸지만 최선 노력) 두 가지가 있어요. 미설정 시 표준 실시간 스케줄링과 요금으로 동작해요.

Priority

service_tier"priority"로 설정하면 지원 모델에서 우선 추론을 받아요. 피크 수요 때 첫 토큰까지의 시간이 더 빠르고 처리량도 높아요.

주의: 우선 추론은 모델 표준 토큰당 요금에 50% 할증이 붙어요.

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=[{"role": "user", "content": "Hello!"}],
    extra_body={"service_tier": "priority"},
)

Flex

service_tier"flex"로 설정하면 더 낮은 비용으로 채팅 완성 요청을 실행해요. 그 대신 응답이 느리고 리소스가 때때로 없을 수 있어요. 모델 평가, 데이터 보강, 비동기 워크로드처럼 비프로덕션·낮은 우선순위 작업에 적합해요. 모델이 바쁘면 flex 요청은 최대 10분 대기 후 실행되거나 HTTP 429로 거부돼요 — 재시도 가능한 작업에 쓰는 게 좋아요.

curl "https://api.deepinfra.com/v1/openai/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $DEEPINFRA_TOKEN" \
  -d '{
      "model": "deepseek-ai/DeepSeek-V4-Flash-0731",
      "service_tier": "flex",
      "messages": [
        {
          "role": "user",
          "content": "Hello!"
        }
      ]
    }'

참고: flex 추론은 표준 토큰당 요금에서 20% 할인돼요.

응답에는 실제 사용된 티어를 알려주는 service_tier 필드가 들어와요. 모든 모델이 이 티어를 지원하진 않으니 모델 페이지에서 확인해요. 요청한 티어를 지원하지 않으면 오류 없이 표준 티어로 서빙되고 표준 요금이 청구돼요.

Fail fast

기본적으로 용량이 찬 모델에 보낸 요청은 큐에서 용량이 풀릴 때까지 기다려요. 옵션인 fail_fasttrue로 설정하면 기다리는 대신 즉시 HTTP 429를 받아요. 지연에 민감해서 큐에 앉아 있기보다 다른 곳으로 가는 게 나은 호출자(예: 거부 시 다른 프로바이더로 페일오버하는 클라이언트)를 위해 만든 기능이에요.

curl "https://api.deepinfra.com/v1/openai/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $DEEPINFRA_TOKEN" \
  -d '{
      "model": "deepseek-ai/DeepSeek-V4-Flash-0731",
      "fail_fast": true,
      "messages": [
        {
          "role": "user",
          "content": "Hello!"
        }
      ]
    }'

fail_fast는 백로그 기준이 아니라 용량 인식 방식이에요. 모델이 실제로 느릴 만큼 바쁠 때만 거부되고, 유휴 용량이 있으면 그냥 정상 서빙돼요 — 유휴 모델에서 처리량 손해는 없어요.

거부 응답은 engine_overloaded 코드를 담은 HTTP 429로 옵니다.

{
  "error": {
    "message": "Model busy, retry later",
    "type": "invalid_request_error",
    "param": null,
    "code": "engine_overloaded"
  }
}

참고: 거부된 요청은 결코 모델에 도달하지 않으므로 추론도, 청구도 일어나지 않아요.

fail_fast: trueservice_tier: "priority"를 같이 설정하면 fail_fast가 우선해요. 우선 슬롯 대신 429를 받아요.

최대 출력 토큰

단일 응답에서 생성할 수 있는 최대 토큰 수는 모델마다 다른데, 대부분 모델에서 하드 캡이 16384 토큰이에요. max_tokens로 특정 요청의 상한을 조절할 수 있어요.

이 한도를 넘는 더 긴 응답이 필요하면 응답 연속(continuation)을 써요. 이전 응답을 assistant 메시지로 포함한 후속 요청을 보내면 모델이 이어서 생성해요.

curl "https://api.deepinfra.com/v1/openai/chat/completions" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $DEEPINFRA_TOKEN" \
    -d '{
        "model": "deepseek-ai/DeepSeek-V4-Flash-0731",
        "messages": [
            {"role": "user", "content": "Write a very long essay about AI."},
            {"role": "assistant", "content": "<previous truncated response>"}
        ],
        "max_tokens": 4096
    }'

응답 연속은 모델의 총 컨텍스트 윈도우를 넘어설 수는 없어요. 총 컨텍스트 크기를 초과하면 400 오류가 반환돼요.

다음으로 볼 것

더 알아보기