SET openai.api_key = 'your_api_key_here';
SET openai.api_uri = 'https://api.openai.com/v1/';
SET openai.prompt_model = 'gpt-4o-mini';
SET openai.embedding_model = 'text-embedding-3-small';
SET openai.api_uri = 'http://127.0.0.1:11434/v1/';
SET openai.api_key = 'none';
SET openai.prompt_model = 'llama3.1:latest';
SET openai.embedding_model = 'mxbai-embed-large';
SELECT * FROM openai.models();
id | object | created | owned_by
--------------------------+--------+---------------------+----------
mxbai-embed-large:latest | model | 2024-11-04 20:48:39 | library
llama3.1:latest | model | 2024-07-25 22:45:02 | library
CREATE TABLE feedback (
feedback text, -- freeform comments from the customer
sentiment text -- positive/neutral/negative from the LLM
);
--
-- Step 1: Create the trigger function
--
CREATE OR REPLACE FUNCTION analyze_sentiment() RETURNS TRIGGER AS $$
DECLARE
response TEXT;
BEGIN
-- Use openai.prompt to classify the sentiment as positive, neutral, or negative
response := openai.prompt(
'You are an advanced sentiment analysis model. Read the given feedback text carefully and classify it as one of the following sentiments only: "positive", "neutral", or "negative". Respond with exactly one of these words and no others, using lowercase and no punctuation',
NEW.feedback
);
-- Set the sentiment field based on the model's response
NEW.sentiment := response;
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
--
-- Step 2: Create the trigger to execute the function before each INSERT or UPDATE
--
CREATE TRIGGER set_sentiment
BEFORE INSERT OR UPDATE ON feedback
FOR EACH ROW
EXECUTE FUNCTION analyze_sentiment();
INSERT INTO feedback (feedback)
VALUES
('The food was not well cooked and the service was slow.'),
('I loved the bisque but the flan was a little too mushy.'),
('This was a wonderful dining experience, and I would come again,
even though there was a spider in the bathroom.');
SELECT * FROM feedback;
-[ RECORD 1 ]-----------------------------------------------------
feedback | The food was not well cooked and the service was slow.
sentiment | negative
-[ RECORD 2 ]-----------------------------------------------------
feedback | I loved the bisque but the flan was a little too mushy.
sentiment | positive
-[ RECORD 3 ]-----------------------------------------------------
feedback | This was a wonderful dining experience, and I would
come again, even though there was a spider in
the bathroom.
sentiment | positive