Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion dev/app/(payload)/admin/importMap.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file modified dev/dev.db
Binary file not shown.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@
"react-mentions": "^4.4.10",
"scroll-into-view-if-needed": "^3.1.0",
"textarea-caret": "^3.0.2",
"zod": "^4.1.7"
"zod": "^4.1.7",
"use-stick-to-bottom": "^1.1.1"
}
}
13 changes: 12 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ export const PLUGIN_NAME = 'plugin-ai'
export const PLUGIN_INSTRUCTIONS_TABLE = `${PLUGIN_NAME}-instructions`
export const PLUGIN_LEXICAL_EDITOR_FEATURE = `${PLUGIN_NAME}-actions-feature`

// Endpoint defaults
// Endpoint defaults
export const PLUGIN_API_ENDPOINT_BASE = `/${PLUGIN_NAME}`
export const PLUGIN_API_ENDPOINT_GENERATE = `${PLUGIN_API_ENDPOINT_BASE}/generate`
export const PLUGIN_API_ENDPOINT_GENERATE_UPLOAD = `${PLUGIN_API_ENDPOINT_GENERATE}/upload`
export const PLUGIN_FETCH_FIELDS_ENDPOINT = `${PLUGIN_API_ENDPOINT_BASE}/fetch-fields`
export const PLUGIN_API_ENDPOINT_AGENT_CHAT = `${PLUGIN_API_ENDPOINT_BASE}/agent/chat`

// LLM Settings
export const PLUGIN_DEFAULT_OPENAI_MODEL = `gpt-4o-mini`
Expand Down
57 changes: 57 additions & 0 deletions src/endpoints/chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { OpenAIChatModelId, OpenAIProviderOptions } from '@ai-sdk/openai/internal'
import type { Endpoint, PayloadRequest } from 'payload'

import { convertToModelMessages, streamText } from 'ai'

import type { PluginConfig } from '../types.js'

import { openai } from '../ai/models/openai/openai.js'
import { PLUGIN_API_ENDPOINT_AGENT_CHAT, PLUGIN_DEFAULT_OPENAI_MODEL } from '../defaults.js'
import { checkAccess } from '../utilities/checkAccess.js'

export const Chat = (pluginConfig: PluginConfig): Endpoint => ({
handler: async (req: PayloadRequest) => {
try {
await checkAccess(req, pluginConfig)

const body = await req.json?.()
const messages = Array.isArray(body?.messages) ? body.messages : []
const system = "";
const modelId: OpenAIChatModelId = "gpt-5"

const result = streamText({
messages: convertToModelMessages(messages),
model: openai(modelId),
providerOptions:{
openai:{
reasoningEffort: "low",
structuredOutputs: true,
} satisfies OpenAIProviderOptions
},
system
})

return result.toUIMessageStreamResponse({
sendReasoning: true,
})

} catch (error) {
req.payload.logger.error(error, 'Error in chat endpoint: ')
const message =
error && typeof error === 'object' && 'message' in error
? (error as any).message
: String(error)

return new Response(JSON.stringify({ error: message }), {
headers: { 'Content-Type': 'application/json' },
status:
message.includes('Authentication required') ||
message.includes('Insufficient permissions')
? 401
: 500,
})
}
},
method: 'post',
path: PLUGIN_API_ENDPOINT_AGENT_CHAT,
})
34 changes: 8 additions & 26 deletions src/endpoints/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,10 @@ import { asyncHandlebars } from '../libraries/handlebars/asyncHandlebars.js'
import { registerEditorHelper } from '../libraries/handlebars/helpers.js'
import { handlebarsHelpersMap } from '../libraries/handlebars/helpersMap.js'
import { replacePlaceholders } from '../libraries/handlebars/replacePlaceholders.js'
import { checkAccess } from '../utilities/checkAccess.js'
import { extractImageData } from '../utilities/extractImageData.js'
import { getGenerationModels } from '../utilities/getGenerationModels.js'

const requireAuthentication = (req: PayloadRequest) => {
if (!req.user) {
throw new Error('Authentication required. Please log in to use AI features.')
}
return true
}

const checkAccess = async (req: PayloadRequest, pluginConfig: PluginConfig) => {
requireAuthentication(req)

if (pluginConfig.access?.generate) {
const hasAccess = await pluginConfig.access.generate({ req })
if (!hasAccess) {
throw new Error('Insufficient permissions to use AI generation features.')
}
}

return true
}
import { Chat } from './chat.js'

