-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathapp.ts
More file actions
193 lines (170 loc) · 6.03 KB
/
Copy pathapp.ts
File metadata and controls
193 lines (170 loc) · 6.03 KB
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
import * as dotenv from 'dotenv';
import { OpenAI } from 'openai';
import { log, wrapOpenAI, init, flush } from 'galileo';
import chalk from 'chalk';
import inquirer from 'inquirer';
// Load environment variables
dotenv.config();
// Check if Galileo logging is enabled
const loggingEnabled = process.env.GALILEO_API_KEY !== undefined;
const projectName = process.env.GALILEO_PROJECT || 'rag_test_typescript';
const logStreamName = process.env.GALILEO_LOG_STREAM || 'dev';
// Initialize OpenAI client with Galileo logging
const client = wrapOpenAI(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }));
// Define document type
interface Document {
id: string;
text: string;
metadata: {
source: string;
category: string;
};
}
// Retriever function with Galileo logging
const retrieveDocuments = log(
{ spanType: 'retriever' },
async (query: string): Promise<Document[]> => {
// TODO: Replace with actual RAG retrieval
const documents: Document[] = [
{
id: "doc1",
text: "Galileo is an observability platform for LLM applications. It helps developers monitor, debug, and improve their AI systems by tracking inputs, outputs, and performance metrics.",
metadata: {
source: "galileo_docs",
category: "product_overview"
}
},
{
id: "doc2",
text: "RAG (Retrieval-Augmented Generation) is a technique that enhances LLM responses by retrieving relevant information from external knowledge sources before generating an answer.",
metadata: {
source: "ai_techniques",
category: "methodology"
}
},
{
id: "doc3",
text: "Common RAG challenges include hallucinations, retrieval quality issues, and context window limitations. Proper evaluation metrics include relevance, faithfulness, and answer correctness.",
metadata: {
source: "ai_techniques",
category: "challenges"
}
},
{
id: "doc4",
text: "Vector databases like Pinecone, Weaviate, and Chroma are optimized for storing embeddings and performing similarity searches, making them ideal for RAG applications.",
metadata: {
source: "tech_stack",
category: "databases"
}
},
{
id: "doc5",
text: "Prompt engineering is crucial for RAG systems. Well-crafted prompts should instruct the model to use retrieved context, avoid making up information, and cite sources when possible.",
metadata: {
source: "best_practices",
category: "prompting"
}
}
];
return documents;
}
);
// Main RAG function
async function rag(query: string): Promise<string> {
const documents = await retrieveDocuments(query);
// Format documents for better readability in the prompt
let formattedDocs = "";
documents.forEach((doc, i) => {
formattedDocs += `Document ${i+1} (Source: ${doc.metadata.source}):\n${doc.text}\n\n`;
});
const prompt = `
Answer the following question based on the context provided. If the answer is not in the context, say you don't know.
Question: ${query}
Context:
${formattedDocs}
`;
try {
console.log(chalk.blue('Generating answer...'));
const response = await client.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful assistant that answers questions based only on the provided context." },
{ role: "user", content: prompt }
],
});
return response.choices[0].message.content?.trim() || 'No response generated';
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return `Error generating response: ${errorMessage}`;
}
}
async function main() {
console.log(chalk.bold.blue('=== Galileo RAG Terminal Demo ==='));
console.log('This demo uses a simulated RAG system to answer your questions.\n');
// Initialize Galileo with project and log stream names
init({
projectName,
logStreamName
});
// Check environment setup
if (loggingEnabled) {
console.log(chalk.green('✅ Galileo logging is enabled'));
console.log(chalk.green(`✅ Project: ${projectName}`));
console.log(chalk.green(`✅ Log Stream: ${logStreamName}`));
} else {
console.log(chalk.yellow('⚠️ Galileo logging is disabled'));
}
const apiKey = process.env.OPENAI_API_KEY;
if (apiKey) {
console.log(chalk.green('✅ OpenAI API Key is set'));
} else {
console.log(chalk.red('❌ OpenAI API Key is missing'));
process.exit(1);
}
// Main interaction loop
let continueSession = true;
while (continueSession) {
try {
// Get user query
const { query } = await inquirer.prompt([
{
type: 'input',
name: 'query',
message: 'Enter your question about Galileo, RAG, or AI techniques:',
validate: (input: string) => input.length > 0 ? true : 'Please enter a question'
}
]);
if (['exit', 'quit', 'q'].includes(query.toLowerCase())) {
break;
}
const result = await rag(query);
console.log(chalk.bold.green('\nAnswer:'));
console.log(chalk.green('-------------------------------------------'));
console.log(result);
console.log(chalk.green('-------------------------------------------'));
// Ask if user wants to continue
const { continue: shouldContinue } = await inquirer.prompt([
{
type: 'confirm',
name: 'continue',
message: 'Do you want to ask another question?',
default: true
}
]);
continueSession = shouldContinue;
} catch (error) {
console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
}
}
// Flush Galileo logs
await flush();
console.log(chalk.bold('\nExiting RAG Demo. Goodbye!'));
}
// Run the main function
if (require.main === module) {
main().catch(error => {
console.error('Unhandled error:', error);
process.exit(1);
});
}