109 lines
3.3 KiB
TypeScript
109 lines
3.3 KiB
TypeScript
import { ref } from 'vue'
|
|
import type { Agent } from '~~/types'
|
|
|
|
export const useAgents = async () => {
|
|
const { addTask, completeTask } = useTasks()
|
|
|
|
const fetchingAgents = ref(false);
|
|
const agents: Ref<Agent[] | null> = useState('agents', () => null);
|
|
const activeAgent = computed(() => {
|
|
if (agents.value === null) return;
|
|
|
|
const routeId = useRoute().params.id;
|
|
if (routeId === undefined) return;
|
|
|
|
const agent = agents.value.find(agent => agent.id === routeId);
|
|
if (agent === undefined) return;
|
|
|
|
return agent;
|
|
});
|
|
|
|
const refreshAgents = async () => {
|
|
if (fetchingAgents.value) return;
|
|
fetchingAgents.value = true;
|
|
|
|
const { data, error } = await useFetch('/api/agents');
|
|
if (error.value) throw error;
|
|
agents.value = data.value!;
|
|
|
|
fetchingAgents.value = false;
|
|
}
|
|
|
|
if (agents.value === null) await refreshAgents();
|
|
|
|
const createAgent = async () => {
|
|
const taskHandle = addTask()
|
|
|
|
try {
|
|
const agent = await $fetch('/api/agents', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({
|
|
name: 'New Agent',
|
|
systemPrompt: 'You are a helpful assistant.'
|
|
})
|
|
});
|
|
|
|
if (agent === undefined) throw new Error('Failed to create agent');
|
|
|
|
if (agents.value === null) agents.value = [];
|
|
|
|
agents.value.push(agent);
|
|
|
|
completeTask(taskHandle)
|
|
|
|
return agent;
|
|
} catch (error) {
|
|
console.error(error);
|
|
completeTask(taskHandle)
|
|
return;
|
|
}
|
|
}
|
|
|
|
let debounceTimeout: NodeJS.Timeout | null = null;
|
|
const updateAgent = async (id: string, data: Partial<Agent>) => {
|
|
if (agents.value === null) agents.value = [];
|
|
|
|
// update the local state always
|
|
agents.value = agents.value.map(agent => {
|
|
if (agent.id === id) return { ...agent, ...data };
|
|
return agent;
|
|
});
|
|
|
|
// falling edge debounce (when the user stops typing)
|
|
if (debounceTimeout !== null) clearTimeout(debounceTimeout);
|
|
debounceTimeout = setTimeout(async () => {
|
|
const taskHandle = addTask()
|
|
|
|
try {
|
|
const agent = await $fetch(`/api/agents/${id}`, {
|
|
method: 'PATCH',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(data)
|
|
});
|
|
|
|
if (agent === undefined) throw new Error('Failed to update agent');
|
|
|
|
const index = agents.value!.findIndex(agent => agent.id === id);
|
|
if (index === -1) throw new Error('Agent not found');
|
|
if (agents.value![index] === null) throw new Error('Agent not found');
|
|
|
|
agents.value![index] = agent;
|
|
|
|
completeTask(taskHandle)
|
|
|
|
return agent;
|
|
} catch (error) {
|
|
console.error(error);
|
|
completeTask(taskHandle)
|
|
return;
|
|
}
|
|
}, 500);
|
|
}
|
|
|
|
return { agents, createAgent, activeAgent, updateAgent };
|
|
} |