Skip to content

Commit e9a026b

Browse files
committed
chat with document updated to support history and a default model
1 parent 37d2317 commit e9a026b

File tree

6 files changed

+59
-16
lines changed

6 files changed

+59
-16
lines changed

src/api/schema.graphql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ type Query @aws_cognito_user_pools @aws_iam {
203203
getFileContents(s3Uri: String!): FileContentsResponse
204204
getConfiguration: ConfigurationResponse
205205
queryKnowledgeBase(input: String!, sessionId: String): String
206-
chatWithDocument(s3Uri: String!, prompt: String!, modelId: String!): String
206+
chatWithDocument(s3Uri: String!, prompt: String!, history: AWSJSON!, modelId: String!): String
207207
getStepFunctionExecution(executionArn: String!): StepFunctionExecutionResponse
208208
submitAnalyticsQuery(query: String!): AnalyticsJob @aws_cognito_user_pools
209209
getAnalyticsJobStatus(jobId: ID!): AnalyticsJob @aws_cognito_user_pools

src/lambda/chat_with_document_resolver/index.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,18 @@ def handler(event, context):
4747

4848
objectKey = event['arguments']['s3Uri']
4949
prompt = event['arguments']['prompt']
50+
history = event['arguments']['history']
51+
52+
full_prompt = "You are an assistant that's responsible for getting details from document text attached here based on questions from the user.\n\n"
53+
full_prompt += "If you don't know the answer, just say that you don't know. Don't try to make up an answer.\n\n"
54+
full_prompt += "Additionally, use the user and assistant responses in the following JSON object to see what's been asked and what the resposes were in the past.\n\n"
55+
full_prompt += "The JSON object is: " + json.dumps(history) + ".\n\n"
56+
full_prompt += "The user's question is: " + prompt
5057

5158
# this feature is not enabled until the model can be selected on the chat screen
5259
# selectedModelId = event['arguments']['modelId']
5360
selectedModelId = get_summarization_model()
54-
61+
5562
logger.info(f"Processing S3 URI: {objectKey}")
5663

5764
output_bucket = os.environ['OUTPUT_BUCKET']
@@ -67,6 +74,9 @@ def handler(event, context):
6774
# full text key
6875
fulltext_key = objectKey + '/summary/fulltext.txt'
6976

77+
logger.info(f"Output Bucket: {output_bucket}")
78+
logger.info(f"Full Text Key: {fulltext_key}")
79+
7080
# read full contents of the object as text
7181
s3 = boto3.client('s3')
7282
response = s3.get_object(Bucket=output_bucket, Key=fulltext_key)
@@ -90,7 +100,7 @@ def handler(event, context):
90100
"role":"user",
91101
"content": [
92102
{
93-
"text": prompt
103+
"text": full_prompt
94104
}
95105
]
96106
}

src/ui/package-lock.json

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/ui/src/components/chat-panel/ChatPanel.jsx

Lines changed: 40 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,17 @@ import './ChatPanel.css';
1010

1111
const logger = new Logger('chatWithDocument');
1212

