Create index.html with js to interact with flask backend, add claude route in the server

This commit is contained in:
Joseph Ferano 2024-11-18 12:18:40 +07:00
parent 5c585e0396
commit c731541d7f
3 changed files with 56 additions and 6 deletions

BIN
favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

31
index.html Normal file
View File

@ -0,0 +1,31 @@
<!DOCTYPE html>
<html>
<head>
<title>Text Input Example</title>
</head>
<body>
<textarea id="textInput" rows="10" cols="50"></textarea>
<textarea id="responseText" rows="30" cols="50"></textarea>
<br>
<button onclick="processText()">Process Text</button>
<script>
function processText() {
var textInput = document.getElementById("textInput").value;
fetch('http://localhost:5000/ask-claude', {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
body: textInput
})
.then(response => response.text())
.then(text => {
var textInput = document.getElementById("responseText");
textInput.value = text;
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>

31
main.py
View File

@ -3,16 +3,35 @@ import os
import time import time
from anthropic import Anthropic from anthropic import Anthropic
from flask import Flask, request, redirect, session, url_for from flask import Flask, request, redirect, session, url_for
from flask_cors import CORS
from dotenv import load_dotenv, find_dotenv from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv()) load_dotenv(find_dotenv())
app = Flask(__name__) client = Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY"),
)
@app.route('/') app = Flask(__name__)
def hello(): CORS(app)
return 'Hello, World!'
@app.route('/ask-claude', methods=['POST'])
def ask_claude():
user_text = request.get_data(as_text=True)
message = client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": user_text,
}
],
model="claude-3-5-haiku-latest",
)
response_text = ""
for t in message.content:
response_text += t.text
return response_text
if __name__ == '__main__': if __name__ == '__main__':
print(os.environ.get("ANTHROPIC_API_KEY")) app.run()
# app.run()