Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@deep-foundation/chatgpt-azure

Package Overview
Dependencies
Maintainers
14
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@deep-foundation/chatgpt-azure - npm Package Compare versions

Comparing version 2.3.1 to 2.3.2

170

deep.json
{
"package": {
"name": "@deep-foundation/chatgpt-azure",
"version": "2.3.1"
"version": "2.3.2"
},

@@ -10,3 +10,3 @@ "data": [

"dependencyId": 0,
"containValue": "Type"
"containValue": "SyncTextFile"
},

@@ -17,4 +17,4 @@ "id": 1

"package": {
"dependencyId": 1,
"containValue": "Reply"
"dependencyId": 0,
"containValue": "Type"
},

@@ -26,3 +26,3 @@ "id": 2

"dependencyId": 1,
"containValue": "Message"
"containValue": "Model"
},

@@ -34,3 +34,3 @@ "id": 3

"dependencyId": 0,
"containValue": "Any"
"containValue": "Value"
},

@@ -42,3 +42,3 @@ "id": 4

"dependencyId": 0,
"containValue": "TreeIncludeUp"
"containValue": "String"
},

@@ -49,4 +49,4 @@ "id": 5

"package": {
"dependencyId": 1,
"containValue": "messagingTree"
"dependencyId": 2,
"containValue": "Message"
},

@@ -57,4 +57,4 @@ "id": 6

"package": {
"dependencyId": 2,
"containValue": "TSX"
"dependencyId": 0,
"containValue": "Any"
},

@@ -65,4 +65,4 @@ "id": 7

"package": {
"dependencyId": 0,
"containValue": "Handler"
"dependencyId": 2,
"containValue": "Reply"
},

@@ -74,3 +74,3 @@ "id": 8

"dependencyId": 0,
"containValue": "clientSupportsJs"
"containValue": "TreeIncludeUp"
},

@@ -81,4 +81,4 @@ "id": 9

"package": {
"dependencyId": 0,
"containValue": "HandleClient"
"dependencyId": 2,
"containValue": "messagingTree"
},

@@ -90,3 +90,3 @@ "id": 10

"dependencyId": 3,
"containValue": "Dependency"
"containValue": "TSX"
},

@@ -97,4 +97,4 @@ "id": 11

"package": {
"dependencyId": 4,
"containValue": "DependencyRoot"
"dependencyId": 0,
"containValue": "Handler"
},

@@ -106,3 +106,3 @@ "id": 12

"dependencyId": 0,
"containValue": "SyncTextFile"
"containValue": "clientSupportsJs"
},

@@ -114,3 +114,3 @@ "id": 13

"dependencyId": 0,
"containValue": "dockerSupportsJs"
"containValue": "HandleClient"
},

@@ -122,3 +122,3 @@ "id": 14

"dependencyId": 0,
"containValue": "HandleInsert"
"containValue": "dockerSupportsJs"
},

@@ -130,3 +130,3 @@ "id": 15

"dependencyId": 0,
"containValue": "Value"
"containValue": "HandleInsert"
},

@@ -137,4 +137,4 @@ "id": 16

"package": {
"dependencyId": 0,
"containValue": "String"
"dependencyId": 4,
"containValue": "Dependency"
},

@@ -146,3 +146,3 @@ "id": 17

"dependencyId": 5,
"containValue": "Model"
"containValue": "DependencyRoot"
},

@@ -152,30 +152,63 @@ "id": 18

