ai-chatbot icon indicating copy to clipboard operation
ai-chatbot copied to clipboard

tools : File_search

Open babakhalid opened this issue 1 year ago • 2 comments

Hello,

Please, how can I add file search in the actions.tsx file and retrieve data from the vector I have in the assistant? I tried this code:

fileSearchTool: {
    description: 'Search and retrieve answers from files based on user queries using vector search.',
    parameters: z.object({
      query: z.string().describe('The search query to find relevant answers from files.')
    }),
    generate: async function* ({ query }) {
      const results = await fetchFileSearchResults(query);
  
      yield (
        <BotCard>
          <div>Searching for answers related to "{query}"...</div>
        </BotCard>
      );
  
      await sleep(1000); // Simulate async operation
  
      return (
        <BotCard>
          <ul>
            {results.map((result, index) => (
              <li key={index}>
                <div><strong>Answer:</strong> {result.answer}</div>
                <div><strong>File:</strong> {result.file}</div>
              </li>
            ))}
          </ul>
        </BotCard>
      );
    }
  },

const fetchFileSearchResults = async (query: string): Promise<FileSearchResult[]> => {
  // Create a new thread with the user's query
  const thread = await openai2.beta.threads.create({
    messages: [
      {
        role: "user",
        content: query,
        // Attach the relevant vector store for file search
        attachments: [{ file_id: "my_vector_store_id", tools: [{ type: "file_search" }] }],
      },
    ],
  });

  const threadId = thread.id;

  // Stream the run results
  const stream = openai2.beta.threads.runs.stream(threadId, {
    assistant_id: "my_assistant_id",
  });

  const results: FileSearchResult[] = [];

  return new Promise((resolve, reject) => {
    stream.on("textDelta", (delta) => {
      if (delta.annotations && delta.annotations.length > 0) {
        delta.annotations.forEach((annotation) => {
          if (annotation.type === "file_path") {
            results.push({
              answer: delta.value,
              file: annotation.text,
            });
          }
        });
      }
    });

    stream.on("end", () => resolve(results));
    stream.on("error", (err) => reject(err));
  });
};

babakhalid avatar May 22 '24 20:05 babakhalid

@babakhalid Have you find any solution for this?

alex-trieb-work avatar Aug 12 '24 11:08 alex-trieb-work

Think youd probably have to createRunAndPoll for assistant? can you return a stream from the tool? im looking into this too and I think the plan is to just take the query pass that into the tool, in the tool query and wait for assistant response and return the output back to the main chat

JClackett avatar Oct 02 '24 13:10 JClackett