Skip to content

Commit

Permalink
work on agent creation and updating
Browse files Browse the repository at this point in the history
  • Loading branch information
eksno committed Apr 22, 2024
1 parent 4cfeff3 commit 68189d0
Show file tree
Hide file tree
Showing 7 changed files with 280 additions and 248 deletions.
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
<script lang="ts">
import * as Dialog from '$lib/components/ui/dialog';
import { Plus } from 'lucide-svelte';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
let open = false;
const handleTrigger = async () => {
open = true;
};
</script>

<Dialog.Root {open} onOpenChange={() => dispatch('close')}>
<Dialog.Root {open}>
<Dialog.Trigger
on:click={handleTrigger}
on:click={() => (open = true)}
class="transition-hover group relative flex aspect-[3/4] flex-col items-center justify-center overflow-hidden rounded-lg border border-primary bg-background from-primary-950 to-primary-800 shadow-lg duration-300 hover:scale-105 hover:bg-gradient-to-br hover:shadow-xl"
>
<Plus class="z-10 text-primary transition-all duration-300 group-hover:scale-150 " size="120" />
Expand Down
10 changes: 5 additions & 5 deletions apps/web/src/lib/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@ export const createCrewSchema = z.object({
});
export type CreateCrewSchema = typeof createCrewSchema;

