create or replace function fnc_26ai_rag_agro (p_ai_prompt IN clob, 
                                    p_oci_cred IN VARCHAR2,
                                    p_id in number,
                                    p_comp_id in varchar2) 
return clob 
as

/*

  Criado por: fernando.leal@oracle.com
  Data: Oct/2025
  Objetivo: demonstrar casos de uso do Oracle AI Database 26ai

  v1 - funcao de RAG para AGRO - leal

*/
														 
    -- modelos: https://docs.oracle.com/en-us/iaas/Content/generative-ai/pretrained-models.htm
    -- cuidado com pre requisito (1)
    gen_ai_endpoint varchar2(500) := 'https://inference.generativeai.us-chicago-1.oci.oraclecloud.com';
    gen_ai_model varchar2(500) := 'meta.llama-4-maverick-17b-128e-instruct-fp8';  

    chat_resp dbms_cloud_types.RESP;
    image_resp dbms_cloud_types.RESP;    

    base64_image CLOB := NULL;
    request_json_part1 CLOB;
    request_json_part2 CLOB;
    request_body BLOB;
    v_ext varchar2(20);

BEGIN
    -- create temp blobs
    dbms_lob.createtemporary(request_body, FALSE);

	select APEX_WEB_SERVICE.BLOB2CLOBBASE64( FILE_BLOB ,'N','N' ) ,
           lower(regexp_replace(file_name, '.*\.([a-zA-Z0-9]+)$', '\1')) 
	  into  base64_image, v_ext  
	  from TB_26AI_AGRO
	 where id = p_id;

    request_json_part1 := to_clob(
     '{
        "compartmentId": "' || p_comp_id || '",
        "servingMode": 
            {
                "modelId": "' || gen_ai_model || '",
				"servingType": "ON_DEMAND"
            }
        ,
        "chatRequest": {
            "apiFormat": "GENERIC",	
            "messages": [
                {
                    "role": "USER",				
					"content": [
						{
							"type": "TEXT",
							"text": "' ||  replace(replace(replace(replace(  p_ai_prompt  ,chr(10),null),chr(13),null),'"',''),'''','')  || '"
						},
						{
							"type": "IMAGE",
                            "imageUrl": {
                                "url": "data:image/' || v_ext || ';base64,');

    request_json_part2 := to_clob('"
                            }    
						}                        
					]
                }
            ],
            "temperature":      0.4,
            "numGenerations":    5,
            "topK":              1
        }
    }');

    -- append part1 json to request blob
    dbms_lob.append(request_body, apex_util.clob_to_blob(p_clob => request_json_part1,p_charset => 'AL32UTF8'));

    -- append  base64 image to request blob
    dbms_lob.append(request_body, apex_util.clob_to_blob(p_clob => base64_image,p_charset => 'AL32UTF8'));

    -- append part2 json to request blob
    dbms_lob.append(request_body, apex_util.clob_to_blob(p_clob => request_json_part2,p_charset => 'AL32UTF8'));

    -- call Gen AI Chat    
    chat_resp := dbms_cloud.send_request(
       credential_name => p_oci_cred,
        uri => gen_ai_endpoint || '/20231130/actions/chat',
        method => dbms_cloud.METHOD_POST,
        body => request_body
    );

    -- clear temp blobs
    dbms_lob.freetemporary(request_body);

    RETURN  json_value( dbms_cloud.get_response_text(chat_resp),'$.chatResponse.choices[0].message.content[0].text')     ;
END;
/