Skip to content

Commit

Permalink
working on crews
Browse files Browse the repository at this point in the history
  • Loading branch information
eksno committed Apr 18, 2024
1 parent c0a3f3f commit 548701a
Show file tree
Hide file tree
Showing 10 changed files with 240 additions and 82 deletions.
8 changes: 4 additions & 4 deletions apps/api/src/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,15 @@ def process_crew(crew: Crew) -> tuple[str, CrewProcessed]:
if not crew.prompt:
raise HTTPException(400, "got no prompt")
if len(crew_model.agents) == 0:
raise ValueError("crew had no agents")
raise HTTPException(400, "crew had no agents")
# Validate agents
for agent in crew_model.agents:
if agent.role == "":
raise ValueError(f"agent {agent.id} had no role")
raise HTTPException(400, f"agent {agent.id} had no role")
if agent.title == "":
raise ValueError(f"agent {agent.id} had no title")
raise HTTPException(400, f"agent {agent.id} had no title")
if agent.system_message == "":
raise ValueError(f"agent {agent.id} had no system message")
raise HTTPException(400, f"agent {agent.id} had no system message")

message: str = crew.prompt["content"]
return message, crew_model
Expand Down
3 changes: 0 additions & 3 deletions apps/web/.env.example

This file was deleted.

3 changes: 2 additions & 1 deletion apps/web/src/lib/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import createClient from 'openapi-fetch';
import type { paths, components } from '$lib/api/v0.d.ts';
import { PUBLIC_API_URI } from '$env/static/public';

const api = createClient<paths>({ baseUrl: 'https://api.aiti.no/' });
const api = createClient<paths>({ baseUrl: PUBLIC_API_URI });
export default api;

type schemas = components['schemas'];
Expand Down
44 changes: 22 additions & 22 deletions apps/web/src/lib/components/ui/prompt-editor/prompt-editor.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<script lang="ts">
import { Loader2 } from 'lucide-svelte';
import { PUBLIC_API_URL } from '$env/static/public';
import * as Dialog from '$lib/components/ui/dialog';
import { Button } from '$lib/components/ui/button';
Expand All @@ -24,27 +23,28 @@
const temperature = 0; // Default to 0 if not provided
const prompt_type = 'generic'; // Default to generic if not provided
const apiUrl = `${PUBLIC_API_URL}/improve?word_limit=${wordLimit}&prompt=${encodeURIComponent(value)}&temperature=${temperature}&prompt_type=${prompt_type}`;
try {
const response = await fetch(apiUrl);
if (!response.ok) {
state = 'error';
console.log(`request failed: ${response.status}, ${response.statusText}`);
}
let data = await response.json();
console.log(data);
state = 'idle';
if (data.startsWith('```markdown')) {
data = data.substring(11); // Remove the starting ```markdown
data = data.substring(0, data.lastIndexOf('```')); // Remove the closing ```
}
value = data;
} catch (error) {
state = 'error';
console.log(`HTTP error! status: ${error}`);
}
// TODO: implement openapi fetche
// const apiUrl = `${PUBLIC_API_URL}/improve?word_limit=${wordLimit}&prompt=${encodeURIComponent(value)}&temperature=${temperature}&prompt_type=${prompt_type}`;
//
// try {
// const response = await fetch(apiUrl);
// if (!response.ok) {
// state = 'error';
// console.log(`request failed: ${response.status}, ${response.statusText}`);
// }
//
// let data = await response.json();
// console.log(data);
// state = 'idle';
// if (data.startsWith('```markdown')) {
// data = data.substring(11); // Remove the starting ```markdown
// data = data.substring(0, data.lastIndexOf('```')); // Remove the closing ```
// }
// value = data;
// } catch (error) {
// state = 'error';
// console.log(`HTTP error! status: ${error}`);
// }
} catch (error) {
state = 'error';
console.error('Error fetching improved prompt:', error);
Expand Down
7 changes: 7 additions & 0 deletions apps/web/src/lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Writable } from 'svelte/store';

import type { Variant } from '$lib/components/ui/button';
import type Stripe from 'stripe';
import type { schemas } from '$lib/api';

