File size: 12,649 Bytes
7c012de |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
import { Express } from "express";
import { createServer, Server } from "http";
import { z } from "zod";
import { storage } from "./storage";
import { searchRequestSchema } from "@shared/schema";
import OpenAI from "openai";
interface GitHubRepo {
id: number;
name: string;
full_name: string;
description: string;
html_url: string;
stargazers_count: number;
language: string;
topics: string[];
created_at: string;
updated_at: string;
}
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// Web search function using DuckDuckGo Instant Answer API
async function searchWeb(query: string, maxResults: number = 10): Promise<any[]> {
try {
const searchUrl = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`;
const response = await fetch(searchUrl);
if (!response.ok) {
console.error('DuckDuckGo API error:', response.status);
return [];
}
const data = await response.json();
const results = [];
// Process instant answer
if (data.AbstractText && data.AbstractURL) {
results.push({
title: data.Heading || query,
content: data.AbstractText,
url: data.AbstractURL,
source: data.AbstractSource || 'Web Search',
type: 'instant_answer'
});
}
// Process related topics
if (data.RelatedTopics && Array.isArray(data.RelatedTopics)) {
for (const topic of data.RelatedTopics.slice(0, maxResults - results.length)) {
if (topic.Text && topic.FirstURL) {
results.push({
title: topic.Text.split(' - ')[0] || topic.Text.substring(0, 60),
content: topic.Text,
url: topic.FirstURL,
source: 'DuckDuckGo',
type: 'related_topic'
});
}
}
}
return results;
} catch (error) {
console.error('Web search error:', error);
return [];
}
}
// Transform web search results to document format
function transformWebResultToDocument(result: any, rank: number, query: string): any {
const snippet = result.content.length > 200 ?
result.content.substring(0, 200) + '...' :
result.content;
return {
id: `web_${Date.now()}_${rank}`,
title: result.title,
content: result.content,
snippet,
source: result.source,
sourceType: 'web',
url: result.url,
metadata: {
search_type: result.type,
fetched_at: new Date().toISOString()
},
relevanceScore: Math.max(0.4, 1 - (rank * 0.15)),
rank: rank + 1,
searchQuery: query,
retrievalTime: Math.random() * 0.2 + 0.1,
tokenCount: Math.floor(result.content.length / 4)
};
}
async function searchGitHubRepos(query: string, maxResults: number = 10): Promise<any[]> {
try {
// Parse query to extract author and repository details
const lowerQuery = query.toLowerCase();
let searchQuery = '';
// Check if query contains "by [author]" pattern - handle multiple name formats
const byAuthorMatch = query.match(/by\s+([a-zA-Z0-9_-]+(?:\s+[a-zA-Z0-9_-]+)*)/i);
if (byAuthorMatch) {
const authorName = byAuthorMatch[1].trim();
const topicPart = query.replace(/by\s+[a-zA-Z0-9_-]+(?:\s+[a-zA-Z0-9_-]+)*/i, '').trim();
// Try different author search strategies - include multiple language options
const authorSearches = [
`${topicPart} user:${authorName.replace(/\s+/g, '')}`, // No language restriction first
`${topicPart} user:${authorName.replace(/\s+/g, '')} language:python`,
`${topicPart} user:${authorName.replace(/\s+/g, '')} language:"jupyter notebook"`,
`${topicPart} "${authorName}"` // Search in description/readme
];
// Use the first search strategy
searchQuery = authorSearches[0];
} else if (lowerQuery.includes('data structures') || lowerQuery.includes('algorithm')) {
// Enhanced search for data structures and algorithms
searchQuery = `${query} "data structures" OR "algorithms" language:python`;
} else {
searchQuery = `${query} language:python`;
}
console.log('GitHub search query:', searchQuery);
const response = await fetch(`https://api.github.com/search/repositories?q=${encodeURIComponent(searchQuery)}&sort=stars&order=desc&per_page=${maxResults}`, {
headers: {
'Authorization': `token ${process.env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'Knowledge-Base-Browser'
}
});
if (!response.ok) {
console.error('GitHub API error:', response.status, response.statusText);
return [];
}
const data = await response.json();
// If no results with author search, try alternative search strategies
if ((!data.items || data.items.length === 0) && byAuthorMatch) {
const authorName = byAuthorMatch[1].trim();
const topicPart = query.replace(/by\s+[a-zA-Z0-9_-]+(?:\s+[a-zA-Z0-9_-]+)*/i, '').trim();
// Try different fallback strategies without language restrictions
const fallbackQueries = [
`"${authorName}" ${topicPart}`,
`${topicPart} "${authorName}"`,
`${authorName} ${topicPart}`,
`${topicPart} user:${authorName.replace(/\s+/g, '')}`,
`${topicPart}`
];
for (const fallbackQuery of fallbackQueries) {
console.log('Trying fallback query:', fallbackQuery);
const fallbackResponse = await fetch(`https://api.github.com/search/repositories?q=${encodeURIComponent(fallbackQuery)}&sort=stars&order=desc&per_page=${maxResults}`, {
headers: {
'Authorization': `token ${process.env.GITHUB_TOKEN}`,
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'Knowledge-Base-Browser'
}
});
if (fallbackResponse.ok) {
const fallbackData = await fallbackResponse.json();
if (fallbackData.items && fallbackData.items.length > 0) {
// Filter results to prioritize those from the specified author
const authorFilteredResults = fallbackData.items.filter((repo: any) =>
repo.owner.login.toLowerCase().includes(authorName.toLowerCase()) ||
repo.full_name.toLowerCase().includes(authorName.toLowerCase()) ||
repo.description?.toLowerCase().includes(authorName.toLowerCase())
);
if (authorFilteredResults.length > 0) {
return authorFilteredResults;
} else {
return fallbackData.items;
}
}
}
}
}
return data.items || [];
} catch (error) {
console.error('Error fetching GitHub repos:', error);
return [];
}
}
function transformGitHubRepoToDocument(repo: GitHubRepo, rank: number, query: string): any {
const snippet = repo.description ?
repo.description.substring(0, 200) + (repo.description.length > 200 ? '...' : '') :
'No description available';
return {
id: repo.id,
title: `${repo.name} - ${repo.full_name}`,
content: `${repo.description || 'No description available'}\n\nRepository: ${repo.full_name}\nLanguage: ${repo.language}\nStars: ${repo.stargazers_count}\nTopics: ${repo.topics.join(', ')}\nCreated: ${repo.created_at}\nLast Updated: ${repo.updated_at}`,
snippet,
source: `GitHub Repository`,
sourceType: 'code',
url: repo.html_url,
metadata: {
stars: repo.stargazers_count,
language: repo.language,
topics: repo.topics,
created_at: repo.created_at,
updated_at: repo.updated_at
},
relevanceScore: Math.max(0.5, 1 - (rank * 0.1)),
rank: rank + 1,
searchQuery: query,
retrievalTime: Math.random() * 0.3 + 0.1,
tokenCount: Math.floor((repo.description?.length || 100) / 4)
};
}
export async function registerRoutes(app: Express): Promise<Server> {
// Enhanced search with web fallback
app.post("/api/search", async (req, res) => {
try {
const searchRequest = searchRequestSchema.parse(req.body);
const streaming = req.body.streaming === true;
const startTime = Date.now();
// First, search local storage
const localResults = await storage.searchDocuments(searchRequest);
let allDocuments = localResults.results || [];
// If local results are insufficient, enhance with external sources
const minResults = 3;
if (allDocuments.length < minResults) {
console.log(`Local search returned ${allDocuments.length} results, fetching external sources...`);
// Check if we should search GitHub for code-related queries
const isCodeQuery = searchRequest.query.toLowerCase().includes('python') ||
searchRequest.query.toLowerCase().includes('data structures') ||
searchRequest.query.toLowerCase().includes('algorithm') ||
searchRequest.query.toLowerCase().includes('repository') ||
searchRequest.query.toLowerCase().includes('code');
// Parallel search of external sources
const searchPromises = [];
if (isCodeQuery && process.env.GITHUB_TOKEN) {
searchPromises.push(
searchGitHubRepos(searchRequest.query, Math.min(5, searchRequest.limit))
.then(repos => repos.map((repo, index) =>
transformGitHubRepoToDocument(repo, index + allDocuments.length, searchRequest.query)
))
);
}
// Always include web search for broader coverage
searchPromises.push(
searchWeb(searchRequest.query, Math.min(5, searchRequest.limit - allDocuments.length))
.then(webResults => webResults.map((result, index) =>
transformWebResultToDocument(result, index + allDocuments.length, searchRequest.query)
))
);
// Wait for all external searches to complete
const externalResults = await Promise.all(searchPromises);
const flattenedResults = externalResults.flat();
// Combine and sort all results by relevance
allDocuments = [...allDocuments, ...flattenedResults]
.sort((a, b) => b.relevanceScore - a.relevanceScore)
.slice(0, searchRequest.limit);
}
const searchTime = (Date.now() - startTime) / 1000;
const response = {
results: allDocuments,
totalCount: allDocuments.length,
searchTime,
query: searchRequest.query,
queryId: Date.now()
};
res.json(response);
} catch (error) {
if (error instanceof z.ZodError) {
res.status(400).json({ message: "Invalid search request", errors: error.errors });
} else {
console.error('Search error:', error);
res.status(500).json({ message: "Internal server error" });
}
}
});
// AI explanation endpoint
app.post("/api/explain", async (req, res) => {
try {
const { title, snippet, content } = req.body;
if (!title || !snippet) {
return res.status(400).json({ message: "Title and snippet are required" });
}
const prompt = `Explain this document in a clear, conversational way suitable for audio playback:
Title: ${title}
Content: ${snippet}
Provide a brief, engaging explanation (2-3 sentences) that would be pleasant to listen to. Focus on the key concepts and practical value.`;
const response = await openai.chat.completions.create({
model: "gpt-4o", // the newest OpenAI model is "gpt-4o" which was released May 13, 2024. do not change this unless explicitly requested by the user
messages: [{ role: "user", content: prompt }],
max_tokens: 150,
temperature: 0.7,
});
const explanation = response.choices[0].message.content;
res.json({ explanation });
} catch (error) {
console.error('AI explanation error:', error);
res.status(500).json({ message: "Failed to generate explanation" });
}
});
// Other routes...
app.get("/api/documents", async (req, res) => {
try {
const limit = parseInt(req.query.limit as string) || 50;
const offset = parseInt(req.query.offset as string) || 0;
const documents = await storage.getDocuments(limit, offset);
res.json(documents);
} catch (error) {
res.status(500).json({ message: "Failed to fetch documents" });
}
});
const httpServer = createServer(app);
return httpServer;
} |