{
"id": "replyInsertHandlerCode",
"type": 1,
"value": {
"value": "async ({ data: { newLink: replyLink, triggeredByLinkId }, deep, require }) => {\n console.log({triggeredByLinkId})\n const startTime = Date.now();\n const PACKAGE_NAME = `@deep-foundation/chatgpt-azure`;\n const axios = require('axios');\n\n const { Configuration, OpenAIApi } = require('openai');\n const chatGPTTypeLinkId = await deep.id(PACKAGE_NAME, 'ChatGPT');\n const conversationTypeLinkId = await deep.id(PACKAGE_NAME, 'Conversation');\n const apiKeyTypeLinkId = await deep.id('@deep-foundation/openai', 'ApiKey');\n const usesApiKeyTypeLinkId = await deep.id('@deep-foundation/openai', 'UsesApiKey');\n const modelTypeLinkId = await deep.id('@deep-foundation/openai', 'Model');\n const usesModelTypeLinkId = await deep.id('@deep-foundation/openai', 'UsesModel');\n const messageTypeLinkId = await deep.id('@deep-foundation/messaging', 'Message');\n const replyTypeLinkId = await deep.id('@deep-foundation/chatgpt-azure', 'Reply');\n const authorTypeLinkId = await deep.id('@deep-foundation/messaging', 'Author');\n const containTypeLinkId = await deep.id('@deep-foundation/core', 'Contain');\n const messagingTreeId = await deep.id('@deep-foundation/messaging', 'messagingTree');\n const systemTypeLinkId = await deep.id('@deep-foundation/chatgpt-azure', 'System');\n const tokensTypeLinkId = await deep.id(\"@deep-foundation/tokens\", \"Tokens\")\n const providedByTypeLinkId = await deep.id(\"@deep-foundation/chatgpt-azure\", \"ProvidedBy\")\n const reservedIds = await deep.reserve(1);\n const chatGPTMessageLinkId = reservedIds.pop();\n let systemMessageId;\n let model;\n let systemMessage;\n await deep.await(replyLink.from_id)\n const { data: [messageLink] } = await deep.select({\n id: replyLink.from_id,\n _not: {\n out: {\n to_id: chatGPTTypeLinkId,\n type_id: authorTypeLinkId,\n },\n },\n });\n if (!messageLink) {\n return 'No need to react to message of this reply.';\n }\n if (!messageLink.value?.value) {\n throw new Error(`Message ##${messageLink.id} must have a value`);\n }\n const message = messageLink.value.value;\n\n const apiKeyLink = await getTokenLink();\n const apiKey = apiKeyLink.value.value;\n const configuration = new Configuration({\n apiKey: apiKey,\n });\n const openai = new OpenAIApi(configuration);\n\n const { data: conversationLink } = await deep.select({\n tree_id: { _eq: messagingTreeId },\n parent: { type_id: { _in: [conversationTypeLinkId, messageTypeLinkId] } },\n link: { id: { _eq: replyLink.from_id } },\n }, {\n table: 'tree',\n variables: { order_by: { depth: \"asc\" } },\n returning: `\n id\n depth\n root_id\n parent_id\n link_id\n parent {\n id\n from_id\n type_id\n to_id\n value\n author: out (where: { type_id: { _eq: ${authorTypeLinkId}} }) { \n id\n from_id\n type_id\n to_id\n }\n tokens: out (where: { type_id: { _eq: ${tokensTypeLinkId}} }) { \n id\n from_id\n type_id\n to_id\n value\n }\n }`\n })\n if (!conversationLink) {\n throw new Error('A conversationLink link is not found');\n }\n const currentConversation = conversationLink.find(\n (link) => link.parent.type_id === conversationTypeLinkId\n );\n\n conversationLink.forEach((link) => {\n if (link.parent.author && link.parent.author.length > 0) {\n link.parent.author = link.parent.author[0];\n }\n });\n\n const {\n data: [linkedModel],\n } = await deep.select({\n type_id: modelTypeLinkId,\n in: {\n type_id: usesModelTypeLinkId,\n from_id: currentConversation.parent.id,\n },\n });\n\n\n const usedModelSelectData = {\n type_id: modelTypeLinkId,\n in: {\n type_id: usesModelTypeLinkId,\n from_id: triggeredByLinkId,\n },\n }\n const {\n data: [userLinkedModel],\n } = await deep.select(usedModelSelectData, {\n returning: `\n id\n value\n in(where: { type_id: { _eq: ${usesModelTypeLinkId} } }) {\n id\n type_id\n from_id\n to_id\n value\n }\n tokens: out(where: { type_id: { _eq: ${tokensTypeLinkId} } }) {\n id\n from_id\n to_id\n value\n }\n endpointLink: out(where: { type_id: { _eq: ${providedByTypeLinkId} } }) {\n id\n from_id\n to_id\n endpoint: to {\n id\n value\n }\n }\n `\n }); \n if(!userLinkedModel) {\n throw new Error(`Failed to find used model. Select data: ${JSON.stringify(usedModelSelectData, null, 2)}`)\n }\n let MAX_TOKENS\n console.log({userLinkedModel})\n if (!userLinkedModel.tokens?.[0]?.value?.value) {\n throw new Error(\"Token limit for the model is not specified.\");\n } else if (userLinkedModel.tokens?.[0]?.value?.value) {\n MAX_TOKENS = userLinkedModel.tokens[0].value.value;\n }\n\n if (!userLinkedModel.endpointLink?.[0]?.endpoint?.value?.value) {\n throw new Error(\"Endpoint for the model is not specified.\");\n }\n const API_ENDPOINT = userLinkedModel.endpointLink[0].endpoint.value?.value;\n\n if (!linkedModel && !userLinkedModel) {\n throw new Error(\"Before using azure-GPT, create a model, tokens, and an endpoint links.\");\n } else if (\n (linkedModel &&\n linkedModel.value?.value &&\n userLinkedModel &&\n userLinkedModel.value?.value) ||\n (linkedModel && linkedModel.value?.value)\n ) {\n model = linkedModel.value.value;\n } else {\n if (!userLinkedModel) {\n throw new Error(`A link with type ##${userLinkedModel} is not found`);\n }\n if (!userLinkedModel.value?.value) {\n throw new Error(`Linked model with user ##${userLinkedModel.id} must have a value`);\n } else {\n model = userLinkedModel.value.value;\n }\n }\n const messageLinks = conversationLink\n .map(item => item.parent)\n .filter(link => link && link.type_id === messageTypeLinkId);\n let allMessages = await getMessages({ messageLinks });\n const messagesToSend = [...allMessages];\n\n const { data: userLinkedSystemMessageLinks } = await deep.select({\n type_id: systemTypeLinkId,\n to_id: triggeredByLinkId,\n }, { returning: `id message: from{ id value} conversation:to{id}` });\n\n const { data: conversationLinkedSystemMessageLink } = await deep.select({\n type_id: systemTypeLinkId,\n to_id: currentConversation.parent.id,\n }, { returning: `id message: from{ id value} conversation:to{id}` });\n\n if (conversationLinkedSystemMessageLink && conversationLinkedSystemMessageLink.length > 0) {\n const systemMessageLink = conversationLinkedSystemMessageLink[0];\n if (!systemMessageLink.message?.value?.value) {\n throw new Error(`System message with link to conversation ##${systemMessageLink.id} must have a value`);\n } else {\n systemMessage = systemMessageLink.message.value.value;\n systemMessageId = systemMessageLink.message;\n await deep.await(systemMessageId.id)\n\n }\n } else if (userLinkedSystemMessageLinks && userLinkedSystemMessageLinks.length > 0) {\n if (userLinkedSystemMessageLinks.length > 1) {\n throw new Error(\"Multiple system messages linked to the user are found\");\n }\n\n const userLinkedSystemMessageLink = userLinkedSystemMessageLinks[0];\n\n if (!userLinkedSystemMessageLink.message?.value?.value) {\n throw new Error(`System message with link to user ##${userLinkedSystemMessageLink.id} must have a value`);\n } else {\n systemMessage = userLinkedSystemMessageLink.message.value.value;\n systemMessageId = userLinkedSystemMessageLink.message;\n await deep.await(systemMessageId.id)\n }\n }\n\n if (systemMessage) {\n const { data: tokensLinkedToSystemMessage } = await deep.select({\n type_id: tokensTypeLinkId,\n from_id: systemMessageId.id,\n to_id: systemMessageId.id,\n });\n if (!tokensLinkedToSystemMessage[0]?.value?.value) {\n throw new Error(`System message does not contain tokens`);\n } else if (tokensLinkedToSystemMessage[0]?.value?.value) {\n let tokenCount = tokensLinkedToSystemMessage[0].value?.value;\n messagesToSend.unshift({\n role: \"system\",\n content: systemMessage,\n tokens: tokenCount,\n });\n }\n }\n\n const tokenLimit = MAX_TOKENS * 7 / 8;\n let totalTokens = 0;\n let messagesToSendToOpenAI = [];\n\n for (let i = messagesToSend.length - 1; i >= 0; i--) {\n const message = messagesToSend[i];\n\n console.log({message})\n if (message.role === 'system' || totalTokens + message.tokens <= tokenLimit) {\n messagesToSendToOpenAI.unshift({ role: message.role, content: message.content });\n totalTokens += message.tokens;\n } else {\n break;\n }\n }\n let response;\n\n try {\n response = await axios.post(API_ENDPOINT, {\n messages: [...messagesToSendToOpenAI]\n }, {\n headers: {\n 'Content-Type': 'application/json',\n 'api-key': apiKey\n }\n });\n } catch (error) {\n console.error('Error making API call:', error.response ? error.response.data : error.message);\n }\n\n const content = response.data.choices[0]?.message?.content;\n\n await deep.serial({\n operations: [\n {\n table: 'links',\n type: 'insert',\n objects: {\n id: chatGPTMessageLinkId,\n type_id: messageTypeLinkId,\n out: {\n data: [\n {\n type_id: authorTypeLinkId,\n to_id: chatGPTTypeLinkId,\n },\n ],\n },\n },\n },\n {\n table: 'strings',\n type: 'insert',\n objects: {\n link_id: chatGPTMessageLinkId,\n value: content\n }\n },\n {\n table: 'links',\n type: 'insert',\n objects: {\n type_id: replyTypeLinkId,\n from_id: chatGPTMessageLinkId,\n to_id: replyLink.from_id,\n },\n },\n ],\n });\n\n async function getMessages({ messageLinks }) {\n return Promise.all(\n messageLinks.map(async (link) => {\n const tokens = link.tokens?.length > 0 ? link.tokens[0].value.value : undefined;\n return {\n role: await getMessageRole({ messageLink: link }),\n content: link.value.value,\n tokens: tokens,\n }\n })\n );\n }\n\n async function getMessageRole({ messageLink }) {\n const authorLink = messageLink.author;\n if (!authorLink) {\n throw new Error(`Author link not found for message ##${messageLink.id}`);\n }\n return authorLink.to_id === chatGPTTypeLinkId ? 'assistant' : 'user';\n }\n\n async function getTokenLink() {\n let resultTokenLink;\n const { data } = await deep.select({\n _or: [\n {\n type_id: apiKeyTypeLinkId,\n in: {\n type_id: containTypeLinkId,\n from_id: triggeredByLinkId,\n },\n },\n {\n from_id: triggeredByLinkId,\n type_id: usesApiKeyTypeLinkId,\n },\n {\n type_id: apiKeyTypeLinkId,\n in: {\n from_id: triggeredByLinkId,\n type_id: usesApiKeyTypeLinkId,\n },\n },\n ],\n })\n console.log(\"FREEPHOENIX888.getTokenLink\", {data})\n if (data.length === 0) {\n throw new Error(`ApiKey ##${apiKeyTypeLinkId} is not found`);\n }\n const usesLinks = data.filter(\n (link) => link.type_id === usesApiKeyTypeLinkId\n );\n if (usesLinks.length > 1) {\n throw new Error(\n `More than 1 links of type ##${usesApiKeyTypeLinkId} are found`\n );\n }\n const usesLink = data.find(\n (link) => link.type_id === usesApiKeyTypeLinkId\n );\n if (usesLink) {\n const tokenLink = data.find((link) => link.id === usesLink.to_id);\n if (!tokenLink) {\n throw new Error(`ApiKey ##${apiKeyTypeLinkId} is not found`);\n } else {\n resultTokenLink = tokenLink;\n }\n } else {\n const tokenLink = data.filter(\n (link) => link.type_id === apiKeyTypeLinkId\n );\n if (tokenLink.length > 1) {\n throw new Error(\n `For 2 or more ApiKey ##${apiKeyTypeLinkId} links you must activate it with usesOpenAiApiKey link`\n );\n } else {\n const tokenLink = data.find(\n (link) => link.type_id === apiKeyTypeLinkId\n );\n if (!tokenLink) {\n throw new Error(`ApiKey ##${apiKeyTypeLinkId} is not found`);\n }\n resultTokenLink = tokenLink;\n }\n }\n if (!resultTokenLink.value?.value) {\n throw new Error(`ApiKey ##${apiKeyTypeLinkId} has no value`);\n }\n return resultTokenLink;\n }\n\n const endTime = Date.now();\n const duration = (endTime - startTime) / 1000;\n return {\n request: {\n model: model,\n messages: [\n ...messagesToSendToOpenAI\n ],\n },\n response: response.data,\n duration: duration,\n totalTokens: totalTokens\n };\n};"
}
},
{
"id": "Endpoint",
"type": 1
"type": 2
},
{
"id": "ProvidedBy",
"type": 2,
"from": 3,
"to": "Endpoint"
},
{
"id": "endpointValue",
"type": 4,
"from": "Endpoint",
"to": 5
},
{
"id": "Manager",
"type": 1
"type": 2
},
{
"id": "Reply",
"id": "System",
"type": 2,
"from": 3,
"to": 4
"from": 6,
"to": 7
},
{
"id": "messagingTreeReply",
"type": 5,
"id": "ChatGPT",
"type": 2
},
{
"id": "Conversation",
"type": 2
},
{
"id": "conversationValue",
"type": 4,
"from": "Conversation",
"to": 5
},
{
"id": "Reply",
"type": 8,
"from": 6,
"to": "Reply"
"to": 7
},
{
"id": "System",
"type": 1,
"from": 3,
"to": 4
"id": "messagingTreeReply",
"type": 9,
"from": 10,
"to": "Reply"
},
{
"id": "managerClientHandlerCode",
"type": 7,
"type": 11,
"value": {

@@ -187,4 +220,4 @@ "value": "async ({ deep, require }) => {\n const React = await deep.import('react');\n const { useState, useMemo } = React;\n const MUI = await deep.import('@mui/material');\n console.log({ MUI })\n const { Box, ThemeProvider, createTheme, Button, Input, Select, InputAdornment, THEME_ID, Paper, Stack, TextField, FormControl, MenuItem, InputLabel, Popper, Typography, Link } = MUI;\n const MUIIcons = await deep.import('@mui/icons-material');\n\n\n return ({ fillSize, style, link }) => {\n\n const [ownerLinkId, setOwnerLinkId] = useState('');\n const [containerLinkId, setContainerLinkId] = useState('');\n\n\n const [apiKey, setApiKey] = useState('');\n\n const handleApiKeyChange = (event) => {\n setApiKey(event.target.value);\n };\n\n\n\n const handleOwnerLinkIdChange = (event) => {\n setOwnerLinkId(event.target.value);\n };\n\n const handleContainerLinkIdChange = (event) => {\n setContainerLinkId(event.target.value);\n };\n\n const [modelLinkId, setModelLinkId] = useState('');\n const handleModelLinkIdChange = (event) => {\n setModelLinkId(event.target.value);\n };\n\n\n\n\n const handleSubmit = async (event) => {\n event.preventDefault();\n console.log({ apiKey, selectedModel: modelLinkId, ownerLinkId, containerLinkId })\n const containTypeLinkId = await deep.id(\"@deep-foundation/core\", \"Contain\");\n const reservedLinkIds = await deep.reserve(6)\n const apiKeyLinkId = reservedLinkIds.pop();\n const containForApiKeyLinkId = reservedLinkIds.pop();\n const usesApiKeyLinkId = reservedLinkIds.pop();\n const containForUsesApiKeyLinkId = reservedLinkIds.pop();\n const usesModelLinkId = reservedLinkIds.pop();\n const containForUsesModelLinkId = reservedLinkIds.pop();\n\n await deep.serial({\n operations: [\n {\n type: 'insert',\n table: 'links',\n objects: {\n id: apiKeyLinkId,\n type_id: await deep.id(\"@deep-foundation/openai\", \"ApiKey\"),\n }\n },\n {\n type: 'insert',\n table: 'strings',\n objects: {\n link_id: apiKeyLinkId,\n value: apiKey\n }\n },\n {\n type: 'insert',\n table: 'links',\n objects: {\n id: containForApiKeyLinkId,\n type_id: containTypeLinkId,\n from_id: containerLinkId,\n to_id: apiKeyLinkId\n }\n },\n {\n type: 'insert',\n table: 'links',\n objects: {\n id: usesApiKeyLinkId,\n type_id: await deep.id(\"@deep-foundation/openai\", \"UsesApiKey\"),\n from_id: ownerLinkId,\n to_id: apiKeyLinkId\n }\n },\n {\n type: 'insert',\n table: 'links',\n objects: {\n id: containForUsesApiKeyLinkId,\n type_id: containTypeLinkId,\n from_id: containerLinkId,\n to_id: usesApiKeyLinkId\n }\n },\n {\n type: 'insert',\n table: 'links',\n objects: {\n id: usesModelLinkId,\n type_id: await deep.id(\"@deep-foundation/openai\", \"UsesModel\"),\n from_id: ownerLinkId,\n to_id: modelLinkId\n }\n },\n {\n type: 'insert',\n table: 'links',\n objects: {\n id: containForUsesModelLinkId,\n type_id: containTypeLinkId,\n from_id: containerLinkId,\n to_id: usesModelLinkId\n }\n },\n ]\n })\n };\n\n const theme = createTheme({\n palette: {\n mode: 'dark',\n },\n })\n\n return (\n <ThemeProvider\n theme={{\n [THEME_ID]: theme\n }}\n >\n <Paper\n component=\"form\"\n sx={{ padding: 5, borderRadius: 5, minWidth: \"250px\", width: \"350px\" }}\n onSubmit={handleSubmit}\n >\n <Stack spacing={3}>\n <ChatGPTTokenTextField apiKey={apiKey} handleApiKeyChange={handleApiKeyChange} />\n <ModelLinkIdSelect modelLinkId={modelLinkId} handleModelLinkIdChange={handleModelLinkIdChange} />\n <OwnerLinkIdTextField ownerLinkId={ownerLinkId} handleOwnerLinkIdChange={handleOwnerLinkIdChange} />\n <ContainerLinkIdTextField containerLinkId={containerLinkId} handleContainerLinkIdChange={handleContainerLinkIdChange} />\n <Button type=\"submit\">Submit</Button>\n </Stack>\n </Paper>\n </ThemeProvider>\n );\n };\n\n function ChatGPTTokenTextField(options: {\n apiKey: string,\n handleApiKeyChange: (apiKey: string) => void\n }) {\n const {\n apiKey,\n handleApiKeyChange\n } = options;\n\n const [popperAnchorEl, setPopperAnchorEl] = useState(null);\n\n const handleHelpClick = (event) => {\n setPopperAnchorEl(popperAnchorEl ? null : event.currentTarget);\n };\n\n const helpContent = (\n <Stack>\n <Typography>\n API Key is required to make requests to chatgpt on your behalf\n </Typography>\n <Link\n target=\"_blank\"\n rel=\"noopener\"\n href=\"https://platform.openai.com/api-keys\"\n >\n Obtain API Key\n </Link>\n </Stack>\n );\n\n return (\n <Stack>\n <TextField label=\"Enter API Key\" variant=\"outlined\" value={apiKey} onChange={handleApiKeyChange} required InputProps={{\n endAdornment: (\n <InputAdornment position=\"end\">\n <Button onClick={handleHelpClick} variant=\"text\">\n <MUIIcons.HelpOutline />\n </Button>\n </InputAdornment>\n )\n }} />\n <Popper open={Boolean(popperAnchorEl)} anchorEl={popperAnchorEl} placement=\"bottom\" sx={{\n zIndex: 9999,\n }}>\n <Paper sx={{ padding: 2 }}>\n {helpContent}\n </Paper>\n </Popper>\n </Stack>\n )\n }\n\n function ModelLinkIdSelect(options: {\n modelLinkId: string,\n handleModelLinkIdChange: (apiKey: string) => void\n }) {\n const {\n modelLinkId,\n handleModelLinkIdChange\n } = options\n const { data: modelLinks } = deep.useDeepSubscription({\n type_id: {\n _id: [\"@deep-foundation/openai\", \"Model\"]\n }\n })\n\n const modelOptions = useMemo(() => {\n if (!modelLinks || modelLinks.length === 0) return null;\n return modelLinks.map((link) => {\n const name = link.value.value;\n return <MenuItem value={link.id}>{name}</MenuItem>\n })\n }, [modelLinks])\n console.log({ modelOptions })\n\n const [popperAnchorEl, setPopperAnchorEl] = useState(null);\n\n const handlePopoverOpen = (event) => {\n console.log(`handlePopoverOpen`, event.currentTarget)\n if (!modelOptions) {\n setPopperAnchorEl(event.currentTarget);\n }\n };\n\n const handlePopoverClose = () => {\n setPopperAnchorEl(null);\n };\n\n\n\n return (\n <FormControl disabled={!modelOptions} onMouseEnter={handlePopoverOpen} onMouseLeave={handlePopoverClose}>\n <InputLabel>ChatGPT\n Model ID</InputLabel>\n <Select\n MenuProps={{\n style: { zIndex: 35001 }\n }}\n value={modelLinkId}\n label=\"ChatGPT Model ID\"\n onChange={handleModelLinkIdChange}\n >\n {\n modelOptions\n }\n </Select>\n <Popper\n sx={{\n zIndex: 9999,\n }}\n open={Boolean(popperAnchorEl)}\n anchorEl={popperAnchorEl}\n placement=\"bottom\"\n >\n <Paper sx={{ padding: 2 }}>\n <Typography>\n No model links of type [\"@deep-foundation/openai\", \"Model\"] available to choose from.\n </Typography>\n </Paper>\n </Popper>\n </FormControl>\n )\n }\n\n function OwnerLinkIdTextField(options: {\n ownerLinkId: string,\n handleOwnerLinkIdChange: (apiKey: string) => void\n }) {\n const { ownerLinkId, handleOwnerLinkIdChange } = options;\n return (\n <TextField label=\"Enter Owner Link ID\" variant=\"outlined\" value={ownerLinkId}\n onChange={handleOwnerLinkIdChange}\n required />\n )\n }\n\n function ContainerLinkIdTextField(options: {\n containerLinkId: string,\n handleContainerLinkIdChange: (apiKey: string) => void\n }) {\n const { containerLinkId, handleContainerLinkIdChange } = options;\n return (\n <TextField label=\"Enter Container Link ID\" variant=\"outlined\" value={containerLinkId}\n onChange={handleContainerLinkIdChange}\n required />\n )\n }\n\n}; "

"id": "managerClientHandler",
"type": 8,
"from": 9,
"type": 12,
"from": 13,
"to": "managerClientHandlerCode"

@@ -194,3 +227,3 @@ },

"id": "handlleManagerClient",
"type": 10,
"type": 14,
"from": "Manager",

@@ -200,18 +233,5 @@ "to": "managerClientHandler"

{
"id": "gpt4EncoderDependency",
"type": 11,
"from": 12,
"to": 12
},
{
"id": "replyInsertHandlerCode",
"type": 13,
"value": {
"value": "async ({ data: { newLink: replyLink, triggeredByLinkId }, deep, require }) => {\n console.log({triggeredByLinkId})\n const startTime = Date.now();\n const PACKAGE_NAME = `@deep-foundation/chatgpt-azure`;\n const axios = require('axios');\n\n const { Configuration, OpenAIApi } = require('openai');\n const chatGPTTypeLinkId = await deep.id(PACKAGE_NAME, 'ChatGPT');\n const conversationTypeLinkId = await deep.id(PACKAGE_NAME, 'Conversation');\n const apiKeyTypeLinkId = await deep.id('@deep-foundation/openai', 'ApiKey');\n const usesApiKeyTypeLinkId = await deep.id('@deep-foundation/openai', 'UsesApiKey');\n const modelTypeLinkId = await deep.id('@deep-foundation/openai', 'Model');\n const usesModelTypeLinkId = await deep.id('@deep-foundation/openai', 'UsesModel');\n const messageTypeLinkId = await deep.id('@deep-foundation/messaging', 'Message');\n const replyTypeLinkId = await deep.id('@deep-foundation/chatgpt-azure', 'Reply');\n const authorTypeLinkId = await deep.id('@deep-foundation/messaging', 'Author');\n const containTypeLinkId = await deep.id('@deep-foundation/core', 'Contain');\n const messagingTreeId = await deep.id('@deep-foundation/messaging', 'messagingTree');\n const systemTypeLinkId = await deep.id('@deep-foundation/chatgpt-azure', 'System');\n const tokensTypeLinkId = await deep.id(\"@deep-foundation/tokens\", \"Tokens\")\n const providedByTypeLinkId = await deep.id(\"@deep-foundation/chatgpt-azure\", \"ProvidedBy\")\n const reservedIds = await deep.reserve(1);\n const chatGPTMessageLinkId = reservedIds.pop();\n let systemMessageId;\n let model;\n let systemMessage;\n await deep.await(replyLink.from_id)\n const { data: [messageLink] } = await deep.select({\n id: replyLink.from_id,\n _not: {\n out: {\n to_id: chatGPTTypeLinkId,\n type_id: authorTypeLinkId,\n },\n },\n });\n if (!messageLink) {\n return 'No need to react to message of this reply.';\n }\n if (!messageLink.value?.value) {\n throw new Error(`Message ##${messageLink.id} must have a value`);\n }\n const message = messageLink.value.value;\n\n const apiKeyLink = await getTokenLink();\n const apiKey = apiKeyLink.value.value;\n const configuration = new Configuration({\n apiKey: apiKey,\n });\n const openai = new OpenAIApi(configuration);\n\n const { data: conversationLink } = await deep.select({\n tree_id: { _eq: messagingTreeId },\n parent: { type_id: { _in: [conversationTypeLinkId, messageTypeLinkId] } },\n link: { id: { _eq: replyLink.from_id } },\n }, {\n table: 'tree',\n variables: { order_by: { depth: \"asc\" } },\n returning: `\n id\n depth\n root_id\n parent_id\n link_id\n parent {\n id\n from_id\n type_id\n to_id\n value\n author: out (where: { type_id: { _eq: ${authorTypeLinkId}} }) { \n id\n from_id\n type_id\n to_id\n }\n tokens: out (where: { type_id: { _eq: ${tokensTypeLinkId}} }) { \n id\n from_id\n type_id\n to_id\n value\n }\n }`\n })\n if (!conversationLink) {\n throw new Error('A conversationLink link is not found');\n }\n const currentConversation = conversationLink.find(\n (link) => link.parent.type_id === conversationTypeLinkId\n );\n\n conversationLink.forEach((link) => {\n if (link.parent.author && link.parent.author.length > 0) {\n link.parent.author = link.parent.author[0];\n }\n });\n\n const {\n data: [linkedModel],\n } = await deep.select({\n type_id: modelTypeLinkId,\n in: {\n type_id: usesModelTypeLinkId,\n from_id: currentConversation.parent.id,\n },\n });\n\n\n const usedModelSelectData = {\n type_id: modelTypeLinkId,\n in: {\n type_id: usesModelTypeLinkId,\n from_id: triggeredByLinkId,\n },\n }\n const {\n data: [userLinkedModel],\n } = await deep.select(usedModelSelectData, {\n returning: `\n id\n value\n in(where: { type_id: { _eq: ${usesModelTypeLinkId} } }) {\n id\n type_id\n from_id\n to_id\n value\n }\n tokens: out(where: { type_id: { _eq: ${tokensTypeLinkId} } }) {\n id\n from_id\n to_id\n value\n }\n endpointLink: out(where: { type_id: { _eq: ${providedByTypeLinkId} } }) {\n id\n from_id\n to_id\n endpoint: to {\n id\n value\n }\n }\n `\n }); \n if(!userLinkedModel) {\n throw new Error(`Failed to find used model. Select data: ${JSON.stringify(usedModelSelectData, null, 2)}`)\n }\n let MAX_TOKENS\n console.log({userLinkedModel})\n if (!userLinkedModel.tokens?.[0]?.value?.value) {\n throw new Error(\"Token limit for the model is not specified.\");\n } else if (userLinkedModel.tokens?.[0]?.value?.value) {\n MAX_TOKENS = userLinkedModel.tokens[0].value.value;\n }\n\n if (!userLinkedModel.endpointLink?.[0]?.endpoint?.value?.value) {\n throw new Error(\"Endpoint for the model is not specified.\");\n }\n const API_ENDPOINT = userLinkedModel.endpointLink[0].endpoint.value?.value;\n\n if (!linkedModel && !userLinkedModel) {\n throw new Error(\"Before using azure-GPT, create a model, tokens, and an endpoint links.\");\n } else if (\n (linkedModel &&\n linkedModel.value?.value &&\n userLinkedModel &&\n userLinkedModel.value?.value) ||\n (linkedModel && linkedModel.value?.value)\n ) {\n model = linkedModel.value.value;\n } else {\n if (!userLinkedModel) {\n throw new Error(`A link with type ##${userLinkedModel} is not found`);\n }\n if (!userLinkedModel.value?.value) {\n throw new Error(`Linked model with user ##${userLinkedModel.id} must have a value`);\n } else {\n model = userLinkedModel.value.value;\n }\n }\n const messageLinks = conversationLink\n .map(item => item.parent)\n .filter(link => link && link.type_id === messageTypeLinkId);\n let allMessages = await getMessages({ messageLinks });\n const messagesToSend = [...allMessages];\n\n const { data: userLinkedSystemMessageLinks } = await deep.select({\n type_id: systemTypeLinkId,\n to_id: triggeredByLinkId,\n }, { returning: `id message: from{ id value} conversation:to{id}` });\n\n const { data: conversationLinkedSystemMessageLink } = await deep.select({\n type_id: systemTypeLinkId,\n to_id: currentConversation.parent.id,\n }, { returning: `id message: from{ id value} conversation:to{id}` });\n\n if (conversationLinkedSystemMessageLink && conversationLinkedSystemMessageLink.length > 0) {\n const systemMessageLink = conversationLinkedSystemMessageLink[0];\n if (!systemMessageLink.message?.value?.value) {\n throw new Error(`System message with link to conversation ##${systemMessageLink.id} must have a value`);\n } else {\n systemMessage = systemMessageLink.message.value.value;\n systemMessageId = systemMessageLink.message;\n await deep.await(systemMessageId.id)\n\n }\n } else if (userLinkedSystemMessageLinks && userLinkedSystemMessageLinks.length > 0) {\n if (userLinkedSystemMessageLinks.length > 1) {\n throw new Error(\"Multiple system messages linked to the user are found\");\n }\n\n const userLinkedSystemMessageLink = userLinkedSystemMessageLinks[0];\n\n if (!userLinkedSystemMessageLink.message?.value?.value) {\n throw new Error(`System message with link to user ##${userLinkedSystemMessageLink.id} must have a value`);\n } else {\n systemMessage = userLinkedSystemMessageLink.message.value.value;\n systemMessageId = userLinkedSystemMessageLink.message;\n await deep.await(systemMessageId.id)\n }\n }\n\n if (systemMessage) {\n const { data: tokensLinkedToSystemMessage } = await deep.select({\n type_id: tokensTypeLinkId,\n from_id: systemMessageId.id,\n to_id: systemMessageId.id,\n });\n if (!tokensLinkedToSystemMessage[0]?.value?.value) {\n throw new Error(`System message does not contain tokens`);\n } else if (tokensLinkedToSystemMessage[0]?.value?.value) {\n let tokenCount = tokensLinkedToSystemMessage[0].value?.value;\n messagesToSend.unshift({\n role: \"system\",\n content: systemMessage,\n tokens: tokenCount,\n });\n }\n }\n\n const tokenLimit = MAX_TOKENS * 7 / 8;\n let totalTokens = 0;\n let messagesToSendToOpenAI = [];\n\n for (let i = messagesToSend.length - 1; i >= 0; i--) {\n const message = messagesToSend[i];\n\n console.log({message})\n if (message.role === 'system' || totalTokens + message.tokens <= tokenLimit) {\n messagesToSendToOpenAI.unshift({ role: message.role, content: message.content });\n totalTokens += message.tokens;\n } else {\n break;\n }\n }\n let response;\n\n try {\n response = await axios.post(API_ENDPOINT, {\n messages: [...messagesToSendToOpenAI]\n }, {\n headers: {\n 'Content-Type': 'application/json',\n 'api-key': apiKey\n }\n });\n } catch (error) {\n console.error('Error making API call:', error.response ? error.response.data : error.message);\n }\n\n const content = response.data.choices[0]?.message?.content;\n\n await deep.serial({\n operations: [\n {\n table: 'links',\n type: 'insert',\n objects: {\n id: chatGPTMessageLinkId,\n type_id: messageTypeLinkId,\n out: {\n data: [\n {\n type_id: authorTypeLinkId,\n to_id: chatGPTTypeLinkId,\n },\n ],\n },\n },\n },\n {\n table: 'strings',\n type: 'insert',\n objects: {\n link_id: chatGPTMessageLinkId,\n value: content\n }\n },\n {\n table: 'links',\n type: 'insert',\n objects: {\n type_id: replyTypeLinkId,\n from_id: chatGPTMessageLinkId,\n to_id: replyLink.from_id,\n },\n },\n ],\n });\n\n async function getMessages({ messageLinks }) {\n return Promise.all(\n messageLinks.map(async (link) => {\n const tokens = link.tokens?.length > 0 ? link.tokens[0].value.value : undefined;\n return {\n role: await getMessageRole({ messageLink: link }),\n content: link.value.value,\n tokens: tokens,\n }\n })\n );\n }\n\n async function getMessageRole({ messageLink }) {\n const authorLink = messageLink.author;\n if (!authorLink) {\n throw new Error(`Author link not found for message ##${messageLink.id}`);\n }\n return authorLink.to_id === chatGPTTypeLinkId ? 'assistant' : 'user';\n }\n\n async function getTokenLink() {\n let resultTokenLink;\n const { data } = await deep.select({\n _or: [\n {\n type_id: apiKeyTypeLinkId,\n in: {\n type_id: containTypeLinkId,\n from_id: triggeredByLinkId,\n },\n },\n {\n from_id: triggeredByLinkId,\n type_id: usesApiKeyTypeLinkId,\n },\n {\n type_id: apiKeyTypeLinkId,\n in: {\n from_id: triggeredByLinkId,\n type_id: usesApiKeyTypeLinkId,\n },\n },\n ],\n })\n console.log(\"FREEPHOENIX888.getTokenLink\", {data})\n if (data.length === 0) {\n throw new Error(`ApiKey ##${apiKeyTypeLinkId} is not found`);\n }\n const usesLinks = data.filter(\n (link) => link.type_id === usesApiKeyTypeLinkId\n );\n if (usesLinks.length > 1) {\n throw new Error(\n `More than 1 links of type ##${usesApiKeyTypeLinkId} are found`\n );\n }\n const usesLink = data.find(\n (link) => link.type_id === usesApiKeyTypeLinkId\n );\n if (usesLink) {\n const tokenLink = data.find((link) => link.id === usesLink.to_id);\n if (!tokenLink) {\n throw new Error(`ApiKey ##${apiKeyTypeLinkId} is not found`);\n } else {\n resultTokenLink = tokenLink;\n }\n } else {\n const tokenLink = data.filter(\n (link) => link.type_id === apiKeyTypeLinkId\n );\n if (tokenLink.length > 1) {\n throw new Error(\n `For 2 or more ApiKey ##${apiKeyTypeLinkId} links you must activate it with usesOpenAiApiKey link`\n );\n } else {\n const tokenLink = data.find(\n (link) => link.type_id === apiKeyTypeLinkId\n );\n if (!tokenLink) {\n throw new Error(`ApiKey ##${apiKeyTypeLinkId} is not found`);\n }\n resultTokenLink = tokenLink;\n }\n }\n if (!resultTokenLink.value?.value) {\n throw new Error(`ApiKey ##${apiKeyTypeLinkId} has no value`);\n }\n return resultTokenLink;\n }\n\n const endTime = Date.now();\n const duration = (endTime - startTime) / 1000;\n return {\n request: {\n model: model,\n messages: [\n ...messagesToSendToOpenAI\n ],\n },\n response: response.data,\n duration: duration,\n totalTokens: totalTokens\n };\n};"
}
},
{
"id": "replyInsertHandler",
"type": 8,
"from": 14,
"type": 12,
"from": 15,
"to": "replyInsertHandlerCode"

@@ -221,3 +241,3 @@ },

"id": "replyHandleInsert",
"type": 15,
"type": 16,
"from": "Reply",

@@ -227,26 +247,6 @@ "to": "replyInsertHandler"

{
"id": "ChatGPT",
"type": 1
},
{
"id": "Conversation",
"type": 1
},
{
"id": "conversationValue",
"type": 16,
"from": "Conversation",
"to": 17
},
{
"id": "ProvidedBy",
"type": 1,
"id": "gpt4EncoderDependency",
"type": 17,
"from": 18,
"to": "Endpoint"
},
{
"id": "endpointValue",
"type": 16,
"from": "Endpoint",
"to": 17
"to": 18
}

@@ -261,2 +261,6 @@ ],

{
"name": "@deep-foundation/openai",
"version": "1.1.1"
},
{
"name": "@deep-foundation/messaging",

@@ -276,8 +280,4 @@ "version": "2.0.0"

"version": "1.0.3"
},
{
"name": "@deep-foundation/openai",
"version": "1.1.0"
}
]
}

@@ -7,3 +7,3 @@ {

"@deep-foundation/messaging": "~2.0.0",
"@deep-foundation/openai": "~1.1.0",
"@deep-foundation/openai": "~1.1.1",
"@deep-foundation/tokens": "^0.0.11",

@@ -13,3 +13,3 @@ "@deep-foundation/tsx": "~0.0.5",

},
"version": "2.3.1",
"version": "2.3.2",
"keywords": [

@@ -16,0 +16,0 @@ "deep-package"

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc