Skip to content

Instantly share code, notes, and snippets.

@daanalytics
Created November 16, 2023 15:39
Show Gist options
  • Save daanalytics/8884ca84fcc7a6f126b6106dc5284714 to your computer and use it in GitHub Desktop.
Save daanalytics/8884ca84fcc7a6f126b6106dc5284714 to your computer and use it in GitHub Desktop.
-/ Create the Get OpenAI Response UDF
--/ Create the UDF
CREATE OR REPLACE FUNCTION get_openai_response(prompt_output text, ai_model_engine text)
RETURNS STRING
LANGUAGE PYTHON
RUNTIME_VERSION = 3.8
HANDLER = 'return_openai_response'
EXTERNAL_ACCESS_INTEGRATIONS = (openai_external_access_integration)
PACKAGES = ('openai')
SECRETS = ('secret' = open_ai_secret)
AS
$$
# Use this function to generate a ChatGPT response
# 1. Submit the prompt_output to the OpenAI API
# 2. Return the chat response
import openai
import _snowflake
openai.api_key = _snowflake.get_generic_secret_string('secret')
def return_openai_response(prompt_output, ai_model_engine):
# This endpoint might change depending on OpenAI's updates
endpoint = "https://api.openai.com/v1/chat/completions"
headers = {
"Authorization": f"Bearer + openai.api_key",
"Content-Type": "application/json",
}
# ChatCompletion OpenAI Library
chat_completion = openai.ChatCompletion.create(
model=ai_model_engine,
messages=[
{"role": "system", "content": "You are a community manager, skilled in writing informative blogposts about the subject area of Data & AI in general and the Snowflake Data Cloud in specific."},
{"role": "user", "content": prompt_output}
]
)
openai_response = chat_completion['choices'][0]['message']['content']
return openai_response
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment