appwrite / templates

Templates for Appwrite Functions ⚑️🌩️
https://appwrite.io
MIT License
121 stars 87 forks source link

Python Prompt-chatgpt templateπŸ› Bug Report: #297

Open sonicviz opened 3 months ago

sonicviz commented 3 months ago

πŸ‘Ÿ Reproduction steps

https://github.com/appwrite/templates/tree/main/python/prompt_chatgpt Fails to run from the included static HTML test interface. Always returns "Failed to query model."

πŸ‘ Expected behavior

It should work?

πŸ‘Ž Actual Behavior

Always returns "Failed to query model." No errors as there was no logging.

So I debugged it according to the latest OpenAI library https://github.com/openai/openai-python/tree/main It appears the OpenAI calls have changed.

Debugged and working version is below, with logging. Suggest including sample logging in any templates to make it easier to debug and also helps users not so familiar with python upskill faster. File: src\main.py

` import os from openai import OpenAI from .utils import get_static_file, throw_if_missing

def main(context): throw_if_missing(os.environ, ["OPENAI_API_KEY"])

if context.req.method == "GET":
    return context.res.send(
        get_static_file("index.html"),
        200,
        {
            "content-type": "text/html; charset=utf-8"
        },
    )

context.log(context.req.body)

try:
    throw_if_missing(context.req.body, ["prompt"])
except ValueError as err:
    return context.res.json({"ok": False, "error": err.message}, 400)

# openai.api_key = os.environ["OPENAI_API_KEY"]

client = OpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)       

context.log("OPENAI_API_KEY" + os.environ["OPENAI_API_KEY"])
context.log("OPENAI_MAX_TOKENS" + os.environ["OPENAI_MAX_TOKENS"])

try:
    # response = openai.ChatCompletion.create(
    #     model="gpt-3.5-turbo",
    #     max_tokens=int(os.environ.get("OPENAI_MAX_TOKENS", "512")),
    #     messages=[{"role": "user", "content": context.req.body["prompt"]}],
    # )
    response = client.chat.completions.create(
        model="gpt-4o",
        max_tokens=int(os.environ.get("OPENAI_MAX_TOKENS", "512")),
        messages=[{"role": "user", "content": context.req.body["prompt"]}],
    )
    context.log(response)
    completion = response.choices[0].message.content
    return context.res.json({"ok": True, "completion": completion}, 200)

except Exception:
    return context.res.json({"ok": False, "error": "Failed to query model."}, 500)

`

🎲 Appwrite version

Appwrite Cloud

πŸ’» Operating system

Windows

🧱 Your Environment

No response

πŸ‘€ Have you spent some time to check if this issue has been raised before?

🏒 Have you read the Code of Conduct?

loks0n commented 3 months ago

Thanks for the report! πŸ™

Feel free to pick this up and open a PR if you are interested.