File size: 3,477 Bytes
b350db1
 
 
 
 
 
 
 
 
 
 
97dbf57
b350db1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a79f08d
 
 
 
 
 
 
 
 
 
 
b350db1
a79f08d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b350db1
 
 
a79f08d
b350db1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
from flask import Flask, request, jsonify
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

app = Flask(__name__)

# モデルロード(起動時1回)
torch.random.manual_seed(0)

model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Phi-3-mini-4k-instruct",
    device_map="cpu",
    torch_dtype="auto",
    trust_remote_code=True
)

tokenizer = AutoTokenizer.from_pretrained(
    "microsoft/Phi-3-mini-4k-instruct"
)

pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer
)

generation_args = {
    "max_new_tokens": 500,
    "return_full_text": False,
    "temperature": 0.0,
    "do_sample": False,
}

# -----------------------
# ルートページ (HTML)
# -----------------------
@app.route("/")
def index():
    return """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Local LLM Chat</title>

<style>
body{
    font-family: Arial;
    background:#111;
    color:white;
    margin:0;
}

#chat{
    height:80vh;
    overflow-y:auto;
    padding:20px;
}

.message{
    margin-bottom:12px;
}

.user{
    color:#6cf;
}

.assistant{
    color:#9f9;
}

#inputArea{
    position:fixed;
    bottom:0;
    width:100%;
    background:#222;
    padding:10px;
}

#input{
    width:80%;
    padding:10px;
    font-size:16px;
}

button{
    padding:10px;
    font-size:16px;
}
</style>
</head>

<body>

<h2 style="padding:10px;">Local Phi-3 Chat</h2>

<div id="chat"></div>

<div id="inputArea">
<input id="input" placeholder="メッセージを入力..." />
<button onclick="send()">送信</button>
</div>

<script>

let messages = [
    {role:"system",content:"You are a helpful assistant."}
]

function add(role,text){

    const chat=document.getElementById("chat")

    const div=document.createElement("div")
    div.className="message "+role

    div.innerText=role+": "+text

    chat.appendChild(div)
    chat.scrollTop=chat.scrollHeight
}

async function send(){

    const input=document.getElementById("input")
    const text=input.value

    if(!text) return

    input.value=""

    add("user",text)

    messages.push({
        role:"user",
        content:text
    })

    const res=await fetch("/v1/chat/completions",{
        method:"POST",
        headers:{
            "Content-Type":"application/json"
        },
        body:JSON.stringify({
            messages:messages
        })
    })

    const data=await res.json()

    const reply=data.choices[0].message.content

    add("assistant",reply)

    messages.push({
        role:"assistant",
        content:reply
    })
}

document.getElementById("input").addEventListener("keypress",function(e){
    if(e.key==="Enter"){
        send()
    }
})

</script>

</body>
</html>
"""

# -----------------------
# OpenAI互換API
# -----------------------
@app.route("/v1/chat/completions", methods=["POST"])
def chat_completions():

    data = request.json
    messages = data.get("messages", [])

    result = pipe(messages, **generation_args)
    text = result[0]["generated_text"]

    response = {
        "id": "chatcmpl-local",
        "object": "chat.completion",
        "choices": [
            {
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": text
                },
                "finish_reason": "stop"
            }
        ]
    }

    return jsonify(response)


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)