Trying to invoke the API with the following parameters. This python API will try to check for grammar errors and display the same in provided JSON format
Input prompt:
http://13.215.182.149:7001/api/correct-grammar?data =
{
‘text’: ‘Travelling cross-country in India offers a vibrant mosaic of cultures, climates and landscapes. From the soaring Himalayas in the North, where majestic mountains rise to the sunny beaches in the South, the diversity amaze. The bustling cities pulse with with energy, while serene villages echo tradition. Temples, palaces, and bustling markets dot the land, showcasing it rich heritage. Sampling aromatic spices and indulging in local cuisines heightens the experience. Despite challenges, navigating India vastness, the warmth of its people and the kaleidoscope of experiences promises an unforgettable journey, leaving impressions that lasts a lifetime.’}
headers = {‘Content Type’: ‘application/json’}
Error from log file:
-
werkzeug.exceptions.UnsupportedMediaType: 415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not ‘application/json’.
-
WARNING! messages is not default parameter.
messages was transferred to model_kwargs.
Please confirm that messages is what you intended.
Below is the python code to generate the output in the provided json format
from flask import Flask, jsonify, request
from dotenv import load_dotenv
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
import os
from cryptography.fernet import Fernet
from logging.handlers import RotatingFileHandler
import logging
import json
import csv
import pprint
def load_key_from_file(filename):
return open(filename, ‘rb’).read()
def decrypt_text(encrypted_text, key_filename):
original_key = load_key_from_file(key_filename)
cipher_suite = Fernet(original_key)
decrypted_text = cipher_suite.decrypt(encrypted_text)
return decrypted_text
encrypted_filename = ‘encrypted_pythonkey.dat’
key_filename = ‘secret_key.key’
encrypted_text = open(encrypted_filename, ‘rb’).read()
decrypted_text = decrypt_text(encrypted_text, key_filename)
load_dotenv()
secret_keyfile = decrypted_text.decode(“utf-8”)
openai_api_key = os.getenv(‘OPENAI_API_KEY’, decrypted_text.decode(“utf-8”).strip())
model_kwargs = {
‘openai_api_key’: openai_api_key
}
function = {
“name”: “grammar_check”,
“description”: “A function that takes in the user input text and highlights the grammatical errors”,
“parameters”: {
“type”: “object”,
“properties”: {
“value”: {
“type”: “string”,
“description”: “this field specifies the grammatically errored word”
},
“phrase”: {
“type”: “string”,
“description”: “this field specifies the complete phrase including the grammatically errored word”
},
“corrective_text”: {
“type”: “string”,
“description”: “this field specifies the corrective replacement text for the errored word”,
},
“corrective_text_phrase”: {
“type”: “string”,
“description”: “this field specifies the complete phrase including the corrective replacement text”,
},
“type_of_error”: {
“type”: “string”,
“description”: “this field specifies the type of error found (such as spelling, punctuation, grammatical)”,
},
“justification”: {
“type”: “string”,
“description”: “this field specifies the the justification for the corrective changes made)”,
}
}
},
“required”: [“value”, “phrase”, “corrective_text”, “corrective_text_phrase”, “type_of_error”, “justification”],
}
messages = [
{“role”: “system”, “content”: “You are a grammar checking tool, please highlight the grammatical errors and extract the relevant data to use as arguments to pass into the given function provided”},
{‘role’: ‘user’, ‘content’: “Please highlight the grammatical errors”}
]
chat_openai = ChatOpenAI(model_name=“gpt-3.5-turbo-0613”,
openai_api_key=openai_api_key,
messages=messages,
functions=[function],
model_kwargs={“function_call”: {“name”: “grammar_check”}}
)
Setting up logging
log_formatter = logging.Formatter(“%(asctime)s [%(levelname)s] - %(message)s”)
file_handler = RotatingFileHandler(‘app.log’, maxBytes=100000, backupCount=5)
file_handler.setFormatter(log_formatter)
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
root_logger.addHandler(file_handler)
app = Flask(name)
@app.route(‘/api/<api_name>’, methods=[‘GET’])
def resolve_api(api_name):
try:
allowed_apis = [‘correct-grammar’]
if api_name not in allowed_apis:
return jsonify({“error”: f"Invalid API route. Allowed routes: {', '.join(allowed_apis)}"}), 400
data = request.json
text = data.get('text')
response = chat_openai.submit_request({"text": text})
content = response["choices"][0]["message"]["function_call"]["arguments"]
content_json = json.loads(content)
return jsonify(content_json)
except Exception as e:
# Log any exceptions
root_logger.exception("An error occurred: %s", e)
return jsonify({"error": "An error occurred while processing the request."}), 500
if name == ‘main’:
app.run(debug=True, host=‘0.0.0.0’, port=7001)