Back

throwing exception when calling AI from Appwrite Function

  • 0
  • Self Hosted
  • Flutter
ZiaChoudhary
6 Oct, 2024, 16:56

Appwrite function is throwing a n exception when I am trying to call Open AI API. Exception: Connection error.

My appwritre version is 1.6.0 Function runtime is Python 3.10 running in Ubuntu 22.04 server

Note: I have tested same code in my local machine and server (without appwrite) it worked as expexted. But in Appwrite, function detects the incoming request, gets required environment variables and it only fails when it tries to call AI API.

Here is my code: main.py:

TypeScript
from langchain_openai import ChatOpenAI
from .utils import throw_if_missing
import os


def main(context):
    throw_if_missing(os.environ, ["OPENAI_API_KEY"])
    context.log("Received request and checking method")
    context.log(f"Prompt: {context.req.body['prompt']}")
    key = os.environ["OPENAI_API_KEY"]
    try:
        throw_if_missing(context.req.body, ["prompt"])
    except ValueError as err:
        context.log(f"Missing required fields: {err}")
        context.log(context.req.body)
        return context.res.json({"ok": False, "error": err.message}, 400)
    context.log(f"Prompt: {context.req.body['prompt']}")
    try:
        context.log("Querying model")
        model = ChatOpenAI(model="gpt-4o-mini",api_key=key)
        response = model.invoke("What is 81 divided by 9?")
        context.log("Model queried successfully")
        context.log(response)
        return context.res.json({"ok": True, "completion": response}, 200)

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

utils.py:

TypeScript
import os

__dirname = os.path.dirname(os.path.abspath(__file__))
static_folder = os.path.join(__dirname, "../static")

def throw_if_missing(obj: object, keys: list[str]) -> None:
    
    missing = [key for key in keys if key not in obj or not obj[key]]
    if missing:
        raise ValueError(f"Missing required fields: {', '.join(missing)}")
TL;DR
Developers are encountering a connection error when attempting to call an Open AI API from an Appwrite function. Testing the code locally and on the server without Appwrite showed it functioning correctly. The issue occurs only when interacting with the AI API in the Appwrite environment. The provided code includes error handling for missing fields. The error is likely due to Appwrite not interacting properly with the AI API call.
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more