export const createAgentSchema = z.object({
export const agentSchema = z.object({
id: z.string(),
title: z.string().min(1).max(50),
description: z.string().max(500).default(''),
published: z.boolean().default(false),
role: z.string().min(1).max(50),
tools: z.string(),
tools: z.array(z.record(z.string(), z.never())),
system_message: z.string().min(20),
model: z.string()
model: z.union([z.literal('gpt-4-turbo'), z.literal('gpt-3.5-turbo')])
});

export type CreateAgentSchema = typeof createAgentSchema;
export type AgentSchema = typeof agentSchema;

// TODO: rename to createUserSchema
export const formSchema = z.object({
Expand Down
186 changes: 75 additions & 111 deletions apps/web/src/routes/app/agents/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { supabase } from '$lib/supabase';
import { fail, error } from '@sveltejs/kit';
import { zod } from 'sveltekit-superforms/adapters';

import { createAgentSchema, editAgentSchema } from '$lib/schema';
import { superValidate } from 'sveltekit-superforms/server';
import { agentSchema } from '$lib/schema';
import { setError, superValidate } from 'sveltekit-superforms/server';
import { pickRandomAvatar } from '$lib/utils';
import api from '$lib/api';

Expand Down Expand Up @@ -34,7 +34,7 @@ export const load = async ({ locals }) => {
});

const form = {
create: await superValidate(zod(createAgentSchema))
agent: await superValidate(zod(agentSchema))
};

return {
Expand All @@ -45,132 +45,96 @@ export const load = async ({ locals }) => {

export const actions = {
create: async ({ request, locals }) => {
const session = await locals.getSession();
console.log('create agent');
const userSession = await locals.getSession();

const form = await superValidate(request, zod(createAgentSchema));
const form = await superValidate(request, zod(agentSchema));

if (!form.valid) {
return fail(400, { form, message: 'unable to create a new agent' });
}
console.log(form);
const randomAvatar = pickRandomAvatar();

let data, error;
const randomAvatar = pickRandomAvatar();

try {
({ data, error } = await supabase
.from('agents')
.insert([
{
profile_id: session?.user.id,
title: form.data.title,
description: form.data.description,
model: form.data.model === 'undefined' ? 'gpt-3.5-turbo' : form.data.model,
role: form.data.role,
published: form.data.published === 'on' ? true : false,
system_message: form.data.system_message,
tools: [
{
id: form.data.id,
parameter: {}
}
],
avatar: randomAvatar.avatarUrl,
version: '1.0'
}
])
.select());
} catch (error) {
console.error(error);
return fail(500, {
message: 'Something went wrong , please try again'
const agent = await api
.POST('/agents/', {
body: {
profile_id: userSession.user.id,
avatar: randomAvatar.avatarUrl,
title: form.data.title,
description: form.data.description,
// published: form.data.published,
role: form.data.role,
tools: form.data.tools,
system_message: form.data.system_message,
model: form.data.model === 'gpt-4-turbo' ? 'gpt-4-turbo-preview' : 'gpt-3.5-turbo'
}
})
.then(({ data: d, error: e }) => {
if (e) {
console.error(`Error creating crew: ${e.detail}`);
return fail(500, {
message:
'Agent create failed. Please try again. If the problem persists, contact support.'
});
}
if (!d) {
console.error(`No data returned from crew creation`);
return fail(500, {
message:
'Agent create failed. Please try again. If the problem persists, contact support.'
});
}
return d;
});
}

if (error) {
console.error('Error creating agent:', error);
return { error, message: error.message };
}

return {
message: 'Agent created successfully please reload the page to view your new agent'
};
return { form };
},
editAgent: async ({ request, url }) => {
const id = url.searchParams.get('id');
update: async ({ request, locals }) => {
console.log('update agent');
const userSession = await locals.getSession();

const form = await superValidate(request, zod(createAgentSchema));
console.log(form, 'form');

const currentAgent = await supabase
.from('agents')
.select('*')
.eq('id', id?.split('$')[1])
.single();

const prev_tools = currentAgent.data.tools;

console.log(prev_tools);
const form = await superValidate(request, zod(agentSchema));

if (!form.valid) {
return fail(400, { form, message: 'Could not edit agent' });
return fail(400, { form, message: 'unable to create a new agent' });
}

console.log(form);

let data, error;

try {
({ data, error } = await supabase
.from('agents')
.update({
const agent = await api
.PATCH('/agents/{id}', {
params: {
path: {
id: form.data.id
}
},
body: {
title: form.data.title,
role: form.data.role,
description: form.data.description,
tools: [
...currentAgent.data.tools,
{
id: form.data.id,
parameter: {}
}
],
published: form.data.published,
role: form.data.role,
tools: form.data.tools,
system_message: form.data.system_message,
model: form.data.model,
published: form.data.published === 'on' ? true : false
})
.eq('id', id?.split('$')[1]));
} catch (error) {
console.error('something when wron when editing agent:', error);
return fail(500, { message: 'Something went wrong, please try again' });
}

if (error) {
console.error('Error editing agent:', error);
return { error };
}

console.log('Agent edited successfully:', data);
return {
message: 'Agent edited successfully please reload to see the changes you made'
};
},
removeTools: async ({ request, url }) => {
const id = url.searchParams.get('id');
const toolId = url.searchParams.get('toolId');
const form = await request.formData();

console.log(id, toolId, 'id, toolId');

const currentAgent = await supabase.from('agents').select('*').eq('id', id).single();

console.log(currentAgent, 'currentAgent');

const deleteTool = currentAgent.data.tools.filter((tool) => tool.id !== toolId);
const { data, error } = await supabase
.from('agents')
.update({
tools: deleteTool
model: form.data.model === 'gpt-4-turbo' ? 'gpt-4-turbo-preview' : 'gpt-3.5-turbo'
}
})
.eq('id', id);
.then(({ data: d, error: e }) => {
if (e) {
console.error(`Error creating crew: ${e.detail}`);
throw fail(500, {
message:
'Agent update failed. Please try again. If the problem persists, contact support.'
});
}
if (!d) {
console.error(`No data returned from crew creation`);
throw fail(500, {
message:
'Agent update failed. Please try again. If the problem persists, contact support.'
});
}
return d;
});

return { form };
}
};
74 changes: 43 additions & 31 deletions apps/web/src/routes/app/agents/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<script lang="ts">
import CreateForm from './CreateForm.svelte';
import UpdateForm from './UpdateForm.svelte';
import * as AlertDialog from '$lib/components/ui/alert-dialog';
import * as Dialog from '$lib/components/ui/dialog';
import { Button } from '$lib/components/ui/button';
import api from '$lib/api';
import { toast } from 'svelte-sonner';
Expand All @@ -25,42 +27,52 @@
return d;
});
};
let open = false;
</script>

<Library.Root>
<Library.CreateButton>
<CreateForm formCreate={data.form.create} />
<CreateForm formCreate={data.form.agent} />
</Library.CreateButton>
{#each data.agents as agent}
<Library.Entry avatar={agent.avatar}>
<div slot="content">
<Library.EntryHeader>
{agent.title}
</Library.EntryHeader>
<Library.EntryContent>
{agent.role}
</Library.EntryContent>
</div>
<div slot="delete">
<AlertDialog.Header>
<AlertDialog.Title>Are you sure absolutely sure?</AlertDialog.Title>
<AlertDialog.Description>
This action cannot be undone. This will permanently delete this agent from our services.
Make sure to delete the agent from all of your own crews before you perform this action.
</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Footer>
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
<Button
on:click={() => {
deleteAgent(agent.id);
data.agents = data.agents.filter((c) => c.id !== agent.id);
}}
variant="destructive"
class="bg-red-900">Delete</Button
>
</AlertDialog.Footer>
</div>
</Library.Entry>
<Dialog.Root {open}>
<Dialog.Trigger>
<Library.Entry on:click={() => (open = true)} avatar={agent.avatar}>
<div slot="content">
<Library.EntryHeader>
{agent.title}
</Library.EntryHeader>
<Library.EntryContent>
{agent.role}
</Library.EntryContent>
</div>
<div slot="delete">
<AlertDialog.Header>
<AlertDialog.Title>Are you sure absolutely sure?</AlertDialog.Title>
<AlertDialog.Description>
This action cannot be undone. This will permanently delete this agent from our
services. Make sure to delete the agent from all of your own crews before you
perform this action.
</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Footer>
<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
<Button
on:click={() => {
deleteAgent(agent.id);
data.agents = data.agents.filter((c) => c.id !== agent.id);
}}
variant="destructive"
class="bg-red-900">Delete</Button
>
</AlertDialog.Footer>
</div>
</Library.Entry>
</Dialog.Trigger>
<Dialog.Content>
<UpdateForm {agent} formUpdate={data.form.agent} />
</Dialog.Content>
</Dialog.Root>
{/each}
</Library.Root>
Loading

0 comments on commit 68189d0

Please sign in to comment.