Skip to content
Merged
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
119 changes: 119 additions & 0 deletions apps/api/src/endpoints/trpc/plants/chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { TRPCError } from '@trpc/server'
import { z } from 'zod'

import {
Fertilizer,
Plant,
type IChore,
type IFertilizer,
type ISpecies,
} from '../../../models'

import { authProcedure } from '../../../procedures/authProcedure'

import { createClient } from '../../../services/openAi'

const messageSchema = z.object({
role: z.enum(['user', 'assistant']),
content: z.string(),
})

export const chat = authProcedure
.input(z.object({
plantId: z.string(),
messages: z.array(messageSchema).min(1),
}))
.mutation(async ({ ctx, input }) => {
const plant = await Plant
.findOne({ _id: input.plantId, user: ctx.userId })
.populate<{ species: ISpecies }>('species')
.populate<{ chores: (Omit<IChore, 'fertilizers' | 'logs'> & { fertilizers: Array<{ fertilizer: IFertilizer, amount: string }> })[] }>({
path: 'chores',
populate: { path: 'fertilizers.fertilizer' },
match: { deletedAt: null },
})
.lean()

if (!plant) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Plant not found',
})
}

const fertilizers = await Fertilizer
.find({ user: ctx.userId, deletedAt: null })
.sort({ name: 1 })
.lean()

const systemParts: string[] = [
'You are an expert on growing plants. The user is chatting about a specific plant in their care.',
'',
'**This plant**',
`- Name: ${plant.name}`,
`- Lifecycle stage: ${plant.lifecycle ?? 'not set'}`,
plant.plantedAt
? `- Planted on: ${new Date(plant.plantedAt).toLocaleDateString('en-US')}`
: '',
plant.notes?.trim()
? `- Notes: ${plant.notes}`
: '',
].filter(Boolean)

const species = plant.species
if (species) {
systemParts.push('', '**Species**', `- Common name: ${species.commonName}`)
if (species.scientificName) systemParts.push(`- Scientific name: ${species.scientificName}`)
if (species.familyCommonName) systemParts.push(`- Family: ${species.familyCommonName}`)
if (species.genus) systemParts.push(`- Genus: ${species.genus}`)
if (species.fertilizerRecommendations?.text) {
systemParts.push('', 'Fertilizer guidance for this species:', species.fertilizerRecommendations.text)
}
}

const chores = plant.chores ?? []
if (chores.length > 0) {
systemParts.push('', '**Chores assigned to this plant**')
chores.forEach((chore, i) => {
const desc = chore.fertilizers?.length
? chore.fertilizers.map(f => `${f.fertilizer.name}${f.amount ? ` (${f.amount})` : ''}`).join(', ')
: chore.description || 'Task'
const recur = chore.recurAmount && chore.recurUnit
? ` every ${chore.recurAmount} ${chore.recurUnit}${chore.recurAmount === 1 ? '' : 's'}`
: ''
systemParts.push(`${i + 1}. ${desc}${recur}`)
})
}

if (fertilizers.length > 0) {
systemParts.push('', '**Fertilizers in the user\'s inventory**')
fertilizers.forEach((f: IFertilizer) => {
const npk = [f.nitrogen, f.phosphorus, f.potassium].map(n => n ?? '—').join('-')
systemParts.push(`- ${f.name}: type ${f.type}, organic: ${f.isOrganic}, N-P-K: ${npk}`)
})
}

systemParts.push(
'',
'Answer in a helpful, concise way. Reference their plant, chores, and fertilizers when relevant. Keep responses focused and practical.',
)

const openai = createClient()
const completion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: systemParts.join('\n') },
...input.messages.map(m => ({ role: m.role as 'user' | 'assistant', content: m.content })),
],
})

const choice = completion.choices[0]
const content = choice?.message?.content ?? ''

return {
message: {
role: 'assistant',
content,
},
}
})
2 changes: 2 additions & 0 deletions apps/api/src/routers/trpc/plants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { router } from '../../trpc'

import { archivePlant } from '../../endpoints/trpc/plants/archivePlant'
import { chat } from '../../endpoints/trpc/plants/chat'
import { createPlant } from '../../endpoints/trpc/plants/createPlant'
import { deletePlant } from '../../endpoints/trpc/plants/deletePlant'
import { listPlantLifecycleEvents } from '../../endpoints/trpc/plants/listPlantLifecycleEvents'
Expand All @@ -10,6 +11,7 @@ import { updatePlant } from '../../endpoints/trpc/plants/updatePlant'

export const plantsRouter = router({
archive: archivePlant,
chat,
create: createPlant,
delete: deletePlant,
list: listPlants,
Expand Down
21 changes: 19 additions & 2 deletions apps/mobile/src/app/plants/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import type { ISpecies } from '@plannting/api/dist/models/Species'

import { AddEditChoreModal } from '../../components/AddEditChoreModal'
import { AddEditPlantModal } from '../../components/AddEditPlantModal'
import { Chat } from '../../components/Chat'
import { DateTimePicker } from '../../components/DateTimePicker'
import { Fab } from '../../components/Fab'
import { FertilizerRecommendations } from '../../components/FertilizerRecommendations'
import { LoadingSkeleton, LoadingSkeletonLine } from '../../components/LoadingSkeleton'
import { PlantHistogram } from '../../components/PlantHistogram'
Expand Down Expand Up @@ -55,6 +57,7 @@ export default function PlantDetailScreen() {
const [showLifecycleChangeDatePicker, setShowLifecycleChangeDatePicker] = React.useState(false)
const [pendingLifecycleChange, setPendingLifecycleChange] = React.useState<{ plantId: string, data: EditFormData } | null>(null)

const [showChat, setShowChat] = React.useState(false)
const [showChoreForm, setShowChoreForm] = React.useState(false)
const [choreFormData, setChoreFormData] = React.useState<{
description: string,
Expand Down Expand Up @@ -227,7 +230,8 @@ export default function PlantDetailScreen() {
}

return (
<ScreenWrapper onRefresh={refetch} style={{ backgroundColor: '#fff' }}>
<>
<ScreenWrapper onRefresh={refetch} style={{ backgroundColor: '#fff' }}>
<ScreenTitle isLoading={isRefetching}>
{plant?.name || <ActivityIndicator size="small" color={palette.textPrimary} />}
</ScreenTitle>
Expand Down Expand Up @@ -324,6 +328,17 @@ export default function PlantDetailScreen() {
</View>
</Modal>

{plant && (
<Chat
endpoint={trpc.plants.chat}
endpointProps={{ plantId: plant._id }}
isVisible={showChat}
onClose={() => setShowChat(false)}
title={plant.name}
description='Ask anything about growing this plant. I know its species, your chores, and your fertilizer inventory.'
/>
)}

<AddEditChoreModal
isVisible={showChoreForm}
mode='add'
Expand Down Expand Up @@ -447,7 +462,9 @@ export default function PlantDetailScreen() {
</TouchableOpacity>
</View>
)}
</ScreenWrapper>
</ScreenWrapper>
{plant && <Fab type='chat' onPress={() => setShowChat(true)} />}
</>
)
}

Expand Down
Loading