语义分块器
“语义分块”是Greg Kamradt在其关于五级嵌入分块的视频教程中提出的新概念:https://youtu.be/8OJC21T2SL4?t=1933。
与使用固定块大小分割文本不同,语义分割器通过嵌入相似度自适应地选择句子间的断点。这确保每个“块”包含语义上相互关联的句子。
我们将其适配为一个LlamaIndex模块。
查看我们下方的笔记本!
注意事项:
- 该正则表达式主要适用于英文句子
- 您可能需要调整断点百分位阈值。
%pip install llama-index-embeddings-openai!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'pg_essay.txt'Will not apply HSTS. The HSTS database must be a regular and non-world-writable file.ERROR: could not open HSTS store at '/home/loganm/.wget-hsts'. HSTS will be disabled.--2024-01-11 15:04:43-- https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txtResolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.109.133, 185.199.111.133, 185.199.108.133, ...Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.109.133|:443... connected.HTTP request sent, awaiting response... 200 OKLength: 75042 (73K) [text/plain]Saving to: ‘pg_essay.txt’
pg_essay.txt 100%[===================>] 73.28K --.-KB/s in 0.04s
2024-01-11 15:04:44 (1.76 MB/s) - ‘pg_essay.txt’ saved [75042/75042]from llama_index.core import SimpleDirectoryReader
# load documentsdocuments = SimpleDirectoryReader(input_files=["pg_essay.txt"]).load_data()from llama_index.core.node_parser import ( SentenceSplitter, SemanticSplitterNodeParser,)from llama_index.embeddings.openai import OpenAIEmbedding
import os
os.environ["OPENAI_API_KEY"] = "sk-..."embed_model = OpenAIEmbedding()splitter = SemanticSplitterNodeParser( buffer_size=1, breakpoint_percentile_threshold=95, embed_model=embed_model)
# also baseline splitterbase_splitter = SentenceSplitter(chunk_size=512)nodes = splitter.get_nodes_from_documents(documents)让我们来看一下语义分割器生成的文本块。
片段 1: IBM 1401
Section titled “Chunk 1: IBM 1401”print(nodes[1].get_content())I didn't write essays. I wrote what beginning writers were supposed to write then, and probably still are: short stories. My stories were awful. They had hardly any plot, just characters with strong feelings, which I imagined made them deep.
The first programs I tried writing were on the IBM 1401 that our school district used for what was then called "data processing." This was in 9th grade, so I was 13 or 14. The school district's 1401 happened to be in the basement of our junior high school, and my friend Rich Draves and I got permission to use it. It was like a mini Bond villain's lair down there, with all these alien-looking machines — CPU, disk drives, printer, card reader — sitting up on a raised floor under bright fluorescent lights.
The language we used was an early version of Fortran. You had to type programs on punch cards, then stack them in the card reader and press a button to load the program into memory and run it. The result would ordinarily be to print something on the spectacularly loud printer.
I was puzzled by the 1401.print(nodes[2].get_content())I couldn't figure out what to do with it. And in retrospect there's not much I could have done with it. The only form of input to programs was data stored on punched cards, and I didn't have any data stored on punched cards. The only other option was to do things that didn't rely on any input, like calculate approximations of pi, but I didn't know enough math to do anything interesting of that type. So I'm not surprised I can't remember any programs I wrote, because they can't have done much. My clearest memory is of the moment I learned it was possible for programs not to terminate, when one of mine didn't. On a machine without time-sharing, this was a social as well as a technical error, as the data center manager's expression made clear.
With microcomputers, everything changed. Now you could have a computer sitting right in front of you, on a desk, that could respond to your keystrokes as it was running instead of just churning through a stack of punch cards and then stopping. [1]
The first of my friends to get a microcomputer built it himself. It was sold as a kit by Heathkit. I remember vividly how impressed and envious I felt watching him sitting in front of it, typing programs right into the computer.
Computers were expensive in those days and it took me years of nagging before I convinced my father to buy one, a TRS-80, in about 1980. The gold standard then was the Apple II, but a TRS-80 was good enough. This was when I really started programming. I wrote simple games, a program to predict how high my model rockets would fly, and a word processor that my father used to write at least one book. There was only room in memory for about 2 pages of text, so he'd write 2 pages at a time and then print them out, but it was a lot better than a typewriter.
Though I liked programming, I didn't plan to study it in college. In college I was going to study philosophy, which sounded much more powerful. It seemed, to my naive high school self, to be the study of the ultimate truths, compared to which the things studied in other fields would be mere domain knowledge. What I discovered when I got to college was that the other fields took up so much of the space of ideas that there wasn't much left for these supposed ultimate truths. All that seemed left for philosophy were edge cases that people in other fields felt could safely be ignored.
I couldn't have put this into words when I was 18. All I knew at the time was that I kept taking philosophy courses and they kept being boring. So I decided to switch to AI.
AI was in the air in the mid 1980s, but there were two things especially that made me want to work on it: a novel by Heinlein called The Moon is a Harsh Mistress, which featured an intelligent computer called Mike, and a PBS documentary that showed Terry Winograd using SHRDLU. I haven't tried rereading The Moon is a Harsh Mistress, so I don't know how well it has aged, but when I read it I was drawn entirely into its world. It seemed only a matter of time before we'd have Mike, and when I saw Winograd using SHRDLU, it seemed like that time would be a few years at most. All you had to do was teach SHRDLU more words.
There weren't any classes in AI at Cornell then, not even graduate classes, so I started trying to teach myself. Which meant learning Lisp, since in those days Lisp was regarded as the language of AI. The commonly used programming languages then were pretty primitive, and programmers' ideas correspondingly so. The default language at Cornell was a Pascal-like language called PL/I, and the situation was similar elsewhere. Learning Lisp expanded my concept of a program so fast that it was years before I started to have a sense of where the new limits were. This was more like it; this was what I had expected college to do. It wasn't happening in a class, like it was supposed to, but that was ok.片段3:完成大学学业 + 研究生院
Section titled “Chunk 3: Finishing up College + Grad School”print(nodes[3].get_content())For the next couple years I was on a roll. I knew what I was going to do.
For my undergraduate thesis, I reverse-engineered SHRDLU. My God did I love working on that program. It was a pleasing bit of code, but what made it even more exciting was my belief — hard to imagine now, but not unique in 1985 — that it was already climbing the lower slopes of intelligence.
I had gotten into a program at Cornell that didn't make you choose a major. You could take whatever classes you liked, and choose whatever you liked to put on your degree. I of course chose "Artificial Intelligence." When I got the actual physical diploma, I was dismayed to find that the quotes had been included, which made them read as scare-quotes. At the time this bothered me, but now it seems amusingly accurate, for reasons I was about to discover.
I applied to 3 grad schools: MIT and Yale, which were renowned for AI at the time, and Harvard, which I'd visited because Rich Draves went there, and was also home to Bill Woods, who'd invented the type of parser I used in my SHRDLU clone. Only Harvard accepted me, so that was where I went.
I don't remember the moment it happened, or if there even was a specific moment, but during the first year of grad school I realized that AI, as practiced at the time, was a hoax. By which I mean the sort of AI in which a program that's told "the dog is sitting on the chair" translates this into some formal representation and adds it to the list of things it knows.
What these programs really showed was that there's a subset of natural language that's a formal language. But a very proper subset. It was clear that there was an unbridgeable gap between what they could do and actually understanding natural language. It was not, in fact, simply a matter of teaching SHRDLU more words. That whole way of doing AI, with explicit data structures representing concepts, was not going to work. Its brokenness did, as so often happens, generate a lot of opportunities to write papers about various band-aids that could be applied to it, but it was never going to get us Mike.
So I looked around to see what I could salvage from the wreckage of my plans, and there was Lisp. I knew from experience that Lisp was interesting for its own sake and not just for its association with AI, even though that was the main reason people cared about it at the time. So I decided to focus on Lisp. In fact, I decided to write a book about Lisp hacking. It's scary to think how little I knew about Lisp hacking when I started writing that book. But there's nothing like writing a book about something to help you learn it. The book, On Lisp, wasn't published till 1993, but I wrote much of it in grad school.
Computer Science is an uneasy alliance between two halves, theory and systems. The theory people prove things, and the systems people build things. I wanted to build things. I had plenty of respect for theory — indeed, a sneaking suspicion that it was the more admirable of the two halves — but building things seemed so much more exciting.
The problem with systems work, though, was that it didn't last. Any program you wrote today, no matter how good, would be obsolete in a couple decades at best. People might mention your software in footnotes, but no one would actually use it. And indeed, it would seem very feeble work. Only people with a sense of the history of the field would even realize that, in its time, it had been good.
There were some surplus Xerox Dandelions floating around the computer lab at one point. Anyone who wanted one to play around with could have one. I was briefly tempted, but they were so slow by present standards; what was the point? No one else wanted one either, so off they went. That was what happened to systems work.
I wanted not just to build things, but to build things that would last.
In this dissatisfied state I went in 1988 to visit Rich Draves at CMU, where he was in grad school. One day I went to visit the Carnegie Institute, where I'd spent a lot of time as a kid. While looking at a painting there I realized something that might seem obvious, but was a big surprise to me. There, right on the wall, was something you could make that would last. Paintings didn't become obsolete. Some of the best ones were hundreds of years old.
And moreover this was something you could make a living doing. Not as easily as you could by writing software, of course, but I thought if you were really industrious and lived really cheaply, it had to be possible to make enough to survive. And as an artist you could be truly independent. You wouldn't have a boss, or even need to get research funding.
I had always liked looking at paintings. Could I make them?相比之下,让我们与使用固定分块大小的基线进行比较。
base_nodes = base_splitter.get_nodes_from_documents(documents)print(base_nodes[2].get_content())This was when I really started programming. I wrote simple games, a program to predict how high my model rockets would fly, and a word processor that my father used to write at least one book. There was only room in memory for about 2 pages of text, so he'd write 2 pages at a time and then print them out, but it was a lot better than a typewriter.
Though I liked programming, I didn't plan to study it in college. In college I was going to study philosophy, which sounded much more powerful. It seemed, to my naive high school self, to be the study of the ultimate truths, compared to which the things studied in other fields would be mere domain knowledge. What I discovered when I got to college was that the other fields took up so much of the space of ideas that there wasn't much left for these supposed ultimate truths. All that seemed left for philosophy were edge cases that people in other fields felt could safely be ignored.
I couldn't have put this into words when I was 18. All I knew at the time was that I kept taking philosophy courses and they kept being boring. So I decided to switch to AI.
AI was in the air in the mid 1980s, but there were two things especially that made me want to work on it: a novel by Heinlein called The Moon is a Harsh Mistress, which featured an intelligent computer called Mike, and a PBS documentary that showed Terry Winograd using SHRDLU. I haven't tried rereading The Moon is a Harsh Mistress, so I don't know how well it has aged, but when I read it I was drawn entirely into its world. It seemed only a matter of time before we'd have Mike, and when I saw Winograd using SHRDLU, it seemed like that time would be a few years at most. All you had to do was teach SHRDLU more words.
There weren't any classes in AI at Cornell then, not even graduate classes, so I started trying to teach myself. Which meant learning Lisp, since in those days Lisp was regarded as the language of AI. The commonly used programming languages then were pretty primitive, and programmers' ideas correspondingly so. The default language at Cornell was a Pascal-like language called PL/I, and the situation was similar elsewhere.from llama_index.core import VectorStoreIndexfrom llama_index.core.response.notebook_utils import display_source_nodevector_index = VectorStoreIndex(nodes)query_engine = vector_index.as_query_engine()base_vector_index = VectorStoreIndex(base_nodes)base_query_engine = base_vector_index.as_query_engine()response = query_engine.query( "Tell me about the author's programming journey through childhood to college")print(str(response))The author's programming journey began in childhood when computers were expensive and not easily accessible. They couldn't do much with computers at that time as the only form of input was data stored on punched cards, which they didn't have. They didn't know enough math to do anything interesting either. However, with the advent of microcomputers, everything changed. The author's friend built a microcomputer from a kit, which impressed and envied the author. Eventually, the author convinced their father to buy a TRS-80 computer, which marked the start of their programming journey. They wrote simple games, a program to predict rocket heights, and even a word processor. Despite their interest in programming, the author initially planned to study philosophy in college but found it boring. They then switched to studying AI, which was in the air during the mid-1980s. The author taught themselves AI since there were no classes available at Cornell at that time. They learned Lisp, which expanded their concept of programming and opened up new possibilities.for n in response.source_nodes: display_source_node(n, source_length=20000)节点ID: 68006b95-c06e-486c-bbb6-be54746aaf22
相似度: 0.8465522042661249
文本: 我当时不知道能用它做什么。回想起来,我确实也做不了什么。程序唯一的输入形式是存储在穿孔卡片上的数据,而我没有任何存储在穿孔卡片上的数据。唯一的选择是做一些不依赖任何输入的事情,比如计算圆周率的近似值,但我的数学知识不足以完成这类有趣的事情。所以我不记得自己写过任何程序也不奇怪,因为它们确实做不了多少事。我最清晰的记忆是当我得知程序可能不会终止的那一刻——当时我的一个程序就没有终止。在没有分时功能的机器上,这既是技术错误也是社交失误,数据中心经理的表情清楚地表明了这一点。
随着微型计算机的出现,一切都改变了。现在你可以拥有一台放在桌前、正对着你的电脑,它能在运行过程中实时响应你的键盘输入,而不仅仅是处理一堆穿孔卡片后就停止工作。[1]
我朋友中第一个拥有微型计算机的人是自己组装的。它是由Heathkit以套件形式出售的。我清晰地记得,看着他坐在电脑前直接将程序输入计算机时,我是多么印象深刻和羡慕。
在那些日子里,电脑非常昂贵,我花了数年时间软磨硬泡,才在1980年左右说服父亲买了一台TRS-80。当时的黄金标准是Apple II,但TRS-80已经足够好了。这是我真正开始编程的时候。我编写了简单的游戏,一个预测我的模型火箭能飞多高的程序,还有一个文字处理器,我父亲用它至少写了一本书。内存中只能容纳大约2页文本,所以他每次写2页然后打印出来,但这比打字机好多了。
虽然我喜欢编程,但我没打算在大学里学习它。我原本计划在大学攻读哲学,这听起来更有力量。在我天真的高中时代看来,哲学似乎是研究终极真理的学科,相比之下,其他领域研究的东西不过是领域知识。当我进入大学后发现,其他学科占据了思想空间的绝大部分,留给这些所谓的终极真理的空间所剩无几。哲学似乎只剩下其他领域认为可以安全忽略的边缘案例。
我18岁时无法用语言表达这一点。当时我只知道我不断选修哲学课程,但它们一直很无聊。所以我决定转向人工智能。
人工智能在20世纪80年代中期风靡一时,但有两件事尤其让我想投身这个领域:海因莱因的小说《月亮是个严厉的女主人》,其中有一个名为迈克的智能计算机;以及一部PBS纪录片,展示了特里·威诺格拉德使用SHRDLU的情景。我后来没重读《月亮是个严厉的女主人》,所以不知道它是否经得起时间考验,但初读时我完全沉浸在那个世界里。拥有迈克这样的智能体似乎只是时间问题,而当我看到威诺格拉德使用SHRDLU时,感觉这个时间最多不过几年。你只需要教SHRDLU更多词汇就行了。
那时康奈尔大学还没有任何人工智能课程,连研究生课程都没有,所以我开始尝试自学。这意味着要学习Lisp,因为在那个年代,Lisp被视为人工智能的语言。当时常用的编程语言相当原始,程序员的思维也相应受限。康奈尔默认使用的是一种类似Pascal的语言PL/I,其他学校的情况也类似。学习Lisp极大地拓展了我对程序概念的认知,以至于多年后我才开始意识到新的边界在哪里。这才像话;这才是我对大学的期待。虽然不像预期的那样发生在课堂上,但这也没关系。
节点ID: a7cc0ef9-400e-47b3-a85b-fb871bfd183d
相似度: 0.8460437724191147
文本内容: 我从未意识到这一点。我甚至没想过这是可能的。虽然理性上我知道艺术是由人创造的——它不是凭空出现的——但创作艺术的人仿佛属于另一个物种。他们要么生活在遥远的过去,要么是《生活》杂志专栏里做着奇特事情的神秘天才。真正能够创作艺术,将那个动词置于那个名词之前,这个想法几乎如同奇迹。
那年秋天我开始在哈佛上艺术课。研究生可以在任何系选课,而我的导师汤姆·奇塔姆非常随和。即使他知道我选的那些奇怪的课程,他也从未说过什么。
所以当时我虽然进入了计算机科学的博士项目,却计划成为一名艺术家,但同时也真心热爱Lisp编程并致力于《On Lisp》的写作。换句话说,和许多研究生一样,我正全力以赴地进行着多个与论文无关的项目。
我看不到摆脱这种困境的出路。我不想从研究生院退学,但除此之外我还能如何脱身呢?我记得当我的朋友罗伯特·莫里斯因编写1988年的互联网蠕虫而被康奈尔大学开除时,我很羡慕他找到了如此引人注目的方式离开研究生院。
然后在1990年4月的一天,墙上出现了一道裂缝。我偶遇了奇塔姆教授,他问我是否准备充分能在当年六月毕业。我的论文一个字都还没写,但在我人生中可能最快的一次思考中,我决定尝试在截止日期前大约5周内完成论文写作,尽可能重用《On Lisp》中的部分内容,于是我能够毫不迟疑地回答:“是的,我觉得可以。几天内我会给您些内容审阅。”
我选择了延续的应用作为主题。回想起来,我本应该写关于宏和嵌入式语言的内容。那里有一个几乎未被探索的完整世界。但我当时只想尽快毕业,而我匆忙写成的论文勉强够用,只是勉强而已。
与此同时,我正在申请艺术院校。我申请了两所:美国的罗德岛设计学院,以及佛罗伦萨的美术学院——由于它是历史最悠久的艺术学校,我想象它应该很不错。罗德岛设计学院录取了我,而美术学院始终没有回音,于是我便动身前往普罗维登斯。
我申请了罗德岛设计学院的美术学士项目,这意味着实际上我必须重新上大学。这并不像听起来那么奇怪,因为我当时只有25岁,而艺术学校里到处都是不同年龄段的人。RISD将我算作大二转学生,并要求我在那个夏天完成基础课程。基础课程指的是每个人都需要修读的基础科目课程,比如素描、色彩和设计。
临近夏末时,我收到了一个巨大的惊喜:一封来自Accademia的信件,由于他们误将信件寄往英国剑桥而非马萨诸塞州剑桥,导致信件延误。信中邀请我参加那年秋天在佛罗伦萨举行的入学考试。
base_response = base_query_engine.query( "Tell me about the author's programming journey through childhood to college")print(str(base_response))The author's programming journey began in childhood when they started writing simple games and programs to predict the flight of model rockets. They also developed a word processor that their father used to write a book. Despite their interest in programming, they initially planned to study philosophy in college. However, they found philosophy courses to be boring and decided to switch to AI. At that time, there were no AI classes at Cornell, so they taught themselves by learning Lisp, which was considered the language of AI. The author's programming journey continued to evolve as they encountered new technologies, such as microcomputers, which allowed for more interactive and accessible programming experiences.for n in base_response.source_nodes: display_source_node(n, source_length=20000)节点ID: 6c0de686-e1be-4ece-b514-7ed6f732b043
相似度: 0.8637606779131186
文本: 这是我真正开始编程的时候。我编写了简单的游戏、一个预测我的模型火箭能飞多高的程序,以及我父亲用来至少写过一本书的文字处理器。内存中只能容纳大约2页文本,所以他每次写2页然后打印出来,但这比打字机好多了。
虽然我喜欢编程,但我没打算在大学里学习它。我原本计划在大学攻读哲学,这听起来更有力量。在我天真的高中时代看来,哲学似乎是研究终极真理的学科,相比之下,其他领域研究的东西不过是领域知识。当我进入大学后发现,其他学科占据了思想空间的绝大部分,留给这些所谓的终极真理的空间所剩无几。哲学似乎只剩下其他领域认为可以安全忽略的边缘案例。
我18岁时无法用语言表达这一点。当时我只知道我不断选修哲学课程,但它们一直很无聊。所以我决定转向人工智能。
人工智能在20世纪80年代中期风靡一时,但有两件事尤其让我想投身这个领域:海因莱因的小说《月亮是个严厉的女主人》,其中有一个名为迈克的智能计算机;以及一部PBS纪录片,展示了特里·威诺格拉德使用SHRDLU的情景。我后来没有重读《月亮是个严厉的女主人》,所以不知道它是否经得起时间考验,但当初阅读时我完全沉浸在那个世界中。拥有迈克这样的智能体似乎只是时间问题,而当我看到威诺格拉德使用SHRDLU时,感觉这个时间最多不过几年。你只需要教SHRDLU更多词汇就行了。
那时康奈尔大学没有任何人工智能课程,连研究生课程都没有,所以我开始尝试自学。这意味着要学习Lisp,因为在那个年代Lisp被视为人工智能的语言。当时常用的编程语言相当原始,程序员的思维也相应受限。康奈尔大学默认使用的是一种类似Pascal的语言PL/I,其他学校的情况也大同小异。
节点ID: c5ba0780-d9d7-436e-9730-ce7fe44539c1
相似度: 0.8571409465192146
文本: 我的工作内容
2021年2月
在大学之前,我在校外主要钻研的两件事就是写作和编程。我不写议论文,而是写当时(可能至今仍是)初学者该写的东西:短篇小说。我的故事糟糕透顶,几乎毫无情节可言,只有情感浓烈的角色——我自以为这样能显得故事有深度。
我最初尝试编写的程序是在IBM 1401上进行的,当时我们学区用它来进行所谓的"数据处理"。那时我正读九年级,大约13或14岁。学区的这台1401恰巧位于我们初中的地下室里,我和朋友里奇·德雷维斯获得了使用许可。那里就像个迷你版邦德反派巢穴,所有外形奇特的机器——中央处理器、磁盘驱动器、打印机、卡片阅读器——都安置在抬高的地板之上,沐浴在明亮的荧光灯下。
我们使用的语言是早期版本的Fortran。你需要在穿孔卡片上输入程序,然后将卡片堆叠在读卡器中,按下按钮将程序加载到内存并运行。结果通常会在那台噪音巨大的打印机上打印出一些内容。
我对1401感到困惑。我不知道该用它做什么。回想起来,我确实也做不了什么。程序唯一的输入形式是存储在穿孔卡片上的数据,而我没有任何存储在穿孔卡片上的数据。唯一的选择是做一些不依赖任何输入的事情,比如计算圆周率的近似值,但我的数学知识不足以完成这类有趣的事情。所以我不惊讶自己记不起写过的任何程序,因为它们确实做不了多少事。我最清晰的记忆是当我得知程序可能不会终止的那一刻——当时我的一个程序就没有终止。在没有分时功能的机器上,这既是技术错误也是社交失误,数据中心经理的表情清楚地表明了这一点。
随着微型计算机的出现,一切都改变了。现在你可以拥有一台放在桌前、正对着你的计算机,它能在运行过程中实时响应你的键盘输入,而不仅仅是处理一堆穿孔卡片后就停止工作。
response = query_engine.query("Tell me about the author's experience in YC")print(str(response))The author had a significant experience in Y Combinator (YC). They initially did not intend for YC to be a full-time job, but as it grew, it started to take up more of their attention. They worked on various projects within YC, including selecting and helping founders, writing essays, and working on internal software. The author found the work engaging and enjoyed the opportunity to learn about startups. However, there were also parts of the job that they did not like, such as disputes between cofounders and dealing with maltreatment of startups. Despite the challenges, the author worked hard and wanted YC to be successful.base_response = base_query_engine.query( "Tell me about the author's experience in YC")print(str(base_response))The author's experience in YC was different from other kinds of work they have done. Instead of deciding for themselves what to work on, the problems came to them. Every 6 months, there was a new batch of startups, and their problems became the author's problems. This work was engaging because the problems were varied, and the good founders were very effective. However, there were parts of the job that the author didn't like, such as disputes between cofounders and dealing with people who maltreated the startups. Despite this, the author worked hard even at the parts they didn't like because they wanted YC to be good.