使用向量数据库pinecone构建应用02:检索增强生成RAG

Building Applications with Vector Databases

下面是这门课的学习笔记:https://www.deeplearning.ai/short-courses/building-applications-vector-databases/

Learn to create six exciting applications of vector databases and implement them using Pinecone.

Build a hybrid search app that combines both text and images for improved multimodal search results.

Learn how to build an app that measures and ranks facial similarity.

文章目录

  • Building Applications with Vector Databases
  • Lesson 2 - Retrieval Augmented Generation (RAG)
      • Import the Needed Packages
      • Setup Pinecone
      • Load the Dataset
      • Prepare the Embeddings and Upsert to Pinecone
      • Connect to OpenAI
      • Run Your Query
      • Build the Prompt
      • Get the Summary

Lesson 2 - Retrieval Augmented Generation (RAG)

使用Pinecone(将维基百科的文档添加到向量库中)和OpenAI的API(gpt-3.5-turbo-instruct)来进行检索增强,生成更好的答案。

在这里插入图片描述

Import the Needed Packages

import warnings
warnings.filterwarnings('ignore')
from datasets import load_dataset
from openai import OpenAI
from pinecone import Pinecone, ServerlessSpec # 用于指定索引部署的服务器规格
from tqdm.auto import tqdm
from DLAIUtils import Utilsimport ast
import os
import pandas as pd

get api key, 这是deeplearning.ai封装好的函数utils

# get api key
utils = Utils()
PINECONE_API_KEY = utils.get_pinecone_api_key()

Setup Pinecone

pinecone = Pinecone(api_key=PINECONE_API_KEY)utils = Utils()
INDEX_NAME = utils.create_dlai_index_name('dl-ai')
if INDEX_NAME in [index.name for index in pinecone.list_indexes()]:pinecone.delete_index(INDEX_NAME)pinecone.create_index(name=INDEX_NAME, dimension=1536, metric='cosine',spec=ServerlessSpec(cloud='aws', region='us-west-2'))index = pinecone.Index(INDEX_NAME)

Load the Dataset

(Note: max_articles_num = 500): To achieve a more comprehensive context for the Language Learning Model, a larger number of articles is generally more beneficial. In this lab, we've initially set max_articles_num to 500 for speedier results, allowing you to observe the outcomes faster. Once you've done an initial run, consider increasing this value to 750 or 1,000. You'll likely notice that the context provided to the LLM becomes richer and better. You can experiment by gradually raising this variable for different queries to observe the improvements in the LLM's contextual understanding.

max_articles_num = 500
df = pd.read_csv('./data/wiki.csv', nrows=max_articles_num)
df.head()

Output

在这里插入图片描述

Prepare the Embeddings and Upsert to Pinecone

prepped = []for i, row in tqdm(df.iterrows(), total=df.shape[0]):meta = ast.literal_eval(row['metadata']) # 转换为 Python 对象prepped.append({'id':row['id'], 'values':ast.literal_eval(row['values']), 'metadata':meta})  # 字典if len(prepped) >= 250:index.upsert(prepped) # 插入到pinecone索引中prepped = []

这段代码的作用是将 DataFrame (df) 中的数据批量预处理,并将预处理后的数据插入到 Pinecone 索引中。让我们逐行解释代码:

  1. prepped = []: 创建一个空列表 prepped,用于存储预处理后的数据。

  2. for i, row in tqdm(df.iterrows(), total=df.shape[0]):: 使用 iterrows() 方法遍历 DataFrame (df) 中的每一行数据,并使用 tqdm() 函数创建一个进度条来显示处理进度。total=df.shape[0] 用于指定总共要处理的行数。

  3. meta = ast.literal_eval(row['metadata']): 从当前行中获取 ‘metadata’ 列的值,并使用 ast.literal_eval() 函数将其转换为 Python 对象。这个列通常包含一些元数据信息。

  4. prepped.append({'id':row['id'], 'values':ast.literal_eval(row['values']), 'metadata':meta}): 将当前行的 ‘id’、‘values’ 和 ‘metadata’ 列的值以字典形式添加到 prepped 列表中。ast.literal_eval() 函数用于安全地将字符串形式的 Python 表达式转换为对应的对象。

  5. if len(prepped) >= 250:: 检查 prepped 列表的长度是否达到了 250。如果达到了,则执行下面的操作。

  6. index.upsert(prepped): 将 prepped 列表中的数据批量插入到 Pinecone 索引中。upsert() 方法用于向索引中添加或更新数据。

  7. prepped = []: 将 prepped 列表重置为空,以便存储下一个批次的预处理数据。

总的来说,这段代码对 DataFrame 中的数据进行了逐行处理,将每一行数据转换成包含 ‘id’、‘values’ 和 ‘metadata’ 字段的字典,然后将这些字典组成的列表批量插入到 Pinecone 索引中。

index.describe_index_stats()

Output

{'dimension': 1536,'index_fullness': 0.0,'namespaces': {'': {'vector_count': 500}},'total_vector_count': 500}

Connect to OpenAI

OPENAI_API_KEY = utils.get_openai_api_key() # 具体函数实现见笔记1
openai_client = OpenAI(api_key=OPENAI_API_KEY)def get_embeddings(articles, model="text-embedding-ada-002"):return openai_client.embeddings.create(input = articles, model=model)

Run Your Query

