LLM聊天服务器

基于FastAPI的LLM聊天交互服务器,支持OpenAI等模型,提供API端点处理用户聊天请求和工具审批。

  • by VyacheslavVanin
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 VyacheslavVanin/mcp-http-host

使用说明

LLM聊天服务器

FastAPI服务器,用于与LLM(OpenAI)进行聊天交互。

配置

配置是通过环境变量和CLI参数进行管理的。

环境变量

变量 描述 默认值
LLM_API_KEY LLM提供程序的API密钥(替代--API-key-file) -
LLM_MODEL 要使用的型号名称 qwen2.5-coder:latest
PORT 运行服务器的端口 8000
LLM_PROVIDER LLM提供者(openai) openai
OPENAI_BASE_URL 与OpenAI兼容的API的基本URL https://openrouter.ai/api/v1

示例 .env 文件:

LLM_API_KEY=your-api-key
LLM_MODEL=qwen2.5-coder:latest
PORT=8000
LLM_PROVIDER=openai

CLI参数

参数 描述 示例
--model 要使用的LLM模型 --model qwen2.5-coder:latest
--port 运行服务器的端口 --port 8000
--provider LLM提供者(openai) --provider openai
--openai-base-url OpenAI API的基本URL --openai-base-url https://api.openai.com/v1
--api-key-file 包含API密钥的文件的路径 --api-key-file /path/to/api.key
--servers-config 服务器配置文件的路径 --servers-config config/servers.json
--current-directory 工作目录 --current-directory /projects
--context-window-size 上下文窗口大小 --context-window-size 2048
--temperature 温度参数 --temperature 0.7
--stream 启用流媒体模式 --stream
--retries-on-llm-error LLM错误的重试次数 --retries-on-llm-error 3
--debug-messages 启用调试消息日志记录 /tmp/llm-requester.messages.log --debug-messages

CLI使用示例:

# Using environment variable
export LLM_API_KEY=your-api-key
uv run main.py --model qwen2.5-coder:latest --port 8000

# Using API key file
uv run main.py --model qwen2.5-coder:latest --port 8000 --api-key-file /path/to/api.key

API终点

  • POST /user_request -处理用户聊天请求
  • POST /approve -处理工具批准/拒绝
  • GET /session_state -获取当前会话状态
  • POST /start_session -创建新会话

请求/响应格式

请求(POST/user_Request)

{
    "input": "user message"
}

响应

{
    "request_id": "uuid",
    "requires_approval": true,
    "tool": {
        "name": "tool-name",
        "arguments": {
            "arg1": "value1",
            "arg2": "value2"
        }
    },
    "message": "response content",
    "model": "model-name",
    "role": "assistant"
}

工具批准(POST/批准)

{
    "request_id": "uuid",
    "approve": true
}

示例用法

import requests

# Start session
response = requests.post("http://localhost:8000/start_session", json={
    "current_directory": "/projects",
    "model": "qwen2.5-coder:latest"
})

# Send message
response = requests.post("http://localhost:8000/user_request", json={
    "input": "Hello, how are you?"
})

# Approve tool call
response = requests.post("http://localhost:8000/approve", json={
    "request_id": "12345",
    "approve": true
})