Skip to content
Closed

o1 #4

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
84 changes: 84 additions & 0 deletions backend/src/code-agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { WebSocket } from 'ws'

import { Message } from 'common/actions'
import { parseMarkdownPatchBlocks, ProjectFileContext } from 'common/util/file'
import { getCoderPrompt } from './system-prompt'
import { assert } from 'common/util/object'
import { OpenAIMessage, promptOpenAI } from './openai-api'
import { FileChange } from 'common/actions'

/**
* Handles code-related actions by interacting with the AI assistant to generate and apply code changes.
*
* The `codeAgent` function serves as the primary handler for processing user instructions related to code modifications.
* It leverages the AI assistant to interpret user requests, generate appropriate responses, and apply necessary changes
* to the codebase in a context-aware manner.
*
* Steps involved:
* 1. Constructs a prompt using the system-generated coder prompt and the latest user message.
* 2. Sends the prompt to the OpenAI API to generate a response.
* 3. Processes the AI's response by removing unnecessary markdown syntax.
* 4. Parses the response into file blocks and generates corresponding file changes.
* 5. Applies the generated patches to the relevant files.
*
* @param userId - The unique identifier of the user initiating the code action.
* @param fileContext - An object representing the current context of project files, including their contents.
* @param messages - An array of user and assistant messages exchanged in the current session.
* @param ws - The WebSocket connection instance for real-time communication with the client.
* @param onResponseChunk - A callback function to handle chunks of the AI assistant's response as they are received.
* @returns An object containing the AI assistant's full response and the list of file changes generated.
*
* @throws Will throw an error if the OpenAI API request fails or returns an unexpected response.
*/
export const codeAgent = async (
userId: string,
fileContext: ProjectFileContext,
messages: Message[],
ws: WebSocket,
onResponseChunk: (chunk: string) => void
) => {
const coderPrompt = getCoderPrompt(fileContext, {
checkFiles: true,
})
const lastMessage = messages[messages.length - 1]
assert(lastMessage.role === 'user', 'Last message must be from user')
assert(
typeof lastMessage.content === 'string',
'Last user message must be text'
)

const infoPrompt = `Please use the above information to answer the user's question:`
const content = [coderPrompt, infoPrompt, lastMessage.content].join('\n\n')

const messagesWithContext = [
...messages.slice(0, -1),
{
...lastMessage,
content,
},
] as OpenAIMessage[]

onResponseChunk('Generating response with o1-preview...\n\n')

const response = await promptOpenAI(
userId,
messagesWithContext,
'o1-preview',
{
temperature: 1,
}
)

onResponseChunk(response + '\n')
console.log('response', response)
const patches = parseMarkdownPatchBlocks(response)
const changes: FileChange[] = patches.map(({ filePath, patch }) => ({
filePath,
content: patch,
type: 'patch',
}))

console.log('changes', changes)

return { response, changes }
}
128 changes: 126 additions & 2 deletions backend/src/generate-patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ export async function generatePatch(
return updatedPatch
}

