Skip to content

Commit d268f95

Browse files
committed
add temperature setting to v2
1 parent 214b8c9 commit d268f95

File tree

4 files changed

+113
-37
lines changed

4 files changed

+113
-37
lines changed

src/client/components/ChatV2/ChatV2.tsx

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,35 +37,40 @@ export const ChatV2 = () => {
3737
const { infoTexts, isLoading: infoTextsLoading } = useInfoTexts()
3838

3939
const { userStatus, isLoading: statusLoading, refetch: refetchStatus } = useUserStatus(courseId)
40+
41+
// local storage states
42+
const localStoragePrefix = 'general'
4043
const [model, setModel] = useLocalStorageState<{ name: string }>('model-v2', {
4144
name: DEFAULT_MODEL,
4245
})
43-
44-
// local storage
45-
const localStoragePrefix = 'general'
4646
// TODO: Do translation
4747
const defaultInstructions = 'Olet avulias avustaja'
4848
const [assistantInstructions, setAssistantInstructions] = useLocalStorageState<{ content: string }>(`${localStoragePrefix}-chat-instructions`, {
4949
content: defaultInstructions,
5050
})
51+
const [modelTemperature, setModelTemperature] = useLocalStorageState<{ value: number }>(`${localStoragePrefix}-chat-model-temperature`, {
52+
value: 0.5,
53+
})
5154
const [message, setMessage] = useLocalStorageState<{ content: string }>(`${localStoragePrefix}-chat-current`, { content: '' })
5255
const [messages, setMessages] = useLocalStorageState<Message[]>(`${localStoragePrefix}-chat-messages`, [])
5356
const [prevResponse, setPrevResponse] = useLocalStorageState<{ id: string }>(`${localStoragePrefix}-prev-response`, { id: '' })
57+
const [fileSearchResult, setFileSearchResult] = useLocalStorageState<FileSearchResult>('last-file-search', null)
5458

55-
// States
59+
// UI States
5660
const [settingsModalOpen, setSettingsModalOpen] = useState(true)
57-
const [activePromptId, setActivePromptId] = useState('')
5861
const [fileName, setFileName] = useState<string>('')
59-
const [completion, setCompletion] = useState<string>('')
60-
const [isCompletionDone, setIsCompletionDone] = useState<boolean>(true)
61-
const [fileSearchResult, setFileSearchResult] = useLocalStorageState<FileSearchResult>('last-file-search', null)
62-
const [streamController, setStreamController] = useState<AbortController>()
6362
const [alertOpen, setAlertOpen] = useState(false)
6463
const [disallowedFileType, setDisallowedFileType] = useState('')
6564
const [tokenUsageWarning, setTokenUsageWarning] = useState('')
6665
const [tokenWarningVisible, setTokenWarningVisible] = useState(false)
67-
const [modelTemperature, setModelTemperature] = useState(0.5)
6866
const [saveConsent, setSaveConsent] = useState(true)
67+
68+
// Chat Streaming states
69+
const [completion, setCompletion] = useState<string>('')
70+
const [isCompletionDone, setIsCompletionDone] = useState<boolean>(true)
71+
const [streamController, setStreamController] = useState<AbortController>()
72+
73+
// RAG states
6974
const [ragIndexId, setRagIndexId] = useState<number | null>(null)
7075
const ragIndex = ragIndices?.find((index) => index.id === ragIndexId) ?? null
7176

@@ -176,7 +181,7 @@ export const ChatV2 = () => {
176181
model: model.name,
177182
formData: new FormData(),
178183
userConsent: true,
179-
modelTemperature,
184+
modelTemperature: modelTemperature.value,
180185
courseId,
181186
abortController: streamController,
182187
saveConsent,
@@ -414,6 +419,8 @@ export const ChatV2 = () => {
414419
setOpen={setSettingsModalOpen}
415420
assistantInstructions={assistantInstructions.content}
416421
setAssistantInstructions={(updatedInstructions) => setAssistantInstructions({ content: updatedInstructions })}
422+
modelTemperature={modelTemperature.value}
423+
setModelTemperature={(updatedTemperature) => setModelTemperature({ value: updatedTemperature })}
417424
model={model.name}
418425
setModel={(name) => setModel({ name })}
419426
setRagIndex={setRagIndexId}

src/client/components/ChatV2/SettingsModal.tsx

Lines changed: 72 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
import { Close } from '@mui/icons-material'
2-
import { Box, IconButton, Modal, TextField, Typography } from '@mui/material'
2+
import { Box, IconButton, Modal, Slider, TextField, Typography } from '@mui/material'
33
import ModelSelector from './ModelSelector'
44
import { validModels } from '../../../config'
55
import React from 'react'
66
import RagSelector from './RagSelector'
77
import { RagIndexAttributes } from '../../../shared/types'
8+
import SettingsButton from './generics/SettingsButton'
89

910
interface SettingsModalProps {
1011
open: boolean
1112
setOpen: (open: boolean) => void
1213
assistantInstructions: string
1314
setAssistantInstructions: (instructions: string) => void
15+
modelTemperature: number
16+
setModelTemperature: (value: number) => void
1417
model: string
1518
setModel: (model: string) => void
1619
setRagIndex: (ragIndex: number) => void
@@ -23,12 +26,18 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
2326
setOpen,
2427
assistantInstructions,
2528
setAssistantInstructions,
29+
modelTemperature,
30+
setModelTemperature,
2631
model,
2732
setModel,
2833
setRagIndex,
2934
ragIndices,
3035
currentRagIndex,
3136
}) => {
37+
const resetSettings = () => {
38+
alert('resetting')
39+
}
40+
3241
return (
3342
<Modal open={open} onClose={() => setOpen(false)}>
3443
<Box
@@ -39,38 +48,78 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
3948
transform: 'translate(-50%, -50%)',
4049
display: 'flex',
4150
flexDirection: 'column',
42-
gap: '1.2rem',
51+
justifyContent: 'space-between',
4352
minWidth: 600,
4453
width: '85vw',
4554
maxWidth: 1000,
46-
minHeight: '70vh',
55+
minHeight: '80vh',
56+
maxHeight: '80vh',
4757
bgcolor: 'background.paper',
4858
boxShadow: 24,
49-
p: '2.5rem',
5059
borderRadius: '0.3rem',
60+
overflow: 'hidden',
5161
}}
5262
>
53-
<IconButton onClick={() => setOpen(false)} sx={{ position: 'absolute', top: 8, right: 8, color: 'grey.500' }}>
63+
<IconButton onClick={() => setOpen(false)} sx={{ position: 'absolute', top: 10, right: 20, color: 'grey.500' }}>
5464
<Close />
5565
</IconButton>
56-
<Typography variant="h6" fontWeight={600}>
57-
Alustus
58-
</Typography>
59-
<Typography variant="body1">
60-
Alustuksella tarkoitetaan yleistason ohjeistusta keskustelulle. Kielimallia voi esimerkiksi pyytää käyttämään akateemista kieltä tai esittämään puutarhuria jota
61-
haastatellaan kaktusten hoidosta.
62-
</Typography>
63-
{/* <ModelSelector currentModel={model} setModel={setModel} models={validModels.map((m) => m.name)} /> */}
64-
{/* Disabled for now due to RAG not functioning cirreclty */}
65-
{/* <RagSelector currentRagIndex={currentRagIndex} setRagIndex={setRagIndex} ragIndices={ragIndices} /> */}
66-
<TextField
67-
multiline
68-
minRows={6}
69-
maxRows={10}
70-
label="Alustuksen sisältö"
71-
value={assistantInstructions}
72-
onChange={(e) => setAssistantInstructions(e.target.value)}
73-
/>
66+
67+
<Box
68+
sx={{
69+
flex: 1,
70+
display: 'flex',
71+
flexDirection: 'column',
72+
gap: '1.2rem',
73+
overflowY: 'auto',
74+
p: '3rem',
75+
}}
76+
>
77+
<Typography variant="h6" fontWeight={600}>
78+
Keskustelun alustus
79+
</Typography>
80+
<Typography variant="body1">
81+
Alustuksella tarkoitetaan yleistason ohjeistusta keskustelulle. Kielimallia voi esimerkiksi pyytää käyttämään akateemista kieltä tai esittämään puutarhuria
82+
jota haastatellaan kaktusten hoidosta.
83+
</Typography>
84+
<TextField
85+
multiline
86+
minRows={6}
87+
maxRows={10}
88+
label="Alustuksen sisältö"
89+
value={assistantInstructions}
90+
onChange={(e) => setAssistantInstructions(e.target.value)}
91+
/>
92+
93+
<Typography variant="h6" fontWeight={600} mt="2rem">
94+
Säädä kielimallin tarkkuutta
95+
</Typography>
96+
<Typography variant="body1">
97+
Suuremmat arvot, kuten 0.8, tekevät tulosteesta satunnaisemman, kun taas pienemmät arvot, kuten 0.2, tekevät siitä tarkemman ja deterministisemmän.
98+
</Typography>
99+
<Box sx={{ border: '1px solid rgba(0,0,0,0.25)', borderRadius: '6px', maxWidth: 500, padding: '2rem' }}>
100+
<Slider
101+
min={0.0}
102+
max={1.0}
103+
step={0.1}
104+
value={modelTemperature}
105+
marks
106+
valueLabelDisplay="auto"
107+
onChange={(_event, value) => setModelTemperature(typeof value === 'number' ? value : modelTemperature)}
108+
/>
109+
<Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
110+
<Typography>Tarkempi</Typography>
111+
<Typography>Satunnainen</Typography>
112+
</Box>
113+
</Box>
114+
115+
{/* <ModelSelector currentModel={model} setModel={setModel} models={validModels.map((m) => m.name)} /> */}
116+
{/* Disabled for now due to RAG not functioning cirreclty */}
117+
{/* <RagSelector currentRagIndex={currentRagIndex} setRagIndex={setRagIndex} ragIndices={ragIndices} /> */}
118+
</Box>
119+
120+
<Box sx={{ padding: '2rem 3rem', display: 'flex', borderTop: '1px solid rgba(0,0,0,0.25)', justifyContent: 'flex-end' }}>
121+
<SettingsButton onClick={resetSettings}>Palauta oletusasetukset</SettingsButton>
122+
</Box>
74123
</Box>
75124
</Modal>
76125
)

src/server/routes/openai.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ const PostStreamSchemaV2 = z.object({
5353
assistantInstructions: z.string().optional(),
5454
messages: z.array(z.any()),
5555
userConsent: z.boolean().optional(),
56-
modelTemperature: z.number().optional(),
56+
modelTemperature: z.number().min(0).max(2).optional(),
5757
saveConsent: z.boolean().optional(),
5858
prevResponseId: z.string().optional(),
5959
courseId: z.string().optional(),
@@ -184,6 +184,7 @@ openaiRouter.post('/stream/v2', upload.single('file'), async (r, res) => {
184184
courseId,
185185
vectorStoreId,
186186
instructions,
187+
temperature: options.modelTemperature,
187188
})
188189

189190
const latestMessage = options.messages[options.messages.length - 1]
@@ -404,8 +405,10 @@ openaiRouter.post('/stream/:courseId/:version?', upload.single('file'), async (r
404405
}
405406

406407
const responsesClient = new ResponsesClient({
407-
model,
408+
model: options.model,
408409
courseId,
410+
instructions: options.assistantInstructions,
411+
temperature: options.modelTemperature,
409412
})
410413

411414
let events

src/server/util/azure/ResponsesAPI.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,22 @@ const client = getAzureOpenAIClient(process.env.GPT_4O_MINI)
3131
export class ResponsesClient {
3232
model: string
3333
instructions: string
34+
temperature: number
3435
tools: FileSearchTool[]
3536

36-
constructor({ model, courseId, vectorStoreId, instructions }: { model: string; courseId?: string; vectorStoreId?: string; instructions?: string }) {
37+
constructor({
38+
model,
39+
temperature,
40+
courseId,
41+
vectorStoreId,
42+
instructions,
43+
}: {
44+
model: string
45+
temperature: number
46+
courseId?: string
47+
vectorStoreId?: string
48+
instructions?: string
49+
}) {
3750
const deploymentId = validModels.find((m) => m.name === model)?.deployment
3851

3952
if (!deploymentId) throw new Error(`Invalid model: ${model}, not one of ${validModels.map((m) => m.name).join(', ')}`)
@@ -47,6 +60,7 @@ export class ResponsesClient {
4760
: [] // needs to retrun empty array for null
4861

4962
this.model = deploymentId
63+
this.temperature = temperature
5064
this.instructions = instructions
5165
this.tools = fileSearchTool
5266
}
@@ -65,6 +79,7 @@ export class ResponsesClient {
6579
model: this.model,
6680
previous_response_id: prevResponseId || undefined,
6781
instructions: this.instructions,
82+
temperature: this.temperature,
6883
input,
6984
stream: true,
7085
tools: this.tools,
@@ -143,6 +158,8 @@ export class ResponsesClient {
143158
break
144159

145160
case 'response.completed':
161+
console.log(`Response completed with temp: ${event.response.temperature}, model: ${event.response.model}`)
162+
146163
await this.write(
147164
{
148165
type: 'complete',

0 commit comments

Comments
 (0)