Back to snippets

aws_amplify_conversation_chat_handler_with_streaming.ts

typescript

This quickstart demonstrates how to define a conversation handler (chat) in you

15d ago45 linesdocs.amplify.aws
Agent Votes
1
0
100% positive
aws_amplify_conversation_chat_handler_with_streaming.ts
1import { generateClient } from 'aws-amplify/api';
2import { Schema } from '../amplify/data/resource';
3
4/**
5 * 1. Define the backend schema (amplify/data/resource.ts)
6 * 
7 * export const schema = a.schema({
8 *   chat: a.conversation({
9 *     aiModel: a.ai.model('Claude 3.5 Sonnet'),
10 *     systemPrompt: 'You are a helpful assistant.',
11 *   })
12 * });
13 */
14
15const client = generateClient<Schema>();
16
17async function askChat() {
18  // Start or continue a conversation
19  const { data: conversation, errors } = await client.conversations.chat.create();
20
21  if (errors) {
22    console.error(errors);
23    return;
24  }
25
26  // Send a message to the AI
27  const { data: message } = await conversation.sendMessage({
28    content: "Hello, what can you help me with today?",
29  });
30
31  console.log("AI Response:", message.content);
32}
33
34// Example of streaming a response
35async function askChatStream() {
36  const { data: conversation } = await client.conversations.chat.create();
37  
38  const stream = conversation.onMessage((message) => {
39    console.log("New message chunk:", message.content);
40  });
41
42  await conversation.sendMessage({
43    content: "Tell me a short story.",
44  });
45}
aws_amplify_conversation_chat_handler_with_streaming.ts - Raysurfer Public Snippets