Skip to content

Commit 3460a7b

Browse files
committed
Convo update
1 parent d75751b commit 3460a7b

File tree

8 files changed

+247
-448
lines changed

8 files changed

+247
-448
lines changed

apps/sim/app/api/copilot/chats/[id]/route.ts

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
import { eq, and } from 'drizzle-orm'
1+
import { and, eq } from 'drizzle-orm'
22
import { type NextRequest, NextResponse } from 'next/server'
33
import { z } from 'zod'
44
import { getSession } from '@/lib/auth'
55
import { createLogger } from '@/lib/logs/console-logger'
6+
import { getRotatingApiKey } from '@/lib/utils'
67
import { db } from '@/db'
78
import { copilotChats } from '@/db/schema'
89
import { executeProviderRequest } from '@/providers'
9-
import { getRotatingApiKey } from '@/lib/utils'
1010

1111
const logger = createLogger('CopilotChatAPI')
1212

@@ -43,12 +43,7 @@ export async function GET(req: NextRequest, { params }: { params: { id: string }
4343
const [chat] = await db
4444
.select()
4545
.from(copilotChats)
46-
.where(
47-
and(
48-
eq(copilotChats.id, chatId),
49-
eq(copilotChats.userId, session.user.id)
50-
)
51-
)
46+
.where(and(eq(copilotChats.id, chatId), eq(copilotChats.userId, session.user.id)))
5247
.limit(1)
5348

5449
if (!chat) {
@@ -94,12 +89,7 @@ export async function PUT(req: NextRequest, { params }: { params: { id: string }
9489
const [existingChat] = await db
9590
.select()
9691
.from(copilotChats)
97-
.where(
98-
and(
99-
eq(copilotChats.id, chatId),
100-
eq(copilotChats.userId, session.user.id)
101-
)
102-
)
92+
.where(and(eq(copilotChats.id, chatId), eq(copilotChats.userId, session.user.id)))
10393
.limit(1)
10494

10595
if (!existingChat) {
@@ -172,22 +162,15 @@ export async function DELETE(req: NextRequest, { params }: { params: { id: strin
172162
const [existingChat] = await db
173163
.select({ id: copilotChats.id })
174164
.from(copilotChats)
175-
.where(
176-
and(
177-
eq(copilotChats.id, chatId),
178-
eq(copilotChats.userId, session.user.id)
179-
)
180-
)
165+
.where(and(eq(copilotChats.id, chatId), eq(copilotChats.userId, session.user.id)))
181166
.limit(1)
182167

183168
if (!existingChat) {
184169
return NextResponse.json({ error: 'Chat not found' }, { status: 404 })
185170
}
186171

187172
// Delete the chat
188-
await db
189-
.delete(copilotChats)
190-
.where(eq(copilotChats.id, chatId))
173+
await db.delete(copilotChats).where(eq(copilotChats.id, chatId))
191174

192175
logger.info(`Deleted chat ${chatId} for user ${session.user.id}`)
193176

@@ -207,10 +190,11 @@ export async function DELETE(req: NextRequest, { params }: { params: { id: strin
207190
export async function generateChatTitle(userMessage: string): Promise<string> {
208191
try {
209192
const apiKey = getRotatingApiKey('anthropic')
210-
193+
211194
const response = await executeProviderRequest('anthropic', {
212195
model: 'claude-3-haiku-20240307', // Use faster, cheaper model for title generation
213-
systemPrompt: 'You are a helpful assistant that generates concise, descriptive titles for chat conversations. Create a title that captures the main topic or question being discussed. Keep it under 50 characters and make it specific and clear.',
196+
systemPrompt:
197+
'You are a helpful assistant that generates concise, descriptive titles for chat conversations. Create a title that captures the main topic or question being discussed. Keep it under 50 characters and make it specific and clear.',
214198
context: `Generate a concise title for a conversation that starts with this user message: "${userMessage}"
215199
216200
Return only the title text, nothing else.`,
@@ -230,4 +214,4 @@ Return only the title text, nothing else.`,
230214
logger.error('Failed to generate chat title:', error)
231215
return 'New Chat' // Fallback title
232216
}
233-
}
217+
}

apps/sim/app/api/copilot/chats/route.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { desc, eq, and } from 'drizzle-orm'
1+
import { and, desc, eq } from 'drizzle-orm'
22
import { type NextRequest, NextResponse } from 'next/server'
33
import { z } from 'zod'
44
import { getSession } from '@/lib/auth'
@@ -34,11 +34,14 @@ export async function GET(req: NextRequest) {
3434

3535
const { searchParams } = new URL(req.url)
3636
const workflowId = searchParams.get('workflowId')
37-
const limit = parseInt(searchParams.get('limit') || '50')
38-
const offset = parseInt(searchParams.get('offset') || '0')
37+
const limit = Number.parseInt(searchParams.get('limit') || '50')
38+
const offset = Number.parseInt(searchParams.get('offset') || '0')
3939

40-
const { workflowId: validatedWorkflowId, limit: validatedLimit, offset: validatedOffset } =
41-
ListChatsSchema.parse({ workflowId, limit, offset })
40+
const {
41+
workflowId: validatedWorkflowId,
42+
limit: validatedLimit,
43+
offset: validatedOffset,
44+
} = ListChatsSchema.parse({ workflowId, limit, offset })
4245

4346
logger.info(`Listing chats for user ${session.user.id}, workflow ${validatedWorkflowId}`)
4447

@@ -63,7 +66,7 @@ export async function GET(req: NextRequest) {
6366
.offset(validatedOffset)
6467

6568
// Process the results to add message counts and clean up data
66-
const processedChats = chats.map(chat => ({
69+
const processedChats = chats.map((chat) => ({
6770
id: chat.id,
6871
title: chat.title,
6972
model: chat.model,
@@ -170,4 +173,4 @@ export async function POST(req: NextRequest) {
170173
logger.error('Failed to create copilot chat:', error)
171174
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
172175
}
173-
}
176+
}

apps/sim/app/api/docs/ask/route.ts

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
import { sql, eq, and } from 'drizzle-orm'
1+
import { and, eq, sql } from 'drizzle-orm'
22
import { type NextRequest, NextResponse } from 'next/server'
33
import { z } from 'zod'
4+
import { getSession } from '@/lib/auth'
45
import { env } from '@/lib/env'
56
import { createLogger } from '@/lib/logs/console-logger'
67
import { getRotatingApiKey } from '@/lib/utils'
78
import { generateEmbeddings } from '@/app/api/knowledge/utils'
8-
import { getSession } from '@/lib/auth'
99
import { db } from '@/db'
10-
import { docsEmbeddings, copilotChats } from '@/db/schema'
10+
import { copilotChats, docsEmbeddings } from '@/db/schema'
1111
import { executeProviderRequest } from '@/providers'
1212
import { getProviderDefaultModel } from '@/providers/models'
1313

@@ -43,10 +43,11 @@ const DocsQuerySchema = z.object({
4343
async function generateChatTitle(userMessage: string): Promise<string> {
4444
try {
4545
const apiKey = getRotatingApiKey('anthropic')
46-
46+
4747
const response = await executeProviderRequest('anthropic', {
4848
model: 'claude-3-haiku-20240307', // Use faster, cheaper model for title generation
49-
systemPrompt: 'You are a helpful assistant that generates concise, descriptive titles for chat conversations. Create a title that captures the main topic or question being discussed. Keep it under 50 characters and make it specific and clear.',
49+
systemPrompt:
50+
'You are a helpful assistant that generates concise, descriptive titles for chat conversations. Create a title that captures the main topic or question being discussed. Keep it under 50 characters and make it specific and clear.',
5051
context: `Generate a concise title for a conversation that starts with this user message: "${userMessage}"
5152
5253
Return only the title text, nothing else.`,
@@ -171,7 +172,8 @@ Content: ${chunkText}`
171172
let conversationContext = ''
172173
if (conversationHistory.length > 0) {
173174
conversationContext = '\n\nConversation History:\n'
174-
conversationHistory.slice(-6).forEach((msg: any) => { // Include last 6 messages for context
175+
conversationHistory.slice(-6).forEach((msg: any) => {
176+
// Include last 6 messages for context
175177
const role = msg.role === 'user' ? 'Human' : 'Assistant'
176178
conversationContext += `${role}: ${msg.content}\n`
177179
})
@@ -270,11 +272,12 @@ export async function POST(req: NextRequest) {
270272

271273
try {
272274
const body = await req.json()
273-
const { query, topK, provider, model, stream, chatId, workflowId, createNewChat } = DocsQuerySchema.parse(body)
275+
const { query, topK, provider, model, stream, chatId, workflowId, createNewChat } =
276+
DocsQuerySchema.parse(body)
274277

275278
// Get session for chat functionality
276279
const session = await getSession()
277-
280+
278281
logger.info(`[${requestId}] Docs RAG query: "${query}"`, {
279282
provider: provider || DOCS_RAG_CONFIG.defaultProvider,
280283
model:
@@ -296,12 +299,7 @@ export async function POST(req: NextRequest) {
296299
const [existingChat] = await db
297300
.select()
298301
.from(copilotChats)
299-
.where(
300-
and(
301-
eq(copilotChats.id, chatId),
302-
eq(copilotChats.userId, session.user.id)
303-
)
304-
)
302+
.where(and(eq(copilotChats.id, chatId), eq(copilotChats.userId, session.user.id)))
305303
.limit(1)
306304

307305
if (existingChat) {
@@ -360,7 +358,14 @@ export async function POST(req: NextRequest) {
360358

361359
// Step 3: Generate response using LLM
362360
logger.info(`[${requestId}] Generating LLM response with ${chunks.length} chunks...`)
363-
const response = await generateResponse(query, chunks, provider, model, stream, conversationHistory)
361+
const response = await generateResponse(
362+
query,
363+
chunks,
364+
provider,
365+
model,
366+
stream,
367+
conversationHistory
368+
)
364369

365370
// Step 4: Format sources for response
366371
const sources = chunks.map((chunk) => ({
@@ -403,7 +408,7 @@ export async function POST(req: NextRequest) {
403408
controller.enqueue(encoder.encode(`data: ${JSON.stringify(metadata)}\n\n`))
404409

405410
let accumulatedResponse = ''
406-
411+
407412
try {
408413
while (true) {
409414
const { done, value } = await reader.read()
@@ -413,10 +418,10 @@ export async function POST(req: NextRequest) {
413418
const chunkText = decoder.decode(value)
414419
// Clean up any object serialization artifacts in streaming content
415420
const cleanedChunk = chunkText.replace(/\[object Object\],?/g, '')
416-
421+
417422
// Accumulate the response content for database saving
418423
accumulatedResponse += cleanedChunk
419-
424+
420425
const contentChunk = {
421426
type: 'content',
422427
content: cleanedChunk,

0 commit comments

Comments
 (0)