본문 바로가기
C.W.K.
Stream
Lesson 03 of 05 · published

POST /api/generate — Raw completion

~16 min · api, completion, fim

Level 0Downloader
0 XP0/41 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

/api/generate 쓸 때

/api/generate는 messages array 대신 prompt 문자열 하나 받아. 이런 모양이 맞을 때:

  • Fill-in-the-middle (FIM) 코드 자동완성. suffix 필드에 cursor 뒤 코드 박으면 모델이 가운데 채워.
  • 대화 framing 없이 one-shot completion 원할 때.
  • Raw mode (raw: true) 보내서 모델 chat template 완전 우회 — 커스텀 prompt 형식 가진 fine-tuned 모델에 유용.

FIM이 킬러 use case

FIM은 endpoint의 성질이 아니라 모델 템플릿의 성질이야. suffix가 뭔가를 하는 건 그 모델의 Ollama 템플릿에 .Suffix 가지가 있을 때뿐이야. 그 가지가 prefix랑 suffix를 모델 고유의 fill-in-the-middle 토큰으로 감싸 주거든. 가지가 없으면 그냥 조용히 무시돼. 지금 그 가지를 갖고 있는 쪽은 qwen2.5-coder (base든 instruct든 전 태그), deepseek-coder-v2, starcoder2, 그리고 codellama:code 같은 Code Llama의 code 태그야. 믿기 전에 확인해. ollama show MODEL --template | grep -c Suffix, 아니면 그 모델 Capabilities 블록에 insert가 있는지 봐. 이런 모델에 prefix랑 suffix를 주면 함수 가운데를 채워 줘. Continue.dev의 local GitHub-Copilot 스타일 자동완성을 이게 굴려. Continue는 autocomplete 역할을 대놓고 FIM 기반이라고 적어 뒀고, provider로 Ollama를, 오픈 모델 추천으로 Qwen2.5-Coder 1.5B/7B를 걸어 뒀어. local 모델 쓰는 도구가 다 이 endpoint를 쓰는 건 아니야. Aider는 ollama_chat/으로 Ollama랑 얘기하고, Cursor의 Tab 모델은 자기네가 돌리는 서비스지 네 suffix 필드가 아니야.

다른 유용한 필드

  • images — base64 image string array (멀티모달 모델용).
  • options — /api/chat이랑 동일.
  • format — /api/chat이랑 동일.
  • raw — boolean이야. true면 prompt에 template을 안 씌워.

Code

Suffix 가지고 FIM completion·python
import httpx

# 가운데 비어있는 코드 — 모델이 채워
prefix = '''def parse_csv(path: str) -> list[dict]:
    """Parse a CSV file and return rows as dicts."""
    with open(path, encoding="utf-8") as f:
        reader = csv.DictReader(f)
'''
suffix = '''
        return rows
'''

resp = httpx.post(
    "http://localhost:11434/api/generate",
    json={
        "model": "qwen2.5-coder:7b",
        "prompt": prefix,
        "suffix": suffix,
        "stream": False,
        "options": {"temperature": 0.2, "num_predict": 200},
    },
    timeout=60.0,
)
print(resp.json()["response"])
# qwen2.5-coder:7b로 실측 (ollama 0.34.1): '        rows = list(reader)'
커스텀 template용 raw mode·python
# 자체 형식 가진 fine-tuned 모델에서 chat template 우회
custom_prompt = "<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n"

resp = httpx.post(
    "http://localhost:11434/api/generate",
    json={
        "model": "my-custom-model",
        "prompt": custom_prompt,
        "raw": True,           # Ollama template skip
        "stream": False,
    },
)
print(resp.json()["response"])

External links

Exercise

/api/generate의 suffix 필드 사용한 작은 complete(prefix, suffix, model) 함수 구현. 먼저 네 모델이 진짜 지원하는지부터 확인해 — ollama show MODEL --template | grep -c Suffix가 0이 아니라 1을 찍어야 해. 진짜 Python 코드 세 개 (list comprehension, try/except, 함수 본문) 가운데 채우는 데 써. Suffix가 도움 될 때랑 작은 모델 헷갈리게 할 때 메모.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인 — 댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.