### Show Manual Guided Instructions
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Updates a specific DOM section to guide the user through a manual authentication process, offering options to open CodeBuddy or directly add a token.
```javascript
function showManualGuidedInstructions() {
// 显示手动引导说明,并提供选择
const autoSection = document.getElementById('autoCallbackSection');
autoSection.innerHTML =
`
手动认证流程
请按照步骤获取Bearer Token
`;
}
```
--------------------------------
### Curl Command Line Examples for CodeBuddy API
Source: https://github.com/xueyue33/codebuddy2api/blob/main/README.md
Provides examples of using curl to make non-streaming and streaming requests to the CodeBuddy API. These commands demonstrate how to set the Authorization header and Content-Type, and how to structure the JSON payload.
```bash
# 非流式请求
curl -X POST "http://127.0.0.1:8001/codebuddy/v1/chat/completions" \
-H "Authorization: Bearer your_secret_password_for_this_service" \
-H "Content-Type: application/json" \
-d '{
"model": "auto-chat",
"messages": [
{"role": "user", "content": "Hello, what is 2+2?"}
]
}'
# 流式请求
curl -X POST "http://127.0.0.1:8001/codebuddy/v1/chat/completions" \
-H "Authorization: Bearer your_secret_password_for_this_service" \
-H "Content-Type: application/json" \
-d '{
"model": "auto-chat",
"messages": [
{"role": "user", "content": "Write a Python hello world script"}
],
"stream": true
}'
```
--------------------------------
### Start OAuth2 Authentication
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Initiates the OAuth2 authentication flow by fetching an authentication URL from the server. It enables a button and displays the URL.
```javascript
async function startAuth() {
const btn = document.getElementById('getAuthBtn');
btn.disabled = true;
btn.innerHTML = ' 正在获取认证链接...';
// 确保清理旧的轮询和状态,并显示链接区域
try {
stopPolling();
} catch (e) {}
currentAuthData = null;
const authUrlSection = document.getElementById('authUrlSection');
const authUrlInput = document.getElementById('authUrlInput');
if (authUrlInput) authUrlInput.value = '';
if (authUrlSection) {
authUrlSection.classList.remove('hidden');
authUrlSection.style.display = 'block';
}
try {
const response = await fetch('/codebuddy/auth/start', {
method: 'GET'
});
const data = await response.json();
// 修正:检查正确的响应字段 `verification_uri_complete`
if (response.ok && data.verification_uri_complete) {
// 保存所有必要信息以供轮询使用
currentAuthData = { auth_state: data.auth_state };
// 修正:使用正确的字段来设置输入框的值,并显示该区域
document.getElementById('authUrlInput').value = data.verification_uri_complete;
const section = document.getElementById('authUrlSection');
section.classList.remove('hidden');
section.style.display = 'block';
showNotification('✅ 认证链接已生成,请点击链接完成登录', 'success');
// 立即开始轮询
pollForToken();
} else {
let errorMessage = data.message || '获取认证链接失败';
showNotification(`❌ ${errorMessage}`, 'error');
resetAuthButton();
}
} catch (error) {
showNotification(`❌ 网络错误: ${error.message}`, 'error');
resetAuthButton();
}
}
```
--------------------------------
### Python Client Integration for CodeBuddy API
Source: https://github.com/xueyue33/codebuddy2api/blob/main/README.md
Demonstrates how to use the OpenAI Python client to interact with the CodeBuddy API for both non-streaming and streaming chat completions. Ensure you have the 'openai' library installed and your API key and base URL are correctly configured.
```python
import openai
client = openai.OpenAI(
api_key="your_secret_password_for_this_service",
base_url="http://127.0.0.1:8001/codebuddy/v1"
)
# 非流式请求
response = client.chat.completions.create(
model="auto-chat",
messages=[
{"role": "user", "content": "你好,2+2等于几?"}
]
)
print(response.choices[0].message.content)
# 流式请求
stream = client.chat.completions.create(
model="auto-chat",
messages=[
{"role": "user", "content": "写一个Python的Hello World脚本"}
],
stream=True
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
```
--------------------------------
### Reset Authentication Button
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Resets the state of the authentication button to its default enabled state with the 'Start Authentication' text.
```javascript
function resetAuthButton() {
const btn = document.getElementById('getAuthBtn');
btn.disabled = false;
btn.innerHTML = ' 开始认证';
}
```
--------------------------------
### Show Manual Instructions Modal
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Dynamically creates and displays a modal dialog to show manual Bearer Token acquisition instructions, including steps and links.
```javascript
function showManualInstructions(instructions) {
// 创建一个模态框显示手动获取指导
const modal = document.createElement('div');
modal.style.cssText =
` position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
`;
const content = document.createElement('div');
content.style.cssText =
` background: white;
border-radius: 0.5rem;
padding: 2rem;
max-width: 500px;
width: 90%;
max-height: 80vh;
overflow-y: auto;
`;
if (document.body.classList.contains('dark')) {
content.style.background = 'var(--card-dark)';
content.style.color = 'var(--text-dark)';
}
content.innerHTML =
`
{
stepsHtml += `
${step}
`;
});
stepsHtml += '';
// 可以选择在页面上显示步骤,或者在模态框中显示
const modal = document.createElement('div');
modal.style.cssText =
` position: fixed;
top: 0;
```
--------------------------------
### Open Authentication URL
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Opens the authentication URL in a new browser tab.
```javascript
function openAuthUrl() {
const url = document.getElementById('authUrlInput').value;
window.open(url, '_blank');
}
```
--------------------------------
### Submit Callback URL
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Processes a user-provided callback URL, extracts the authorization code, and simulates submission for token processing.
```javascript
async function submitCallbackUrl() {
const callbackUrl = document.getElementById('callbackUrl').value.trim();
if (!callbackUrl) {
showNotification('请输入回调链接', 'error');
return;
}
// 尝试从URL中提取授权码
try {
const url = new URL(callbackUrl);
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');
if (code) {
showNotification('正在处理授权码...', 'info');
// 这里需要调用后端API来处理授权码
// 暂时显示成功消息
showNotification('授权码已提交,正在获取token...', 'success');
document.getElementById('callbackUrl').value = '';
} else {
showNotification('URL中未找到授权码,请确认链接正确', 'error');
}
} catch (error) {
showNotification('无效的URL格式', 'error');
}
}
```
--------------------------------
### Test Credential
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Tests a specific credential by its index. It sends a POST request to the chat completions endpoint to simulate usage.
```javascript
async function testCredential(index) {
showNotification(`正在测试凭证 #${index + 1}...`, 'info');
// 找到要测试的凭证的原始数据
const originalCred = credentialsCache[index];
if (!originalCred) return;
try {
const response = await fetch('/codebuddy/v1/chat/completions', {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
// 在后端,token管理器是轮换的,我们无法直接指定用哪个token
// 所以这里的测试实际上是测试下一个将被轮换到的token
// 为了更精确,理想的后端应该有一个专门的测试接口
// 但在当前架构下,这是最好的模拟
model: 'claude-4.0',
messages: [{ role: 'user', content: 'test' }],
max_tokens: 1
})
});
if (response.ok) {
showNotification(`凭证 #${index + 1} 测试成功! ✓`, 'success');
credentialsCache[index].status = 'valid';
} else {
showNotification(`凭证 #${index + 1} 无效或已过期 ✗`, 'error');
credentialsCache[index].status = 'invalid';
}
} catch (error) {
showNotification(`网络错误: ${error.message}`, 'error');
credentialsCache[index].status = 'invalid';
} finally {
// 重新渲染列表以更新图标
displayCredentials();
}
}
```
--------------------------------
### Copy Authentication URL
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Copies the authentication URL from the input field to the clipboard and shows a success notification.
```javascript
function copyAuthUrl() {
const input = document.getElementById('authUrlInput');
input.select();
document.execCommand('copy');
showNotification('认证链接已复制到剪贴板', 'success');
}
```
--------------------------------
### Show Notification
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Displays a notification message to the user. Use 'error', 'success', or 'info' for the type.
```javascript
showNotification("操作失败: ${error.message}", "error");
```
```javascript
showNotification("正在恢复自动轮换...", "info");
```
```javascript
showNotification(`✓ ${data.message}`, "success");
```
```javascript
showNotification(`恢复失败: ${errorData.detail}`, "error");
```
```javascript
showNotification(`网络错误: ${error.message}`, "error");
```
```javascript
showNotification(`正在测试凭证 #${index + 1}...`, "info");
```
```javascript
showNotification(`凭证 #${index + 1} 测试成功! ✓`, "success");
```
```javascript
showNotification(`凭证 #${index + 1} 无效或已过期 ✗`, "error");
```
```javascript
showNotification("请输入测试消息", "error");
```
```javascript
showNotification("API 调用失败", "error");
```
```javascript
showNotification("API 测试成功!", "success");
```
```javascript
showNotification(`测试失败: ${error.message}`, "error");
```
```javascript
showNotification('认证链接已复制到剪贴板', 'success');
```
--------------------------------
### Chat Completions
Source: https://github.com/xueyue33/codebuddy2api/blob/main/README.md
This endpoint allows you to interact with the chat model for both non-streaming and streaming responses. It is compatible with OpenAI API clients.
```APIDOC
## POST /codebuddy/v1/chat/completions
### Description
This endpoint processes chat messages and returns completions. It supports both standard and streaming responses, making it compatible with OpenAI API clients.
### Method
POST
### Endpoint
/codebuddy/v1/chat/completions
### Parameters
#### Header Parameters
- **Authorization** (string) - Required - Bearer Token obtained from CODEBUDDY_PASSWORD in .env file.
- **Content-Type** (string) - Required - application/json
#### Request Body
- **model** (string) - Required - The model to use for completions (e.g., "auto-chat").
- **messages** (array) - Required - A list of message objects, where each object has a "role" (user or assistant) and "content" (the message text).
- **stream** (boolean) - Optional - If true, enables streaming responses. Defaults to false.
### Request Example
```json
{
"model": "auto-chat",
"messages": [
{"role": "user", "content": "Hello, what is 2+2?"}
],
"stream": false
}
```
### Response
#### Success Response (200)
- **choices** (array) - Contains the completion choices. Each choice includes a message with role and content.
- **message** (object)
- **content** (string) - The generated text content of the response.
#### Response Example (Non-streaming)
```json
{
"choices": [
{
"message": {
"content": "2+2 equals 4."
}
}
]
}
```
#### Response Example (Streaming)
```json
{
"choices": [
{
"delta": {
"content": "The answer is "
}
},
{
"delta": {
"content": "4."
}
}
]
}
```
```
--------------------------------
### Show Notification
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Displays a notification message to the user. Can be used for informational, success, or error messages.
```javascript
showNotification('已在新窗口打开认证页面,请完成登录', 'info');
```
--------------------------------
### Test API Endpoint
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Tests the chat completions API endpoint with user-provided model, message, and stream option. Displays results or errors.
```javascript
async function testAPI() {
const model = document.getElementById('testModel').value;
const message = document.getElementById('testMessage').value;
const stream = document.getElementById('testStream').checked;
const resultDiv = document.getElementById('testResult');
if (!message.trim()) {
showNotification('请输入测试消息', 'error');
return;
}
resultDiv.innerHTML = '正在发送请求...\n';
try {
const response = await fetch('/codebuddy/v1/chat/completions', {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
model: model,
messages: [{ role: 'user', content: message }],
stream: stream
})
});
if (stream) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
resultDiv.innerHTML = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data.trim() === '[DONE]') {
resultDiv.innerHTML += '\n\n[流结束]';
continue;
}
try {
const parsed = JSON.parse(data);
resultDiv.innerHTML += JSON.stringify(parsed, null, 2) + '\n\n';
} catch (e) {
// 忽略解析错误
}
}
}
resultDiv.scrollTop = resultDiv.scrollHeight;
}
} else {
const data = await response.json();
resultDiv.innerHTML = JSON.stringify(data, null, 2);
}
if (!response.ok) {
showNotification('API 调用失败', 'error');
} else {
showNotification('API 测试成功!', 'success');
}
} catch (error) {
resultDiv.innerHTML = `错误: ${error.message}`;
showNotification(`测试失败: ${error.message}`, 'error');
}
}
```
--------------------------------
### Show Manual Callback Section
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Toggles the visibility of the manual callback section and hides the auto callback section. Stops any ongoing polling.
```javascript
function showManualCallback() {
document.getElementById('manualCallbackSection').style.display = 'block';
document.getElementById('autoCallbackSection').style.display = 'none';
stopPolling();
}
```
--------------------------------
### Wait for Auto Callback
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Toggles the visibility of the auto callback section and hides the manual callback section. Initiates token polling if authentication data is available.
```javascript
function waitForAutoCallback() {
document.getElementById('manualCallbackSection').style.display = 'none';
document.getElementById('autoCallbackSection').style.display = 'block';
if (currentAuthData) {
pollForToken();
}
}
```
--------------------------------
### Resume Auto Rotation
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Resumes the automatic credential rotation process. It sends a POST request to the server and updates the UI based on the response.
```javascript
async function resumeAutoRotation() {
showNotification('正在恢复自动轮换...', 'info');
try {
const response = await fetch('/codebuddy/v1/credentials/auto', {
method: 'POST',
headers: getAuthHeaders()
});
if (response.ok) {
const data = await response.json();
showNotification(`✓ ${data.message}`, 'success');
loadCurrentCredentialStatus(); // 刷新状态显示
} else {
const errorData = await response.json();
showNotification(`恢复失败: ${errorData.detail}`, 'error');
}
} catch (error) {
showNotification(`网络错误: ${error.message}`, 'error');
}
}
```
--------------------------------
### Poll for Token
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Periodically fetches for an access token using a POST request to the /codebuddy/auth/poll endpoint. Handles various response statuses like authorization pending, slow down, expired token, and access denied.
```javascript
function pollForToken() {
if (!currentAuthData) return;
stopPolling(); // 清除之前的轮询
const poll = async () => {
try {
const response = await fetch('/codebuddy/auth/poll', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ auth_state: currentAuthData.auth_state // 修正:发送auth_state
})
});
const data = await response.json();
if (response.ok && data.access_token) {
// 认证成功
stopPolling();
showNotification('🎉 认证成功!Token已自动保存', 'success');
// 隐藏认证区域
document.getElementById('authUrlSection').style.display = 'none';
resetAuthButton(); // 刷新凭证列表
loadCredentials(); // 清理认证数据
currentAuthData = null;
} else if (data.error === 'authorization_pending') {
// 继续等待用户授权
console.log('等待用户授权...');
} else if (data.error === 'slow_down') {
// 减慢轮询频率
console.log('减慢轮询频率');
} else if (data.error === 'expired_token') {
// Token过期,停止轮询
stopPolling();
showNotification('认证链接已过期,请重新开始认证', 'warning');
resetAuthButton();
document.getElementById('authUrlSection').style.display = 'none';
} else if (data.error === 'access_denied') {
// 用户拒绝授权
stopPolling();
showNotification('用户拒绝了授权请求', 'warning');
resetAuthButton();
document.getElementById('authUrlSection').style.display = 'none';
} else {
// 其他错误
console.error('轮询错误:', data);
}
} catch (error) {
console.error('轮询网络错误:', error);
}
};
// 立即执行一次
poll();
// 设置轮询间隔(每5秒一次)
authPollingInterval = setInterval(poll, 5000);
}
```
--------------------------------
### Stop Polling
Source: https://github.com/xueyue33/codebuddy2api/blob/main/frontend/admin.html
Clears the interval timer for token polling if it is active.
```javascript
function stopPolling() {
if (authPollingInterval) {
clearInterval(authPollingInterval);
authPollingInterval = null;
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.