浏览器中js流式和非流式调用ollama模型api笔记
流式请求ollama后台大模型api,注意与openai的api请求类似,需要将stream设置为true才会流式输出。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" /> <script type="module"> // 准备要发送的数据 const data = { "stream":true, "model": "gemma:2b", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "你是谁?!" } ] }; // 使用fetch发送请求 const response = await fetch('http://localhost:11434/v1/chat/completions', { method: 'POST', // 请求方法 headers: { 'Content-Type': 'application/json' // 设置请求头 }, body: JSON.stringify(data) // 请求体 }); // 检查响应状态码 if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}${response.statusText}`); } // 将响应体设置为可读流,并逐步输出数据到可写流 const reader = response.body.getReader(); const decoder = new TextDecoder(); const textDecoder = new TextEncoder(); while (true) { cons...
点击查看剩余70%
网友评论