史蒂夫·乔布斯传记_Chapter 1: Childhood

Chapter 1: Childhood


The Adoption

When Paul Jobs was mustered out of the Coast Guard after World War II, he made a wager with his crewmates. They had arrived in San Francisco, where their ship was decommissioned, and Paul bet that he would find himself a wife within two weeks. He was a taut, tattooed engine mechanic, six feet tall, with a passing resemblance to James Dean. But it wasn’t his looks that got him a date with Clara Hagopian, a sweet-humored daughter of Armenian immigrants. It was the fact that he and his friends had a car, unlike the group she had originally planned to go out with that evening. Ten days later, in March 1946, Paul got engaged to Clara and won his wager. It would turn out to be a happy marriage, one that lasted until death parted them more than forty years later.

Paul Reinhold Jobs had been raised on a dairy farm in Germantown, Wisconsin. Even though his father was an alcoholic and sometimes abusive, Paul ended up with a gentle and calm disposition under his leathery exterior. After dropping out of high school, he wandered through the Midwest picking up work as a mechanic until, at age nineteen, he joined the Coast Guard, even though he didn’t know how to swim. He was deployed on the USS General M. C. Meigs and spent much of the war ferrying troops to Italy for General Patton. His talent as a machinist and fireman earned him commendations, but he occasionally found himself in minor trouble and never rose above the rank of seaman.

Clara was born in New Jersey, where her parents had landed after fleeing the Turks in Armenia, and they moved to the Mission District of San Francisco when she was a child. She had a secret that she rarely mentioned to anyone: She had been married before, but her husband had been killed in the war. So when she met Paul Jobs on that first date, she was primed to start a new life.

Like many who lived through the war, they had experienced enough excitement that, when it was over, they desired simply to settle down, raise a family, and lead a less eventful life. They had little money, so they moved to Wisconsin and lived with Paul’s parents for a few years, then headed for Indiana, where he got a job as a machinist for International Harvester. His passion was tinkering with old cars, and he made money in his spare time buying, restoring, and selling them. Eventually he quit his day job to become a full-time used car salesman.

Clara, however, loved San Francisco, and in 1952 she convinced her husband to move back there. They got an apartment in the Sunset District facing the Pacific, just south of Golden Gate Park, and he took a job working for a finance company as a “repo man,” picking the locks of cars whose owners hadn’t paid their loans and repossessing them. He also bought, repaired, and sold some of the cars, making a decent enough living in the process.

There was, however, something missing in their lives. They wanted children, but Clara had suffered an ectopic pregnancy, in which the fertilized egg was implanted in a fallopian tube rather than the uterus, and she had been unable to have any. So by 1955, after nine years of marriage, they were looking to adopt a child.

Like Paul Jobs, Joanne Schieble was from a rural Wisconsin family of German heritage. Her father, Arthur Schieble, had immigrated to the outskirts of Green Bay, where he and his wife owned a mink farm and dabbled successfully in various other businesses, including real estate and photoengraving. He was very strict, especially regarding his daughter’s relationships, and he had strongly disapproved of her first love, an artist who was not a Catholic. Thus it was no surprise that he threatened to cut Joanne off completely when, as a graduate student at the University of Wisconsin, she fell in love with Abdulfattah “John” Jandali, a Muslim teaching assistant from Syria.

Jandali was the youngest of nine children in a prominent Syrian family. His father owned oil refineries and multiple other businesses, with large holdings in Damascus and Homs, and at one point pretty much controlled the price of wheat in the region. His mother, he later said, was a “traditional Muslim woman” who was a “conservative, obedient housewife.” Like the Schieble family, the Jandalis put a premium on education. Abdulfattah was sent to a Jesuit boarding school, even though he was Muslim, and he got an undergraduate degree at the American University in Beirut before entering the University of Wisconsin to pursue a doctoral degree in political science.

In the summer of 1954, Joanne went with Abdulfattah to Syria. They spent two months in Homs, where she learned from his family to cook Syrian dishes. When they returned to Wisconsin she discovered that she was pregnant. They were both twenty-three, but they decided not to get married. Her father was dying at the time, and he had threatened to disown her if she wed Abdulfattah. Nor was abortion an easy option in a small Catholic community. So in early 1955, Joanne traveled to San Francisco, where she was taken into the care of a kindly doctor who sheltered unwed mothers, delivered their babies, and quietly arranged closed adoptions.

Joanne had one requirement: Her child must be adopted by college graduates. So the doctor arranged for the baby to be placed with a lawyer and his wife. But when a boy was born—on February 24, 1955—the designated couple decided that they wanted a girl and backed out. Thus it was that the boy became the son not of a lawyer but of a high school dropout with a passion for mechanics and his salt-of-the-earth wife who was working as a bookkeeper. Paul and Clara named their new baby Steven Paul Jobs.

When Joanne found out that her baby had been placed with a couple who had not even graduated from high school, she refused to sign the adoption papers. The standoff lasted weeks, even after the baby had settled into the Jobs household. Eventually Joanne relented, with the stipulation that the couple promise—indeed sign a pledge—to fund a savings account to pay for the boy’s college education.

There was another reason that Joanne was balky about signing the adoption papers. Her father was about to die, and she planned to marry Jandali soon after. She held out hope, she would later tell family members, sometimes tearing up at the memory, that once they were married, she could get their baby boy back.

Arthur Schieble died in August 1955, after the adoption was finalized. Just after Christmas that year, Joanne and Abdulfattah were married in St. Philip the Apostle Catholic Church in Green Bay. He got his PhD in international politics the next year, and then they had another child, a girl named Mona. After she and Jandali divorced in 1962, Joanne embarked on a dreamy and peripatetic life that her daughter, who grew up to become the acclaimed novelist Mona Simpson, would capture in her book Anywhere but Here. Because Steve’s adoption had been closed, it would be twenty years before they would all find each other.

Steve Jobs knew from an early age that he was adopted. “My parents were very open with me about that,” he recalled. He had a vivid memory of sitting on the lawn of his house, when he was six or seven years old, telling the girl who lived across the street. “So does that mean your real parents didn’t want you?” the girl asked. “Lightning bolts went off in my head,” according to Jobs. “I remember running into the house, crying. And my parents said, ‘No, you have to understand.’ They were very serious and looked me straight in the eye. They said, ‘We specifically picked you out.’ Both of my parents said that and repeated it slowly for me. And they put an emphasis on every word in that sentence.”

Abandoned. Chosen. Special. Those concepts became part of who Jobs was and how he regarded himself. His closest friends think that the knowledge that he was given up at birth left some scars. “I think his desire for complete control of whatever he makes derives directly from his personality and the fact that he was abandoned at birth,” said one longtime colleague, Del Yocam. “He wants to control his environment, and he sees the product as an extension of himself.” Greg Calhoun, who became close to Jobs right after college, saw another effect. “Steve talked to me a lot about being abandoned and the pain that caused,” he said. “It made him independent. He followed the beat of a different drummer, and that came from being in a different world than he was born into.”

Later in life, when he was the same age his biological father had been when he abandoned him, Jobs would father and abandon a child of his own. (He eventually took responsibility for her.) Chrisann Brennan, the mother of that child, said that being put up for adoption left Jobs “full of broken glass,” and it helps to explain some of his behavior. “He who is abandoned is an abandoner,” she said. Andy Hertzfeld, who worked with Jobs at Apple in the early 1980s, is among the few who remained close to both Brennan and Jobs. “The key question about Steve is why he can’t control himself at times from being so reflexively cruel and harmful to some people,” he said. “That goes back to being abandoned at birth. The real underlying problem was the theme of abandonment in Steve’s life.”

Jobs dismissed this. “There’s some notion that because I was abandoned, I worked very hard so I could do well and make my parents wish they had me back, or some such nonsense, but that’s ridiculous,” he insisted. “Knowing I was adopted may have made me feel more independent, but I have never felt abandoned. I’ve always felt special. My parents made me feel special.” He would later bristle whenever anyone referred to Paul and Clara Jobs as his “adoptive” parents or implied that they were not his “real” parents. “They were my parents 1,000%,” he said. When speaking about his biological parents, on the other hand, he was curt: “They were my sperm and egg bank. That’s not harsh, it’s just the way it was, a sperm bank thing, nothing more.”

Silicon Valley

The childhood that Paul and Clara Jobs created for their new son was, in many ways, a stereotype of the late 1950s. When Steve was two they adopted a girl they named Patty, and three years later they moved to a tract house in the suburbs. The finance company where Paul worked as a repo man, CIT, had transferred him down to its Palo Alto office, but he could not afford to live there, so they landed in a subdivision in Mountain View, a less expensive town just to the south.

There Paul tried to pass along his love of mechanics and cars. “Steve, this is your workbench now,” he said as he marked off a section of the table in their garage. Jobs remembered being impressed by his father’s focus on craftsmanship. “I thought my dad’s sense of design was pretty good,” he said, “because he knew how to build anything. If we needed a cabinet, he would build it. When he built our fence, he gave me a hammer so I could work with him.”

Fifty years later the fence still surrounds the back and side yards of the house in Mountain View. As Jobs showed it off to me, he caressed the stockade panels and recalled a lesson that his father implanted deeply in him. It was important, his father said, to craft the backs of cabinets and fences properly, even though they were hidden. “He loved doing things right. He even cared about the look of the parts you couldn’t see.”

His father continued to refurbish and resell used cars, and he festooned the garage with pictures of his favorites. He would point out the detailing of the design to his son: the lines, the vents, the chrome, the trim of the seats. After work each day, he would change into his dungarees and retreat to the garage, often with Steve tagging along. “I figured I could get him nailed down with a little mechanical ability, but he really wasn’t interested in getting his hands dirty,” Paul later recalled. “He never really cared too much about mechanical things.”

“I wasn’t that into fixing cars,” Jobs admitted. “But I was eager to hang out with my dad.” Even as he was growing more aware that he had been adopted, he was becoming more attached to his father. One day when he was about eight, he discovered a photograph of his father from his time in the Coast Guard. “He’s in the engine room, and he’s got his shirt off and looks like James Dean. It was one of those Oh wow moments for a kid. Wow, oooh, my parents were actually once very young and really good-looking.”

Through cars, his father gave Steve his first exposure to electronics. “My dad did not have a deep understanding of electronics, but he’d encountered it a lot in automobiles and other things he would fix. He showed me the rudiments of electronics, and I got very interested in that.” Even more interesting were the trips to scavenge for parts. “Every weekend, there’d be a junkyard trip. We’d be looking for a generator, a carburetor, all sorts of components.” He remembered watching his father negotiate at the counter. “He was a good bargainer, because he knew better than the guys at the counter what the parts should cost.” This helped fulfill the pledge his parents made when he was adopted. “My college fund came from my dad paying $50 for a Ford Falcon or some other beat-up car that didn’t run, working on it for a few weeks, and selling it for $250—and not telling the IRS.”

The Jobses’ house and the others in their neighborhood were built by the real estate developer Joseph Eichler, whose company spawned more than eleven thousand homes in various California subdivisions between 1950 and 1974. Inspired by Frank Lloyd Wright’s vision of simple modern homes for the American “everyman,” Eichler built inexpensive houses that featured floor-to-ceiling glass walls, open floor plans, exposed post-and-beam construction, concrete slab floors, and lots of sliding glass doors. “Eichler did a great thing,” Jobs said on one of our walks around the neighborhood. “His houses were smart and cheap and good. They brought clean design and simple taste to lower-income people. They had awesome little features, like radiant heating in the floors. You put carpet on them, and we had nice toasty floors when we were kids.”

Jobs said that his appreciation for Eichler homes instilled in him a passion for making nicely designed products for the mass market. “I love it when you can bring really great design and simple capability to something that doesn’t cost much,” he said as he pointed out the clean elegance of the houses. “It was the original vision for Apple. That’s what we tried to do with the first Mac. That’s what we did with the iPod.”

Across the street from the Jobs family lived a man who had become successful as a real estate agent. “He wasn’t that bright,” Jobs recalled, “but he seemed to be making a fortune. So my dad thought, ‘I can do that.’ He worked so hard, I remember. He took these night classes, passed the license test, and got into real estate. Then the bottom fell out of the market.” As a result, the family found itself financially strapped for a year or so while Steve was in elementary school. His mother took a job as a bookkeeper for Varian Associates, a company that made scientific instruments, and they took out a second mortgage. One day his fourth-grade teacher asked him, “What is it you don’t understand about the universe?” Jobs replied, “I don’t understand why all of a sudden my dad is so broke.” He was proud that his father never adopted a servile attitude or slick style that may have made him a better salesman. “You had to suck up to people to sell real estate, and he wasn’t good at that and it wasn’t in his nature. I admired him for that.” Paul Jobs went back to being a mechanic.

His father was calm and gentle, traits that his son later praised more than emulated. He was also resolute. Jobs described one example:

Nearby was an engineer who was working at Westinghouse. He was a single guy, beatnik type. He had a girlfriend. She would babysit me sometimes. Both my parents worked, so I would come here right after school for a couple of hours. He would get drunk and hit her a couple of times. She came over one night, scared out of her wits, and he came over drunk, and my dad stood him down—saying “She’s here, but you’re not coming in.” He stood right there. We like to think everything was idyllic in the 1950s, but this guy was one of those engineers who had messed-up lives.

What made the neighborhood different from the thousands of other spindly-tree subdivisions across America was that even the ne’er-do-wells tended to be engineers. “When we moved here, there were apricot and plum orchards on all of these corners,” Jobs recalled. “But it was beginning to boom because of military investment.” He soaked up the history of the valley and developed a yearning to play his own role. Edwin Land of Polaroid later told him about being asked by Eisenhower to help build the U-2 spy plane cameras to see how real the Soviet threat was. The film was dropped in canisters and returned to the NASA Ames Research Center in Sunnyvale, not far from where Jobs lived. “The first computer terminal I ever saw was when my dad brought me to the Ames Center,” he said. “I fell totally in love with it.”

Other defense contractors sprouted nearby during the 1950s. The Lockheed Missiles and Space Division, which built submarine-launched ballistic missiles, was founded in 1956 next to the NASA Center; by the time Jobs moved to the area four years later, it employed twenty thousand people. A few hundred yards away, Westinghouse built facilities that produced tubes and electrical transformers for the missile systems. “You had all these military companies on the cutting edge,” he recalled. “It was mysterious and high-tech and made living here very exciting.”

In the wake of the defense industries there arose a booming economy based on technology. Its roots stretched back to 1938, when David Packard and his new wife moved into a house in Palo Alto that had a shed where his friend Bill Hewlett was soon ensconced. The house had a garage—an appendage that would prove both useful and iconic in the valley—in which they tinkered around until they had their first product, an audio oscillator. By the 1950s, Hewlett-Packard was a fast-growing company making technical instruments.

Fortunately there was a place nearby for entrepreneurs who had outgrown their garages. In a move that would help transform the area into the cradle of the tech revolution, Stanford University’s dean of engineering, Frederick Terman, created a seven-hundred-acre industrial park on university land for private companies that could commercialize the ideas of his students. Its first tenant was Varian Associates, where Clara Jobs worked. “Terman came up with this great idea that did more than anything to cause the tech industry to grow up here,” Jobs said. By the time Jobs was ten, HP had nine thousand employees and was the blue-chip company where every engineer seeking financial stability wanted to work.

The most important technology for the region’s growth was, of course, the semiconductor. William Shockley, who had been one of the inventors of the transistor at Bell Labs in New Jersey, moved out to Mountain View and, in 1956, started a company to build transistors using silicon rather than the more expensive germanium that was then commonly used. But Shockley became increasingly erratic and abandoned his silicon transistor project, which led eight of his engineers—most notably Robert Noyce and Gordon Moore—to break away to form Fairchild Semiconductor. That company grew to twelve thousand employees, but it fragmented in 1968, when Noyce lost a power struggle to become CEO. He took Gordon Moore and founded a company that they called Integrated Electronics Corporation, which they soon smartly abbreviated to Intel. Their third employee was Andrew Grove, who later would grow the company by shifting its focus from memory chips to microprocessors. Within a few years there would be more than fifty companies in the area making semiconductors.

The exponential growth of this industry was correlated with the phenomenon famously discovered by Moore, who in 1965 drew a graph of the speed of integrated circuits, based on the number of transistors that could be placed on a chip, and showed that it doubled about every two years, a trajectory that could be expected to continue. This was reaffirmed in 1971, when Intel was able to etch a complete central processing unit onto one chip, the Intel 4004, which was dubbed a “microprocessor.” Moore’s Law has held generally true to this day, and its reliable projection of performance to price allowed two generations of young entrepreneurs, including Steve Jobs and Bill Gates, to create cost projections for their forward-leaning products.

The chip industry gave the region a new name when Don Hoefler, a columnist for the weekly trade paper Electronic News, began a series in January 1971 entitled “Silicon Valley USA.” The forty-mile Santa Clara Valley, which stretches from South San Francisco through Palo Alto to San Jose, has as its commercial backbone El Camino Real, the royal road that once connected California’s twenty-one mission churches and is now a bustling avenue that connects companies and startups accounting for a third of the venture capital investment in the United States each year. “Growing up, I got inspired by the history of the place,” Jobs said. “That made me want to be a part of it.”

Like most kids, he became infused with the passions of the grown-ups around him. “Most of the dads in the neighborhood did really neat stuff, like photovoltaics and batteries and radar,” Jobs recalled. “I grew up in awe of that stuff and asking people about it.” The most important of these neighbors, Larry Lang, lived seven doors away. “He was my model of what an HP engineer was supposed to be: a big ham radio operator, hard-core electronics guy,” Jobs recalled. “He would bring me stuff to play with.” As we walked up to Lang’s old house, Jobs pointed to the driveway. “He took a carbon microphone and a battery and a speaker, and he put it on this driveway. He had me talk into the carbon mike and it amplified out of the speaker.” Jobs had been taught by his father that microphones always required an electronic amplifier. “So I raced home, and I told my dad that he was wrong.”

“No, it needs an amplifier,” his father assured him. When Steve protested otherwise, his father said he was crazy. “It can’t work without an amplifier. There’s some trick.”

“I kept saying no to my dad, telling him he had to see it, and finally he actually walked down with me and saw it. And he said, ‘Well I’ll be a bat out of hell.’”

Jobs recalled the incident vividly because it was his first realization that his father did not know everything. Then a more disconcerting discovery began to dawn on him: He was smarter than his parents. He had always admired his father’s competence and savvy. “He was not an educated man, but I had always thought he was pretty damn smart. He didn’t read much, but he could do a lot. Almost everything mechanical, he could figure it out.” Yet the carbon microphone incident, Jobs said, began a jarring process of realizing that he was in fact more clever and quick than his parents. “It was a very big moment that’s burned into my mind. When I realized that I was smarter than my parents, I felt tremendous shame for having thought that. I will never forget that moment.” This discovery, he later told friends, along with the fact that he was adopted, made him feel apart—detached and separate—from both his family and the world.

Another layer of awareness occurred soon after. Not only did he discover that he was brighter than his parents, but he discovered that they knew this. Paul and Clara Jobs were loving parents, and they were willing to adapt their lives to suit a son who was very smart—and also willful. They would go to great lengths to accommodate him. And soon Steve discovered this fact as well. “Both my parents got me. They felt a lot of responsibility once they sensed that I was special. They found ways to keep feeding me stuff and putting me in better schools. They were willing to defer to my needs.”

So he grew up not only with a sense of having once been abandoned, but also with a sense that he was special. In his own mind, that was more important in the formation of his personality.

School

Even before Jobs started elementary school, his mother had taught him how to read. This, however, led to some problems once he got to school. “I was kind of bored for the first few years, so I occupied myself by getting into trouble.” It also soon became clear that Jobs, by both nature and nurture, was not disposed to accept authority. “I encountered authority of a different kind than I had ever encountered before, and I did not like it. And they really almost got me. They came close to really beating any curiosity out of me.”

His school, Monta Loma Elementary, was a series of low-slung 1950s buildings four blocks from his house. He countered his boredom by playing pranks. “I had a good friend named Rick Ferrentino, and we’d get into all sorts of trouble,” he recalled. “Like we made little posters announcing ‘Bring Your Pet to School Day.’ It was crazy, with dogs chasing cats all over, and the teachers were beside themselves.” Another time they convinced some kids to tell them the combination numbers for their bike locks. “Then we went outside and switched all of the locks, and nobody could get their bikes. It took them until late that night to straighten things out.” When he was in third grade, the pranks became a bit more dangerous. “One time we set off an explosive under the chair of our teacher, Mrs. Thurman. We gave her a nervous twitch.”

Not surprisingly, he was sent home two or three times before he finished third grade. By then, however, his father had begun to treat him as special, and in his calm but firm manner he made it clear that he expected the school to do the same. “Look, it’s not his fault,” Paul Jobs told the teachers, his son recalled. “If you can’t keep him interested, it’s your fault.” His parents never punished him for his transgressions at school. “My father’s father was an alcoholic and whipped him with a belt, but I’m not sure if I ever got spanked.” Both of his parents, he added, “knew the school was at fault for trying to make me memorize stupid stuff rather than stimulating me.” He was already starting to show the admixture of sensitivity and insensitivity, bristliness and detachment, that would mark him for the rest of his life.

When it came time for him to go into fourth grade, the school decided it was best to put Jobs and Ferrentino into separate classes. The teacher for the advanced class was a spunky woman named Imogene Hill, known as “Teddy,” and she became, Jobs said, “one of the saints of my life.” After watching him for a couple of weeks, she figured that the best way to handle him was to bribe him. “After school one day, she gave me this workbook with math problems in it, and she said, ‘I want you to take it home and do this.’ And I thought, ‘Are you nuts?’ And then she pulled out one of these giant lollipops that seemed as big as the world. And she said, ‘When you’re done with it, if you get it mostly right, I will give you this and five dollars.’ And I handed it back within two days.” After a few months, he no longer required the bribes. “I just wanted to learn and to please her.”

She reciprocated by getting him a hobby kit for grinding a lens and making a camera. “I learned more from her than any other teacher, and if it hadn’t been for her I’m sure I would have gone to jail.” It reinforced, once again, the idea that he was special. “In my class, it was just me she cared about. She saw something in me.”

It was not merely intelligence that she saw. Years later she liked to show off a picture of that year’s class on Hawaii Day. Jobs had shown up without the suggested Hawaiian shirt, but in the picture he is front and center wearing one. He had, literally, been able to talk the shirt off another kid’s back.

Near the end of fourth grade, Mrs. Hill had Jobs tested. “I scored at the high school sophomore level,” he recalled. Now that it was clear, not only to himself and his parents but also to his teachers, that he was intellectually special, the school made the remarkable proposal that he skip two grades and go right into seventh; it would be the easiest way to keep him challenged and stimulated. His parents decided, more sensibly, to have him skip only one grade.

The transition was wrenching. He was a socially awkward loner who found himself with kids a year older. Worse yet, the sixth grade was in a different school, Crittenden Middle. It was only eight blocks from Monta Loma Elementary, but in many ways it was a world apart, located in a neighborhood filled with ethnic gangs. “Fights were a daily occurrence; as were shakedowns in bathrooms,” wrote the Silicon Valley journalist Michael S. Malone. “Knives were regularly brought to school as a show of macho.” Around the time that Jobs arrived, a group of students were jailed for a gang rape, and the bus of a neighboring school was destroyed after its team beat Crittenden’s in a wrestling match.

Jobs was often bullied, and in the middle of seventh grade he gave his parents an ultimatum. “I insisted they put me in a different school,” he recalled. Financially this was a tough demand. His parents were barely making ends meet, but by this point there was little doubt that they would eventually bend to his will. “When they resisted, I told them I would just quit going to school if I had to go back to Crittenden. So they researched where the best schools were and scraped together every dime and bought a house for $21,000 in a nicer district.”

The move was only three miles to the south, to a former apricot orchard in Los Altos that had been turned into a subdivision of cookie-cutter tract homes. Their house, at 2066 Crist Drive, was one story with three bedrooms and an all-important attached garage with a roll-down door facing the street. There Paul Jobs could tinker with cars and his son with electronics.

Its other significant attribute was that it was just over the line inside what was then the Cupertino-Sunnyvale School District, one of the safest and best in the valley. “When I moved here, these corners were still orchards,” Jobs pointed out as we walked in front of his old house. “The guy who lived right there taught me how to be a good organic gardener and to compost. He grew everything to perfection. I never had better food in my life. That’s when I began to appreciate organic fruits and vegetables.”

Even though they were not fervent about their faith, Jobs’s parents wanted him to have a religious upbringing, so they took him to the Lutheran church most Sundays. That came to an end when he was thirteen. In July 1968 Life magazine published a shocking cover showing a pair of starving children in Biafra. Jobs took it to Sunday school and confronted the church’s pastor. “If I raise my finger, will God know which one I’m going to raise even before I do it?”

The pastor answered, “Yes, God knows everything.”

Jobs then pulled out the Life cover and asked, “Well, does God know about this and what’s going to happen to those children?”

“Steve, I know you don’t understand, but yes, God knows about that.”

Jobs announced that he didn’t want to have anything to do with worshipping such a God, and he never went back to church. He did, however, spend years studying and trying to practice the tenets of Zen Buddhism. Reflecting years later on his spiritual feelings, he said that religion was at its best when it emphasized spiritual experiences rather than received dogma. “The juice goes out of Christianity when it becomes too based on faith rather than on living like Jesus or seeing the world as Jesus saw it,” he told me. “I think different religions are different doors to the same house. Sometimes I think the house exists, and sometimes I don’t. It’s the great mystery.”

Paul Jobs was then working at Spectra-Physics, a company in nearby Santa Clara that made lasers for electronics and medical products. As a machinist, he crafted the prototypes of products that the engineers were devising. His son was fascinated by the need for perfection. “Lasers require precision alignment,” Jobs said. “The really sophisticated ones, for airborne applications or medical, had very precise features. They would tell my dad something like, ‘This is what we want, and we want it out of one piece of metal so that the coefficients of expansion are all the same.’ And he had to figure out how to do it.” Most pieces had to be made from scratch, which meant that Paul had to create custom tools and dies. His son was impressed, but he rarely went to the machine shop. “It would have been fun if he had gotten to teach me how to use a mill and lathe. But unfortunately I never went, because I was more interested in electronics.”

One summer Paul took Steve to Wisconsin to visit the family’s dairy farm. Rural life did not appeal to Steve, but one image stuck with him. He saw a calf being born, and he was amazed when the tiny animal struggled up within minutes and began to walk. “It was not something she had learned, but it was instead hardwired into her,” he recalled. “A human baby couldn’t do that. I found it remarkable, even though no one else did.” He put it in hardware-software terms: “It was as if something in the animal’s body and in its brain had been engineered to work together instantly rather than being learned.”

In ninth grade Jobs went to Homestead High, which had a sprawling campus of two-story cinderblock buildings painted pink that served two thousand students. “It was designed by a famous prison architect,” Jobs recalled. “They wanted to make it indestructible.” He had developed a love of walking, and he walked the fifteen blocks to school by himself each day.

He had few friends his own age, but he got to know some seniors who were immersed in the counterculture of the late 1960s. It was a time when the geek and hippie worlds were beginning to show some overlap. “My friends were the really smart kids,” he said. “I was interested in math and science and electronics. They were too, and also into LSD and the whole counterculture trip.”

His pranks by then typically involved electronics. At one point he wired his house with speakers. But since speakers can also be used as microphones, he built a control room in his closet, where he could listen in on what was happening in other rooms. One night, when he had his headphones on and was listening in on his parents’ bedroom, his father caught him and angrily demanded that he dismantle the system. He spent many evenings visiting the garage of Larry Lang, the engineer who lived down the street from his old house. Lang eventually gave Jobs the carbon microphone that had fascinated him, and he turned him on to Heathkits, those assemble-it-yourself kits for making ham radios and other electronic gear that were beloved by the soldering set back then. “Heathkits came with all the boards and parts color-coded, but the manual also explained the theory of how it operated,” Jobs recalled. “It made you realize you could build and understand anything. Once you built a couple of radios, you’d see a TV in the catalogue and say, ‘I can build that as well,’ even if you didn’t. I was very lucky, because when I was a kid both my dad and the Heathkits made me believe I could build anything.”

Lang also got him into the Hewlett-Packard Explorers Club, a group of fifteen or so students who met in the company cafeteria on Tuesday nights. “They would get an engineer from one of the labs to come and talk about what he was working on,” Jobs recalled. “My dad would drive me there. I was in heaven. HP was a pioneer of light-emitting diodes. So we talked about what to do with them.” Because his father now worked for a laser company, that topic particularly interested him. One night he cornered one of HP’s laser engineers after a talk and got a tour of the holography lab. But the most lasting impression came from seeing the small computers the company was developing. “I saw my first desktop computer there. It was called the 9100A, and it was a glorified calculator but also really the first desktop computer. It was huge, maybe forty pounds, but it was a beauty of a thing. I fell in love with it.”

The kids in the Explorers Club were encouraged to do projects, and Jobs decided to build a frequency counter, which measures the number of pulses per second in an electronic signal. He needed some parts that HP made, so he picked up the phone and called the CEO. “Back then, people didn’t have unlisted numbers. So I looked up Bill Hewlett in Palo Alto and called him at home. And he answered and chatted with me for twenty minutes. He got me the parts, but he also got me a job in the plant where they made frequency counters.” Jobs worked there the summer after his freshman year at Homestead High. “My dad would drive me in the morning and pick me up in the evening.”

His work mainly consisted of “just putting nuts and bolts on things” on an assembly line. There was some resentment among his fellow line workers toward the pushy kid who had talked his way in by calling the CEO. “I remember telling one of the supervisors, ‘I love this stuff, I love this stuff,’ and then I asked him what he liked to do best. And he said, ‘To fuck, to fuck.’” Jobs had an easier time ingratiating himself with the engineers who worked one floor above. “They served doughnuts and coffee every morning at ten. So I’d go upstairs and hang out with them.”

Jobs liked to work. He also had a newspaper route—his father would drive him when it was raining—and during his sophomore year spent weekends and the summer as a stock clerk at a cavernous electronics store, Haltek. It was to electronics what his father’s junkyards were to auto parts: a scavenger’s paradise sprawling over an entire city block with new, used, salvaged, and surplus components crammed onto warrens of shelves, dumped unsorted into bins, and piled in an outdoor yard. “Out in the back, near the bay, they had a fenced-in area with things like Polaris submarine interiors that had been ripped and sold for salvage,” he recalled. “All the controls and buttons were right there. The colors were military greens and grays, but they had these switches and bulb covers of amber and red. There were these big old lever switches that, when you flipped them, it was awesome, like you were blowing up Chicago.”

At the wooden counters up front, laden with thick catalogues in tattered binders, people would haggle for switches, resistors, capacitors, and sometimes the latest memory chips. His father used to do that for auto parts, and he succeeded because he knew the value of each better than the clerks. Jobs followed suit. He developed a knowledge of electronic parts that was honed by his love of negotiating and turning a profit. He would go to electronic flea markets, such as the San Jose swap meet, haggle for a used circuit board that contained some valuable chips or components, and then sell those to his manager at Haltek.

Jobs was able to get his first car, with his father’s help, when he was fifteen. It was a two-tone Nash Metropolitan that his father had fitted out with an MG engine. Jobs didn’t really like it, but he did not want to tell his father that, or miss out on the chance to have his own car. “In retrospect, a Nash Metropolitan might seem like the most wickedly cool car,” he later said. “But at the time it was the most uncool car in the world. Still, it was a car, so that was great.” Within a year he had saved up enough from his various jobs that he could trade up to a red Fiat 850 coupe with an Abarth engine. “My dad helped me buy and inspect it. The satisfaction of getting paid and saving up for something, that was very exciting.”

That same summer, between his sophomore and junior years at Homestead, Jobs began smoking marijuana. “I got stoned for the first time that summer. I was fifteen, and then began using pot regularly.” At one point his father found some dope in his son’s Fiat. “What’s this?” he asked. Jobs coolly replied, “That’s marijuana.” It was one of the few times in his life that he faced his father’s anger. “That was the only real fight I ever got in with my dad,” he said. But his father again bent to his will. “He wanted me to promise that I’d never use pot again, but I wouldn’t promise.” In fact by his senior year he was also dabbling in LSD and hash as well as exploring the mind-bending effects of sleep deprivation. “I was starting to get stoned a bit more. We would also drop acid occasionally, usually in fields or in cars.”

He also flowered intellectually during his last two years in high school and found himself at the intersection, as he had begun to see it, of those who were geekily immersed in electronics and those who were into literature and creative endeavors. “I started to listen to music a whole lot, and I started to read more outside of just science and technology—Shakespeare, Plato. I loved King Lear.” His other favorites included Moby-Dick and the poems of Dylan Thomas. I asked him why he related to King Lear and Captain Ahab, two of the most willful and driven characters in literature, but he didn’t respond to the connection I was making, so I let it drop. “When I was a senior I had this phenomenal AP English class. The teacher was this guy who looked like Ernest Hemingway. He took a bunch of us snowshoeing in Yosemite.”

One course that Jobs took would become part of Silicon Valley lore: the electronics class taught by John McCollum, a former Navy pilot who had a showman’s flair for exciting his students with such tricks as firing up a Tesla coil. His little stockroom, to which he would lend the key to pet students, was crammed with transistors and other components he had scored.

McCollum’s classroom was in a shed-like building on the edge of the campus, next to the parking lot. “This is where it was,” Jobs recalled as he peered in the window, “and here, next door, is where the auto shop class used to be.” The juxtaposition highlighted the shift from the interests of his father’s generation. “Mr. McCollum felt that electronics class was the new auto shop.”

McCollum believed in military discipline and respect for authority. Jobs didn’t. His aversion to authority was something he no longer tried to hide, and he affected an attitude that combined wiry and weird intensity with aloof rebelliousness. McCollum later said, “He was usually off in a corner doing something on his own and really didn’t want to have much of anything to do with either me or the rest of the class.” He never trusted Jobs with a key to the stockroom. One day Jobs needed a part that was not available, so he made a collect call to the manufacturer, Burroughs in Detroit, and said he was designing a new product and wanted to test out the part. It arrived by air freight a few days later. When McCollum asked how he had gotten it, Jobs described—with defiant pride—the collect call and the tale he had told. “I was furious,” McCollum said. “That was not the way I wanted my students to behave.” Jobs’s response was, “I don’t have the money for the phone call. They’ve got plenty of money.”

Jobs took McCollum’s class for only one year, rather than the three that it was offered. For one of his projects, he made a device with a photocell that would switch on a circuit when exposed to light, something any high school science student could have done. He was far more interested in playing with lasers, something he learned from his father. With a few friends, he created light shows for parties by bouncing lasers off mirrors that were attached to the speakers of his stereo system

# conscious_memory.py import time import logging import math import numpy as np from collections import defaultdict, deque from typing import List, Dict, Any, Tuple, Set from datetime import datetime, timedelta from enum import Enum from dataclasses import dataclass, field # 配置日志 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger('MemorySystem') # 在conscious_memory.py中 def store_from_perception(perception_input): # 从感知输入创建记忆 content = { "type": perception_input["sensor_type"].value, "description": perception_input["data"]["content"] } # ...存储到记忆系统 # 情感类型枚举 class EmotionType(Enum): JOY = 1 SADNESS = 2 FEAR = 3 ANGER = 4 SURPRISE = 5 DISGUST = 6 NEUTRAL = 7 # 记忆内容类型 class MemoryContentType(Enum): VISUAL = "visual" AUDITORY = "auditory" OLFACTORY = "olfactory" TACTILE = "tactile" EMOTIONAL = "emotional" CONCEPTUAL = "conceptual" EVENT = "event" TRAUMA = "trauma" DAILY = "daily" # 基于间隔重复的记忆强度模型 @dataclass class MemoryStrength: base: float = 1.0 # 初始强度 (0.0-1.0) decay_rate: float = 0.01 # 每日衰减率 last_accessed: float = field(default_factory=time.time) # 最后访问时间戳 reinforcement_count: int = 0 # 强化次数 next_review: float = field(default_factory=lambda: time.time() + 24 * 3600) # 下次复习时间 def current_strength(self) -> float: """计算当前记忆强度,考虑时间衰减和强化""" hours_passed = (time.time() - self.last_accessed) / 3600 # 应用指数衰减 decay_factor = math.exp(-self.decay_rate * hours_passed / 24) base_strength = self.base * decay_factor # 强化奖励 reinforcement_bonus = min(0.3, self.reinforcement_count * 0.05) return max(0.0, min(1.0, base_strength + reinforcement_bonus)) def reinforce(self, reinforcement: float = 0.15): """强化记忆,增加基础强度并调整衰减率""" self.base = min(1.0, self.base + reinforcement) self.reinforcement_count += 1 self.last_accessed = time.time() # 根据强化次数调整衰减率 self.decay_rate = max(0.001, self.decay_rate * (0.9 ** self.reinforcement_count)) # 设置下次复习时间(间隔增长) review_interval = 24 * (2 ** min(5, self.reinforcement_count)) # 指数增长,最多32天 self.next_review = time.time() + review_interval * 3600 # 情感关联模型 @dataclass class EmotionalAssociation: emotion: EmotionType intensity: float # 0.0-1.0 context: str = "" # 情感关联的上下文描述 class MemorySystem: """增强型记忆系统 - 支持情感关联、时间衰减和多模态索引""" def __init__(self, initial_memories: List[Dict] = None): self.memories = [] # 所有记忆存储 self.memory_strengths = {} # 记忆ID -> MemoryStrength self.memory_index = defaultdict(list) # 标签索引 # 多模态索引 self.emotion_index = defaultdict(list) # 情感索引: emotion_name -> list of (memory_id, intensity) self.context_index = defaultdict(list) # 上下文关键词索引 self.temporal_index = defaultdict(list) # 时间索引 (按天分组) self.content_type_index = defaultdict(list) # 内容类型索引 # 情感关联网络 self.emotion_network = defaultdict(list) # 情感 -> 相关记忆ID # 初始化记忆 if initial_memories: for mem in initial_memories: self.store( content=mem["content"], tags=mem.get("tags", []), emotional_associations=mem.get("emotional_associations", []) ) def store(self, content: Dict, tags: List[str] = None, emotional_associations: List[EmotionalAssociation] = None) -> str: """存储记忆,支持情感关联""" # 创建记忆条目 memory_id = f"mem_{int(time.time() * 1000)}" timestamp = time.time() # 确保内容类型是枚举值 content_type = content.get("type") if isinstance(content_type, MemoryContentType): content["type"] = content_type.value memory_entry = { "id": memory_id, "content": content, "timestamp": timestamp, "tags": tags or [], "emotional_associations": emotional_associations or [], "retrieval_count": 0, "content_type": content.get("type", MemoryContentType.CONCEPTUAL.value) } # 添加到记忆库 self.memories.append(memory_entry) self.memory_strengths[memory_id] = MemoryStrength() # 索引标签 for tag in memory_entry["tags"]: self.memory_index[tag].append(memory_id) # 索引情感关联 for emotion_assoc in memory_entry["emotional_associations"]: emotion_key = emotion_assoc.emotion.name # 存储记忆ID和强度 self.emotion_index[emotion_key].append((memory_id, emotion_assoc.intensity)) # 构建情感网络 self.emotion_network[emotion_key].append({ "memory_id": memory_id, "intensity": emotion_assoc.intensity, "context": emotion_assoc.context }) # 索引上下文关键词 if "description" in content: for word in content["description"].split(): if len(word) > 3: # 只索引有意义的词 self.context_index[word.lower()].append(memory_id) # 索引时间 (按日期分组) date_key = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d") self.temporal_index[date_key].append(memory_id) # 索引内容类型 content_type = memory_entry["content_type"] self.content_type_index[content_type].append(memory_id) logger.info(f"存储新记忆: {content.get('type')} (ID: {memory_id}, 标签: {tags})") return memory_id def retrieve(self, context: Dict, affective_state: Dict, max_results: int = 5) -> List[Dict]: """增强型记忆检索,考虑情感状态和上下文""" # 情感状态分析 current_emotion = affective_state.get("emotion", {}).get("current_emotion", "NEUTRAL") emotion_intensity = affective_state.get("emotion", {}).get("intensity", 0.5) # 使用集合避免重复 candidate_memory_ids = set() # 1. 标签匹配 if "tags" in context: for tag in context["tags"]: candidate_memory_ids.update(self.memory_index.get(tag, [])) # 2. 情感匹配 - 使用优化后的情感索引 emotion_memories = self.emotion_index.get(current_emotion.upper(), []) for mem_id, intensity in emotion_memories: if intensity >= emotion_intensity * 0.7: candidate_memory_ids.add(mem_id) # 3. 上下文关键词匹配 if "keywords" in context: for keyword in context["keywords"]: candidate_memory_ids.update(self.context_index.get(keyword.lower(), [])) # 4. 时间相关性 (最近事件优先) if "time_recency" in context and context["time_recency"]: # 获取最近30天的日期键 recent_dates = self._get_recent_date_keys(30) for date in recent_dates: candidate_memory_ids.update(self.temporal_index.get(date, [])) # 5. 内容类型过滤 if "content_types" in context: for ctype in context["content_types"]: candidate_memory_ids.update(self.content_type_index.get(ctype, [])) # 6. 通过情感网络扩展(关联情感) if "emotion_network" in context and context["emotion_network"]: # 获取当前情感的关联情感 related_emotions = self._get_related_emotions(current_emotion) for emotion in related_emotions: # 添加这些情感的记忆 for mem_id, _ in self.emotion_index.get(emotion, []): candidate_memory_ids.add(mem_id) # 转换为记忆对象并评分 candidate_memories = [self._get_memory_by_id(mid) for mid in candidate_memory_ids] scored_memories = self._score_memories(candidate_memories, context, affective_state) # 按分数排序并返回前N个结果 scored_memories.sort(key=lambda x: x[1], reverse=True) return [mem[0] for mem in scored_memories[:max_results]] def reinforce_memory(self, memory_id: str, reinforcement: float = 0.15): """强化特定记忆""" if memory_id in self.memory_strengths: self.memory_strengths[memory_id].reinforce(reinforcement) logger.info(f"强化记忆 {memory_id},新强度: {self.memory_strengths[memory_id].current_strength():.2f}") def reinforce_related_memories(self, memory_id: str, radius: int = 2): """强化相关记忆(基于情感网络)""" main_memory = self._get_memory_by_id(memory_id) if not main_memory: return 0 reinforced_count = 0 # 获取主记忆的情感 for emotion_assoc in main_memory["emotional_associations"]: emotion_key = emotion_assoc.emotion.name # 获取情感网络中的相关记忆 for related in self.emotion_network.get(emotion_key, []): if related["memory_id"] != memory_id: self.reinforce_memory(related["memory_id"], reinforcement=0.1) reinforced_count += 1 return reinforced_count def decay_memories(self, decay_factor: float = 0.05): """定期衰减记忆强度""" for memory_id, strength in self.memory_strengths.items(): # 衰减率与当前强度成正比 decay_rate = decay_factor * (1 - strength.current_strength()) strength.decay_rate = min(0.1, strength.decay_rate + decay_rate) logger.info(f"记忆衰减完成,总衰减因子: {decay_factor}") def forget_weak_memories(self, threshold: float = 0.1): """遗忘强度低于阈值的记忆""" to_forget = [] for mem in self.memories: strength = self.memory_strengths[mem["id"]].current_strength() if strength < threshold: to_forget.append(mem["id"]) # 移除记忆 for memory_id in to_forget: self._remove_memory(memory_id) if to_forget: logger.warning(f"遗忘{len(to_forget)}个弱记忆: {', '.join(to_forget)}") return to_forget def get_emotion_network(self, emotion: str) -> List[Dict]: """获取特定情感相关的记忆网络""" return self.emotion_network.get(emotion.upper(), []) def get_stats(self) -> Dict: """获取记忆系统统计信息""" total_memories = len(self.memories) strengths = [s.current_strength() for s in self.memory_strengths.values()] return { "total_memories": total_memories, "tag_distribution": {tag: len(ids) for tag, ids in self.memory_index.items()}, "emotion_distribution": {emo: len(ids) for emo, ids in self.emotion_index.items()}, "content_type_distribution": {ctype: len(ids) for ctype, ids in self.content_type_index.items()}, "avg_strength": sum(strengths) / total_memories if total_memories else 0, "weak_memories": sum(1 for s in strengths if s < 0.3), "next_review_count": sum(1 for s in self.memory_strengths.values() if s.next_review < time.time() + 24 * 3600) } def get_memory_timeline(self, days: int = 30) -> List[Dict]: """获取时间线视图(最近days天的记忆)""" timeline = defaultdict(list) cutoff = time.time() - days * 24 * 3600 for mem in self.memories: if mem["timestamp"] > cutoff: date = datetime.fromtimestamp(mem["timestamp"]).strftime("%Y-%m-%d") timeline[date].append({ "id": mem["id"], "content_preview": mem["content"].get("description", "")[:50] + "..." if len(mem["content"].get("description", "")) > 50 else mem["content"].get("description", ""), "strength": self.memory_strengths[mem["id"]].current_strength() }) # 转换为按日期排序的列表 sorted_timeline = [] for date in sorted(timeline.keys(), reverse=True): sorted_timeline.append({ "date": date, "memories": timeline[date] }) return sorted_timeline # ===== 内部辅助方法 ===== def _get_recent_date_keys(self, days: int) -> List[str]: """获取最近days天的日期键(格式:YYYY-MM-DD)""" today = datetime.today() return [(today - timedelta(days=i)).strftime("%Y-%m-%d") for i in range(days)] def _get_related_emotions(self, base_emotion: str) -> List[str]: """获取与基础情感相关的情感""" # 简单映射 - 实际应用中应更复杂 emotion_groups = { "JOY": ["JOY", "SURPRISE"], "FEAR": ["FEAR", "DISGUST"], "SADNESS": ["SADNESS"], "ANGER": ["ANGER"], "NEUTRAL": [] } return emotion_groups.get(base_emotion.upper(), []) def _score_memories(self, memories: List[Dict], context: Dict, affective_state: Dict) -> List[Tuple[Dict, float]]: """为记忆计算综合相关性分数""" scored = [] current_emotion = affective_state.get("emotion", {}).get("current_emotion", "NEUTRAL") emotion_intensity = affective_state.get("emotion", {}).get("intensity", 0.5) for mem in memories: if not mem: continue mem_id = mem["id"] strength = self.memory_strengths[mem_id].current_strength() # 1. 基础分数 (记忆强度 + 检索次数) score = strength * 0.6 + min(1.0, mem["retrieval_count"] * 0.1) # 2. 情感匹配分数 emotion_score = 0 for assoc in mem["emotional_associations"]: if assoc.emotion.name == current_emotion: # 情感强度匹配度 intensity_match = 1.0 - abs(assoc.intensity - emotion_intensity) emotion_score = intensity_match * 0.3 break score += emotion_score # 3. 时间衰减补偿 (最近记忆加分) recency = 1 - (time.time() - mem["timestamp"]) / (365 * 24 * 3600) score += recency * 0.1 # 4. 上下文匹配分数 if "keywords" in context: context_words = set(word.lower() for word in context["keywords"]) content_words = set(mem["content"].get("description", "").lower().split()) match_count = len(context_words & content_words) score += min(0.2, match_count * 0.05) # 5. 情感网络加成 (如果与当前情感网络相关) if "emotion_network" in context and context["emotion_network"]: for assoc in mem["emotional_associations"]: if assoc.emotion.name in self._get_related_emotions(current_emotion): score += 0.05 # 更新检索计数 mem["retrieval_count"] += 1 self.memory_strengths[mem_id].last_accessed = time.time() scored.append((mem, score)) return scored def _get_memory_by_id(self, memory_id: str) -> Dict: """通过ID获取记忆""" for mem in self.memories: if mem["id"] == memory_id: return mem return None def _remove_memory(self, memory_id: str): """从系统中完全移除记忆""" # 从主列表移除 self.memories = [mem for mem in self.memories if mem["id"] != memory_id] # 从索引中移除 for index in [self.memory_index, self.emotion_index, self.context_index, self.temporal_index, self.content_type_index]: for key, ids in index.items(): if memory_id in ids: ids.remove(memory_id) # 从情感网络中移除 for emotion, associations in self.emotion_network.items(): self.emotion_network[emotion] = [a for a in associations if a["memory_id"] != memory_id] # 移除强度记录 if memory_id in self.memory_strengths: del self.memory_strengths[memory_id] logger.info(f"完全移除记忆: {memory_id}") # ===== 测试用例 ===== if __name__ == "__main__": print("=== 增强型记忆系统测试 ===") # 初始化记忆系统 memory_system = MemorySystem() # 创建情感关联 birthday_joy = EmotionalAssociation(EmotionType.JOY, 0.9, "生日派对") accident_fear = EmotionalAssociation(EmotionType.FEAR, 0.85, "车祸现场") # 添加记忆 memory_system.store( content={"type": MemoryContentType.EVENT.value, "description": "我的10岁生日派对", "location": "家里后院"}, tags=["childhood", "celebration"], emotional_associations=[birthday_joy] ) memory_system.store( content={"type": MemoryContentType.EVENT.value, "description": "高中毕业典礼", "location": "学校礼堂"}, tags=["education", "achievement"], emotional_associations=[EmotionalAssociation(EmotionType.JOY, 0.8)] ) memory_system.store( content={"type": MemoryContentType.TRAUMA.value, "description": "目睹严重车祸", "location": "市中心"}, tags=["accident", "trauma"], emotional_associations=[accident_fear] ) # 添加近期记忆 recent_memory_id = memory_system.store( content={"type": MemoryContentType.DAILY.value, "description": "早晨喝咖啡阅读新闻", "location": "厨房"}, tags=["routine", "morning"] ) # 模拟检索上下文 context = { "tags": ["celebration"], "keywords": ["生日"], "time_recency": True, "emotion_network": True # 启用情感网络扩展 } # 模拟情感状态 affective_state = { "emotion": { "current_emotion": "JOY", "intensity": 0.7 } } # 检索记忆 print("\n检索与'庆祝'相关的记忆:") results = memory_system.retrieve(context, affective_state) for mem in results: print( f" - {mem['content']['description']} (强度: {memory_system.memory_strengths[mem['id']].current_strength():.2f})") # 强化特定记忆 print("\n强化近期记忆:") memory_system.reinforce_memory(recent_memory_id) # 强化相关记忆 print("\n强化相关记忆:") reinforced_count = memory_system.reinforce_related_memories(recent_memory_id) print(f"强化了{reinforced_count}个相关记忆") # 模拟时间流逝 print("\n模拟时间流逝(30天)...") for _ in range(30): memory_system.decay_memories(decay_factor=0.01) # 再次检索 print("\n再次检索相同上下文:") results = memory_system.retrieve(context, affective_state) for mem in results: strength = memory_system.memory_strengths[mem['id']].current_strength() print(f" - {mem['content']['description']} (衰减后强度: {strength:.2f})") # 遗忘弱记忆 print("\n遗忘弱记忆:") forgotten = memory_system.forget_weak_memories(threshold=0.3) if forgotten: print(f"已遗忘记忆: {', '.join(forgotten)}") else: print("没有需要遗忘的记忆") # 获取系统统计 stats = memory_system.get_stats() print("\n系统统计:") print(f"总记忆数: {stats['total_memories']}") print(f"平均强度: {stats['avg_strength']:.2f}") print(f"弱记忆数: {stats['weak_memories']}") print(f"需要复习的记忆数: {stats['next_review_count']}") # 获取时间线视图 print("\n最近7天记忆时间线:") timeline = memory_system.get_memory_timeline(days=7) for day in timeline: print(f"\n{day['date']}:") for mem in day["memories"]: print(f" - {mem['content_preview']} (强度: {mem['strength']:.2f})") 这个对吗?
08-11
我们是不是应该先修改这个啊?# conscious_memory.py import time import logging from collections import defaultdict from typing import List, Dict, Any class MemorySystem: """记忆系统 - 负责信息的存储和检索""" def __init__(self): self.logger = logging.getLogger('MemorySystem') self.memories = [] self.memory_index = defaultdict(list) def store(self, content: Dict, tags: List[str] = None): """存储记忆""" memory_entry = { "id": f"mem_{int(time.time() * 1000)}", "content": content, "timestamp": time.time(), "tags": tags or [], "retrieval_count": 0 } self.memories.append(memory_entry) # 索引标签 for tag in memory_entry["tags"]: self.memory_index[tag].append(memory_entry["id"]) self.logger.info(f"存储新记忆: {content.get('type')} (标签: {', '.join(tags) if tags else '无'})") def retrieve(self, context: Dict, affective_state: Dict) -> List[Dict]: """检索相关记忆""" # 简化的检索逻辑 - 实际应使用向量搜索 query_tags = [] if "type" in context: query_tags.append(context["type"]) if "source" in context: query_tags.append(context["source"]) # 添加情感标签 emotion = affective_state["emotion"]["current_emotion"] if emotion != "neutral": query_tags.append(emotion) # 从索引中查找 results = [] for tag in query_tags: for mem_id in self.memory_index.get(tag, []): memory = next((m for m in self.memories if m["id"] == mem_id), None) if memory: memory["retrieval_count"] += 1 results.append(memory) # 按检索次数排序(简单相关性) results.sort(key=lambda x: x["retrieval_count"], reverse=True) return results[:5] # 返回最多5个相关记忆 def get_stats(self) -> Dict: """获取记忆系统统计信息""" return { "total_memories": len(self.memories), "tag_distribution": {tag: len(ids) for tag, ids in self.memory_index.items()}, "avg_retrieval": sum(m["retrieval_count"] for m in self.memories) / len( self.memories) if self.memories else 0 }
08-11
好哒 我们来进行下一步 查缺补漏 这个应该怎么办# conscious_memory.py import time import logging import math import numpy as np from collections import defaultdict from typing import List, Dict, Any, Tuple from datetime import datetime, timedelta from enum import Enum from dataclasses import dataclass # 配置日志 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger('MemorySystem') # 情感类型枚举 class EmotionType(Enum): JOY = 1 SADNESS = 2 FEAR = 3 ANGER = 4 SURPRISE = 5 DISGUST = 6 NEUTRAL = 7 # 记忆内容类型 class MemoryContentType(Enum): VISUAL = "visual" AUDITORY = "auditory" OLFACTORY = "olfactory" TACTILE = "tactile" EMOTIONAL = "emotional" CONCEPTUAL = "conceptual" # 记忆强度模型 @dataclass class MemoryStrength: base: float = 1.0 # 初始强度 (0.0-1.0) decay_rate: float = 0.01 # 每日衰减率 last_accessed: float = time.time() # 最后访问时间戳 def current_strength(self) -> float: """计算当前记忆强度,考虑时间衰减""" days_passed = (time.time() - self.last_accessed) / (24 * 3600) decay_factor = math.exp(-self.decay_rate * days_passed) return max(0.0, self.base * decay_factor) def reinforce(self, reinforcement: float = 0.15): """强化记忆,增加基础强度""" self.base = min(1.0, self.base + reinforcement) self.last_accessed = time.time() # 情感关联模型 @dataclass class EmotionalAssociation: emotion: EmotionType intensity: float # 0.0-1.0 context: str = "" # 情感关联的上下文描述 class MemorySystem: """增强型记忆系统 - 支持情感关联、时间衰减和多模态索引""" def __init__(self, initial_memories: List[Dict] = None): self.memories = [] # 所有记忆存储 self.memory_strengths = {} # 记忆ID -> MemoryStrength self.memory_index = defaultdict(list) # 标签索引 # 多模态索引 self.emotion_index = defaultdict(list) # 情感索引 self.context_index = defaultdict(list) # 上下文关键词索引 self.temporal_index = defaultdict(list) # 时间索引 (按天分组) # 情感关联网络 self.emotion_network = defaultdict(list) # 情感 -> 相关记忆ID # 初始化记忆 if initial_memories: for mem in initial_memories: self.store(mem["content"], mem.get("tags", []), mem.get("emotional_associations", [])) def store(self, content: Dict, tags: List[str] = None, emotional_associations: List[EmotionalAssociation] = None) -> str: """存储记忆,支持情感关联""" # 创建记忆条目 memory_id = f"mem_{int(time.time() * 1000)}" timestamp = time.time() memory_entry = { "id": memory_id, "content": content, "timestamp": timestamp, "tags": tags or [], "emotional_associations": emotional_associations or [], "retrieval_count": 0, "content_type": content.get("type", MemoryContentType.CONCEPTUAL.value) } # 添加到记忆库 self.memories.append(memory_entry) self.memory_strengths[memory_id] = MemoryStrength() # 索引标签 for tag in memory_entry["tags"]: self.memory_index[tag].append(memory_id) # 索引情感关联 for emotion_assoc in memory_entry["emotional_associations"]: emotion_key = emotion_assoc.emotion.name self.emotion_index[emotion_key].append(memory_id) # 构建情感网络 self.emotion_network[emotion_key].append({ "memory_id": memory_id, "intensity": emotion_assoc.intensity, "context": emotion_assoc.context }) # 索引上下文关键词 if "description" in content: for word in content["description"].split(): if len(word) > 3: # 只索引有意义的词 self.context_index[word.lower()].append(memory_id) # 索引时间 (按日期分组) date_key = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d") self.temporal_index[date_key].append(memory_id) logger.info(f"存储新记忆: {content.get('type')} (ID: {memory_id}, 标签: {tags})") return memory_id def retrieve(self, context: Dict, affective_state: Dict, max_results: int = 5) -> List[Dict]: """增强型记忆检索,考虑情感状态和上下文""" # 情感状态分析 current_emotion = affective_state.get("emotion", {}).get("current_emotion", "NEUTRAL") emotion_intensity = affective_state.get("emotion", {}).get("intensity", 0.5) # 候选记忆收集 candidate_memories = [] # 1. 标签匹配 if "tags" in context: for tag in context["tags"]: candidate_memories.extend(self._get_memories_by_tag(tag)) # 2. 情感匹配 candidate_memories.extend(self._get_memories_by_emotion(current_emotion, emotion_intensity)) # 3. 上下文关键词匹配 if "keywords" in context: for keyword in context["keywords"]: candidate_memories.extend(self._get_memories_by_keyword(keyword)) # 4. 时间相关性 (最近事件优先) if "time_recency" in context and context["time_recency"]: candidate_memories.extend(self._get_recent_memories()) # 去重并计算相关性分数 scored_memories = self._score_memories(candidate_memories, context, affective_state) # 按分数排序并返回前N个结果 scored_memories.sort(key=lambda x: x[1], reverse=True) return [mem[0] for mem in scored_memories[:max_results]] def reinforce_memory(self, memory_id: str, reinforcement: float = 0.15): """强化特定记忆""" if memory_id in self.memory_strengths: self.memory_strengths[memory_id].reinforce(reinforcement) logger.info(f"强化记忆 {memory_id},新强度: {self.memory_strengths[memory_id].base:.2f}") def decay_memories(self, decay_factor: float = 0.05): """定期衰减记忆强度""" for memory_id, strength in self.memory_strengths.items(): # 衰减率与当前强度成正比 decay_rate = decay_factor * (1 - strength.current_strength()) strength.decay_rate += decay_rate logger.info(f"记忆衰减完成,总衰减因子: {decay_factor}") def forget_weak_memories(self, threshold: float = 0.1): """遗忘强度低于阈值的记忆""" forgotten = [] for memory in self.memories[:]: strength = self.memory_strengths[memory["id"]].current_strength() if strength < threshold: self._remove_memory(memory["id"]) forgotten.append(memory["id"]) if forgotten: logger.warning(f"遗忘{len(forgotten)}个弱记忆: {', '.join(forgotten)}") return forgotten def get_emotion_network(self, emotion: str) -> List[Dict]: """获取特定情感相关的记忆网络""" return self.emotion_network.get(emotion.upper(), []) def get_stats(self) -> Dict: """获取记忆系统统计信息""" total_memories = len(self.memories) strengths = [s.current_strength() for s in self.memory_strengths.values()] return { "total_memories": total_memories, "tag_distribution": {tag: len(ids) for tag, ids in self.memory_index.items()}, "emotion_distribution": {emo: len(ids) for emo, ids in self.emotion_index.items()}, "avg_strength": sum(strengths) / total_memories if total_memories else 0, "weak_memories": sum(1 for s in strengths if s < 0.3) } # ===== 内部辅助方法 ===== def _get_memories_by_tag(self, tag: str) -> List[Dict]: """通过标签获取记忆""" return [self._get_memory_by_id(mid) for mid in self.memory_index.get(tag, [])] def _get_memories_by_emotion(self, emotion: str, intensity: float) -> List[Dict]: """通过情感获取记忆,考虑情感强度""" emotion = emotion.upper() memories = [] for mem_id in self.emotion_index.get(emotion, []): mem = self._get_memory_by_id(mem_id) # 检查情感强度是否匹配 for assoc in mem["emotional_associations"]: if assoc.emotion.name == emotion and assoc.intensity >= intensity * 0.7: memories.append(mem) break return memories def _get_memories_by_keyword(self, keyword: str) -> List[Dict]: """通过关键词获取记忆""" keyword = keyword.lower() return [self._get_memory_by_id(mid) for mid in self.context_index.get(keyword, [])] def _get_recent_memories(self, days: int = 30) -> List[Dict]: """获取近期记忆""" recent_memories = [] cutoff = time.time() - days * 24 * 3600 for mem in self.memories: if mem["timestamp"] > cutoff: recent_memories.append(mem) return recent_memories def _score_memories(self, memories: List[Dict], context: Dict, affective_state: Dict) -> List[Tuple[Dict, float]]: """为记忆计算综合相关性分数""" scored = [] current_emotion = affective_state.get("emotion", {}).get("current_emotion", "NEUTRAL") for mem in memories: if not mem: continue mem_id = mem["id"] strength = self.memory_strengths[mem_id].current_strength() # 1. 基础分数 (记忆强度 + 检索次数) score = strength * 0.6 + min(1.0, mem["retrieval_count"] * 0.1) # 2. 情感匹配分数 emotion_score = 0 for assoc in mem["emotional_associations"]: if assoc.emotion.name == current_emotion: emotion_score = assoc.intensity * 0.3 break score += emotion_score # 3. 时间衰减补偿 (最近记忆加分) recency = 1 - (time.time() - mem["timestamp"]) / (365 * 24 * 3600) score += recency * 0.1 # 4. 上下文匹配分数 if "keywords" in context: context_words = set(word.lower() for word in context["keywords"]) content_words = set(mem["content"].get("description", "").lower().split()) match_count = len(context_words & content_words) score += match_count * 0.05 # 更新检索计数 mem["retrieval_count"] += 1 self.memory_strengths[mem_id].last_accessed = time.time() scored.append((mem, score)) return scored def _get_memory_by_id(self, memory_id: str) -> Dict: """通过ID获取记忆""" for mem in self.memories: if mem["id"] == memory_id: return mem return None def _remove_memory(self, memory_id: str): """从系统中完全移除记忆""" # 从主列表移除 self.memories = [mem for mem in self.memories if mem["id"] != memory_id] # 从索引中移除 for index in [self.memory_index, self.emotion_index, self.context_index]: for key, ids in index.items(): if memory_id in ids: ids.remove(memory_id) # 从情感网络中移除 for emotion, associations in self.emotion_network.items(): self.emotion_network[emotion] = [a for a in associations if a["memory_id"] != memory_id] # 移除强度记录 if memory_id in self.memory_strengths: del self.memory_strengths[memory_id] logger.info(f"完全移除记忆: {memory_id}") # ===== 测试用例 ===== if __name__ == "__main__": print("=== 增强型记忆系统测试 ===") # 初始化记忆系统 memory_system = MemorySystem() # 创建情感关联 birthday_joy = EmotionalAssociation(EmotionType.JOY, 0.9, "生日派对") accident_fear = EmotionalAssociation(EmotionType.FEAR, 0.85, "车祸现场") # 添加记忆 memory_system.store( content={"type": "event", "description": "我的10岁生日派对", "location": "家里后院"}, tags=["childhood", "celebration"], emotional_associations=[birthday_joy] ) memory_system.store( content={"type": "event", "description": "高中毕业典礼", "location": "学校礼堂"}, tags=["education", "achievement"], emotional_associations=[EmotionalAssociation(EmotionType.JOY, 0.8)] ) memory_system.store( content={"type": "trauma", "description": "目睹严重车祸", "location": "市中心"}, tags=["accident", "trauma"], emotional_associations=[accident_fear] ) # 添加近期记忆 recent_memory_id = memory_system.store( content={"type": "daily", "description": "早晨喝咖啡阅读新闻", "location": "厨房"}, tags=["routine", "morning"] ) # 模拟检索上下文 context = { "tags": ["celebration"], "keywords": ["生日"], "time_recency": True } # 模拟情感状态 affective_state = { "emotion": { "current_emotion": "JOY", "intensity": 0.7 } } # 检索记忆 print("\n检索与'庆祝'相关的记忆:") results = memory_system.retrieve(context, affective_state) for mem in results: print( f" - {mem['content']['description']} (强度: {memory_system.memory_strengths[mem['id']].current_strength():.2f})") # 强化特定记忆 print("\n强化近期记忆:") memory_system.reinforce_memory(recent_memory_id) # 模拟时间流逝 print("\n模拟时间流逝(30天)...") for _ in range(30): memory_system.decay_memories(decay_factor=0.01) # 再次检索 print("\n再次检索相同上下文:") results = memory_system.retrieve(context, affective_state) for mem in results: strength = memory_system.memory_strengths[mem['id']].current_strength() print(f" - {mem['content']['description']} (衰减后强度: {strength:.2f})") # 遗忘弱记忆 print("\n遗忘弱记忆:") forgotten = memory_system.forget_weak_memories(threshold=0.3) if forgotten: print(f"已遗忘记忆: {', '.join(forgotten)}") else: print("没有需要遗忘的记忆") # 获取系统统计 stats = memory_system.get_stats() print("\n系统统计:") print(f"总记忆数: {stats['total_memories']}") print(f"平均强度: {stats['avg_strength']:.2f}") print(f"弱记忆数: {stats['weak_memories']}")
08-11
先展示下效果 https://pan.quark.cn/s/e81b877737c1 Node.js 是一种基于 Chrome V8 引擎的 JavaScript 执行环境,它使开发者能够在服务器端执行 JavaScript 编程,显著促进了全栈开发的应用普及。 在 Node.js 的开发流程中,`node_modules` 文件夹用于存储所有依赖的模块,随着项目的进展,该文件夹可能会变得异常庞大,其中包含了众多可能已不再需要的文件和文件夹,这不仅会消耗大量的硬盘空间,还可能减慢项目的加载时间。 `ModClean 2.0` 正是为了应对这一挑战而设计的工具。 `ModClean` 是一款用于清理 `node_modules` 的软件,其核心功能是移除那些不再被使用的文件和文件夹,从而确保项目的整洁性和运行效率。 `ModClean 2.0` 是此工具的改进版本,在原有功能上增加了更多特性,从而提高了清理工作的效率和精确度。 在 `ModClean 2.0` 中,用户可以设置清理规则,例如排除特定的模块或文件类型,以防止误删重要文件。 该工具通常会保留项目所依赖的核心模块,但会移除测试、文档、示例代码等非运行时必需的部分。 通过这种方式,`ModClean` 能够协助开发者优化项目结构,减少不必要的依赖,加快项目的构建速度。 使用 `ModClean` 的步骤大致如下:1. 需要先安装 `ModClean`,在项目的根目录中执行以下命令: ``` npm install modclean -g ```2. 创建配置文件 `.modcleanrc.json` 或 `.modcleanrc.js`,设定希望清理的规则。 比如,可能需要忽略 `LICENSE` 文件或整个 `docs`...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值