创建模型 (POST /api/create)

创建模型接口允许你基于现有模型创建自定义模型,可以修改系统提示、参数、模板等配置。

基本用法

curl http://localhost:11434/api/create -d '{
  "name": "my-model",
  "modelfile": "FROM llama3.2\nSYSTEM 你是一个友好的助手"
}'

响应(流式):

{"status":"reading model metadata"}
{"status":"creating model layer"}
{"status":"writing layer sha256:abc123..."}
{"status":"success"}

Modelfile 语法

Modelfile 是创建模型的配置文件,语法如下:

FROM 指令

指定基础模型:

FROM llama3.2

SYSTEM 指令

设置系统提示:

SYSTEM 你是一个专业的 Python 开发者,回答简洁准确。

PARAMETER 指令

设置模型参数:

PARAMETER temperature 0.7
PARAMETER num_ctx 4096
PARAMETER stop "###"
PARAMETER stop "User:"

常用参数:

参数说明
temperature随机性(0-2)
num_ctx上下文长度
num_predict最大生成 token
top_p核采样阈值
top_k候选词数量
stop停止词
repeat_penalty重复惩罚

TEMPLATE 指令

自定义提示模板:

TEMPLATE """{{ .System }}

User: {{ .Prompt }}
Assistant:"""

模板变量:

  • {{ .System }} - 系统提示
  • {{ .Prompt }} - 用户输入
  • {{ .Response }} - 模型响应(用于继续生成)

MESSAGE 指令

预设对话消息:

MESSAGE user 你好
MESSAGE assistant 你好!有什么可以帮你的吗?

完整示例

FROM llama3.2

SYSTEM 你是一个专业的技术文档撰写者,擅长写清晰、准确的技术文档。

PARAMETER temperature 0.3
PARAMETER num_ctx 4096
PARAMETER stop "---"
PARAMETER stop "###"

TEMPLATE """{{ .System }}

### 任务
{{ .Prompt }}

### 输出
"""

MESSAGE user 写一个 Python 函数
MESSAGE assistant 好的,我来写一个 Python 函数。

代码示例

Python

import requests

def create_model(name, modelfile):
    response = requests.post(
        "http://localhost:11434/api/create",
        json={
            "name": name,
            "modelfile": modelfile
        },
        stream=True
    )
    
    for line in response.iter_lines():
        if line:
            import json
            data = json.loads(line)
            print(data.get("status", ""))

modelfile = """
FROM llama3.2
SYSTEM 你是一个友好的助手
PARAMETER temperature 0.7
"""

create_model("my-assistant", modelfile)

创建专业模型

def create_coding_assistant():
    modelfile = """
FROM llama3.2
SYSTEM 你是一个专业的程序员,擅长多种编程语言。回答问题时:
1. 先分析问题
2. 给出解决方案
3. 提供代码示例
4. 解释关键点

PARAMETER temperature 0.3
PARAMETER num_ctx 8192
"""
    
    create_model("coding-assistant", modelfile)

create_coding_assistant()

创建翻译模型

def create_translator(target_lang="英文"):
    modelfile = f"""
FROM llama3.2
SYSTEM 你是一个专业的翻译助手。将用户输入的内容翻译成{target_lang}。
只输出翻译结果,不要添加任何解释或说明。

PARAMETER temperature 0.1
"""
    
    create_model(f"translator-{target_lang}", modelfile)

create_translator("英文")
create_translator("日文")

JavaScript

async function createModel(name, modelfile) {
    const response = await fetch('http://localhost:11434/api/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, modelfile })
    });
    
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const lines = decoder.decode(value).split('\n').filter(Boolean);
        for (const line of lines) {
            const data = JSON.parse(line);
            console.log(data.status);
        }
    }
}

const modelfile = `
FROM llama3.2
SYSTEM 你是一个友好的助手
`;

await createModel('my-assistant', modelfile);

Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

type CreateRequest struct {
    Name      string `json:"name"`
    Modelfile string `json:"modelfile"`
}

func createModel(name, modelfile string) error {
    req := CreateRequest{
        Name:      name,
        Modelfile: modelfile,
    }
    
    body, _ := json.Marshal(req)
    resp, err := http.Post(
        "http://localhost:11434/api/create",
        "application/json",
        bytes.NewReader(body),
    )
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    
    data, _ := io.ReadAll(resp.Body)
    fmt.Println(string(data))
    
    return nil
}

func main() {
    modelfile := `FROM llama3.2
SYSTEM 你是一个友好的助手
PARAMETER temperature 0.7`
    
    createModel("my-assistant", modelfile)
}

从文件创建

def create_from_file(name, modelfile_path):
    with open(modelfile_path, "r") as f:
        modelfile = f.read()
    
    create_model(name, modelfile)

create_from_file("custom-model", "my-model.Modelfile")

修改现有模型

def modify_model(source, new_name, modifications):
    response = requests.post(
        "http://localhost:11434/api/show",
        json={"name": source}
    )
    
    original = response.json().get("modelfile", "")
    
    new_modelfile = original
    for key, value in modifications.items():
        if key == "system":
            lines = new_modelfile.split("\n")
            lines = [l for l in lines if not l.startswith("SYSTEM ")]
            lines.append(f'SYSTEM {value}')
            new_modelfile = "\n".join(lines)
        elif key == "temperature":
            lines = new_modelfile.split("\n")
            lines = [l for l in lines if "PARAMETER temperature" not in l]
            lines.append(f'PARAMETER temperature {value}')
            new_modelfile = "\n".join(lines)
    
    create_model(new_name, new_modelfile)

modify_model("llama3.2", "friendly-llama", {
    "system": "你是一个非常友好的助手",
    "temperature": 0.8
})

注意事项

  1. 模型名称规范:只能包含小写字母、数字和 .-_
  2. 基础模型必须存在:FROM 指定的模型需要先下载
  3. 创建过程是异步的:大模型可能需要较长时间
  4. 会覆盖同名模型:如果模型已存在会被覆盖