chats.ts•1.91 kB
/**
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { MessageSchema, type MessageData } from '@genkit-ai/ai/model';
import { z } from 'genkit';
// Our flow will take a sessionId along with each question to track the chat history.
// The host application should keep track of these ids somewhere.
export const ChatSessionInputSchema = z.object({
  sessionId: z.string(),
  question: z.string(),
});
// The flow will respond with an array of messages,
// which includes all history up until that point
// plus the last exchange with the model.
export const ChatSessionOutputSchema = z.object({
  sessionId: z.string(),
  history: z.array(MessageSchema),
});
export type ChatHistory = Array<MessageData>;
// This is a very simple local storage for chat history.
// Each conversation is identified by a sessionId generated by the application.
// The constructor accepts a preamble of messages, which serve as a system prompt.
export class ChatHistoryStore {
  private preamble: ChatHistory;
  private sessions: Map<string, ChatHistory> = new Map<string, ChatHistory>();
  constructor(preamble: ChatHistory = []) {
    this.preamble = preamble;
  }
  write(sessionId: string, history: ChatHistory) {
    this.sessions.set(sessionId, history);
  }
  read(sessionId: string): ChatHistory {
    return this.sessions.get(sessionId) || this.preamble;
  }
}