mirror of
https://github.com/rowboatlabs/rowboat.git
synced 2026-04-29 02:24:02 +02:00
add generate for agent instructions
This commit is contained in:
parent
7bc3203ed2
commit
a7975ff4ff
7 changed files with 460 additions and 203 deletions
|
|
@ -1,19 +1,6 @@
|
|||
'use server';
|
||||
import { convertToCopilotWorkflow } from "../lib/types/copilot_types";
|
||||
import { convertFromAgenticAPIChatMessages } from "../lib/types/agents_api_types";
|
||||
import { convertToCopilotMessage } from "../lib/types/copilot_types";
|
||||
import { convertToCopilotApiMessage } from "../lib/types/copilot_types";
|
||||
import { convertToCopilotApiChatContext } from "../lib/types/copilot_types";
|
||||
import { CopilotAPIResponse } from "../lib/types/copilot_types";
|
||||
import { CopilotAPIRequest } from "../lib/types/copilot_types";
|
||||
import { CopilotChatContext } from "../lib/types/copilot_types";
|
||||
import { CopilotMessage } from "../lib/types/copilot_types";
|
||||
import { CopilotAssistantMessage } from "../lib/types/copilot_types";
|
||||
import { AgenticAPIChatRequest } from "../lib/types/agents_api_types";
|
||||
import { CopilotWorkflow } from "../lib/types/copilot_types";
|
||||
import { Workflow } from "../lib/types/workflow_types";
|
||||
import { WorkflowTool } from "../lib/types/workflow_types";
|
||||
import { WorkflowPrompt } from "../lib/types/workflow_types";
|
||||
import { WorkflowAgent } from "../lib/types/workflow_types";
|
||||
import { EmbeddingRecord } from "../lib/types/datasource_types";
|
||||
import { WebpageCrawlResponse } from "../lib/types/tool_types";
|
||||
|
|
@ -27,10 +14,8 @@ import { openai } from "@ai-sdk/openai";
|
|||
import FirecrawlApp, { ScrapeResponse } from '@mendable/firecrawl-js';
|
||||
import { embeddingModel } from "../lib/embedding";
|
||||
import { apiV1 } from "rowboat-shared";
|
||||
import { zodToJsonSchema } from 'zod-to-json-schema';
|
||||
import { Claims, getSession } from "@auth0/nextjs-auth0";
|
||||
import { callClientToolWebhook, getAgenticApiResponse, mockToolResponse, runRAGToolCall } from "../lib/utils";
|
||||
import { assert } from "node:console";
|
||||
import { check_query_limit } from "../lib/rate_limiting";
|
||||
import { QueryLimitError } from "../lib/client_utils";
|
||||
import { projectAuthCheck } from "./project_actions";
|
||||
|
|
@ -114,153 +99,6 @@ export async function getAssistantResponse(
|
|||
};
|
||||
}
|
||||
|
||||
export async function getCopilotResponse(
|
||||
projectId: string,
|
||||
messages: z.infer<typeof CopilotMessage>[],
|
||||
current_workflow_config: z.infer<typeof Workflow>,
|
||||
context: z.infer<typeof CopilotChatContext> | null,
|
||||
): Promise<{
|
||||
message: z.infer<typeof CopilotAssistantMessage>,
|
||||
rawRequest: unknown,
|
||||
rawResponse: unknown,
|
||||
}> {
|
||||
await projectAuthCheck(projectId);
|
||||
if (!await check_query_limit(projectId)) {
|
||||
throw new QueryLimitError();
|
||||
}
|
||||
|
||||
// prepare request
|
||||
const request: z.infer<typeof CopilotAPIRequest> = {
|
||||
messages: messages.map(convertToCopilotApiMessage),
|
||||
workflow_schema: JSON.stringify(zodToJsonSchema(CopilotWorkflow)),
|
||||
current_workflow_config: JSON.stringify(convertToCopilotWorkflow(current_workflow_config)),
|
||||
context: context ? convertToCopilotApiChatContext(context) : null,
|
||||
};
|
||||
console.log(`copilot request`, JSON.stringify(request, null, 2));
|
||||
|
||||
// call copilot api
|
||||
const response = await fetch(process.env.COPILOT_API_URL + '/chat', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${process.env.COPILOT_API_KEY || 'test'}`,
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
console.error('Failed to call copilot api', response);
|
||||
throw new Error(`Failed to call copilot api: ${response.statusText}`);
|
||||
}
|
||||
|
||||
// parse and return response
|
||||
const json: z.infer<typeof CopilotAPIResponse> = await response.json();
|
||||
console.log(`copilot response`, JSON.stringify(json, null, 2));
|
||||
if ('error' in json) {
|
||||
throw new Error(`Failed to call copilot api: ${json.error}`);
|
||||
}
|
||||
// remove leading ```json and trailing ```
|
||||
const msg = convertToCopilotMessage({
|
||||
role: 'assistant',
|
||||
content: json.response.replace(/^```json\n/, '').replace(/\n```$/, ''),
|
||||
});
|
||||
|
||||
// validate response schema
|
||||
assert(msg.role === 'assistant');
|
||||
if (msg.role === 'assistant') {
|
||||
for (const part of msg.content.response) {
|
||||
if (part.type === 'action') {
|
||||
switch (part.content.config_type) {
|
||||
case 'tool': {
|
||||
const test = {
|
||||
name: 'test',
|
||||
description: 'test',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
} as z.infer<typeof WorkflowTool>;
|
||||
// iterate over each field in part.content.config_changes
|
||||
// and test if the final object schema is valid
|
||||
// if not, discard that field
|
||||
for (const [key, value] of Object.entries(part.content.config_changes)) {
|
||||
const result = WorkflowTool.safeParse({
|
||||
...test,
|
||||
[key]: value,
|
||||
});
|
||||
if (!result.success) {
|
||||
console.log(`discarding field ${key} from ${part.content.config_type}: ${part.content.name}`, result.error.message);
|
||||
delete part.content.config_changes[key];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'agent': {
|
||||
const test = {
|
||||
name: 'test',
|
||||
description: 'test',
|
||||
type: 'conversation',
|
||||
instructions: 'test',
|
||||
prompts: [],
|
||||
tools: [],
|
||||
model: 'gpt-4o',
|
||||
ragReturnType: 'chunks',
|
||||
ragK: 10,
|
||||
connectedAgents: [],
|
||||
controlType: 'retain',
|
||||
} as z.infer<typeof WorkflowAgent>;
|
||||
// iterate over each field in part.content.config_changes
|
||||
// and test if the final object schema is valid
|
||||
// if not, discard that field
|
||||
for (const [key, value] of Object.entries(part.content.config_changes)) {
|
||||
const result = WorkflowAgent.safeParse({
|
||||
...test,
|
||||
[key]: value,
|
||||
});
|
||||
if (!result.success) {
|
||||
console.log(`discarding field ${key} from ${part.content.config_type}: ${part.content.name}`, result.error.message);
|
||||
delete part.content.config_changes[key];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'prompt': {
|
||||
const test = {
|
||||
name: 'test',
|
||||
type: 'base_prompt',
|
||||
prompt: "test",
|
||||
} as z.infer<typeof WorkflowPrompt>;
|
||||
// iterate over each field in part.content.config_changes
|
||||
// and test if the final object schema is valid
|
||||
// if not, discard that field
|
||||
for (const [key, value] of Object.entries(part.content.config_changes)) {
|
||||
const result = WorkflowPrompt.safeParse({
|
||||
...test,
|
||||
[key]: value,
|
||||
});
|
||||
if (!result.success) {
|
||||
console.log(`discarding field ${key} from ${part.content.config_type}: ${part.content.name}`, result.error.message);
|
||||
delete part.content.config_changes[key];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
part.content.error = `Unknown config type: ${part.content.config_type}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
message: msg as z.infer<typeof CopilotAssistantMessage>,
|
||||
rawRequest: request,
|
||||
rawResponse: json,
|
||||
};
|
||||
}
|
||||
|
||||
export async function suggestToolResponse(toolId: string, projectId: string, messages: z.infer<typeof apiV1.ChatMessage>[]): Promise<string> {
|
||||
await projectAuthCheck(projectId);
|
||||
if (!await check_query_limit(projectId)) {
|
||||
|
|
|
|||
217
apps/rowboat/app/actions/copilot_actions.ts
Normal file
217
apps/rowboat/app/actions/copilot_actions.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
'use server';
|
||||
import {
|
||||
convertToCopilotWorkflow, convertToCopilotMessage, convertToCopilotApiMessage,
|
||||
convertToCopilotApiChatContext, CopilotAPIResponse, CopilotAPIRequest,
|
||||
CopilotChatContext, CopilotMessage, CopilotAssistantMessage, CopilotWorkflow
|
||||
} from "../lib/types/copilot_types";
|
||||
import {
|
||||
Workflow, WorkflowTool, WorkflowPrompt, WorkflowAgent
|
||||
} from "../lib/types/workflow_types";
|
||||
import { z } from 'zod';
|
||||
import { zodToJsonSchema } from 'zod-to-json-schema';
|
||||
import { assert } from "node:console";
|
||||
import { check_query_limit } from "../lib/rate_limiting";
|
||||
import { QueryLimitError } from "../lib/client_utils";
|
||||
import { projectAuthCheck } from "./project_actions";
|
||||
|
||||
export async function getCopilotResponse(
|
||||
projectId: string,
|
||||
messages: z.infer<typeof CopilotMessage>[],
|
||||
current_workflow_config: z.infer<typeof Workflow>,
|
||||
context: z.infer<typeof CopilotChatContext> | null
|
||||
): Promise<{
|
||||
message: z.infer<typeof CopilotAssistantMessage>;
|
||||
rawRequest: unknown;
|
||||
rawResponse: unknown;
|
||||
}> {
|
||||
await projectAuthCheck(projectId);
|
||||
if (!await check_query_limit(projectId)) {
|
||||
throw new QueryLimitError();
|
||||
}
|
||||
|
||||
// prepare request
|
||||
const request: z.infer<typeof CopilotAPIRequest> = {
|
||||
messages: messages.map(convertToCopilotApiMessage),
|
||||
workflow_schema: JSON.stringify(zodToJsonSchema(CopilotWorkflow)),
|
||||
current_workflow_config: JSON.stringify(convertToCopilotWorkflow(current_workflow_config)),
|
||||
context: context ? convertToCopilotApiChatContext(context) : null,
|
||||
};
|
||||
console.log(`copilot request`, JSON.stringify(request, null, 2));
|
||||
|
||||
// call copilot api
|
||||
const response = await fetch(process.env.COPILOT_API_URL + '/chat', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${process.env.COPILOT_API_KEY || 'test'}`,
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
console.error('Failed to call copilot api', response);
|
||||
throw new Error(`Failed to call copilot api: ${response.statusText}`);
|
||||
}
|
||||
|
||||
// parse and return response
|
||||
const json: z.infer<typeof CopilotAPIResponse> = await response.json();
|
||||
console.log(`copilot response`, JSON.stringify(json, null, 2));
|
||||
if ('error' in json) {
|
||||
throw new Error(`Failed to call copilot api: ${json.error}`);
|
||||
}
|
||||
// remove leading ```json and trailing ```
|
||||
const msg = convertToCopilotMessage({
|
||||
role: 'assistant',
|
||||
content: json.response.replace(/^```json\n/, '').replace(/\n```$/, ''),
|
||||
});
|
||||
|
||||
// validate response schema
|
||||
assert(msg.role === 'assistant');
|
||||
if (msg.role === 'assistant') {
|
||||
for (const part of msg.content.response) {
|
||||
if (part.type === 'action') {
|
||||
switch (part.content.config_type) {
|
||||
case 'tool': {
|
||||
const test = {
|
||||
name: 'test',
|
||||
description: 'test',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
} as z.infer<typeof WorkflowTool>;
|
||||
// iterate over each field in part.content.config_changes
|
||||
// and test if the final object schema is valid
|
||||
// if not, discard that field
|
||||
for (const [key, value] of Object.entries(part.content.config_changes)) {
|
||||
const result = WorkflowTool.safeParse({
|
||||
...test,
|
||||
[key]: value,
|
||||
});
|
||||
if (!result.success) {
|
||||
console.log(`discarding field ${key} from ${part.content.config_type}: ${part.content.name}`, result.error.message);
|
||||
delete part.content.config_changes[key];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'agent': {
|
||||
const test = {
|
||||
name: 'test',
|
||||
description: 'test',
|
||||
type: 'conversation',
|
||||
instructions: 'test',
|
||||
prompts: [],
|
||||
tools: [],
|
||||
model: 'gpt-4o',
|
||||
ragReturnType: 'chunks',
|
||||
ragK: 10,
|
||||
connectedAgents: [],
|
||||
controlType: 'retain',
|
||||
} as z.infer<typeof WorkflowAgent>;
|
||||
// iterate over each field in part.content.config_changes
|
||||
// and test if the final object schema is valid
|
||||
// if not, discard that field
|
||||
for (const [key, value] of Object.entries(part.content.config_changes)) {
|
||||
const result = WorkflowAgent.safeParse({
|
||||
...test,
|
||||
[key]: value,
|
||||
});
|
||||
if (!result.success) {
|
||||
console.log(`discarding field ${key} from ${part.content.config_type}: ${part.content.name}`, result.error.message);
|
||||
delete part.content.config_changes[key];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'prompt': {
|
||||
const test = {
|
||||
name: 'test',
|
||||
type: 'base_prompt',
|
||||
prompt: "test",
|
||||
} as z.infer<typeof WorkflowPrompt>;
|
||||
// iterate over each field in part.content.config_changes
|
||||
// and test if the final object schema is valid
|
||||
// if not, discard that field
|
||||
for (const [key, value] of Object.entries(part.content.config_changes)) {
|
||||
const result = WorkflowPrompt.safeParse({
|
||||
...test,
|
||||
[key]: value,
|
||||
});
|
||||
if (!result.success) {
|
||||
console.log(`discarding field ${key} from ${part.content.config_type}: ${part.content.name}`, result.error.message);
|
||||
delete part.content.config_changes[key];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
part.content.error = `Unknown config type: ${part.content.config_type}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
message: msg as z.infer<typeof CopilotAssistantMessage>,
|
||||
rawRequest: request,
|
||||
rawResponse: json,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getCopilotAgentInstructions(
|
||||
projectId: string,
|
||||
messages: z.infer<typeof CopilotMessage>[],
|
||||
current_workflow_config: z.infer<typeof Workflow>,
|
||||
agentName: string,
|
||||
): Promise<string> {
|
||||
await projectAuthCheck(projectId);
|
||||
if (!await check_query_limit(projectId)) {
|
||||
throw new QueryLimitError();
|
||||
}
|
||||
|
||||
// prepare request
|
||||
const request: z.infer<typeof CopilotAPIRequest> = {
|
||||
messages: messages.map(convertToCopilotApiMessage),
|
||||
workflow_schema: JSON.stringify(zodToJsonSchema(CopilotWorkflow)),
|
||||
current_workflow_config: JSON.stringify(convertToCopilotWorkflow(current_workflow_config)),
|
||||
context: {
|
||||
type: 'agent',
|
||||
agentName: agentName,
|
||||
}
|
||||
};
|
||||
console.log(`copilot request`, JSON.stringify(request, null, 2));
|
||||
|
||||
// call copilot api
|
||||
const response = await fetch(process.env.COPILOT_API_URL + '/edit_agent_instructions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${process.env.COPILOT_API_KEY || 'test'}`,
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
console.error('Failed to call copilot api', response);
|
||||
throw new Error(`Failed to call copilot api: ${response.statusText}`);
|
||||
}
|
||||
|
||||
// parse and return response
|
||||
const json = await response.json();
|
||||
console.log(`copilot response`, JSON.stringify(json, null, 2));
|
||||
let copilotResponse: z.infer<typeof CopilotAPIResponse>;
|
||||
try {
|
||||
copilotResponse = CopilotAPIResponse.parse(json);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse copilot response', e);
|
||||
throw new Error(`Failed to parse copilot response: ${e}`);
|
||||
}
|
||||
if ('error' in copilotResponse) {
|
||||
throw new Error(`Failed to call copilot api: ${copilotResponse.error}`);
|
||||
}
|
||||
|
||||
// return response
|
||||
return copilotResponse.response;
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
"use client";
|
||||
import { WithStringId } from "../../../lib/types/types";
|
||||
import { AgenticAPITool } from "../../../lib/types/agents_api_types";
|
||||
import { WorkflowPrompt, WorkflowAgent } from "../../../lib/types/workflow_types";
|
||||
import { WorkflowPrompt, WorkflowAgent, Workflow } from "../../../lib/types/workflow_types";
|
||||
import { DataSource } from "../../../lib/types/datasource_types";
|
||||
import { Button, Divider, Dropdown, DropdownItem, DropdownMenu, DropdownTrigger, Input, Radio, RadioGroup, Select, SelectItem } from "@nextui-org/react";
|
||||
import { z } from "zod";
|
||||
|
|
@ -9,10 +9,19 @@ import { DataSourceIcon } from "../../../lib/components/datasource-icon";
|
|||
import { ActionButton, StructuredPanel } from "../../../lib/components/structured-panel";
|
||||
import { EditableField } from "../../../lib/components/editable-field";
|
||||
import { Label } from "../../../lib/components/label";
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { PlusIcon, SparklesIcon } from "lucide-react";
|
||||
import { List } from "./config_list";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { usePreviewModal } from "./preview-modal";
|
||||
import { Modal, ModalContent, ModalHeader, ModalBody, ModalFooter } from "@nextui-org/react";
|
||||
import { Textarea } from "@nextui-org/react";
|
||||
import { PreviewModalProvider } from "./preview-modal";
|
||||
import { CopilotMessage } from "@/app/lib/types/copilot_types";
|
||||
import { getCopilotAgentInstructions } from "@/app/actions/copilot_actions";
|
||||
|
||||
export function AgentConfig({
|
||||
projectId,
|
||||
workflow,
|
||||
agent,
|
||||
usedAgentNames,
|
||||
agents,
|
||||
|
|
@ -22,6 +31,8 @@ export function AgentConfig({
|
|||
handleUpdate,
|
||||
handleClose,
|
||||
}: {
|
||||
projectId: string,
|
||||
workflow: z.infer<typeof Workflow>,
|
||||
agent: z.infer<typeof WorkflowAgent>,
|
||||
usedAgentNames: Set<string>,
|
||||
agents: z.infer<typeof WorkflowAgent>[],
|
||||
|
|
@ -57,6 +68,9 @@ export function AgentConfig({
|
|||
});
|
||||
}
|
||||
|
||||
const [showGenerateModal, setShowGenerateModal] = useState(false);
|
||||
const { showPreview } = usePreviewModal();
|
||||
|
||||
return <StructuredPanel title={agent.name} actions={[
|
||||
<ActionButton
|
||||
key="close"
|
||||
|
|
@ -113,22 +127,34 @@ export function AgentConfig({
|
|||
|
||||
<Divider />
|
||||
|
||||
<div className="w-full flex flex-col">
|
||||
<EditableField
|
||||
key="instructions"
|
||||
value={agent.instructions}
|
||||
onChange={(value) => {
|
||||
handleUpdate({
|
||||
...agent,
|
||||
instructions: value
|
||||
});
|
||||
}}
|
||||
markdown
|
||||
label="Instructions"
|
||||
multiline
|
||||
mentions
|
||||
mentionsAtValues={atMentions}
|
||||
/>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex justify-between items-center">
|
||||
<Label label="Instructions" />
|
||||
<Button
|
||||
variant="light"
|
||||
size="sm"
|
||||
startContent={<SparklesIcon size={16} />}
|
||||
onPress={() => setShowGenerateModal(true)}
|
||||
>
|
||||
Generate
|
||||
</Button>
|
||||
</div>
|
||||
<div className="w-full flex flex-col">
|
||||
<EditableField
|
||||
key="instructions"
|
||||
value={agent.instructions}
|
||||
onChange={(value) => {
|
||||
handleUpdate({
|
||||
...agent,
|
||||
instructions: value
|
||||
});
|
||||
}}
|
||||
markdown
|
||||
multiline
|
||||
mentions
|
||||
mentionsAtValues={atMentions}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Divider />
|
||||
|
|
@ -270,6 +296,150 @@ export function AgentConfig({
|
|||
<SelectItem key="relinquish_to_start" value="relinquish_to_start">Relinquish to 'start' agent</SelectItem>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Divider />
|
||||
|
||||
<PreviewModalProvider>
|
||||
<GenerateInstructionsModal
|
||||
projectId={projectId}
|
||||
workflow={workflow}
|
||||
agent={agent}
|
||||
isOpen={showGenerateModal}
|
||||
onClose={() => setShowGenerateModal(false)}
|
||||
currentInstructions={agent.instructions}
|
||||
onApply={(newInstructions) => {
|
||||
handleUpdate({
|
||||
...agent,
|
||||
instructions: newInstructions
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</PreviewModalProvider>
|
||||
</div>
|
||||
</StructuredPanel>;
|
||||
}
|
||||
|
||||
function GenerateInstructionsModal({
|
||||
projectId,
|
||||
workflow,
|
||||
agent,
|
||||
isOpen,
|
||||
onClose,
|
||||
currentInstructions,
|
||||
onApply
|
||||
}: {
|
||||
projectId: string,
|
||||
workflow: z.infer<typeof Workflow>,
|
||||
agent: z.infer<typeof WorkflowAgent>,
|
||||
isOpen: boolean,
|
||||
onClose: () => void,
|
||||
currentInstructions: string,
|
||||
onApply: (newInstructions: string) => void
|
||||
}) {
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { showPreview } = usePreviewModal();
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setPrompt("");
|
||||
setIsLoading(false);
|
||||
setError(null);
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const msgs: z.infer<typeof CopilotMessage>[] = [
|
||||
{
|
||||
role: 'user',
|
||||
content: prompt,
|
||||
},
|
||||
];
|
||||
const newInstructions = await getCopilotAgentInstructions(projectId, msgs, workflow, agent.name);
|
||||
|
||||
onClose();
|
||||
|
||||
showPreview(
|
||||
currentInstructions,
|
||||
newInstructions,
|
||||
true, // markdown enabled
|
||||
"Generated Instructions",
|
||||
"Review the changes below:", // message before diff
|
||||
() => onApply(newInstructions) // apply callback
|
||||
);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'An unexpected error occurred');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (prompt.trim() && !isLoading) {
|
||||
handleGenerate();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={onClose} size="lg">
|
||||
<ModalContent>
|
||||
<ModalHeader>Generate Instructions</ModalHeader>
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4">
|
||||
{error && (
|
||||
<div className="p-2 bg-red-50 border border-red-200 rounded-lg flex gap-2 justify-between items-center text-sm">
|
||||
<p className="text-red-600">{error}</p>
|
||||
<Button
|
||||
size="sm"
|
||||
color="danger"
|
||||
onClick={() => {
|
||||
setError(null);
|
||||
handleGenerate();
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
label="What should this agent do?"
|
||||
placeholder="e.g., This agent should help users analyze their data and provide insights..."
|
||||
variant="bordered"
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button
|
||||
variant="light"
|
||||
onPress={onClose}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handleGenerate}
|
||||
isLoading={isLoading}
|
||||
disabled={!prompt.trim()}
|
||||
>
|
||||
Generate
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,8 @@ import { CopilotAssistantMessageActionPart } from "../../../lib/types/copilot_ty
|
|||
import { CopilotUserMessage } from "../../../lib/types/copilot_types";
|
||||
import { Workflow } from "../../../lib/types/workflow_types";
|
||||
import { z } from "zod";
|
||||
import { getCopilotResponse } from "../../../actions/actions";
|
||||
import { Action } from "./copilot_actions";
|
||||
import { getCopilotResponse } from "@/app/actions/copilot_actions";
|
||||
import { Action } from "./copilot_action_components";
|
||||
import clsx from "clsx";
|
||||
import { Action as WorkflowDispatch } from "./workflow_editor";
|
||||
import MarkdownContent from "../../../lib/components/markdown-content";
|
||||
|
|
|
|||
|
|
@ -2,13 +2,11 @@
|
|||
import { createContext, useContext, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { z } from "zod";
|
||||
import { CopilotAssistantMessage } from "../../../lib/types/copilot_types";
|
||||
import { CopilotAssistantMessageActionPart } from "../../../lib/types/copilot_types";
|
||||
import { Workflow } from "../../../lib/types/workflow_types";
|
||||
import { PreviewModalProvider, usePreviewModal } from './preview-modal';
|
||||
import { getAppliedChangeKey } from "./copilot";
|
||||
import { AlertTriangleIcon, CheckCheckIcon, CheckIcon, ChevronsDownIcon, ChevronsUpIcon, EyeIcon, PencilIcon, PlusIcon } from "lucide-react";
|
||||
import { Tooltip } from "@nextui-org/react";
|
||||
|
||||
const ActionContext = createContext<{
|
||||
msgIndex: number;
|
||||
|
|
@ -176,6 +174,11 @@ export function ActionField({
|
|||
(action.config_type === 'prompt' && field === 'prompt') ||
|
||||
(action.config_type === 'tool' && field === 'description');
|
||||
|
||||
// generate apply change function
|
||||
const applyChangeHandler = () => {
|
||||
handleApplyChange(msgIndex, actionIndex, field);
|
||||
}
|
||||
|
||||
// generate preview modal function
|
||||
const previewModalHandler = () => {
|
||||
if (previewCondition) {
|
||||
|
|
@ -183,16 +186,13 @@ export function ActionField({
|
|||
oldValue ? (typeof oldValue === 'string' ? oldValue : JSON.stringify(oldValue)) : undefined,
|
||||
(typeof newValue === 'string' ? newValue : JSON.stringify(newValue)),
|
||||
markdownPreviewCondition,
|
||||
`${action.name} - ${field}`
|
||||
`${action.name} - ${field}`,
|
||||
"Review changes",
|
||||
applyChangeHandler
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// generate apply change function
|
||||
const applyChangeHandler = () => {
|
||||
handleApplyChange(msgIndex, actionIndex, field);
|
||||
}
|
||||
|
||||
return <div className="flex flex-col bg-white rounded-sm">
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="text-xs font-semibold px-2 py-1 text-gray-600">{field}</div>
|
||||
|
|
@ -3,6 +3,8 @@ import clsx from "clsx";
|
|||
import MarkdownContent from "../../../lib/components/markdown-content";
|
||||
import React, { PureComponent } from 'react';
|
||||
import ReactDiffViewer, { DiffMethod } from 'react-diff-viewer-continued';
|
||||
import { XIcon } from "lucide-react";
|
||||
import { Button } from "@nextui-org/react";
|
||||
|
||||
// Create the context type
|
||||
export type PreviewModalContextType = {
|
||||
|
|
@ -10,13 +12,15 @@ export type PreviewModalContextType = {
|
|||
oldValue: string | undefined,
|
||||
newValue: string,
|
||||
markdown: boolean,
|
||||
title: string
|
||||
title: string,
|
||||
message?: string,
|
||||
onApply?: () => void
|
||||
) => void;
|
||||
};
|
||||
|
||||
// Create the context
|
||||
export const PreviewModalContext = createContext<PreviewModalContextType>({
|
||||
showPreview: () => {}
|
||||
export const PreviewModalContext = createContext<PreviewModalContextType>({
|
||||
showPreview: () => { }
|
||||
});
|
||||
|
||||
// Export the hook for easy usage
|
||||
|
|
@ -29,6 +33,8 @@ export function PreviewModalProvider({ children }: { children: React.ReactNode }
|
|||
newValue: string;
|
||||
markdown: boolean;
|
||||
title: string;
|
||||
message?: string;
|
||||
onApply?: () => void;
|
||||
isOpen: boolean;
|
||||
}>({
|
||||
newValue: '',
|
||||
|
|
@ -48,8 +54,16 @@ export function PreviewModalProvider({ children }: { children: React.ReactNode }
|
|||
return () => window.removeEventListener('keydown', handleEsc);
|
||||
}, []);
|
||||
|
||||
const showPreview = (oldValue: string | undefined, newValue: string, markdown: boolean, title: string) => {
|
||||
setModalProps({ oldValue, newValue, markdown, title, isOpen: true });
|
||||
// Update the showPreview function
|
||||
const showPreview = (
|
||||
oldValue: string | undefined,
|
||||
newValue: string,
|
||||
markdown: boolean,
|
||||
title: string,
|
||||
message?: string,
|
||||
onApply?: () => void
|
||||
) => {
|
||||
setModalProps({ oldValue, newValue, markdown, title, message, onApply, isOpen: true });
|
||||
};
|
||||
|
||||
return (
|
||||
|
|
@ -71,12 +85,16 @@ function PreviewModal({
|
|||
newValue,
|
||||
markdown = false,
|
||||
title,
|
||||
message,
|
||||
onApply,
|
||||
onClose,
|
||||
}: {
|
||||
oldValue?: string | undefined;
|
||||
newValue: string;
|
||||
markdown?: boolean;
|
||||
title: string;
|
||||
message?: string;
|
||||
onApply?: () => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const buttonLabel = oldValue === undefined ? 'Preview' : 'Diff';
|
||||
|
|
@ -84,18 +102,30 @@ function PreviewModal({
|
|||
console.log(oldValue, newValue);
|
||||
|
||||
return <div className="fixed left-0 top-0 w-full h-full bg-gray-500/50 backdrop-blur-sm flex justify-center items-center z-50">
|
||||
<div className="bg-gray-100 rounded-md p-2 flex flex-col w-[90%] h-[90%] max-w-7xl max-h-[800px]">
|
||||
<button className="self-end text-gray-500 hover:text-gray-700 flex items-center gap-1"
|
||||
<div className="bg-white rounded-md p-2 flex flex-col w-[90%] gap-4 h-[90%] max-w-7xl max-h-[800px]">
|
||||
<button className="self-end text-gray-500 hover:text-gray-700 flex items-center gap-1"
|
||||
onClick={onClose}
|
||||
>
|
||||
<svg className="w-4 h-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
|
||||
<path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1" d="M6 18 17.94 6M18 18 6.06 6" />
|
||||
</svg>
|
||||
<div className="text-sm">Close</div>
|
||||
<XIcon className="w-4 h-4" />
|
||||
</button>
|
||||
<div className="flex flex-col overflow-auto">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="text-md font-semibold">{title}</div>
|
||||
{message && <div className="text-sm text-gray-600">{message}</div>}
|
||||
</div>
|
||||
{onApply && <Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
onClick={() => {
|
||||
onApply();
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
Apply changes
|
||||
</Button>}
|
||||
</div>
|
||||
<div className="bg-gray-100 rounded-md p-2 flex flex-col overflow-auto">
|
||||
<div className="flex items-center gap-2 justify-end">
|
||||
<div className="flex items-center">
|
||||
<button className={clsx("text-sm text-gray-500 hover:text-gray-700 px-2 py-1 rounded-t-md", {
|
||||
'bg-white': view === 'preview',
|
||||
|
|
|
|||
|
|
@ -861,6 +861,8 @@ export function WorkflowEditor({
|
|||
/>
|
||||
{state.present.selection?.type === "agent" && <AgentConfig
|
||||
key={state.present.selection.name}
|
||||
projectId={state.present.workflow.projectId}
|
||||
workflow={state.present.workflow}
|
||||
agent={state.present.workflow.agents.find((agent) => agent.name === state.present.selection!.name)!}
|
||||
usedAgentNames={new Set(state.present.workflow.agents.filter((agent) => agent.name !== state.present.selection!.name).map((agent) => agent.name))}
|
||||
agents={state.present.workflow.agents}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue