😀
Intersection of AI and Web Development
HomeKnowledgeGitHubDiscussions
  • 👋Welcome!
  • Before Start
    • 主流平台
    • 名词概念
      • Token
      • Prompt
      • Temperature
      • Top K and Top P
      • Vector & Embeddings
    • CoT and ReAct
  • Practice
    • 发起一次提问和对话
    • Server-Sent Events流式对话
      • 客户端调用
      • 服务端处理
    • Openai Function Calling
      • 获取当前时间 - function calling
      • FunctionCalling实现实时搜索
        • openai functions 入参
        • 设定 functions
    • 通过Embeddings实现PDF检索
      • 上传识别PDF
      • 获取文本,按句整理
      • 上传并按限定长度分割Documents
      • Openai Embeddings 向量化及存储
    • 结合语音输入实现对话
      • 通过麦克风识别语音输入
      • Memory Chat & Conversation
    • Chrome侧边栏对话插件
  • Others
    • Framework and SDK
由 GitBook 提供支持
在本页

这有帮助吗?

  1. Practice
  2. 通过Embeddings实现PDF检索

上传并按限定长度分割Documents

从这里开始,我们需要编写api来接收客户端处理过的语句。

先按固定长度以及向量数据库特有的类型来处理。

声明Document的类型

./types.ts
export interface DocumentParams {
    pageContent: string
    metadata: Record<string, any>
}
/**
 * Interface for interacting with a document.
 */
export declare class Document implements DocumentParams {
    pageContent: string
    metadata: Record<string, any>
    constructor(fields?: Partial<DocumentParams>)
}

编写一个分割Document的方法

./common.ts
import { Document } from './types'
import _ from 'lodash'

const defaultDocLength = 500;
const splitTextInDoc = ({
    flattenSentenceList,
    docLength,
}: {
    flattenSentenceList: Array<{ sentence: string; pageList: number[] }>
    docLength?: number
}) => {
    if (!flattenSentenceList?.length) return false

    let docs: Array<Document> = [],
    _doc_text = '';

    const splitDocLength = docLength || defaultDocLength
    
    let currentPageList: any = []
    _.map(flattenSentenceList, sentenceItem => {
        const { sentence, pageList } = sentenceItem || {}
        if (sentence.length + _doc_text.length > splitDocLength) {
            docs.push({
                pageContent: _doc_text,
                metadata: { page: currentPageList.join(','), pageContent: _doc_text },
            })
            _doc_text = sentence
            currentPageList = [...pageList]
        } else {
            _doc_text += sentence
            currentPageList = _.uniq(currentPageList.concat([...pageList]))
        }
    })

    // 补上最后一段
    if (_doc_text.length) {
        docs.push({
            pageContent: _doc_text,
            metadata: { page: currentPageList.join(','), pageContent: _doc_text },
        })
    }
    return docs
}

上一页获取文本,按句整理下一页Openai Embeddings 向量化及存储

最后更新于1年前

这有帮助吗?