query = "what is the berlin wall?"embed = get_embeddings([query])
res = index.query(vector=embed.data[0].embedding, top_k=3, include_metadata=True)
text = [r['metadata']['text'] for r in res['matches']]
print('\n'.join(text))

对上文text = [r['metadata']['text'] for r in res['matches']]中r的解释:

在上述代码中,r 表示查询结果中的每个匹配项。让我们用一个示例来说明其作用。

假设我们有一个文本嵌入索引,其中包含了一些城市的文本描述以及对应的嵌入向量。当我们对这个索引进行查询时,我们得到了一些与查询向量最相似的匹配项。

例如,假设我们的索引中有以下一些匹配项:

[{'vector': [0.1, 0.2, 0.3], 'metadata': {'city': 'Berlin', 'text': 'Berlin is the capital of Germany.'}},{'vector': [0.2, 0.3, 0.4], 'metadata': {'city': 'Paris', 'text': 'Paris is the capital of France.'}},{'vector': [0.3, 0.4, 0.5], 'metadata': {'city': 'London', 'text': 'London is the capital of the United Kingdom.'}}]

在这个例子中,r 表示查询结果中的每个匹配项。每个匹配项都是一个字典,包含了向量 (vector) 和元数据 (metadata) 两个键。metadata 中包含了与匹配项相关的元数据信息,比如城市名称和文本描述。

如果我们想要提取每个匹配项的文本描述,我们可以通过访问 r['metadata']['text'] 来获取,这样就能得到每个匹配项的文本描述。

Output

Egon Krenz was elected by the politburo to be Honecker's successor. Krenz tried to show that he was looking for change within the GDR but the citizens did not trust him. On November 9, 1989, the SED announced that East Germans would be able to travel to West Berlin the next day. The spokesman who announced the new travel law incorrectly said that it would take effect immediately, implying the Berlin Wall would open that night. People began to gather at border checkpoints at the wall hoping to be let through, but the guards told them that they had no orders to let citizens through. As the number of people grew, the guards became alarmed and tried to contact their superiors but had no responses. Unwilling to use force, the chief guard at the checkpoint relented at 10:54pm and ordered the gate to be opened. Thousands of East-Germans swarmed into West Berlin and the purpose of the wall was deemed now obsolete. The fall of the wall destroyed the SED politically as well as the career of its leader, Egon Krenz. On December 1, 1989, the GDR government revoked the law that guaranteed the SED the right to rule the East German political system, effectively ending communist rule in the GDR.On 18 March 1990, there were free elections in the GDR. The "Alliance for Germany", a group of political parties who wanted to unify the GDR with West Germany, won that election. This process, when East Germany was taken over by the West, is known also the Wende in Germany.
Berlin (; ) is the capital city of Germany. It is the largest city in the European Union by population, with around 3.7 million people in 2020. Berlin residents come from about 190 different countries.The city is in the eastern part of Germany in Central Europe and is surrounded by many forests and lakes. Berlin has an area of . The rivers Havel, Dahme and Spree run through Berlin. It has a temperate climate.Berlin is home to many famous buildings and monuments, like the Siegessäule, the Brandenburger Tor, the Reichstag and the boulevard Unter den Linden. On the boulevard is the Humboldt University. The city has many nightlife options.Berlin is an important city for the history of Germany. The King of Prussia and the Emperor of Germany lived in Berlin. The government of Germany was in Berlin for many years. Bombs destroyed many buildings in the city in World War Two. The city was split into West Berlin and East Berlin after World War Two. After the Berlin Wall was built in 1961 very few people were allowed to cross from East Berlin into West Berlin. The wall divided the city until 1989 when the East German government decided to allow anyone to cross, and people decided to tear down the wall.Berlin is a world city of culture, start ups, politics, media and science. There are a lot of technology companies in the city. They are important for the city's economy. Many planes and trains travel to and from Berlin because the city is an important place for tourism and business.
The German Democratic Republic (GDR) ( (DDR)), commonly called East Germany (), was founded on 7 October 1949, after World War II. It was formed from part of the Soviet occupation zone of Germany, including part of the city of Berlin. It is no longer a nation by itself since the two parts of Germany, East Germany and West Germany, reunified in 1990.The GDR was ruled by the Socialist Unity Party of Germany (SED).History 
After World War II, the four Allied Occupation Zones in Germany were each controlled by a different country. The countries that controlled these parts of Germany were France, the United Kingdom, the United States, and the Soviet Union. The French, American, and British parts of Germany formed West Germany (the Bundesrepublik). Part of the Soviet section became East Germany, and other parts became western Poland and small parts of other countries.Walter Ulbricht, the head of the SED, also had a lot of power. Pieck died in 1960, and Ulbricht became "Chairman of the State Council". Now he was really the head of state.On 13 August 1961, the Berlin Wall was built.  Many people were shot dead by East German soldiers when they tried to escape the GDR.  According to the SED this was to make it hard for American spies to use West Berlin as a place to work from, but it also made it hard for normal people to move between east and west.
History 1244 The first writings about a place called Berlin.1451 The Hohenzollern family moved to Berlin as the place to rule their country161848 After the Thirty Years' War in Germany, the number of people that lived in Berlin dropped to only 6000.1701 Berlin became capital of Prussia.1709 Berlin and its neighbor city Cölln (not Köln/Cologne) are combined to form the new Berlin.1806 The army of Napoleon Bonaparte moved into Berlin.1871 Berlin became capital of the German Empire.1920 The Old Berlin and some neighbour towns are combined into "Greater Berlin" (Groß-Berlin).1945 The town is divided into four sectors, used by the allies of World War II. There is a Soviet Sector, an American Sector, a British Sector and a French Sector.1949 After foundation of the two Germanies, the town is still divided. There is now West Berlin and East Berlin.1961 The Berlin Wall was built by the communist government of East Germany between the two halves of Berlin.1990 After German reunification, the Berlin Wall is torn down, and there is only one Berlin again. The new Berlin becomes the capital of one Germany.2001 23 boroughs of Berlin were changed into 122006 FIFA World Cup Final held at OlympiastadionPeople In 2018, Berlin had 3.75 million registered inhabitants in an area of . The city's population density was 4,206 inhabitants per km2. Berlin is the most populous city in Germany an the European Union. The entire Berlin-Brandenburg capital region has a population of more than 6 million in an area of . More than 2.0 million households were counted in the city. Around 60 percent of them were single-person households.
Landmarks Alexanderplatz Berliner Dom (Berlin's cathedral)Berlin Hauptbahnhof (Main Railway station)Brandenburg GateEast Side Gallery (Former Berlin Wall)Fernsehturm (TV tower - the highest building in Germany)Potsdamer PlatzReichstag building (home of the Bundestag)Rotes Rathaus (office of the Governing Mayor)Siegessäule (Statue of Victory)Tiergarten (Central Park)Unter den Linden (Main boulevard)Cuisine The Berlin cuisine and culinary offerings vary greatly. 23 restaurants in Berlin have been awarded one or more Michelin stars in 2021, which ranks the city at the top for the number of restaurants in Germany. Many local foods originated from north German culinary traditions and include rustic and hearty dishes with pork, goose, fish, peas, beans, cucumbers, or potatoes. Typical Berliner fare include popular street food like the Currywurst Buletten (meat balls) and the Berliner doughnut, known in Berlin as . German bakeries offering a variety of breads and pastries are widespread. One of Europe's largest delicatessen market is found at the department store KaDeWe. Among the world's largest chocolate stores is Fassbender & Rausch.Berlin is also home to a diverse gastronomy scene reflecting the immigrant history of the city. Immigrants brought their culinary traditions to the city, such as the modern fast-food version of the doner kebab. Asian cuisine like Chinese, Vietnamese, Thai, Indian, Korean, and Japanese restaurants, as well as Spanish tapas bars, Italian, and Greek cuisine, can be found in many parts of the city.Economy
There are more than 20 communities with a population of at least 10,000 people in 2019, including German, Turkish, Polish, Syrian, Italian, Bulgarian, Russian, Lebanese, Palestinian, Serbian, Bosnian, Vietnamese, American, Romanian, Croatian, Chinese, Austrian, Ukrainian, French, British, Spanish, Israeli, Indian and Iranian communities.In 2019, there were 777,345 registered residents of foreign nationality and another 542,975 German citizens with a "migration background", meaning they or one of their parents immigrated to Germany after 1955. Berlin residents originate from about 190 different countries.GeographyBerlin is in northeastern Germany, in an area of low-lying marshy woodlands with a mainly flat terrain. It is part of the Northern European Plain. The river Spree and Havel are the two main rivers in the city. In Spandau, a borough in the west of Berlin, the Spree empties into the river Havel, which flows from north to south through western Berlin. The largest lakes being the Tegeler See, the Großer Wannsee and the Großer Müggelsee.The Arkenberge hills in Pankow at  elevation are the highest point in Berlin. The Müggelberge (mountains) at  elevation is the highest natural point and the lowest is the Spektesee in Spandau, at  elevation.Boroughs Charlottenburg-WilmersdorfFriedrichshain-KreuzbergLichtenberg-HohenschönhausenMarzahn-HellersdorfMitte (Central)NeuköllnPankowReinickendorfSpandauSteglitz-ZehlendorfTempelhof-SchönebergTreptow-KöpenickEducation
In the German reunification, the GDR joined West Germany by approving its constitution in 1990. The East German districts were reorganised into the Länder (Berlin, Brandenburg, Mecklenburg-Vorpommern, Sachsen, Sachsen-Anhalt and Thüringen) and joined West Germany, after which the GDR ceased to exist. Fidel Castro had long ago renamed the small Cuban island of Cayo Blanco del Sur and one of its beaches in honor of the GDR, though it remained part of Cuba.Even though the western and the eastern part joined back together in 1990, people from former West Germany still call people from East Germany "Ossi". This comes from the German word "Osten" which means "East". Ossi is not always meant kindly.After the reunification, many people became angry because the new government was from the west and didn't like East Germany. They closed down lots of the places people worked and tried to make it look like East Germany never existed. This made lots of people lose their jobs and become poor. Today lots of people who used to live in East Germany want it to come back. This is called "Ostalgie", which means "East nostalgia".
EconomyIn 2018, the GDP of Berlin totaled €147 billion. The city is the largest metropolitan economy in Germany and the third largest in the European Union. Berlin's economy is dominated by the service sector, with around 85% of all companies doing business in services. In 2019, the total labor force in Berlin was about 2.0 million. Important economic sectors in Berlin include life sciences, transportation, information and communication technologies, media and music, advertising and design, biotechnology, environmental services, construction, e-commerce, retail, hotel business, and medical engineering.Research and development are important for the city. Berlin is part of the Eurozone.Sister cities 
Berlin has partnerships with 17 cities. Each of the 12 boroughs also has their sister cities, sometimes called twin cities.ReferencesOther websites - Official page www.berlin.deBerlin Sightseeing ToursEXBERLINER - English City MagazineBerlin City Panoramas - Panoramic Views and virtual Tours of BerlinOlympic cities
EducationBerlin is one of the most renowned centers of higher education and research in Germany and the world. Historically, 57 Nobel Prize winners are affiliated with the Berlin-based universities.The city has four universities and more than 40 private, professional, and technical colleges in 2020. Around 200.000 students were enrolled in 2019. Among them around 20% have an international background.The three largest universities combined have approximately 110,000 students. There are the Free University of Berlin (Free University of Berlin, FU Berlin) with about 35,000 students, the Humboldt University of Berlin (HU Berlin) with 40,000 students, and the Technical University of Berlin (TU Berlin) with 35,000 students. The Charité Medical School has around 9,000 students. The Berlin University of the Arts (UdK) has about 4,000 students and the ESMT Berlin is a leading business schools in Germany. The Berlin School of Economics and Law (HWR) has an enrollment of about 11,000 students, the Berlin University of Applied Sciences and Technology (BHT) of about 12,000 students, and the Hochschule für Technik und Wirtschaft (University of Applied Sciences for Engineering and Economics, HTW) of about 14,000 students.Culture Berlin is famous for its numerous cultural institutions, many of which enjoy international reputation. It is a trendsetting city. Young people, creatives and entrepreneurs continue to settle in the city and make Berlin a popular entertainment center in the world.
August 13  1961: Building of the Berlin Wall begins.August 14  1945: Japan announces its surrender at the end of World War II.August 14/15  1947: India is partitioned at independence from the UK, as the new mainly Islamic state of Pakistan is created.August 15  1960: The Republic of the Congo becomes independent.August 15  1971: Bahrain becomes independent.August 16  1977: Elvis Presley dies aged 42, leading to a worldwide outpouring of grief.August 17  1945: Indonesia declares independence from the Netherlands.August 17  1960: Gabon becomes independent.August 17  1962: Peter Fechter becomes the first person to be shot dead at the Berlin Wall.August 19  43 BC: Augustus becomes Roman consul.August 19  14: Augustus dies.August 19  1919: Afghanistan becomes independent.August 19  1991: The August Coup against Mikhail Gorbachev, in the Soviet Union, begins.August 20  1940: Leon Trotsky is fatally wounded with an ice pick in Mexico.August 20  1968: The Prague Spring uprising is crushed.August 20  1991: Estonia regains its independence from the Soviet Union.August 21  1959: Hawaii becomes the 50th State of the US.August 24  79: Vesuvius erupts, destroying Pompeii and neighbouring Herculaneum.August 24  1991: Ukraine regains independence from the Soviet Union.August 25  1825: Uruguay declares independence from Brazil.

Build the Prompt

query = "write an article titled: what is the berlin wall?"
embed = get_embeddings([query])
res = index.query(vector=embed.data[0].embedding, top_k=3, include_metadata=True)contexts = [x['metadata']['text'] for x in res['matches']
]prompt_start = ("Answer the question based on the context below.\n\n"+"Context:\n"
)prompt_end = (f"\n\nQuestion: {query}\nAnswer:"
)prompt = (prompt_start + "\n\n---\n\n".join(contexts) + prompt_end
)print(prompt)

Output

Answer the question based on the context below.Context:
Egon Krenz was elected by the politburo to be Honecker's successor. Krenz tried to show that he was looking for change within the GDR but the citizens did not trust him. On November 9, 1989, the SED announced that East Germans would be able to travel to West Berlin the next day. The spokesman who announced the new travel law incorrectly said that it would take effect immediately, implying the Berlin Wall would open that night. People began to gather at border checkpoints at the wall hoping to be let through, but the guards told them that they had no orders to let citizens through. As the number of people grew, the guards became alarmed and tried to contact their superiors but had no responses. Unwilling to use force, the chief guard at the checkpoint relented at 10:54pm and ordered the gate to be opened. Thousands of East-Germans swarmed into West Berlin and the purpose of the wall was deemed now obsolete. The fall of the wall destroyed the SED politically as well as the career of its leader, Egon Krenz. On December 1, 1989, the GDR government revoked the law that guaranteed the SED the right to rule the East German political system, effectively ending communist rule in the GDR.On 18 March 1990, there were free elections in the GDR. The "Alliance for Germany", a group of political parties who wanted to unify the GDR with West Germany, won that election. This process, when East Germany was taken over by the West, is known also the Wende in Germany.---Berlin (; ) is the capital city of Germany. It is the largest city in the European Union by population, with around 3.7 million people in 2020. Berlin residents come from about 190 different countries.The city is in the eastern part of Germany in Central Europe and is surrounded by many forests and lakes. Berlin has an area of . The rivers Havel, Dahme and Spree run through Berlin. It has a temperate climate.Berlin is home to many famous buildings and monuments, like the Siegessäule, the Brandenburger Tor, the Reichstag and the boulevard Unter den Linden. On the boulevard is the Humboldt University. The city has many nightlife options.Berlin is an important city for the history of Germany. The King of Prussia and the Emperor of Germany lived in Berlin. The government of Germany was in Berlin for many years. Bombs destroyed many buildings in the city in World War Two. The city was split into West Berlin and East Berlin after World War Two. After the Berlin Wall was built in 1961 very few people were allowed to cross from East Berlin into West Berlin. The wall divided the city until 1989 when the East German government decided to allow anyone to cross, and people decided to tear down the wall.Berlin is a world city of culture, start ups, politics, media and science. There are a lot of technology companies in the city. They are important for the city's economy. Many planes and trains travel to and from Berlin because the city is an important place for tourism and business.---History 1244 The first writings about a place called Berlin.1451 The Hohenzollern family moved to Berlin as the place to rule their country161848 After the Thirty Years' War in Germany, the number of people that lived in Berlin dropped to only 6000.1701 Berlin became capital of Prussia.1709 Berlin and its neighbor city Cölln (not Köln/Cologne) are combined to form the new Berlin.1806 The army of Napoleon Bonaparte moved into Berlin.1871 Berlin became capital of the German Empire.1920 The Old Berlin and some neighbour towns are combined into "Greater Berlin" (Groß-Berlin).1945 The town is divided into four sectors, used by the allies of World War II. There is a Soviet Sector, an American Sector, a British Sector and a French Sector.1949 After foundation of the two Germanies, the town is still divided. There is now West Berlin and East Berlin.1961 The Berlin Wall was built by the communist government of East Germany between the two halves of Berlin.1990 After German reunification, the Berlin Wall is torn down, and there is only one Berlin again. The new Berlin becomes the capital of one Germany.2001 23 boroughs of Berlin were changed into 122006 FIFA World Cup Final held at OlympiastadionPeople In 2018, Berlin had 3.75 million registered inhabitants in an area of . The city's population density was 4,206 inhabitants per km2. Berlin is the most populous city in Germany an the European Union. The entire Berlin-Brandenburg capital region has a population of more than 6 million in an area of . More than 2.0 million households were counted in the city. Around 60 percent of them were single-person households.---The German Democratic Republic (GDR) ( (DDR)), commonly called East Germany (), was founded on 7 October 1949, after World War II. It was formed from part of the Soviet occupation zone of Germany, including part of the city of Berlin. It is no longer a nation by itself since the two parts of Germany, East Germany and West Germany, reunified in 1990.The GDR was ruled by the Socialist Unity Party of Germany (SED).History 
After World War II, the four Allied Occupation Zones in Germany were each controlled by a different country. The countries that controlled these parts of Germany were France, the United Kingdom, the United States, and the Soviet Union. The French, American, and British parts of Germany formed West Germany (the Bundesrepublik). Part of the Soviet section became East Germany, and other parts became western Poland and small parts of other countries.Walter Ulbricht, the head of the SED, also had a lot of power. Pieck died in 1960, and Ulbricht became "Chairman of the State Council". Now he was really the head of state.On 13 August 1961, the Berlin Wall was built.  Many people were shot dead by East German soldiers when they tried to escape the GDR.  According to the SED this was to make it hard for American spies to use West Berlin as a place to work from, but it also made it hard for normal people to move between east and west.---Landmarks Alexanderplatz Berliner Dom (Berlin's cathedral)Berlin Hauptbahnhof (Main Railway station)Brandenburg GateEast Side Gallery (Former Berlin Wall)Fernsehturm (TV tower - the highest building in Germany)Potsdamer PlatzReichstag building (home of the Bundestag)Rotes Rathaus (office of the Governing Mayor)Siegessäule (Statue of Victory)Tiergarten (Central Park)Unter den Linden (Main boulevard)Cuisine The Berlin cuisine and culinary offerings vary greatly. 23 restaurants in Berlin have been awarded one or more Michelin stars in 2021, which ranks the city at the top for the number of restaurants in Germany. Many local foods originated from north German culinary traditions and include rustic and hearty dishes with pork, goose, fish, peas, beans, cucumbers, or potatoes. Typical Berliner fare include popular street food like the Currywurst Buletten (meat balls) and the Berliner doughnut, known in Berlin as . German bakeries offering a variety of breads and pastries are widespread. One of Europe's largest delicatessen market is found at the department store KaDeWe. Among the world's largest chocolate stores is Fassbender & Rausch.Berlin is also home to a diverse gastronomy scene reflecting the immigrant history of the city. Immigrants brought their culinary traditions to the city, such as the modern fast-food version of the doner kebab. Asian cuisine like Chinese, Vietnamese, Thai, Indian, Korean, and Japanese restaurants, as well as Spanish tapas bars, Italian, and Greek cuisine, can be found in many parts of the city.Economy---August 13  1961: Building of the Berlin Wall begins.August 14  1945: Japan announces its surrender at the end of World War II.August 14/15  1947: India is partitioned at independence from the UK, as the new mainly Islamic state of Pakistan is created.August 15  1960: The Republic of the Congo becomes independent.August 15  1971: Bahrain becomes independent.August 16  1977: Elvis Presley dies aged 42, leading to a worldwide outpouring of grief.August 17  1945: Indonesia declares independence from the Netherlands.August 17  1960: Gabon becomes independent.August 17  1962: Peter Fechter becomes the first person to be shot dead at the Berlin Wall.August 19  43 BC: Augustus becomes Roman consul.August 19  14: Augustus dies.August 19  1919: Afghanistan becomes independent.August 19  1991: The August Coup against Mikhail Gorbachev, in the Soviet Union, begins.August 20  1940: Leon Trotsky is fatally wounded with an ice pick in Mexico.August 20  1968: The Prague Spring uprising is crushed.August 20  1991: Estonia regains its independence from the Soviet Union.August 21  1959: Hawaii becomes the 50th State of the US.August 24  79: Vesuvius erupts, destroying Pompeii and neighbouring Herculaneum.August 24  1991: Ukraine regains independence from the Soviet Union.August 25  1825: Uruguay declares independence from Brazil.---After Mikhail Gorbachev had started glasnost and perestroika in the Soviet Union, many people in the GDR wanted reforms, too. In 1989, there were lots of demonstrations against the SED and for McDonalds and Nike. In the city of Leipzig, people met every Monday and demonstrated, and so these demonstrations are called Montagsdemonstrationen ("Monday Demonstrations"). Erich Honecker wished that the Soviets would use its army to suppress these demonstrations.  The Soviet Union, with its own political and economical problems, refused and did not want to help Eastern Europe anymore.  Honecker was eventually forced to resign on October 18, 1989.---EconomyIn 2018, the GDP of Berlin totaled €147 billion. The city is the largest metropolitan economy in Germany and the third largest in the European Union. Berlin's economy is dominated by the service sector, with around 85% of all companies doing business in services. In 2019, the total labor force in Berlin was about 2.0 million. Important economic sectors in Berlin include life sciences, transportation, information and communication technologies, media and music, advertising and design, biotechnology, environmental services, construction, e-commerce, retail, hotel business, and medical engineering.Research and development are important for the city. Berlin is part of the Eurozone.Sister cities 
Berlin has partnerships with 17 cities. Each of the 12 boroughs also has their sister cities, sometimes called twin cities.ReferencesOther websites - Official page www.berlin.deBerlin Sightseeing ToursEXBERLINER - English City MagazineBerlin City Panoramas - Panoramic Views and virtual Tours of BerlinOlympic cities---There are more than 20 communities with a population of at least 10,000 people in 2019, including German, Turkish, Polish, Syrian, Italian, Bulgarian, Russian, Lebanese, Palestinian, Serbian, Bosnian, Vietnamese, American, Romanian, Croatian, Chinese, Austrian, Ukrainian, French, British, Spanish, Israeli, Indian and Iranian communities.In 2019, there were 777,345 registered residents of foreign nationality and another 542,975 German citizens with a "migration background", meaning they or one of their parents immigrated to Germany after 1955. Berlin residents originate from about 190 different countries.GeographyBerlin is in northeastern Germany, in an area of low-lying marshy woodlands with a mainly flat terrain. It is part of the Northern European Plain. The river Spree and Havel are the two main rivers in the city. In Spandau, a borough in the west of Berlin, the Spree empties into the river Havel, which flows from north to south through western Berlin. The largest lakes being the Tegeler See, the Großer Wannsee and the Großer Müggelsee.The Arkenberge hills in Pankow at  elevation are the highest point in Berlin. The Müggelberge (mountains) at  elevation is the highest natural point and the lowest is the Spektesee in Spandau, at  elevation.Boroughs Charlottenburg-WilmersdorfFriedrichshain-KreuzbergLichtenberg-HohenschönhausenMarzahn-HellersdorfMitte (Central)NeuköllnPankowReinickendorfSpandauSteglitz-ZehlendorfTempelhof-SchönebergTreptow-KöpenickEducation---EducationBerlin is one of the most renowned centers of higher education and research in Germany and the world. Historically, 57 Nobel Prize winners are affiliated with the Berlin-based universities.The city has four universities and more than 40 private, professional, and technical colleges in 2020. Around 200.000 students were enrolled in 2019. Among them around 20% have an international background.The three largest universities combined have approximately 110,000 students. There are the Free University of Berlin (Free University of Berlin, FU Berlin) with about 35,000 students, the Humboldt University of Berlin (HU Berlin) with 40,000 students, and the Technical University of Berlin (TU Berlin) with 35,000 students. The Charité Medical School has around 9,000 students. The Berlin University of the Arts (UdK) has about 4,000 students and the ESMT Berlin is a leading business schools in Germany. The Berlin School of Economics and Law (HWR) has an enrollment of about 11,000 students, the Berlin University of Applied Sciences and Technology (BHT) of about 12,000 students, and the Hochschule für Technik und Wirtschaft (University of Applied Sciences for Engineering and Economics, HTW) of about 14,000 students.Culture Berlin is famous for its numerous cultural institutions, many of which enjoy international reputation. It is a trendsetting city. Young people, creatives and entrepreneurs continue to settle in the city and make Berlin a popular entertainment center in the world.Question: write an article titled: what is the berlin wall?
Answer:

Get the Summary

res = openai_client.completions.create(model="gpt-3.5-turbo-instruct",prompt=prompt,temperature=0,max_tokens=636,top_p=1,frequency_penalty=0,presence_penalty=0,stop=None
)
print('-' * 80)
print(res.choices[0].text)

这段代码使用了 OpenAI API 客户端,向 GPT-3.5 Turbo Instruct 模型发出一个文本生成的请求,并获取生成的文本结果。

让我们逐行解释代码:

  1. res = openai_client.completions.create(...): 这一行代码通过 OpenAI API 客户端向 GPT-3.5 Turbo Instruct 模型发出一个文本生成请求。具体来说,它使用了 completions.create() 方法来创建一个文本完成任务。传递给这个方法的参数包括:

    • model="gpt-3.5-turbo-instruct":指定了要使用的模型,这里是 GPT-3.5 Turbo Instruct。
    • prompt=prompt:给定了一个提示文本,作为模型生成文本的起点。
    • temperature=0:设置了温度参数为 0,这将导致模型生成的文本更加确定性和精确。
    • max_tokens=636:限制了生成文本的最大长度为 636 个 token。
    • top_p=1:设置了 top-p 参数为 1,这表示模型在生成文本时将考虑所有概率大于等于给定阈值的 token。
    • frequency_penalty=0presence_penalty=0:设置了频率惩罚和存在性惩罚的值为 0,这意味着模型不会对 token 的频率和存在性进行惩罚。
    • stop=None:没有设置停止词,生成的文本将在达到最大长度后自动终止。
  2. print('-' * 80): 打印了一个由 ‘-’ 字符构成的分隔线,用于将不同的生成结果分隔开来。

  3. print(res.choices[0].text): 打印了生成文本的内容。res.choices[0].text 表示从 API 响应中获取第一个候选项的文本内容,并打印出来。

Output

--------------------------------------------------------------------------------The Berlin Wall was a physical barrier that divided the city of Berlin, Germany from 1961 to 1989. It was built by the communist government of East Germany, also known as the German Democratic Republic (GDR), to prevent its citizens from fleeing to the democratic West Germany. The wall was a symbol of the Cold War and the division between the communist and capitalist ideologies.The construction of the wall began on August 13, 1961, and it consisted of a concrete wall, barbed wire, and guard towers. The wall stretched for 96 miles, dividing the city into East and West Berlin. The East side was controlled by the Soviet Union and the West side by the United States, Great Britain, and France.The purpose of the wall was to prevent East Germans from escaping to the West, where they could enjoy more freedom and a better standard of living. The GDR government claimed that the wall was built to protect its citizens from Western imperialism and fascism. However, the real reason was to stop the mass exodus of skilled workers and professionals, which was causing economic problems for the GDR.The wall was heavily guarded, and anyone caught trying to escape faced severe consequences, including imprisonment or even death. Despite the risks, many East Germans attempted to cross the wall, and over 5,000 people were successful in doing so. However, over 100 people lost their lives while trying to escape.The fall of the Berlin Wall on November 9, 1989, marked the end of the Cold War and the beginning of German reunification. The announcement of new travel laws by the East German government led to a misunderstanding, and thousands of East Germans gathered at the wall, demanding to be let through. The guards, overwhelmed by the crowd, eventually opened the gates, and people from both sides of the wall celebrated together.The fall of the wall was a significant event in history, symbolizing the end of communist rule in Eastern Europe and the reunification of Germany. Today, only a few sections of the wall remain as a reminder of the division that once existed in Berlin. The Berlin Wall serves as a powerful reminder of the consequences of political division and the importance of freedom and unity.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/698414.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Vue单文件学习项目综合案例Demo,黑马vue教程

文章目录 前言一、小黑记事本二、购物车三、小黑记账清单 前言 bilibili视频地址 一、小黑记事本 效果图 主代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"/><meta http-equiv"X-UA-Compatible&…

Open CASCADE学习|绘制砂轮

今天绘制一个砂轮&#xff0c;其轮廓由两条直线段和两段圆弧构成&#xff0c;圆弧分别与直线相切&#xff0c;两条圆弧之间相交而非相切。建模思路是&#xff1a;先给定两条直线段的起始点及长度&#xff0c;画出直线段&#xff0c;然后给定其中一圆弧的半径及圆心角&#xff0…

4核8G服务器能承受多少并发?

腾讯云4核8G服务器能承受多少并发&#xff1f;阿腾云的4核8G服务器可以支持20个访客同时访问&#xff0c;关于4核8G服务器承载量并发数qps计算测评&#xff0c;云服务器上运行程序效率不同支持人数在线人数不同&#xff0c;公网带宽也是影响4核8G服务器并发数的一大因素&#x…

Nginx网络服务

一、Nginx概述 1.1Nginx介绍 Nginx&#xff1a; 一款高新能、轻量级Web服务软件稳定性高系统资源消耗低对HTTP并发连接的处理能力高单台物理服务器可支持30 000&#xff5e;50 000个并发请求。 Nginx 是开源、高性能、高可靠的 Web 和反向代理服务器&#xff0c;而且支持热部…

【LeetCode: 889. 根据前序和后序遍历构造二叉树 + DFS】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

使用Lombok @Data 出现java: 找不到符号 的问题

第一种&#xff1a;pom依赖最好如下方式 <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>RELEASE</version><scope>compile</scope> </dependency>第二种&#xff1…

【Azure 架构师学习笔记】- Azure Databricks (10) -- UC 使用

本文属于【Azure 架构师学习笔记】系列。 本文属于【Azure Databricks】系列。 接上文 【Azure 架构师学习笔记】- Azure Databricks (9) – UC权限 在前面的文章&#xff1a;【Azure 架构师学习笔记】- Azure Databricks (6) - 配置Unity Catalog中演示了如何配置一个UC。 本文…

UE5 骨骼重定向

1.通过 VRoidStudio 1.26.0 软件创建模型 导出 2.下载ue插件 https://github.com/ruyo/VRM4U/releases 安装 重启 3.拖入创建的模型 到指定文件夹 4.为模型创建 IK绑定&#xff0c;重定向骨骼根 新增链条 5.创建IK 重定向&#xff0c;指定源 和 目标 IK绑定 6.

基于MPPT最大功率跟踪算法的涡轮机控制系统simulink建模与仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序与模型 4.系统原理简介 5.完整工程文件 1.课题概述 基于MPPT最大功率跟踪算法的涡轮机控制系统simulink建模与仿真.mppt采用爬山法实现&#xff0c;仿真输出MPPT控制效果&#xff0c;功率&#xff0c;转速等。 2.系统仿真结果 …

Thymeleaf无法显示模板视图,加载页面显示404状态问题的解决方法

本篇文章主要讲解&#xff1a;Thymeleaf无法显示模板视图&#xff0c;加载页面显示404状态问题的解决方法 日期&#xff1a;2024年2月23日 作者&#xff1a;任聪聪 现象说明&#xff1a; 1.只返回输出模板的名称&#xff0c;如图&#xff1a; 2.显示报错信息&#xff1a; Whi…

C#WinForm窗体TableLayout控件布局

Winform界面TablLayout是常用的控件之一 可以实现界面任意位置布局&#xff0c;在表格中添加其他控件默认只能占用一个单元格&#xff0c;如果想跨任意数量行列需要使用两个函数设置&#xff0c;下面举例 新建Tab表 设置插入按钮布局 // // button1 // this.tableLayoutPanel…

第三百六十三回

文章目录 1. 概念介绍2. 实现方法2.1 环绕效果2.2 立体效果 3. 示例代码4. 内容总结 我们在上一章回中介绍了"自定义SlideImageSwitch组件"相关的内容&#xff0c;本章回中将介绍两种阴影效果.闲话休提&#xff0c;让我们一起Talk Flutter吧。 1. 概念介绍 我们在本…

Python作图

图效果 import numpy as np import matplotlib.pyplot as plt# 定义函数 def sigmoid(x):return 1 / (1 np.exp(-x))def tanh(x):return np.tanh(x)def relu(x):return np.maximum(0, x)def leaky_relu(x, alpha0.01):return np.where(x > 0, x, alpha*x)# 生成数据 x np…

Android Jetpack Compose 沉浸式状态栏的实现

目录 概述效果展示代码实现总结 概述 说到沉浸式状态栏&#xff0c;很多小伙伴可能不太熟悉&#xff0c;其实让Android的状态栏的颜色和APP的主题颜色相同&#xff0c;给人感觉状态栏和APP就是一体的。沉浸式的状态栏让页面看起来更舒服&#xff0c;实现沉浸式状态栏也很简单&…

Zookeeper未授权访问漏洞

Zookeeper漏洞介绍 Zookeeper支持某些特定的四字查询命令&#xff0c;可以未授权访问&#xff0c;从而泄露zookeeper服务的相关信息&#xff0c;这些信息可能作为进一步入侵其他系统和服务的跳板&#xff0c;利用这些信息实现权限提升并逐渐扩大攻击范围。 常见的四字命令有 e…

MyBatisPlus条件构造器和常用接口

前置配置文章 一、wapper介绍 wrapper的继承体系&#xff1a; Wrapper &#xff1a; 条件构造抽象类&#xff0c;最顶端父类 AbstractWrapper &#xff1a; 用于查询条件封装&#xff0c;生成 sql 的 where 条件 QueryWrapper &#xff1a; 查询条件封装UpdateWrapper &#x…

【Pytorch深度学习开发实践学习】B站刘二大人课程笔记整理lecture06 Logistic回归

【Pytorch深度学习开发实践学习】B站刘二大人课程笔记整理lecture06 Logistic回归 课程网址 Pytorch深度学习实践 部分课件内容&#xff1a; import torchx_data torch.tensor([[1.0],[2.0],[3.0]]) y_data torch.tensor([[0.0],[0.0],[1.0]])class LogisticRegressionModel(…

2.22 Qt day3 多界面跳转+qss登录界面优化+发布软件+对话框

思维导图&#xff1a; 完善对话框&#xff0c;点击登录对话框&#xff0c;如果账号和密码匹配&#xff0c;则弹出信息对话框&#xff0c;给出提示”登录成功“&#xff0c;提供一个Ok按钮&#xff0c;用户点击Ok后&#xff0c;关闭登录界面&#xff0c;跳转到其他界面 如果账号…

Linux系统运维:离线安装sar-性能监视和分析工具

目 录 一、前言 二、系统环境 三、安装sar &#xff08;一&#xff09;准备工作 1、下载 sar 工具的安装包&#xff1a; 2、将安装包传输到 CentOS 服务器 &#xff08;二&#xff09;安装工作 1、解压 2、配置安装 3、编译 4、安装 &#xff08;三&#xff0…

产品渲染3D效果图一张多少钱,哪个平台更有性价比?

产品渲染3D效果图的价格受到多方面因素的影响&#xff0c;包括但不限于产品类型、渲染难度以及输出尺寸等。如果效果图需要后期处理&#xff0c;还有可能增加其他费用。接下来&#xff0c;我们来了解一下产品渲染效果图的费用情况。 1.产品渲染3D效果图一张多少钱&#xff1f; …