UNPKG

genosdb

Version:

GenosDB (GDB): distributed graph database in real-time, peer-to-peer, scalable storage - efficient querying of complex relationships.

22 lines (17 loc) 2.41 kB
function j(u){const $=u.map;return u.map=async function(...f){let h={},b=null;if(f.forEach((Y)=>{if(typeof Y==="object")h={...h,...Y};if(typeof Y==="function")b=Y}),h.prompt)try{const Y=await v(h.prompt);console.log("Query generated from AI:",Y),h={...h,...Y},delete h.prompt}catch(Y){console.error("Error generating query from AI:",Y.message),h.query={}}return $.call(this,h,b)},u}async function v(u){const $=` You are an assistant that converts natural language instructions into a structured MongoDB query object. Rules: - Output ONLY a valid JSON object with the fields: "query", "order", and "field". - Use MongoDB operators such as "\$between", "\$gt", "\$lt". - For ranges, use "\$between": [min, max]. - For sorting, use "order": "asc" or "desc" and specify the "field". - "\$edge" operator: allows chaining queries to related/descendant entities. - No extra text, no explanations, no formatting besides the JSON. Examples: Input: "Find people aged 10 to 20 and sort them by age descending" Output: {"query": {"age": {"\$between": [10, 20]}}, "order": "desc", "field": "age"} Input: "Find a Company, then find a Developer descendant, then find that Developer's descendant named Bob." Output: {"query": {"type":"Company", "\$edge": {"role":"Developer", "\$edge": {"name":"Bob"}}}} Instruction: "${u}" `;try{const f=await w($);if(f&&typeof f==="object"&&f.query)return{query:f.query,order:f.order||"asc",field:f.field||Object.keys(f.query)[0]};throw new Error("Invalid AI response format")}catch(f){return console.warn("Using empty query due to AI error:",f.message),{query:{}}}}async function w(u){try{const f=await fetch("https://text.pollinations.ai/",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:[{role:"system",content:"You are an assistant specialized in converting natural language to structured queries."},{role:"user",content:u}],model:"openai",seed:Math.floor(Math.random()*1000),jsonMode:!0})});if(!f.ok)throw new Error(`Pollinations API error: ${f.statusText}`);const h=await f.json();try{return typeof h==="string"?JSON.parse(h):h}catch{return h}}catch($){throw console.error("Error processing prompt with API:",$.message),$}}var x=(u)=>{return console.log("\uD83E\uDDE0 AI: AIQuery module loaded."),j(u)};export{j as withModule,x as init};