<<<写在前面>>>

搜了一圈 github 没有发现基于 PHP 链接 ollama 的项目,大多用 webui (基于docker)或者浏览器插件搞定,于是任务抛给 deepseek,写了个基础页面出来。前面是安装教程后面是代码,我服务器是 php8.2 + brew httpd server。

安装 ollama

🔗ollama 下载

双击安装

下载模型

macos 下只需shell 输入

1
ollama run deepseek-r1:8b

就会自动下载模型,速度慢下来了可以用Ctrl+C中断然后重新 run 一次。

增加httpd timeout 时间

1
vim /usr/local/etc/httpd/extra/httpd-default.conf

找到超时设置Timeout 15,时长增加到600

PHP code

那么压力给到本地deepseek,输出代码经过修正如下:

PHP_code
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<?php
// 处理AI对话请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
header('Content-Type: application/json');

$userMessage = $_POST['message'];

// Ollama API配置
$ollamaUrl = 'http://localhost:11434/api/generate';
$requestData = [
'model' => 'deepseek-r1:1.5b',
// 'model' => 'deepseek-r1:8b',
'prompt' => $userMessage,
'stream' => false
];

// 发起API请求
$ch = curl_init($ollamaUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

// 设置连接超时时间为 10 分钟(600 秒)
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);
// 设置执行超时时间为 10 分钟(600 秒)
curl_setopt($ch, CURLOPT_TIMEOUT, 600);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
if ($httpCode !== 200) {
error_log("API请求失败: HTTP $httpCode, Curl错误信息: $curlError");
echo json_encode(['error' => "API请求失败: HTTP $httpCode, Curl错误信息: $curlError"]);
exit;
}

$responseData = json_decode($response, true);
$responseText = $responseData['response'] ?? '';
// 处理 <think></think> 部分,用折叠框包裹
$pattern = '/<think>(.*?)<\/think>/is';
$replacement = '<details><summary>思考过程</summary>$1</details>';
$responseText = preg_replace($pattern, $replacement, $responseText);
echo json_encode(['response' => $responseText]);
exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
<meta charset="UTF-8">
<title>Ollama聊天界面</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Roboto', Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #F9F9F9;
}

.chat-container {
background-color: white;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
padding: 20px;
}

.chat-history {
height: 400px;
overflow-y: auto;
border: 1px solid #E0E0E0;
border-radius: 4px;
padding: 10px;
margin-bottom: 20px;
}

.message {
display: flex;
align-items: flex-start;
margin-bottom: 15px;
}

.avatar {
width: 40px;
height: 40px;
border-radius: 50%;
background-size: cover;
margin-right: 10px;
}

.user-avatar {
background-image: url('user_avatar.png');
/* 替换为用户头像的实际路径 */
}

.ai-avatar {
background-image: url('ai_avatar.ico');
/* 替换为AI头像的实际路径 */
}

.message-content {
margin: inherit;
padding: 1px 30px;
border-radius: 18px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
max-width: 80%;
/* 把这个值调大以增加聊天框宽度 */
}



.user-message .message-content {
background-color: #E3F2FD;
color: #333;
}

.ai-message .message-content {
background-color: #F5F5F5;
color: #333;
}

.input-container {
display: flex;
gap: 10px;
}

input[type="text"] {
flex: 1;
padding: 10px;
border: 1px solid #E0E0E0;
border-radius: 4px;
font-size: 16px;
}

button {
padding: 10px 20px;
background-color: #4285F4;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}

button:hover {
background-color: #357AE8;
}

.think {
margin-top: 14px;
background: rgba(187, 85, 21, 0.2);
/* 使用 rgba 确保透明度可调整 */
border-radius: 8px;
/* 添加圆角 */
padding: 12px;
/* 添加内边距,让内容与边框有一定间隔 */
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
/* 添加轻微阴影 */
transition: all 0.3s cubic-bezier(.25,.8,.25,1);
/* 添加过渡效果,使交互更平滑 */
}

.think:hover {
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
/* 鼠标悬停时增加阴影深度 */
}
</style>
<!-- 引入 marked.js 库 -->
<script src="https://cdn.bootcss.com/marked/0.8.1/marked.min.js"></script>
</head>

<body>
<div class="chat-container">
<div class="chat-history" id="chatHistory">
<!-- 聊天记录将在这里显示 -->
</div>
<div class="input-container">
<input type="text" id="userInput" placeholder="输入你的消息...">
<button onclick="sendMessage()">发送</button>
</div>
</div>

<script>
// 添加消息到聊天历史
function addMessage(message, isUser) {
const chatHistory = document.getElementById('chatHistory');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${isUser ? 'user-message': 'ai-message'}`;

const avatarDiv = document.createElement('div');
avatarDiv.className = `avatar ${isUser ? 'user-avatar': 'ai-avatar'}`;
messageDiv.appendChild(avatarDiv);

const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
// 渲染 Markdown 文本
const renderedMessage = marked.parse(message);
contentDiv.innerHTML = renderedMessage;

// 为 details 元素添加 think 类
const detailsElements = contentDiv.querySelectorAll('details');
detailsElements.forEach((details) => {
details.classList.add('think');
});

messageDiv.appendChild(contentDiv);

chatHistory.appendChild(messageDiv);
chatHistory.scrollTop = chatHistory.scrollHeight;
}

// 处理发送消息
async function sendMessage() {
const userInput = document.getElementById('userInput');
const message = userInput.value.trim();

if (!message) return;

// 清空输入框
userInput.value = '';

// 显示用户消息
addMessage(message, true);

// 创建 AbortController 用于超时控制
const controller = new AbortController();
const signal = controller.signal;

// 设置 10 分钟(600000 毫秒)的超时时间
const timeoutId = setTimeout(() => {
controller.abort();
}, 600000);

try {
const response = await fetch('index.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `message=${encodeURIComponent(message)}`,
signal
});

// 清除超时定时器
clearTimeout(timeoutId);

if (!response.ok) {
throw new Error('请求失败');
}

const data = await response.json();

if (data.error) {
addMessage(`错误: ${data.error}`, false);
} else {
addMessage(data.response, false);
}
} catch (error) {
if (error.name === 'AbortError') {
addMessage('请求超时,请稍后重试', false);
} else {
addMessage(`请求失败: ${error.message}`, false);
}
}
}

// 允许通过回车键发送消息
document.getElementById('userInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>

</html>

效果

代码还有些问题,有较多地方有待优化。
如果网络不好断联了就会提示失败,本地运行问题不大。

PHP 页面效果(未优化)
PHP 页面效果(未优化)