export type SvelteEvent<E extends Event = Event, T extends EventTarget = Element> = E & {
currentTarget: EventTarget & T;
Expand All @@ -28,6 +29,12 @@ export interface ContextMap {
export interface CrewContext {
receiver: Writable<{ node: Node; targetCount: number } | null>;
count: Writable<{ agents: number; prompts: number }>;
profileId: Writable<string>;
crew: Writable<schemas['Crew']>;
agents: Writable<schemas['Agent'][]>;
publishedAgents: Writable<schemas['Agent'][]>;
nodes: Writable<Node[]>;
edges: Writable<Edge[]>;
}

export type Categories =
Expand Down
7 changes: 0 additions & 7 deletions apps/web/src/routes/app/crews/[id]/+layout.svelte
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
<script lang="ts">
import { SvelteFlowProvider } from '@xyflow/svelte';
import { setContext } from 'svelte';
import { writable } from 'svelte/store';
setContext('crew', {
receiver: writable(null),
count: writable({ agents: 0, prompts: 0 })
});
</script>

<SvelteFlowProvider>
Expand Down
25 changes: 18 additions & 7 deletions apps/web/src/routes/app/crews/[id]/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { error, redirect } from '@sveltejs/kit';
import api, { type schemas } from '$lib/api';
import type { Edge, Node } from '@xyflow/svelte';
import { writable } from 'svelte/store';
import { getWritablePrompt } from '$lib/utils.js';
import type { CrewContext } from '$lib/types/index.js';

const processEdges = (crewEdges: schemas['Crew']['edges']): Edge[] => {
let edges: Edge[] = [];
Expand Down Expand Up @@ -57,7 +60,7 @@ const getNodesByCrewId = async (crew_id: string): Promise<Node[]> => {
return nodes;
};

export const load = async ({ locals: { getSession }, params }) => {
export const load = async ({ locals: { getSession }, params }): Promise<CrewContext> => {
const { id } = params;
const session = await getSession();
const profileId = session?.user?.id as string;
Expand Down Expand Up @@ -135,13 +138,21 @@ export const load = async ({ locals: { getSession }, params }) => {
throw error(500, 'Failed to load published agents');
}

// TODO: get the prompt count and receiver agent if it exists
const count = { agents: userAgents.length, prompts: 0 };
const receiver = null;
const nodes = getWritablePrompt(await getNodesByCrewId(crew.id));
const edges = processEdges(crew.edges);

return {
profileId: profileId,
crew: crew,
myAgents: userAgents,
publishedAgents: publishedAgents,
nodes: await getNodesByCrewId(crew.id),
edges: processEdges(crew.edges)
count: writable(count),
receiver: writable(receiver),
profileId: writable(profileId),
crew: writable(crew),
agents: writable(userAgents),
publishedAgents: writable(publishedAgents),
nodes: writable(nodes),
edges: writable(edges)
};
};

Expand Down
60 changes: 26 additions & 34 deletions apps/web/src/routes/app/crews/[id]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,24 @@
import * as Dialog from '$lib/components/ui/dialog';
import { AgentLibrary } from '$lib/components/ui/library';
import * as CustomNode from '$lib/components/ui/custom-node';
import { getContext, getWritablePrompt, getCleanNodes } from '$lib/utils';
import { getContext, getCleanNodes } from '$lib/utils';
import type { PanelAction } from '$lib/types';
import { AGENT_LIMIT, PROMPT_LIMIT } from '$lib/config.js';
import { AGENT_LIMIT, PROMPT_LIMIT } from '$lib/config';
import { goto } from '$app/navigation';
import { setContext } from 'svelte';
export let data;
const { receiver, count } = getContext('crew');
let initialized = false;
$: if (initialized) {
data.crew.receiver_id = $receiver ? $receiver.node.id : null;
}
let title = data.crew.title;
$: data.crew.title = title;
let description = data.crew.description;
$: data.crew.description = description;
setContext('crew', data);
let { count, receiver, profileId, crew, agents, publishedAgents, nodes, edges } =
getContext('crew');
let openAgentLibrary = false;
let status: 'saving' | 'running' | 'idle' = 'idle';
let actions: PanelAction[];
$: actions = [
let panelActions: PanelAction[];
$: panelActions = [
{
name: 'Run',
loading: status === 'running',
Expand All @@ -67,8 +61,8 @@
{
nodes: getCleanNodes($nodes),
edges: $edges,
title,
description,
title: $crew.title,
description: $crew.description,
receiver_id: $receiver?.node.id ?? null
},
null,
Expand Down Expand Up @@ -138,21 +132,13 @@
return { nodes, edges };
}
const nodes = writable<Node[]>(getWritablePrompt(data.nodes));
const edges = writable<Edge[]>(data.edges);
$: data.nodes = getCleanNodes($nodes);
$: data.edges = $edges;
layout();
async function save() {
status = 'saving';
const response = await (
await fetch('?/save', {
method: 'POST',
body: JSON.stringify(data.crew)
body: JSON.stringify(crew)
})
).json();
Expand Down Expand Up @@ -187,17 +173,17 @@
function addAgent(data: any) {
if ($count.agents >= AGENT_LIMIT) return;
const existingNode = $nodes.find((node) => node.id === data.id);
const existingNode = $nodes.find((node) => node.id === id);
if (existingNode) {
console.log(`Node with ID ${data.id} already exists.`);
console.log(`Node with ID ${id} already exists.`);
return;
}
const position = { ...getViewport() };
nodes.update((v) => [
...v,
{
id: data.id,
id: id,
type: 'agent',
position,
selectable: false,
Expand Down Expand Up @@ -230,6 +216,8 @@
$count.prompts++;
}
layout();
</script>

<div style="height:100vh;">
Expand All @@ -240,9 +228,8 @@
{nodeTypes}
fitView
oninit={() => {
setReceiver(data.crew.receiver_id);
initialized = true;
data.nodes.forEach((n) => {
setReceiver($receiver ? $receiver.node.id : null);
getCleanNodes($nodes).forEach((n) => {
if (n.type === 'agent') {
$count.agents++;
} else {
Expand Down Expand Up @@ -284,7 +271,12 @@
<Background class="!bg-background" />

<Panel position="top-right">
<RightEditorSidebar bind:description bind:title {actions} let:action>
<RightEditorSidebar
bind:description={$crew.description}
bind:title={$crew.title}
actions={panelActions}
let:action
>
{#if action.isCustom}
<Dialog.Root open={openAgentLibrary} onOpenChange={(o) => (openAgentLibrary = o)}>
<Dialog.Trigger>
Expand All @@ -294,8 +286,8 @@
</Dialog.Trigger>
<Dialog.Content class="max-w-6xl">
<AgentLibrary
myAgents={data.myAgents}
publishedAgents={data.publishedAgents}
myAgents={agents}
{publishedAgents}
on:load-agent={({ detail }) => {
addAgent(detail);
}}
Expand Down
Loading

0 comments on commit 548701a

Please sign in to comment.