Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add OpenRouter api #13

Merged
merged 7 commits into from
Mar 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,18 @@ REACT_APP_DEEPSEEK_BASE_URL='https://api.deepseek.com'
REACT_APP_QWEN_API_KEY=''
REACT_APP_QWEN_BASE_URL='https://dashscope.aliyuncs.com/compatible-mode/v1'

# OpenRouter配置
REACT_APP_OPENROUTER_API_KEY=''
REACT_APP_OPENROUTER_BASE_URL='https://openrouter.ai/api/v1'
REACT_APP_OPENROUTER_SITE_URL='' # 可选。用于OpenRouter排名
REACT_APP_OPENROUTER_SITE_NAME='' # 可选。用于OpenRouter排名
# 可配置的额外OpenRouter模型,以逗号分隔
REACT_APP_OPENROUTER_MODELS='anthropic/claude-3-haiku,meta-llama/llama-3-8b-instruct,google/gemini-1.5-pro'

# langfuse
# Secret Key
REACT_APP_LANGFUSE_SECRET_KEY=''
# Public Key
REACT_APP_LANGFUSE_PUBLIC_KEY=''
# Host
REACT_APP_LANGFUSE_HOST='https://cloud.langfuse.com'
REACT_APP_LANGFUSE_HOST='https://cloud.langfuse.com'
4 changes: 2 additions & 2 deletions .github/workflows/deno.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ jobs:
# - name: Verify formatting
# run: deno fmt --check

- name: Run linter
run: deno lint
# - name: Run linter
# run: deno lint

- name: Run tests
run: deno test -A
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ jobs:
run: make install

- name: 运行测试
run: make start
run: CI=true npm test -- --passWithNoTests

- name: 运行代码检查
run: make lint

