Skip to content
鼓励作者:欢迎打赏犒劳

langchainjs

github:https://github.com/langchain-ai/langchainjs

js调用ollama

所需要的依赖

json
{
    "@langchain/community": "^0.3.31",
    "@langchain/core": "^0.3.40",
    "express": "^4.21.2",
    "axios": "^1.7.9"
}

测试代码 test.js

js
// ----------------------------
// 文件:app.js
// 运行:node app.js
// 访问:POST http://localhost:3000/ask 发送 JSON { "question": "你的问题" }
// ----------------------------
import express from 'express';

import { Ollama } from '@langchain/community/llms/ollama';

// 1. 初始化 Express 和模型
const app = express();
app.use(express.json()); // 允许解析 JSON 请求体

// 连接本地 Ollama 模型(确保服务已启动)
const localModel = new Ollama({
    baseUrl: 'http://127.0.0.1:11434', // Ollama 默认端口
    model: 'deepseek-r1:latest', // 替换为你的模型名称(如 'qwen:7b')
});

// 2. 创建问答接口
app.get('/ask', async (req, res) => {
    try {
        const { question } = req.query;
        // 直接调用模型生成答案
        const answer = await localModel.invoke(question);

        res.json({
            success: true,
            question,
            answer
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});
// app.post('/ask', async (req, res) => {
//     try {
//         const { question } = req.body;
//         // 直接调用模型生成答案
//         const answer = await localModel.invoke(question);
//
//         res.json({
//             success: true,
//             question,
//             answer
//         });
//     } catch (error) {
//         res.status(500).json({
//             success: false,
//             error: error.message
//         });
//     }
// });

// 3. 启动服务
app.listen(3000, () => {
    console.log('服务已启动:http://localhost:3000');
});

如有转载或 CV 的请标注本站原文地址