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

chat: add saving toggle (fixes #7232) #7233

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
8 changes: 8 additions & 0 deletions chatapi/src/config/nano.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import nano from 'nano';
import dotenv from 'dotenv';

dotenv.config();

const db = nano(process.env.COUCHDB_HOST || 'https://couchdb:5984').use('chat_history');

export default db;
12 changes: 12 additions & 0 deletions chatapi/src/config/openai.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Configuration, OpenAIApi } from 'openai';
import dotenv from 'dotenv';

dotenv.config();

const configuration = new Configuration({
'apiKey': process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

export default openai;
32 changes: 26 additions & 6 deletions chatapi/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import express from 'express';
import { chatWithGpt } from './services/gpt-prompt.service';
import dotenv from 'dotenv';
import cors from 'cors';

import { getChatDocument } from './utils/db.utils';
import { chat, chatNoSave } from './services/chat.service';

dotenv.config();

const app = express();
Expand All @@ -20,24 +22,42 @@ app.get('/', (req: any, res: any) => {

app.post('/', async (req: any, res: any) => {
try {
const userInput = req.body.content;
const { data, save } = req.body;

if (userInput && typeof userInput === 'string') {
const response = await chatWithGpt(userInput);
if (!save) {
const response = await chatNoSave(data.content);
res.status(200).json({
'status': 'Success',
'chat': response
});
} else if (save && data && typeof data === 'object') {
const response = await chat(data);
res.status(201).json({
'status': 'Success',
'chat': response?.completionText,
'history': response?.history,
'couchDBResponse': response?.couchSaveResponse
});
} else {
res.status(400).json({ 'error': 'Bad Request', 'message': 'The "content" field must be a non-empty string.' });
res.status(400).json({ 'error': 'Bad Request', 'message': 'The "data" field must be a non-empty object' });
}
} catch (error: any) {
res.status(500).json({ 'error': 'Internal Server Error', 'message': error.message });
}
});

app.get('/conversation/:id', async (req: any, res: any) => {
try {
const { id } = req.params;
const conversation = await getChatDocument(id);
res.status(200).json({
'status': 'Success',
conversation
});
} catch (error: any) {
res.status(500).json({ 'error': 'Internal Server Error', 'message': error.message });
}
});

const port = process.env.SERVE_PORT || 5000;

app.listen(port, () => console.log(`Server running on port ${port}`)); // eslint-disable-line no-console
5 changes: 0 additions & 5 deletions chatapi/src/models/database-actions.model.ts

This file was deleted.

7 changes: 7 additions & 0 deletions chatapi/src/models/db-doc.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface DbDoc {
_id: string;
_rev: string;
user: string;
time: number;
conversations: [];
}
72 changes: 72 additions & 0 deletions chatapi/src/services/chat.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { DocumentInsertResponse } from 'nano';

import db from '../config/nano.config';
import { gptChat } from '../utils/gpt-chat.utils';
import { getChatDocument } from '../utils/db.utils';
import { handleChatError } from '../utils/chat-error.utils';
import { ChatMessage } from '../models/chat-message.model';

/**
* Create a chat conversation & save in couchdb
* @param data - Chat data including content and additional information
* @returns Object with completion text and CouchDB save response
*/
export async function chat(data: any): Promise<{
completionText: string;
couchSaveResponse: DocumentInsertResponse;
} | undefined> {
const { content, ...dbData } = data;
const messages: ChatMessage[] = [];

if (dbData._id) {
const history = await getChatDocument(dbData._id);
dbData.conversations = history;

for (const { query, response } of history) {
messages.push({ 'role': 'user', 'content': query });
messages.push({ 'role': 'assistant', 'content': response });
}
} else {
dbData.conversations = [];
}

dbData.conversations.push({ 'query': content, 'response': '' });
const res = await db.insert(dbData);

messages.push({ 'role': 'user', content });

try {
const completionText = await gptChat(messages);

dbData.conversations.pop();
dbData.conversations.push({ 'query': content, 'response': completionText });

dbData._id = res?.id;
dbData._rev = res?.rev;
const couchSaveResponse = await db.insert(dbData);

return {
completionText,
couchSaveResponse
};
} catch (error: any) {
handleChatError(error);
}
}

export async function chatNoSave(content: any): Promise< string | undefined> {
const messages: ChatMessage[] = [];

messages.push({ 'role': 'user', content });

try {
const completionText = await gptChat(messages);
messages.push({
'role': 'assistant', 'content': completionText
});

return completionText;
} catch (error: any) {
handleChatError(error);
}
}
68 changes: 0 additions & 68 deletions chatapi/src/services/gpt-prompt.service.ts

This file was deleted.

7 changes: 7 additions & 0 deletions chatapi/src/utils/chat-error.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function handleChatError(error: any) {
if (error.response) {
throw new Error(`GPT Service Error: ${error.response.status} - ${error.response.data?.error?.code}`);
} else {
throw new Error(error.message);
}
}
17 changes: 17 additions & 0 deletions chatapi/src/utils/db.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import db from '../config/nano.config';
import { DbDoc } from '../models/db-doc.model';

/**
* Retrieves chat history from CouchDB for a given document ID.
* @param id - Document ID
* @returns Array of chat conversations
*/
export async function getChatDocument(id: string) {
try {
const res = await db.get(id) as DbDoc;
return res.conversations;
// Should return user, team data as well particularly for the /conversations endpoint
} catch (error) {
return [];
}
}
21 changes: 21 additions & 0 deletions chatapi/src/utils/gpt-chat.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import openai from '../config/openai.config';
import { ChatMessage } from '../models/chat-message.model';

/**
* Uses openai's createChatCompletion endpoint to generate chat completions
* @param messages - Array of chat messages
* @returns Completion text
*/
export async function gptChat(messages: ChatMessage[]): Promise<string> {
const completion = await openai.createChatCompletion({
'model': 'gpt-3.5-turbo',
messages,
});

const completionText = completion.data.choices[0]?.message?.content;
if (!completionText) {
throw new Error('Unexpected API response');
}

return completionText;
}
32 changes: 0 additions & 32 deletions chatapi/src/utils/nano-couchdb.ts

This file was deleted.

5 changes: 4 additions & 1 deletion src/app/chat/chat.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
<button type="submit" mat-raised-button [planetSubmit]="spinnerOn" color="primary" i18n>
Chat
<mat-icon>send</mat-icon>
</button>
</button>
<mat-slide-toggle ngModel formControlName="saveChat" color="primary">
Save Chat
</mat-slide-toggle>
</form>
</div>
</div>
4 changes: 4 additions & 0 deletions src/app/chat/chat.component.scss
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,7 @@ textarea:focus {
border-color: #007bff;
box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}

mat-slide-toggle {
margin-right: auto;
}
17 changes: 15 additions & 2 deletions src/app/chat/chat.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { ActivatedRoute, Router } from '@angular/router';
import { CustomValidators } from '../validators/custom-validators';
import { showFormErrors } from '../shared/table-helpers';
import { ChatService } from '../shared/chat.service';
import { UserService } from '../shared/user.service';
import { CouchService } from '../shared/couchdb.service';

@Component({
selector: 'planet-chat',
Expand All @@ -14,6 +16,11 @@ import { ChatService } from '../shared/chat.service';
export class ChatComponent implements OnInit {
spinnerOn = true;
promptForm: FormGroup;
data = {
user: this.userService.get(),
time: this.couchService.datePlaceholder,
content: ''
};
messages: any[] = [];
conversations: any[] = [];

Expand All @@ -24,7 +31,9 @@ export class ChatComponent implements OnInit {
private route: ActivatedRoute,
private router: Router,
private changeDetectorRef: ChangeDetectorRef,
private chatService: ChatService
private chatService: ChatService,
private userService: UserService,
private couchService: CouchService
) {}

ngOnInit() {
Expand All @@ -41,6 +50,7 @@ export class ChatComponent implements OnInit {
createForm() {
this.promptForm = this.formBuilder.group({
prompt: [ '', CustomValidators.required ],
saveChat: [ false ],
});
}

Expand All @@ -58,10 +68,13 @@ export class ChatComponent implements OnInit {
}

submitPrompt() {
const save = this.promptForm.get('saveChat').value;
const content = this.promptForm.get('prompt').value;
this.messages.push({ role: 'user', content });

this.chatService.getPrompt(content).subscribe(
this.data.content = content;

this.chatService.getPrompt(this.data, save).subscribe(
(completion: any) => {
this.conversations.push({
query: content,
Expand Down
Loading
Loading