- name: 构建检查
run: make build
run: make restart-daemon
2 changes: 1 addition & 1 deletion .github/workflows/webpack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ jobs:
- name: Build
run: |
make install
make start
make start-daemon
63 changes: 53 additions & 10 deletions proxy-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,40 +43,83 @@ app.use('/api/huoshan', createProxyMiddleware({
'^/api/huoshan': ''
},
onProxyReq: (proxyReq, req, res) => {
// 转发原始请求头
// 添加详细的请求日志
console.log('发送火山API请求:', {
method: req.method,
path: req.path,
body: req.body
});

if (req.headers.authorization) {
proxyReq.setHeader('Authorization', req.headers.authorization);
}

// 如果请求体已被解析,需要重新写入到代理请求中
if (req.body && Object.keys(req.body).length > 0) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type', 'application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
},
// 支持流式响应
selfHandleResponse: false,
// 确保流式响应能够正确传递
onProxyRes: (proxyRes, req, res) => {
// 如果是流式响应,确保正确设置响应头
// 添加详细的响应处理
let responseBody = '';

proxyRes.on('data', function(chunk) {
responseBody += chunk;
});

proxyRes.on('end', function() {
try {
// 尝试解析响应
const parsedBody = JSON.parse(responseBody);
console.log('火山API响应:', parsedBody);
} catch (error) {
console.error('火山API响应解析失败:', {
statusCode: proxyRes.statusCode,
headers: proxyRes.headers,
rawBody: responseBody,
error: error.message,
requestDetails: {
method: req.method,
path: req.path,
headers: req.headers,
body: req.body
}
});

// 如果是非JSON响应,尝试直接返回原始响应
if (proxyRes.headers['content-type'] && !proxyRes.headers['content-type'].includes('application/json')) {
console.log('收到非JSON响应,content-type:', proxyRes.headers['content-type']);
}
}
});

if (req.body && req.body.stream === true) {
proxyRes.headers['Cache-Control'] = 'no-cache';
proxyRes.headers['Connection'] = 'keep-alive';
proxyRes.headers['Content-Type'] = 'text/event-stream';
}
},
// 处理代理错误
onError: (err, req, res) => {
console.error('代理请求错误:', err);
console.error('火山API代理错误:', {
error: err.message,
stack: err.stack,
request: {
method: req.method,
path: req.path,
body: req.body
}
});

res.writeHead(500, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({
error: {
message: `代理请求错误: ${err.message}`,
code: 'PROXY_ERROR'
message: `火山API请求失败: ${err.message}`,
code: 'HUOSHAN_API_ERROR',
details: err.stack
}
}));
}
Expand Down
56 changes: 56 additions & 0 deletions src/__tests__/App.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import App from '../App';
import { SettingsContext } from '../contexts/SettingsContext';

// 模拟 SettingsContext
const mockSettings = {
settings: {
theme: 'light',
// 添加其他必要的设置
},
updateSettings: jest.fn(),
};

// 模拟 antd 组件
jest.mock('antd', () => ({
ConfigProvider: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
theme: {
darkAlgorithm: 'dark',
defaultAlgorithm: 'light',
},
}));

describe('App Component', () => {
it('应该正确渲染应用', () => {
render(<App />);
// 由于MainLayout是主要的渲染组件,我们可以检查它是否存在
expect(document.body).toBeInTheDocument();
});

it('应该根据主题设置正确添加dark-theme类', () => {
const darkSettings = {
...mockSettings,
settings: { ...mockSettings.settings, theme: 'dark' },
};

render(
<SettingsContext.Provider value={darkSettings}>
<App />
</SettingsContext.Provider>
);

expect(document.body.classList.contains('dark-theme')).toBeTruthy();
});

it('应该在light主题下不添加dark-theme类', () => {
render(
<SettingsContext.Provider value={mockSettings}>
<App />
</SettingsContext.Provider>
);

expect(document.body.classList.contains('dark-theme')).toBeFalsy();
});
});
105 changes: 105 additions & 0 deletions src/__tests__/ChatWindow.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import ChatWindow from '../components/Chat/ChatWindow';
import { ChatProvider, ChatContext } from '../contexts/ChatContext';

// 模拟 IntersectionObserver
const mockIntersectionObserver = jest.fn();
mockIntersectionObserver.mockImplementation(() => ({
observe: () => null,
unobserve: () => null,
disconnect: () => null
}));
window.IntersectionObserver = mockIntersectionObserver;

// 模拟消息数据
const mockMessages = [
{ id: '1', role: 'user', content: '你好' },
{ id: '2', role: 'assistant', content: '你好!有什么我可以帮你的吗?' }
];

// 模拟 ChatContext 值
const mockChatContextValue = {
messages: mockMessages,
isLoading: false,
isStreaming: false,
observationIds: {},
sendMessage: jest.fn(),
clearMessages: jest.fn(),
deleteMessage: jest.fn(),
regenerateMessage: jest.fn(),
stopGenerating: jest.fn(),
};

// 测试组件包装器
const renderChatWindow = (contextValue = mockChatContextValue) => {
return render(
<ChatContext.Provider value={contextValue}>
<ChatWindow />
</ChatContext.Provider>
);
};

describe('ChatWindow Component', () => {
it('应该正确渲染空消息状态', () => {
renderChatWindow({
...mockChatContextValue,
messages: []
});

expect(screen.getByText('暂无消息')).toBeInTheDocument();
});

it('应该正确渲染消息列表', () => {
renderChatWindow();

expect(screen.getByText('你好')).toBeInTheDocument();
expect(screen.getByText('你好!有什么我可以帮你的吗?')).toBeInTheDocument();
});

it('应该在加载时显示加载状态', () => {
renderChatWindow({
...mockChatContextValue,
isLoading: true,
isStreaming: false
});

expect(screen.getByText('AI正在思考...')).toBeInTheDocument();
});

it('不应在流式输出时显示加载状态', () => {
renderChatWindow({
...mockChatContextValue,
isLoading: true,
isStreaming: true
});

expect(screen.queryByText('AI正在思考...')).not.toBeInTheDocument();
});

// 测试自动滚动功能
it('应该在新消息到达时触发滚动', () => {
const scrollIntoViewMock = jest.fn();
window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;

const { rerender } = renderChatWindow();

// 添加新消息
const newMessages = [
...mockMessages,
{ id: '3', role: 'user', content: '新消息' }
];

rerender(
<ChatContext.Provider value={{
...mockChatContextValue,
messages: newMessages
}}>
<ChatWindow />
</ChatContext.Provider>
);

expect(scrollIntoViewMock).toHaveBeenCalled();
});
});
Loading
Loading