/**
* Generates a patch file based on the differences between the old and new file contents.
*
* This function analyzes the modifications made to a file by comparing its original content (`oldContent`)
* with the updated content (`newContent`). It leverages the user's message history and the full AI response
* to ensure that the generated patch accurately reflects the intended changes in a context-aware manner.
*
* @param userId - The unique identifier of the user initiating the patch generation.
* @param oldContent - The original content of the file before any changes.
* @param newContent - The updated content of the file after modifications.
* @param filePath - The specific file path where the patch will be applied.
* @param messageHistory - An array of previous messages exchanged, providing context for the changes.
* @param fullResponse - The complete response from the AI, which may include explanations or additional instructions relevant to the patch.
* @returns A string representing the generated patch that can be applied to the original file.
*/
const generatePatchPrompt = async (
userId: string,
oldContent: string,
Expand All @@ -52,7 +67,115 @@ And here's a sketch of the changes:
${newContent}
\`\`\`

Please produce a patch file based on this change.
Please produce a patch file based on this change. Respond with the patch file only.

For example:

Sketch of the changes:

\`\`\`
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import { z } from "zod";
import models from "./models";
import { ArticleNodeDataType } from "@/lib/types";

// ... (keep all existing code up to the souvenirValidationSchema)

// Base Souvenir Validation Schema

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this code looks familiar... o.o

const baseSouvenirValidationSchema = {
article_id: z.number().int().positive(),
type: ArticleNodeDataType,
created_at: z.date().optional(),
};

// Discriminated union for souvenir data based on type
const souvenirDataSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal(ArticleNodeDataType.Enum.code),
data: z.object({
souvenir: z.object({
steps: z.array(z.string()),
components: z.array(z.object({
fn: z.string(),
name: z.string(),
})),
srcs: z.array(z.string()).optional(),
}),
}),
}),
// Add other types here as needed
]);

const souvenirValidationSchema = {
...baseSouvenirValidationSchema,
...souvenirDataSchema.shape,
};

const souvenirInsertSchema = createInsertSchema(
models.souvenirs,
souvenirValidationSchema
);
const souvenirSelectSchema = createSelectSchema(
models.souvenirs,
souvenirValidationSchema
);

// ... (keep the rest of the existing code)
\`\`\`


Patch:
\`\`\`
diff --git a/apps/ebook-web/db/schemas.ts b/apps/ebook-web/db/schemas.ts
index 0b3b1c3b0..b3b8b0b3b 100644
--- a/apps/ebook-web/db/schemas.ts
+++ b/apps/ebook-web/db/schemas.ts
@@ -47,23 +47,37 @@ const articleSelectSchema = createSelectSchema(
articleValidationSchema
);

-const souvenirValidationSchema = {
+// Base Souvenir Validation Schema
+const baseSouvenirValidationSchema = {
article_id: z.number().int().positive(),
type: ArticleNodeDataType,
- data: z.object({
+ created_at: z.date().optional(),
+};
+
+// Discriminated union for souvenir data based on type
+const souvenirDataSchema = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal(ArticleNodeDataType.Enum.code),
+ data: z.object({
souvenir: z.object({
steps: z.array(z.string()),
- components: z.array(
- z.object({
- fn: z.string(),
- name: z.string(),
- })
- ),
+ components: z.array(z.object({
+ fn: z.string(),
+ name: z.string(),
+ })),
srcs: z.array(z.string()).optional(),
}),
}),
+ // Add other types here as needed
+]);
+
+const souvenirValidationSchema = {
+ ...baseSouvenirValidationSchema,
+ ...souvenirDataSchema.shape,
};
+
const souvenirInsertSchema = createInsertSchema(
models.souvenirs,
souvenirValidationSchema
\`\`\`

`.trim()

const messages = [
Expand All @@ -64,6 +187,7 @@ Please produce a patch file based on this change.
return await promptOpenAI(
userId,
messages,
'ft:gpt-4o-2024-08-06:manifold-markets:run-1:A4VfZwvz'
'o1-mini'
// 'ft:gpt-4o-2024-08-06:manifold-markets:run-1:A4VfZwvz'
)
}
16 changes: 9 additions & 7 deletions backend/src/main-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ import { generatePatch } from './generate-patch'
import { requestRelevantFiles } from './request-files-prompt'
import { processStreamWithFiles } from './process-stream'
import { countTokens } from './util/token-counter'
import { codeAgent } from './code-agent'

const O1_ENABLED = true
/**
* Prompt claude, handle tool calls, and generate file changes.
*/
Expand All @@ -37,10 +39,8 @@ export async function mainPrompt(
const tools = getTools()

let shouldCheckFiles = true
if (Object.keys(fileContext.files).length === 0) {
const system = getSystemPrompt(fileContext, {
checkFiles: true,
})
if (Object.keys(fileContext.files).length === 0 || O1_ENABLED) {
const system = getSystemPrompt(fileContext)
// If the fileContext.files is empty, use prompts to select files and add them to context.
const responseChunk = await updateFileContext(
ws,
Expand All @@ -54,6 +54,10 @@ export async function mainPrompt(
shouldCheckFiles = false
}

if (O1_ENABLED) {
return await codeAgent(userId, fileContext, messages, ws, onResponseChunk)
}

const lastMessage = messages[messages.length - 1]
const fileProcessingPromises: Promise<FileChange | null>[] = []
let toolCall: ToolCall | null = null
Expand All @@ -75,9 +79,7 @@ ${STOP_MARKER}
}

while (!isComplete && iterationCount < MAX_ITERATIONS) {
const system = getSystemPrompt(fileContext, {
checkFiles: shouldCheckFiles,
})
const system = getSystemPrompt(fileContext)
const messagesWithContinuedMessage = continuedMessages
? [...messages, ...continuedMessages]
: messages
Expand Down
7 changes: 4 additions & 3 deletions backend/src/openai-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,18 @@ const timeoutPromise = (ms: number) =>
export async function promptOpenAI(
userId: string,
messages: OpenAIMessage[],
model: string
model: string,
options: { temperature?: number } = {}
) {
const openai = getOpenAI(userId)
try {
const response = await Promise.race([
openai.chat.completions.create({
model,
messages,
temperature: 0,
temperature: options.temperature ?? 1,
}),
timeoutPromise(200000) as Promise<OpenAI.Chat.ChatCompletion>,
timeoutPromise(1_000_000) as Promise<OpenAI.Chat.ChatCompletion>,
])

if (
Expand Down
Loading