13-
const getChatResponse = async (s3Uri, prompt) => {
13+
const getChatResponse = async (s3Uri, prompt, history) => {
1414
logger.debug('s3URI:', s3Uri);
15-
15+
logger.debug('history:', history);
1616
// commenting this out until model selection for chat is available again on this screen
1717
// logger.debug('modelId:', modelId);
1818
const modelId = 'us.amazon.nova-pro-v1:0';
19-
const response = await API.graphql({ query: chatWithDocument, variables: { s3Uri, prompt, modelId } });
19+
const strHistory = JSON.stringify(history);
20+
const response = await API.graphql({
21+
query: chatWithDocument,
22+
variables: { s3Uri, prompt, history: strHistory, modelId },
23+
});
2024
// logger.debug('response:', response);
2125
return response;
2226
};
@@ -35,6 +39,7 @@ const ChatPanel = (item) => {
3539
const [error, setError] = useState(null);
3640
// const [modelId, setModelId] = useState(modelOptions[0].value);
3741
const [chatQueries, setChatQueries] = useState([]);
42+
const [jsonChatHistory, setJsonChatHistory] = useState([]);
3843
const textareaRef = useRef(null);
3944
const { objectKey } = item;
4045
let rowId = 0;
@@ -71,8 +76,8 @@ const ChatPanel = (item) => {
7176
textareaRef.current.value = '';
7277

7378
// comment out sending the model ID until model selection is available again on this screen
74-
// const chatResponse = getChatResponse(objectKey, prompt, modelId);
75-
const chatResponse = getChatResponse(objectKey, prompt);
79+
// const chatResponse = getChatResponse(objectKey, prompt, history, modelId);
80+
const chatResponse = getChatResponse(objectKey, prompt, jsonChatHistory);
7681

7782
let chatResponseData = {};
7883

@@ -87,6 +92,13 @@ const ChatPanel = (item) => {
8792
dt: new Date().toLocaleTimeString(),
8893
type: 'msg',
8994
};
95+
96+
const chatItem = {
97+
ask: prompt,
98+
response: cResponse.cr.content[0].text,
99+
};
100+
101+
setJsonChatHistory((prevChatHistory) => [...prevChatHistory, chatItem]);
90102
}
91103
})
92104
.catch((r) => {
@@ -158,9 +170,30 @@ const ChatPanel = (item) => {
158170
<p>To start chatting to this document, enter your message below.</p>
159171
)}
160172

161-
<FormField label="Your message" className="chat-composer-container">
173+
{/* <FormField label="Your message" className="chat-composer-container">
162174
<textarea name="postContent" ref={textareaRef} rows={6} className="chat-textarea" id="chatTextarea" />
163-
</FormField>
175+
</FormField> */}
176+
177+
<div style={{ gap: '8px', width: '100%' }}>
178+
<FormField label="Your message" style={{ flex: 8 }}>
179+
<input
180+
type="text"
181+
name="postContent"
182+
ref={textareaRef}
183+
style={{ padding: '3px', width: '100%' }}
184+
id="chatTextarea"
185+
onKeyDown={(e) => {
186+
if (e.key === 'Enter') {
187+
handlePromptSubmit();
188+
}
189+
}}
190+
/>
191+
</FormField>
192+
193+
<Button variant="primary" onClick={handlePromptSubmit}>
194+
Send
195+
</Button>
196+
</div>
164197

165198
{/* <FormField label="Model">
166199
<select name="model" id="modelSelect" onChange={handleModelIdChange}>
@@ -171,10 +204,6 @@ const ChatPanel = (item) => {
171204
))}
172205
</select>
173206
</FormField> */}
174-
175-
<Button variant="primary" onClick={handlePromptSubmit}>
176-
Send
177-
</Button>
178207
</Container>
179208
</SpaceBetween>
180209
</div>

src/ui/src/graphql/queries/chatWithDocument.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import gql from 'graphql-tag';
44

55
export default gql`
6-
query Query($s3Uri: String!, $prompt: String!, $modelId: String!) {
7-
chatWithDocument(s3Uri: $s3Uri, prompt: $prompt, modelId: $modelId)
6+
query Query($s3Uri: String!, $prompt: String!, $history: AWSJSON!, $modelId: String!) {
7+
chatWithDocument(s3Uri: $s3Uri, prompt: $prompt, history: $history, modelId: $modelId)
88
}
99
`;

template.yaml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5725,11 +5725,14 @@ Resources:
57255725
Variables:
57265726
LOG_LEVEL: !Ref LogLevel
57275727
OUTPUT_BUCKET: !Ref OutputBucket
5728+
CONFIGURATION_TABLE_NAME: !Ref ConfigurationTable
57285729
LoggingConfig:
57295730
LogGroup: !Ref ChatWithDocumentResolverFunctionLogGroup
57305731
Policies:
57315732
- S3ReadPolicy:
57325733
BucketName: !Ref OutputBucket
5734+
- DynamoDBCrudPolicy:
5735+
TableName: !Ref ConfigurationTable
57335736
- Statement:
57345737
- !If
57355738
- ShouldUseDocumentKnowledgeBase

0 commit comments

Comments
 (0)