Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[language-platform] adding the ability to fetch precise context #78

Closed
wants to merge 44 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
d64dd55
initial move from prev repo
cesrjimenez Jul 11, 2023
4e28d0a
update return
cesrjimenez Jul 11, 2023
eba538b
sending user selection
cesrjimenez Jul 24, 2023
6e62cef
adding console for debugging
cesrjimenez Jul 25, 2023
d828db0
debug
cesrjimenez Jul 25, 2023
13ed782
debug again
cesrjimenez Jul 25, 2023
677a8b1
debug again again
cesrjimenez Jul 25, 2023
f6935d1
Merge branch 'main' into cesar+ef/cody-fetch-precise-context-broken
cesrjimenez Jul 26, 2023
5b74c96
updates because of recent main changes
cesrjimenez Jul 26, 2023
43c3586
wip
cesrjimenez Jul 26, 2023
6d170de
quick clean up
cesrjimenez Jul 26, 2023
48f6b64
removing console.logs
cesrjimenez Jul 27, 2023
4ac29ad
Read git data from editor (#397)
efritz Jul 27, 2023
1e63a22
quick fix on import
cesrjimenez Jul 27, 2023
f1dbff8
dirty wip - add accordion to show precise context used
cesrjimenez Jul 28, 2023
dc80c4f
adding hover text
cesrjimenez Jul 28, 2023
efa77de
quick deconstruction
cesrjimenez Jul 28, 2023
960d2d8
Merge branch 'main' into cesar+ef/cody-fetch-precise-context-broken
cesrjimenez Jul 28, 2023
ad4061a
update version
cesrjimenez Aug 7, 2023
4e46c55
Merge branch 'main' into cesar+ef/cody-fetch-precise-context-broken
cesrjimenez Aug 7, 2023
d3f62d0
update name
cesrjimenez Aug 7, 2023
656d083
freaky deaky.
efritz Aug 7, 2023
8052dfb
freaky deaky take 2.
efritz Aug 7, 2023
0eb2e3d
Merge branch 'main' into cesar+ef/cody-fetch-precise-context
efritz Aug 9, 2023
45b0265
Remove package?
efritz Aug 9, 2023
e3fd76e
Update symbol display.
efritz Aug 9, 2023
3501fe9
Add trace logs.
efritz Aug 9, 2023
e647f0f
Add link.
efritz Aug 11, 2023
d26809a
Merge branch 'main' into cesar+ef/cody-fetch-precise-context
efritz Aug 11, 2023
44a401c
Add link to symbols.
efritz Aug 11, 2023
4ebdab8
WIP.
efritz Aug 11, 2023
e0f8105
Fix space placement.
efritz Aug 11, 2023
c47c384
WIP.
efritz Aug 11, 2023
6c6a506
WIP.
efritz Aug 11, 2023
9e80b63
WIP.
efritz Aug 11, 2023
a3a546e
Fix type.
efritz Aug 11, 2023
6f7e4ad
WIP.
efritz Aug 14, 2023
d150768
WIP.
efritz Aug 14, 2023
bd4060f
Bump version.
efritz Aug 14, 2023
49be6bf
Bump version.
efritz Aug 14, 2023
1bc9904
Bump version.
efritz Aug 14, 2023
9c6ff10
WIP.
efritz Aug 14, 2023
f5d220b
WIP.
efritz Aug 14, 2023
c67e544
?
efritz Aug 14, 2023
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
1 change: 1 addition & 0 deletions cli/src/client/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export async function createCodebaseContext(
codebase,
embeddingsSearch,
new LocalKeywordContextFetcherMock(),
null,
null
)

Expand Down
2 changes: 1 addition & 1 deletion lib/shared/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sourcegraph/cody-shared",
"version": "0.0.5",
"version": "0.0.0-codyintel.experimental.10",
"description": "Cody shared library",
"license": "Apache-2.0",
"repository": {
Expand Down
11 changes: 7 additions & 4 deletions lib/shared/src/chat/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ConfigurationWithAccessToken } from '../configuration'
import { Editor } from '../editor'
import { PrefilledOptions, withPreselectedOptions } from '../editor/withPreselectedOptions'
import { SourcegraphEmbeddingsSearchClient } from '../embeddings/client'
import { GraphContextFetcher } from '../graph-context'
import { SourcegraphIntentDetectorClient } from '../intent-detector/client'
import { SourcegraphBrowserCompletionsClient } from '../sourcegraph-api/completions/browserClient'
import { CompletionsClientConfig, SourcegraphCompletionsClient } from '../sourcegraph-api/completions/client'
Expand Down Expand Up @@ -86,8 +87,8 @@ export async function createClient({
}

const embeddingsSearch = repoId ? new SourcegraphEmbeddingsSearchClient(graphqlClient, repoId, true) : null

const codebaseContext = new CodebaseContext(config, config.codebase, embeddingsSearch, null, null)
const graphContext = new GraphContextFetcher(graphqlClient, editor)
const codebaseContext = new CodebaseContext(config, config.codebase, embeddingsSearch, null, null, graphContext)

const intentDetector = new SourcegraphIntentDetectorClient(graphqlClient, completionsClient)

Expand Down Expand Up @@ -141,8 +142,10 @@ export async function createClient({
isMessageInProgress = true
transcript.addInteraction(interaction)

const { prompt, contextFiles } = await transcript.getPromptForLastInteraction(getPreamble(config.codebase))
transcript.setUsedContextFilesForLastInteraction(contextFiles)
const { prompt, contextFiles, preciseContexts } = await transcript.getPromptForLastInteraction(
getPreamble(config.codebase)
)
transcript.setUsedContextFilesForLastInteraction(contextFiles, preciseContexts)

const responsePrefix = interaction.getAssistantMessage().prefix ?? ''
let rawText = ''
Expand Down
4 changes: 3 additions & 1 deletion lib/shared/src/chat/recipes/chat-question.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export class ChatQuestion implements Recipe {

public async getInteraction(humanChatInput: string, context: RecipeContext): Promise<Interaction | null> {
const truncatedText = truncateText(humanChatInput, MAX_HUMAN_INPUT_TOKENS)

return Promise.resolve(
new Interaction(
{ speaker: 'human', text: truncatedText, displayText: humanChatInput },
Expand Down Expand Up @@ -60,6 +59,9 @@ export class ChatQuestion implements Recipe {
if (isCodebaseContextRequired) {
const codebaseContextMessages = await codebaseContext.getContextMessages(text, numResults)
contextMessages.push(...codebaseContextMessages)
// TODO: Put this in getContextMessages?
// Let's leave this here for now :)
contextMessages.push(...(await codebaseContext.getGraphContextMessages()))
}

const isEditorContextRequired = intentDetector.isEditorContextRequired(text)
Expand Down
22 changes: 18 additions & 4 deletions lib/shared/src/chat/transcript/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ContextFile, ContextMessage, OldContextMessage } from '../../codebase-context/messages'
import { ContextFile, ContextMessage, OldContextMessage, PreciseContext } from '../../codebase-context/messages'
import { PluginFunctionExecutionInfo } from '../../plugins/api/types'
import { CHARS_PER_TOKEN, MAX_AVAILABLE_PROMPT_LENGTH } from '../../prompt/constants'
import { PromptMixin } from '../../prompt/prompt-mixin'
Expand Down Expand Up @@ -35,6 +35,7 @@ export class Transcript {
context,
fullContext,
usedContextFiles,
usedPreciseContext,
timestamp,
pluginExecutionInfos,
}) => {
Expand All @@ -59,6 +60,7 @@ export class Transcript {
})
),
usedContextFiles || [],
usedPreciseContext || [],
timestamp || new Date().toISOString(),
pluginExecutionInfos || []
)
Expand Down Expand Up @@ -166,9 +168,9 @@ export class Transcript {
maxPromptLength: number = MAX_AVAILABLE_PROMPT_LENGTH,
pluginsPrompt: Message[] = [],
onlyHumanMessages: boolean = false
): Promise<{ prompt: Message[]; contextFiles: ContextFile[] }> {
): Promise<{ prompt: Message[]; contextFiles: ContextFile[]; preciseContexts: PreciseContext[] }> {
if (this.interactions.length === 0) {
return { prompt: [], contextFiles: [] }
return { prompt: [], contextFiles: [], preciseContexts: [] }
}

const lastInteractionWithContextIndex = await this.getLastInteractionWithContextIndex()
Expand All @@ -193,11 +195,17 @@ export class Transcript {
)
// Return what context fits in the window
const contextFiles: ContextFile[] = []
const preciseContexts: PreciseContext[] = []
for (const msg of truncatedMessages) {
const contextFile = (msg as ContextMessage).file
if (contextFile) {
contextFiles.push(contextFile)
}

const preciseContext = (msg as ContextMessage).preciseContext
if (preciseContext) {
preciseContexts.push(preciseContext)
}
}

// Filter out extraneous fields from ContextMessage instances
Expand All @@ -206,17 +214,23 @@ export class Transcript {
return {
prompt: [...preamble, ...truncatedMessages],
contextFiles,
preciseContexts,
}
}

public setUsedContextFilesForLastInteraction(
contextFiles: ContextFile[],
preciseContexts: PreciseContext[] = [],
pluginExecutionInfos: PluginFunctionExecutionInfo[] = []
): void {
if (this.interactions.length === 0) {
throw new Error('Cannot set context files for empty transcript')
}
this.interactions[this.interactions.length - 1].setUsedContext(contextFiles, pluginExecutionInfos)
this.interactions[this.interactions.length - 1].setUsedContext(
contextFiles,
pluginExecutionInfos,
preciseContexts
)
}

public toChat(): ChatMessage[] {
Expand Down
13 changes: 11 additions & 2 deletions lib/shared/src/chat/transcript/interaction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ContextFile, ContextMessage } from '../../codebase-context/messages'
import { ContextFile, ContextMessage, PreciseContext } from '../../codebase-context/messages'
import { PluginFunctionExecutionInfo } from '../../plugins/api/types'

import { ChatMessage, InteractionMessage } from './messages'
Expand All @@ -8,6 +8,7 @@ export interface InteractionJSON {
assistantMessage: InteractionMessage
fullContext: ContextMessage[]
usedContextFiles: ContextFile[]
usedPreciseContext: PreciseContext[]
pluginExecutionInfos: PluginFunctionExecutionInfo[]
timestamp: string

Expand All @@ -21,6 +22,7 @@ export class Interaction {
private assistantMessage: InteractionMessage,
private fullContext: Promise<ContextMessage[]>,
private usedContextFiles: ContextFile[],
private usedPreciseContext: PreciseContext[] = [],
public readonly timestamp: string = new Date().toISOString(),
private pluginExecutionInfos: PluginFunctionExecutionInfo[] = []
) {}
Expand All @@ -47,9 +49,14 @@ export class Interaction {
return contextMessages.length > 0
}

public setUsedContext(usedContextFiles: ContextFile[], pluginExecutionInfos: PluginFunctionExecutionInfo[]): void {
public setUsedContext(
usedContextFiles: ContextFile[],
pluginExecutionInfos: PluginFunctionExecutionInfo[],
usedPreciseContext: PreciseContext[]
): void {
this.usedContextFiles = usedContextFiles
this.pluginExecutionInfos = pluginExecutionInfos
this.usedPreciseContext = usedPreciseContext
}

/**
Expand All @@ -61,6 +68,7 @@ export class Interaction {
{
...this.assistantMessage,
contextFiles: this.usedContextFiles,
preciseContext: this.usedPreciseContext,
pluginExecutionInfos: this.pluginExecutionInfos,
},
]
Expand All @@ -77,6 +85,7 @@ export class Interaction {
assistantMessage: this.assistantMessage,
fullContext: await this.fullContext,
usedContextFiles: this.usedContextFiles,
usedPreciseContext: this.usedPreciseContext,
pluginExecutionInfos: this.pluginExecutionInfos,
timestamp: this.timestamp,
}
Expand Down
3 changes: 2 additions & 1 deletion lib/shared/src/chat/transcript/messages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ContextFile } from '../../codebase-context/messages'
import { ContextFile, PreciseContext } from '../../codebase-context/messages'
import { PluginFunctionExecutionInfo } from '../../plugins/api/types'
import { Message } from '../../sourcegraph-api'

Expand All @@ -13,6 +13,7 @@ export interface ChatButton {
export interface ChatMessage extends Message {
displayText?: string
contextFiles?: ContextFile[]
preciseContext?: PreciseContext[]
pluginExecutionInfos?: PluginFunctionExecutionInfo[]
buttons?: ChatButton[]
data?: any
Expand Down
5 changes: 5 additions & 0 deletions lib/shared/src/chat/transcript/transcript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ describe('Transcript', () => {
'dummy-codebase',
embeddings,
defaultKeywordContextFetcher,
null,
null
),
})
Expand Down Expand Up @@ -118,6 +119,7 @@ describe('Transcript', () => {
'dummy-codebase',
embeddings,
defaultKeywordContextFetcher,
null,
null
),
firstInteraction: true,
Expand Down Expand Up @@ -153,6 +155,7 @@ describe('Transcript', () => {
'dummy-codebase',
embeddings,
defaultKeywordContextFetcher,
null,
null
)

Expand Down Expand Up @@ -239,6 +242,7 @@ describe('Transcript', () => {
'dummy-codebase',
embeddings,
defaultKeywordContextFetcher,
null,
null
)

Expand Down Expand Up @@ -316,6 +320,7 @@ describe('Transcript', () => {
'dummy-codebase',
embeddings,
defaultKeywordContextFetcher,
null,
null
)

Expand Down
8 changes: 5 additions & 3 deletions lib/shared/src/chat/useClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { isErrorLike } from '../common'
import { ConfigurationWithAccessToken } from '../configuration'
import { Editor, NoopEditor } from '../editor'
import { PrefilledOptions, withPreselectedOptions } from '../editor/withPreselectedOptions'
import { GraphContextFetcher } from '../graph-context'
import { SourcegraphIntentDetectorClient } from '../intent-detector/client'
import { SourcegraphBrowserCompletionsClient } from '../sourcegraph-api/completions/browserClient'
import { SourcegraphGraphQLAPIClient } from '../sourcegraph-api/graphql'
Expand Down Expand Up @@ -278,14 +279,15 @@ export const useClient = ({
repoNames.push(activeEditor.repoName)
}
}

const graphContext = new GraphContextFetcher(graphqlClient, editor)
const unifiedContextFetcherClient = new UnifiedContextFetcherClient(graphqlClient, repoIds)
const codebaseContext = new CodebaseContext(
config,
undefined,
null,
null,
null,
graphContext,
unifiedContextFetcherClient
)

Expand All @@ -307,10 +309,10 @@ export const useClient = ({
setIsMessageInProgressState(true)
onEvent?.('submit')

const { prompt, contextFiles } = await transcript.getPromptForLastInteraction(
const { prompt, contextFiles, preciseContexts } = await transcript.getPromptForLastInteraction(
getMultiRepoPreamble(repoNames)
)
transcript.setUsedContextFilesForLastInteraction(contextFiles)
transcript.setUsedContextFilesForLastInteraction(contextFiles, preciseContexts)

const responsePrefix = interaction.getAssistantMessage().prefix ?? ''
let rawText = ''
Expand Down
37 changes: 37 additions & 0 deletions lib/shared/src/codebase-context/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Configuration } from '../configuration'
import { EmbeddingsSearch } from '../embeddings'
import { GraphContextFetcher } from '../graph-context'
import { ContextResult, FilenameContextFetcher, KeywordContextFetcher } from '../local-context'
import { isMarkdownFile, populateCodeContextTemplate, populateMarkdownContextTemplate } from '../prompt/templates'
import { Message } from '../sourcegraph-api'
Expand All @@ -22,6 +23,7 @@ export class CodebaseContext {
private embeddings: EmbeddingsSearch | null,
private keywords: KeywordContextFetcher | null,
private filenames: FilenameContextFetcher | null,
private graph: GraphContextFetcher | null,
private unifiedContextFetcher?: UnifiedContextFetcher | null,
private rerank?: (query: string, results: ContextResult[]) => Promise<ContextResult[]>
) {}
Expand Down Expand Up @@ -208,6 +210,41 @@ export class CodebaseContext {
const results = await this.filenames.getContext(query, options.numCodeResults + options.numTextResults)
return results
}

public async getGraphContextMessages(): Promise<ContextMessage[]> {
// NOTE(auguste): I recommend checking out populateCodeContextTemplate and using
// that in the long-term, but this will do for now :)

if (!this.graph) {
return Promise.resolve([])
}

const contextMessages: ContextMessage[] = []
for (const preciseContext of await this.graph.getContext()) {
const fence = '```'
const symbolName = `${preciseContext.symbol.scipName} (${preciseContext.symbol.scipDescriptorSuffix})`
// TODO - check comparison value
const repo =
preciseContext.repositoryName !== this.getCodebase()
? ` in repository ${preciseContext.repositoryName}`
: ''
const text = `The symbol ${symbolName} is defined in the file ${preciseContext.filepath}${repo} as:\n\n${fence}${preciseContext.definitionSnippet}${fence}`
console.log({ text }) // DEBUGGING

contextMessages.push({
speaker: 'human',
file: {
repoName: preciseContext.repositoryName,
fileName: preciseContext.filepath,
},
preciseContext,
text,
})
contextMessages.push({ speaker: 'assistant', text: 'okay' })
}

return contextMessages
}
}

function groupResultsByFile(results: EmbeddingsSearchResult[]): { file: ContextFile; results: string[] }[] {
Expand Down
13 changes: 13 additions & 0 deletions lib/shared/src/codebase-context/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,21 @@ export interface ContextFile {
source?: ContextFileSource
}

export interface PreciseContext {
symbol: {
scipName: string
scipDescriptorSuffix: string
fuzzyName?: string
}
definitionSnippet: string
repositoryName: string
filepath: string
canonicalLocationURL: string
}

export interface ContextMessage extends Message {
file?: ContextFile
preciseContext?: PreciseContext
}

export interface OldContextMessage extends Message {
Expand Down
Loading