const extendContextWithPromptFields = (
data: object,
Expand All @@ -57,13 +39,13 @@ const extendContextWithPromptFields = (
)
return new Proxy(data, {
get: (target, prop: string) => {
const field = fieldsMap.get(prop as string)
const field = fieldsMap.get(prop)
if (field?.getter) {
const value = field.getter(data, ctx)
return Promise.resolve(value).then((v) => new asyncHandlebars.SafeString(v))
}
// {{prop}} escapes content by default. Here we make sure it won't be escaped.
const value = typeof target === "object" ? (target as any)[prop] : undefined
const value = typeof target === 'object' ? (target as any)[prop] : undefined
return typeof value === 'string' ? new asyncHandlebars.SafeString(value) : value
},
// It's used by the handlebars library to determine if the property is enumerable
Expand Down Expand Up @@ -167,6 +149,7 @@ const assignPrompt = async (

export const endpoints: (pluginConfig: PluginConfig) => Endpoints = (pluginConfig) =>
({
chat: Chat(pluginConfig),
textarea: {
//TODO: This is the main endpoint for generating content - its just needs to be renamed to 'generate' or something.
handler: async (req: PayloadRequest) => {
Expand Down Expand Up @@ -359,17 +342,16 @@ export const endpoints: (pluginConfig: PluginConfig) => Endpoints = (pluginConfi
const editImages = []
for (const img of images) {
const serverURL =
req.payload.config?.serverURL ||
process.env.SERVER_URL ||
process.env.NEXT_PUBLIC_SERVER_URL
req.payload.config?.serverURL ||
process.env.SERVER_URL ||
process.env.NEXT_PUBLIC_SERVER_URL

let url = img.image.thumbnailURL || img.image.url
if (!url.startsWith('http')) {
url = `${serverURL}${url}`
}

try {

const response = await fetch(url, {
headers: {
//TODO: Further testing needed or so find a proper way.
Expand Down
1 change: 1 addition & 0 deletions src/exports/client.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { LexicalEditorFeatureClient } from '../fields/LexicalEditor/feature.client.js'
export { InstructionsContext } from '../providers/InstructionsProvider/context.js'
export { InstructionsProvider } from '../providers/InstructionsProvider/InstructionsProvider.js'
export { AgentProvider } from '../providers/AgentProvider/AgentProvider.js'
4 changes: 4 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ const payloadAiPlugin =
{
path: '@ai-stack/payloadcms/client#InstructionsProvider',
},
{
path: '@ai-stack/payloadcms/client#AgentProvider',
},
]

incomingConfig.admin = {
Expand Down Expand Up @@ -142,6 +145,7 @@ const payloadAiPlugin =
...(incomingConfig.endpoints ?? []),
pluginEndpoints.textarea,
pluginEndpoints.upload,
pluginEndpoints.chat,
fetchFields(pluginConfig),
],
globals: globals.map((global) => {
Expand Down
30 changes: 30 additions & 0 deletions src/providers/AgentProvider/AgentProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use client'

import React from 'react'

import styles from '../../ui/AgentSidebar/agent-sidebar.module.css'
import { AgentSidebar } from '../../ui/AgentSidebar/AgentSidebar.js'
import { PluginIcon } from '../../ui/Icons/Icons.js'

export const AgentProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [open, setOpen] = React.useState(true)

return (
<>
{children}

<button
aria-label="Open AI Agent sidebar"
className={`${styles.launcher} ${open ? styles.launcherActive : ''}`}
onClick={() => setOpen(!open)}
type="button"
>
<PluginIcon hasDivider={false} isLoading={false} />
{/*<span>Compose</span>*/}
</button>
<AgentSidebar onCloseAction={() => setOpen(false)} open={open} />
</>
)
}

export default AgentProvider
18 changes: 9 additions & 9 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ export interface PluginConfigAccess {
* Control access to AI generation features (generate text, images, audio)
* @default () => !!req.user (requires authentication)
*/
generate?: ({ req }: { req: PayloadRequest }) => Promise<boolean> | boolean
generate?: ({ req }: { req: PayloadRequest }) => boolean | Promise<boolean>
/**
* Control access to AI settings/configuration
* @default () => !!req.user (requires authentication)
*/
settings?: ({ req }: { req: PayloadRequest }) => Promise<boolean> | boolean
settings?: ({ req }: { req: PayloadRequest }) => boolean | Promise<boolean>
}

export interface PluginOptions {
Expand Down Expand Up @@ -116,6 +116,7 @@ export type GenerateTextarea<T = any> = (args: {
export interface Endpoints {
textarea: Omit<Endpoint, 'root'>
upload: Omit<Endpoint, 'root'>
chat: Omit<Endpoint, 'root'>
}

export type ActionMenuItems =
Expand Down Expand Up @@ -151,13 +152,12 @@ export type SeedPromptOptions = {

export type SeedPromptData = Omit<TypedCollection[typeof PLUGIN_INSTRUCTIONS_TABLE], 'createdAt' | 'id' | 'updatedAt'>

export type SeedPromptResult = {
data?: SeedPromptData
prompt: string
system: string
} | {
data?: SeedPromptData
} | false | undefined | void
export type SeedPromptResult =
| { data?: SeedPromptData }
| { data?: SeedPromptData; prompt: string; system: string }
| false
| undefined
| void

export type SeedPromptFunction = (options: SeedPromptOptions) => Promise<SeedPromptResult> | SeedPromptResult

Expand Down
Loading