imtoken最新版官网|chains

作者: imtoken最新版官网
2024-03-09 22:19:15

chains是什么意思_chains的翻译_音标_读音_用法_例句_爱词霸在线词典

ns是什么意思_chains的翻译_音标_读音_用法_例句_爱词霸在线词典首页翻译背单词写作校对词霸下载用户反馈专栏平台登录chains是什么意思_chains用英语怎么说_chains的翻译_chains翻译成_chains的中文意思_chains怎么读,chains的读音,chains的用法,chains的例句翻译人工翻译试试人工翻译翻译全文简明柯林斯牛津chains高中英 [tʃeɪnz]美 [tʃeɪnz]释义n.链( chain的名词复数 ); 连串; 连锁店或旅馆; 一系列的事物点击 人工翻译,了解更多 人工释义实用场景例句全部He liked to shock with his gold chains and loud clothes.他喜欢戴金链子,穿花里胡哨的衣服来招人反感。柯林斯例句The chains were at different heights on the wall.挂在墙上的链子高低不齐。柯林斯例句Supermarket chains have shaved prices.超市连锁店已经稍稍降价。柯林斯例句Deep - sea valleys are the counterparts of the mountain chains.深海里的峡谷相当于陆地上的山脉.《简明英汉词典》Mayors wear chains round their necks as badges of office.市长们戴着象征职位的项链.《简明英汉词典》The captives are wearing chains.俘虏们带着镣铐.《简明英汉词典》The prisoner's ankle chains clanked as they walked.犯人走路时脚镣叮当作响.《现代英汉综合大词典》The prisoners are in chains.囚犯上了镣铐.《现代英汉综合大词典》The dogs were leaping and growling at the full stretch of their chains.那些狗又蹦又叫,把链子绷得紧紧的。柯林斯例句All the wheels of the truck were tied up with iron chains to avoid skidding on the ice road.大卡车的所有轮子上都捆上了铁链,以防止在结冰的路面上打滑.《用法词典》 She saw the earrings, the bracelets, the pins, the chains.在珠宝柜台,她又久久逗留,欣赏着那些耳环, 手镯, 饰针和金链条.英汉文学 - 嘉莉妹妹Mad guard dogs slavered at the end of their chains.拴在链子上的看门狗狂躁地流着口水。辞典例句Proteins are complex macromolecules made up of one of more polypeptide chains.蛋白质是复杂的大分子,由一条或几条多肽链组成.辞典例句Polymers consist of long molecular chains of covalently bonded atoms.高聚物都是由共价链联接原子而形成的长链分子所组成.辞典例句In a tableau, she once represented " Poland Breaking Her Chains. "但在一次舞台造型中, 她扮演 “ 挣脱了锁链的波兰 ”.辞典例句收起实用场景例句真题例句全部四级六级考研And McDonald's wasn't alone in slowing down: Other chains also saw their drive-through performance slow down.2018年6月四级真题(第一套)听力 Section ABig fast food chains in New York city have started to obey a first-of-its-kind rule requiring them to post calorie counts right on the menu.2016年6月四级真题(第一套)听力 Section ASpeed, of course, is essential to the drive-through experience, and drive-throughs are hugely important to chains such as McDonald's, Burger king and Taco Bell.2018年6月四级真题(第一套)听力 Section AStarting last Saturday, chains big enough to fall under the rule will face penalties of up to 2, 000 dollars for not showing calorie information in a prominent spot on their menus, preferably next to the price.2016年6月四级真题(第一套)听力 Section AThe microwave and fast-food chains were the biggest catalysts, but the big food companies—which want to sell anything except the raw ingredients that go into cooking—made the home cook an endangered species.2015年12月四级真题(第三套)阅读 Section BIced coffees sold by some popular chains are contaminated.出自-2010年12月听力原文The World Cancer Research Fund (WCRF) conducted a survey of iced coffees sold by some popular chains in Britain including Starbucks, Caffe Nero and Costa Coffee to gauge the calories as studies increasingly link obesity with cancer出自-2010年12月听力原文As stories go through the chains of people, they are refined, corrected and sorted out until they come finally to me and I have a chance to read through most stories before I go on the air.2015年12月六级真题(第一套)听力 Section AMost large supermarket chains have cured ham in little packets.2018年6月六级真题(第二套)听力 Section AThese examples are just the tip of the iceberg, but they demonstrate how helping customers get more use of their materials can transform value chains and operations.2019年6月六级真题(第二套)阅读 Section BBig chains have been collecting sales tax nationwide because they typically have physical stores in whatever state a purchase is being shipped to.2020年考研真题(英语一)翻译 Section ⅢFast-food chains should also stop offering "inducements" such as toys, cute animals and mobile phone credit to lure young customers, Stephenson said.2011年考研真题(英语二)阅读理解 Section ⅡThe ruling is a victory for big chains with a presence in many states, since they usually collect sales tax on online purchases already.2020年考研真题(英语一)翻译 Section ⅢThen there's the fact that large American companies are much more globalized than ever before, with supply chains spread across a larger number of countries.2020年考研真题(英语二)阅读理解 Section Ⅱ收起真题例句英英释义Noun1. metal shackles; for hands or legs收起英英释义行业词典法律镣铐   释义实用场景例句真题例句英英释义行

chain是什么意思_chain的翻译_音标_读音_用法_例句_爱词霸在线词典

n是什么意思_chain的翻译_音标_读音_用法_例句_爱词霸在线词典首页翻译背单词写作校对词霸下载用户反馈专栏平台登录chain是什么意思_chain用英语怎么说_chain的翻译_chain翻译成_chain的中文意思_chain怎么读,chain的读音,chain的用法,chain的例句翻译人工翻译试试人工翻译翻译全文简明柯林斯牛津chain高中/CET4/CET6英 [tʃeɪn]美 [tʃeɪn]释义常用高考讲解n.链条; 手铐; 约束; 一连串; 连锁店v.拴住,束缚大小写变形:ChainCHAIN点击 人工翻译,了解更多 人工释义词态变化复数: chains;第三人称单数: chains;过去式: chained;过去分词: chained;现在分词: chaining;实用场景例句全部链子链条连锁连续束缚(figurative)I've been chained to my desk all week (= because there was so much work) .我整个星期都在伏案工作,脱不开身。牛津词典The doors were always locked and chained.那些门总是上着锁链。牛津词典She chained her bicycle to the gate.她用链子把自行车锁在大门上。牛津词典The dog was chained up for the night.夜间那条狗用链子拴起来。牛津词典a chain of command (= a system in an organization by which instructions are passed from one person to another)指挥系统牛津词典mountain/island chains山脉;岛群牛津词典Volunteers formed a human chain to rescue precious items from the burning house.志愿者排成一条长龙,从着火的房子里手传手把贵重物品抢救出来。牛津词典a chain of supermarkets/a supermarket chain连锁超市牛津词典the chains of fear/misery恐惧的桎梏;苦难的枷锁牛津词典a short length of chain一截短链条牛津词典She wore a heavy gold chain around her neck.她戴着一条粗实的金项链。牛津词典The mayor wore his chain of office.市长佩戴着标志他职务的链徽。牛津词典a bicycle chain自行车链条牛津词典The prisoners were kept in chains (= with chains around their arms and legs, to prevent them from escaping) .囚犯戴着镣铐。牛津词典to set in motion a chain of events触发一连串的事件牛津词典Students tried to form a human chain around the parliament.学生们试图在议会四周围成人墙。柯林斯高阶英语词典...a large supermarket chain.大型连锁超市柯林斯高阶英语词典...Italy's leading chain of cinemas.意大利最大的连锁影院柯林斯高阶英语词典...the bizarre chain of events that led to his departure in January 1938.促使他于1938年1月离去的一连串离奇事件柯林斯高阶英语词典...a chain of islands known as the Windward Islands...名为“向风群岛”的岛群柯林斯高阶英语词典She chained her bike to the railings...她把自行车锁在栏杆上。柯林斯高阶英语词典His open shirt revealed a fat gold chain...他的衬衫敞着,露出一条很粗的金链。柯林斯高阶英语词典The dogs were leaping and growling at the full stretch of their chains.那些狗又蹦又叫,把链子绷得紧紧的。柯林斯高阶英语词典He'd spent four and a half years in windowless cells, much of the time in chains.他已经在没有窗户的牢房里呆了4年半,多数时间都戴着镣铐。柯林斯高阶英语词典He had to break right now the chains of habit that bound him to the present.他必须现在就打破把他束缚在当前境况的习惯。柯林斯高阶英语词典The dog was chained to the leg of the one solid garden seat...狗被拴在公园一个固定座位的腿上。柯林斯高阶英语词典收起实用场景例句真题例句全部四级六级高考考研On the demand side, those trends include the ongoing addition of more than 70 million people a year, a growing number of people wanting to move up the food chain to consume -72- highly grain-intensive meat products, and the massive diversion ( ' , 转向) of U.S. grain to the production of bio-fuel.出自-2016年6月阅读原文In a multi-state study of assisted living , for instance, University of North Carolina researchers found that a host of variables—the facility's type, size or age; whether a chain owned it; how attractive the neighborhood was—had no significant relationship to how the residents fared in terms of illness, mental decline, hospitalizations or mortality.出自-2016年6月阅读原文Big fast food chains in New York City have started to obey a first-of-its-kind rule requiring them to post calorie counts right on the menu.出自-2016年6月听力原文The microwave and fast-food chains were the biggest catalysts ( ' , 催化剂 ), but the big food companies—which want to sell anything except the raw ingredients that go into cooking—made the home cook an endangered species.出自-2015年12月阅读原文But their beds were provided by private individuals, rather than a hotel chain出自-2013年12月阅读原文On the demand side, those trends include the ongoing addition of more than 70 million people a year, a growing number of people wanting to move up the food chain to consume highly grain-intensive meat products, and the massive diversion of U.S. grain to t2016年6月四级真题(第一套)阅读 Section BThat's the vision of a hotel chain that plans to send digital keys to guests' phones via an app instead of making them check in and get the traditional plastic swipe cards.2015年12月四级真题(第二套)听力 Section Acut the salary of senior executivesrelocate some of its chain storesadjust its promotion strategiesreduce the size of its staffTo experiment on its new business concept.出自-2017年6月阅读原文None of the chain's stores in the Washington metropolitan area are to be closed.出自-2017年6月阅读原文It's also pushing ahead in 2016 with an expansion of Bluemercury, the beauty chain it bought last year.出自-2017年6月阅读原文2% in November and December at stores open more than a year, a disappointing holiday season performance that capped a difficult year for a department store chain facing wideranging challenges.出自-2017年6月阅读原文In the year to August 2007, IKEA, a Swedish furniture chain, sold over one million kitchens worldwide.出自-2016年6月阅读原文In less-developed countries, such as those of sub-Saharan Africa and South-East Asia, wastage tends to occur primarily at the farmer-producer end of the supply chain.出自-2013年12月阅读原文They run chain stores in central London.出自-2011年12月听力原文Iced coffees sold by some popular chains are contaminated.出自-2010年12月听力原文The World Cancer Research Fund (WCRF) conducted a survey of iced coffees sold by some popular chains in Britain including Starbucks, Caffe Nero and Costa Coffee to gauge the calories as studies increasingly link obesity with cancer出自-2010年12月听力原文But after General mills bought Epic in 2016, Collins and Forrest suddenly had the resources they needed to expand their supply chain.2019年12月六级真题(第三套)阅读 Section BIn addition to supplying milk from their own 85-head herd, they began to help other farmers in the area convent from conventional to certified organic and grass-fed in order to enter the Maple Hill supply chain.2019年12月六级真题(第三套)阅读 Section BMacy's reported its sales plunged 5.2% in November and December at stores open more than a year, a disappointing holiday season performance that capped a difficult year for a department store chain facing wide—ranging challenges.2017年6月六级真题(第一套)阅读 Section COnce one person looks at their phone, other people feel compelled to do the same, starting a chain reaction.2017年12月六级真题(第一套)阅读 Section BPenguins, like other seabirds and marine mammals, occupy higher levels in the food chain and they are what we call bio-indicators of their ecosystems.2019年12月六级真题(第三套)阅读 Section CThe partnership benefits both sides by allowing unconventional partners for example, two companies from two different industries to work together on a specific aspect of the value chain, like, in this example, an engine firm with an accessory one.2019年6月六级真题(第二套)阅读 Section BWhen they started researching the supply chain, they learned that only 2-3% of all Bison is actually grass-fed.2019年12月六级真题(第三套)阅读 Section BAlthough the main attraction was the soup, Roze's chain shops also set a new standard for dining out.2018年高考英语江苏卷 阅读理解 阅读B 原文Demand comes mainly from two sources: independent mom-and-pop grocery stores which, unlike large retail chains, are too small to buy straight from producers, and food service operators that cater to consumers when they don’t eat at home.出自-2010年考研阅读原文The power and ambition of the giants of the digital economy is astonishing - Amazon has just announced the purchase of the upmarket grocery chain Whole Foods for $13.5 billion, but two years ago Facebook paid even more than that to acquire the WhatsApp me2018年考研真题(英语二)阅读理解 Section Ⅱ收起真题例句英英释义Noun1. a series of things depending on each other as if linked together;"the chain of command""a complicated concatenation of circumstances"2. (chemistry) a series of linked atoms (generally in an organic molecule)3. a series of (usually metal) rings or links fitted into one another to make a flexible ligament4. a number of similar establishments (stores or restaurants or banks or hotels or theaters) under one ownership5. anything that acts as a restraint6. a unit of length7. a series of hills or mountains;"the valley was between two ranges of hills""the plains lay just beyond the mountain range"8. metal shackles; for hands or legs9. a necklace made by a stringing objects together;"a string of beads""a strand of pearls";Verb1. connect or arrange into a chain by linking2. fasten or secure with chains;"Chain the chairs together"收起英英释义词组搭配pull (或 yank) someone's chain(US informal)tease someone, typically by leading them to believe something untrue(美,非正式)戏弄,揶揄某人(尤指使其相信不实之事)收起词组搭配同义词辨析fasten, tie, bind, secure, chain这些动词都有"扎牢,捆,绑"之意。fasten: 指把某物牢牢地拴在、钉在或锁在另一物上,使不能任意移动。tie: 普通用词,指用绳索等将东西扎紧捆牢。bind: 多指把两个或两个以上的人或物牢牢地系或扎在一起。secure: 指将某物紧紧地固定起来,使之完全无损。chain: 专指用链条或金属环将某人或某物锁住或系住。同义词vt.用锁链拴住;束缚bindfastenrestrainshackle其他释义necklacethreadnetworkuniteseriesfetterconnectionleashqueueridgerope反义词cut行业词典医学链:一群物体呈线状相连,或端端相连,例如,化合物中原子或基团集合   单个细菌细胞的集合等   数学链   物理学链图   [graph]   航海科技台链   船舶台链   为了确定位置或提供导航信息工作在同一频率或同一基频的几个发射台构成的台组。   释义词态变化实用场景例句真题例句英英释义词组搭配同义词辨析同义词反义词行

CHAIN中文(繁體)翻譯:劍橋詞典

CHAIN中文(繁體)翻譯:劍橋詞典

詞典

翻譯

文法

同義詞詞典

+Plus

劍橋詞典+Plus

Shop

劍橋詞典+Plus

我的主頁

+Plus 幫助

退出

劍橋詞典+Plus

我的主頁

+Plus 幫助

退出

登錄

/

註冊

正體中文 (繁體)

查找

查找

英語-中文(繁體)

chain 在英語-中文(繁體)詞典中的翻譯

chainnoun uk

Your browser doesn't support HTML5 audio

/tʃeɪn/ us

Your browser doesn't support HTML5 audio

/tʃeɪn/

chain noun

(CONNECTED THINGS)

Add to word list

Add to word list

B2 [ C ] a set of connected or related things

一連串,一系列(的事物)

She has built up a chain of 180 bookshops across the country.

她在全國各地開了180家連鎖書店。

His resignation was followed by a remarkable chain of events.

在他辭職之後,發生了一系列引人注目的事件。

更多範例减少例句The supermarket chain announced that it was cutting the cost of all its fresh and frozen meat.Jonson has run the gamut of hotel work, from porter to owner of a large chain of hotels.The Rockies are a mountain chain in the western USA.As part of the centenary celebrations a chain of beacons was lit across the region.They are not only the world's biggest fast-food chain, but also the industry's trendsetter.

chain noun

(RINGS)

A2 [ C or U ] (a length of) rings usually made of metal that are connected together and used for fastening, pulling, supporting, or limiting freedom, or as jewellery

鏈條,鏈子;鎖鏈;項鍊

The gates were locked with a padlock and a heavy steel chain.

大門被一把掛鎖和一根沉重的鋼鏈鎖著。

Put the chain on the door if you are alone in the house.

你要是一個人在家就把鏈子鉤在門上。

Mary was wearing a beautiful silver chain around her neck.

瑪麗脖子上戴著一條漂亮的銀項鍊。

 in chains

tied with chains

戴著鎖鏈;用鏈條拴著

The hostages were kept in chains for 23 hours a day.

人質一天裡有23小時戴著鐐銬。

[ plural ] a fact or situation that limits a person's freedom

枷鎖,束縛,桎梏

At last the country has freed itself from the chains of the authoritarian regime.

這個國家最終從獨裁政權的束縛中解放了出來。

chain noun

(HOUSE SALE)

[ C ] UK a situation in which someone selling a house cannot complete the sale because the person who wants to buy it needs to sell their house first

售屋鏈(指賣家無法售出房屋,原因是買家尚未售出自己的房屋)

Some sellers refuse to exchange contracts with buyers who are in a chain.

有些賣家拒絕和售屋鏈裡的買家成交。

chainverb [ T usually + adv/prep ] uk

Your browser doesn't support HTML5 audio

/tʃeɪn/ us

Your browser doesn't support HTML5 audio

/tʃeɪn/

to fasten someone or something using a chain

用鏈條鎖住,拴住;束縛

It's so cruel to keep a pony chained up like that all the time.

把一匹小馬一直那樣拴著真是太殘忍了。

They chained themselves to lampposts in protest at the judge's decision.

為了抗議法官的判決,他們把自己拴在燈柱上。

figurative I don't want a job where I'm chained to a desk for eight hours a day.

我不想要一份一天八小時都被拴在辦公桌前的工作。

(chain在劍橋英語-中文(繁體)詞典的翻譯 © Cambridge University Press)

chain的例句

chain

Four of the kinematic chains have an identical topology.

來自 Cambridge English Corpus

To maximize the translational entropy of the polymer chains, the inaccessible volume between colloidal particles must be minimized.

來自 Cambridge English Corpus

To transform the sensor information to a human body configuration, we model the body into several open loop kinematic chains.

來自 Cambridge English Corpus

The two rule sets can be shown to denote the same chains.

來自 Cambridge English Corpus

In (15a) who satisfies the wh-criterion (which is now stated in terms of chains).

來自 Cambridge English Corpus

A similar argument gives the same phase differences dk between two adjacent chains.

來自 Cambridge English Corpus

Here the amplified beams of both chains are superposed automatically due to the optical properties of the phase conjugated signal.

來自 Cambridge English Corpus

To begin, first consider a situation in which two closed, circular strands or chains wind around each other in space.

來自 Cambridge English Corpus

示例中的觀點不代表劍橋詞典編輯、劍橋大學出版社和其許可證頒發者的觀點。

B2,A2

chain的翻譯

中文(簡體)

有联系的事, 一连串,一系列(的事物), 链条…

查看更多內容

西班牙語

cadena, encadenar, cadena [feminine]…

查看更多內容

葡萄牙語

série (de acontecimentos), cadeia, corrente…

查看更多內容

更多語言

in Marathi

日語

土耳其語

法語

加泰羅尼亞語

in Dutch

in Tamil

in Hindi

in Gujarati

丹麥語

in Swedish

馬來西亞語

德語

挪威語

in Urdu

in Ukrainian

俄語

in Telugu

阿拉伯語

in Bengali

捷克語

印尼語

泰語

越南語

波蘭語

韓語

意大利語

साखळी…

查看更多內容

鎖, チェーン, (レストラン、店の)チェーン…

查看更多內容

zincir, halka, mağazalar/lokantalar zinciri…

查看更多內容

chaîne [feminine], série [feminine], suite [feminine]…

查看更多內容

cadena, sèrie, encadenar…

查看更多內容

ketting, reeks, ketenen…

查看更多內容

இணைக்கப்பட்ட அல்லது தொடர்புடைய விஷயங்களின் தொகுப்பு, (ஒரு நீளம்) மோதிரங்கள் பொதுவாக உலோகத்தால் ஆனது, அவை ஒன்றாக இணைக்கப்பட்டு கட்டுதல்…

查看更多內容

श्रृंखला, सिलसिला, ज़ंजीर…

查看更多內容

ચેન, શ્રેણી, સિલસિલો…

查看更多內容

kæde, lænke, række…

查看更多內容

kedja, kätting, följd…

查看更多內容

rantai, rentetan, merantaikan…

查看更多內容

die Kette, anketten…

查看更多內容

lenke [masculine], kjetting [masculine], kjede [masculine]…

查看更多內容

لمبا سلسلہ, کسی بھی چیز کا وسیع دائرہ, متعلقہ واقعات کا سلسلہ…

查看更多內容

ланцюг, цеп, ланцюжок…

查看更多內容

цепь, сеть, прикреплять цепью…

查看更多內容

ముడివడి ఉన్న లేక పరస్పర సంబంధం ఉన్న వస్తువుల వర్గం/ శ్రేణి/వరుస, గొలుసు/సంకెల…

查看更多內容

سِلْسِلة, يُكَبّل, يُقَيّد…

查看更多內容

একই মালিকানায় একাধিক ব্যবসায়িক সংস্থা, শিকল, শৃঙ্খল…

查看更多內容

řetěz, řetízek, uvázat na řetěz…

查看更多內容

rantai, rangkaian, merantai…

查看更多內容

โซ่, เหตุการณ์ที่เกิดต่อเนื่องกัน, ล่ามโซ่…

查看更多內容

dây xích, chuỗi, xích lại…

查看更多內容

łańcuch, łańcuszek, sieć…

查看更多內容

체인, 사슬, 체인점…

查看更多內容

catena, incatenare, serie…

查看更多內容

需要一個翻譯器嗎?

獲得快速、免費的翻譯!

翻譯器工具

chain的發音是什麼?

在英語詞典中查看 chain 的釋義

瀏覽

Chagas disease

chagrin

chagrined

chai

chain

chain gang

chain letter

chain mail

chain of command

chain更多的中文(繁體)翻譯

全部

key chain

chain gang

chain mail

chain-smoke

chain store

choke chain

cold chain

查看全部意思»

「每日一詞」

flexitarian

A flexitarian way of eating consists mainly of vegetarian food but with some meat.

關於這個

部落格

Forget doing it or forget to do it? Avoiding common mistakes with verb patterns (2)

March 06, 2024

查看更多

新詞

stochastic parrot

March 04, 2024

查看更多

已添加至 list

回到頁面頂端

內容

英語-中文(繁體)例句翻譯

©劍橋大學出版社與評估2024

學習

學習

學習

新詞

幫助

紙本出版

Word of the Year 2021

Word of the Year 2022

Word of the Year 2023

開發

開發

開發

詞典API

連按兩下查看

搜尋Widgets

執照資料

關於

關於

關於

無障礙閱讀

劍橋英語教學

劍橋大學出版社與評估

授權管理

Cookies與隱私保護

語料庫

使用條款

京ICP备14002226号-2

©劍橋大學出版社與評估2024

劍橋詞典+Plus

我的主頁

+Plus 幫助

退出

詞典

定義

清晰解釋自然的書面和口頭英語

英語

學習詞典

基礎英式英語

基礎美式英語

翻譯

點選箭頭改變翻譯方向。

雙語詞典

英語-中文(簡體)

Chinese (Simplified)–English

英語-中文(繁體)

Chinese (Traditional)–English

英語-荷蘭文

荷蘭語-英語

英語-法語

法語-英語

英語-德語

德語-英語

英語-印尼語

印尼語-英語

英語-義大利語

義大利語-英語

英語-日語

日語-英語

英語-挪威語

挪威語-英語

英語-波蘭語

波蘭語-英語

英語-葡萄牙語

葡萄牙語-英語

英語-西班牙語

西班牙語-英語

English–Swedish

Swedish–English

半雙語詞典

英語-阿拉伯語

英語-孟加拉文

英語-加泰羅尼亞語

英語-捷克語

英語-丹麥語

English–Gujarati

英語-印地語

英語-韓語

英語-馬來語

英語-馬拉地語

英語-俄語

English–Tamil

English–Telugu

英語-泰語

英語-土耳其語

英語-烏克蘭文

English–Urdu

英語-越南語

翻譯

文法

同義詞詞典

Pronunciation

劍橋詞典+Plus

Shop

劍橋詞典+Plus

我的主頁

+Plus 幫助

退出

登錄 /

註冊

正體中文 (繁體)  

Change

English (UK)

English (US)

Español

Русский

Português

Deutsch

Français

Italiano

中文 (简体)

正體中文 (繁體)

Polski

한국어

Türkçe

日本語

Tiếng Việt

हिंदी

தமிழ்

తెలుగు

關注我們!

選擇一本詞典

最近的詞和建議

定義

清晰解釋自然的書面和口頭英語

英語

學習詞典

基礎英式英語

基礎美式英語

文法與同義詞詞典

對自然書面和口頭英語用法的解釋

英語文法

同義詞詞典

Pronunciation

British and American pronunciations with audio

English Pronunciation

翻譯

點選箭頭改變翻譯方向。

雙語詞典

英語-中文(簡體)

Chinese (Simplified)–English

英語-中文(繁體)

Chinese (Traditional)–English

英語-荷蘭文

荷蘭語-英語

英語-法語

法語-英語

英語-德語

德語-英語

英語-印尼語

印尼語-英語

英語-義大利語

義大利語-英語

英語-日語

日語-英語

英語-挪威語

挪威語-英語

英語-波蘭語

波蘭語-英語

英語-葡萄牙語

葡萄牙語-英語

英語-西班牙語

西班牙語-英語

English–Swedish

Swedish–English

半雙語詞典

英語-阿拉伯語

英語-孟加拉文

英語-加泰羅尼亞語

英語-捷克語

英語-丹麥語

English–Gujarati

英語-印地語

英語-韓語

英語-馬來語

英語-馬拉地語

英語-俄語

English–Tamil

English–Telugu

英語-泰語

英語-土耳其語

英語-烏克蘭文

English–Urdu

英語-越南語

詞典+Plus

詞彙表

選擇語言

正體中文 (繁體)  

English (UK)

English (US)

Español

Русский

Português

Deutsch

Français

Italiano

中文 (简体)

Polski

한국어

Türkçe

日本語

Tiếng Việt

हिंदी

தமிழ்

తెలుగు

內容

英語-中文(繁體) 

 

Noun 

chain (CONNECTED THINGS)

chain (RINGS)

in chains

chain (HOUSE SALE)

Verb

例句

Translations

文法

所有翻譯

我的詞彙表

把chain添加到下面的一個詞彙表中,或者創建一個新詞彙表。

更多詞彙表

前往詞彙表

對該例句有想法嗎?

例句中的單詞與輸入詞條不匹配。

該例句含有令人反感的內容。

取消

提交

例句中的單詞與輸入詞條不匹配。

該例句含有令人反感的內容。

取消

提交

从零开始认识langchain(四)组件-链(chains) - 知乎

从零开始认识langchain(四)组件-链(chains) - 知乎首发于langchain切换模式写文章登录/注册从零开始认识langchain(四)组件-链(chains)西西嘛呦​武汉理工大学 软件工程硕士西西嘛呦:从零开始认识langchain(一)初识langchain西西嘛呦:从零开始认识langchain(二)组件-数据连接(data connection)西西嘛呦:从零开始认识langchain(三)组件-模型IO(model I/O)Part1总体介绍对于简单的应用来说,孤立地使用LLM是没有问题的,但更复杂的应用需要将LLM串联起来--要么相互串联,要么与其他组件串联。LangChain为这种 "链式 "应用提供了Chain接口。我们非常笼统地将链定义为对组件的调用序列,其中可以包括其他链。基本接口很简单:class Chain(BaseModel, ABC):

"""Base interface that all chains should implement."""

memory: BaseMemory

callbacks: Callbacks

def __call__(

self,

inputs: Any,

return_only_outputs: bool = False,

callbacks: Callbacks = None,

) -> Dict[str, Any]:

...

这种将组件组成一个链的想法简单而强大。它极大地简化了复杂应用程序的实现,并使之更加模块化,这反过来又使调试、维护和改进你的应用程序变得更加容易。欲了解更多细节,请查看:如何使用不同的链功能的演练:https://python.langchain.com/docs/modules/chains/how_to/熟悉核心构件链的基础知识:https://python.langchain.com/docs/modules/chains/foundational/文档,了解如何将文档纳入链中:https://python.langchain.com/docs/modules/chains/document/最受欢迎的链,用于最常见的用例:https://python.langchain.com/docs/modules/chains/popular/额外的,可以看到一些更高级的链和集成,你可以使用开箱即用的链。:https://python.langchain.com/docs/modules/chains/additional/1为什么我们需要链链允许我们将多个组件结合在一起,创建一个单一的、连贯的应用程序。例如,我们可以创建一个链,接受用户输入,用PromptTemplate格式化,然后将格式化的响应传递给LLM。我们可以通过将多个链组合在一起,或将链与其他组件组合在一起,建立更复杂的链。看一个简单使用的例子:LLMChain是最基本的构建块链。它接受一个提示模板,用用户输入的格式化它,并从LLM返回响应。要使用LLMChain,首先要创建一个提示模板。from langchain.llms import OpenAI

from langchain.prompts import PromptTemplate

llm = OpenAI(temperature=0.9)

prompt = PromptTemplate(

input_variables=["product"],

template="What is a good name for a company that makes {product}?",

)

我们现在可以创建一个非常简单的链,它将接受用户的输入,用它来格式化提示,然后将其发送到LLM。from langchain.chains import LLMChain

chain = LLMChain(llm=llm, prompt=prompt)

# Run the chain only specifying the input variable.

print(chain.run("colorful socks"))

Colorful Toes Co.

如果有多个变量,你可以用一个字典一次输入它们。prompt = PromptTemplate(

input_variables=["company", "product"],

template="What is a good name for {company} that makes {product}?",

)

chain = LLMChain(llm=llm, prompt=prompt)

print(chain.run({

'company': "ABC Startup",

'product': "colorful socks"

}))

Socktopia Colourful Creations.

你也可以在LLMChain中使用一个聊天模型:from langchain.chat_models import ChatOpenAI

from langchain.prompts.chat import (

ChatPromptTemplate,

HumanMessagePromptTemplate,

)

human_message_prompt = HumanMessagePromptTemplate(

prompt=PromptTemplate(

template="What is a good name for a company that makes {product}?",

input_variables=["product"],

)

)

chat_prompt_template = ChatPromptTemplate.from_messages([human_message_prompt])

chat = ChatOpenAI(temperature=0.9)

chain = LLMChain(llm=chat, prompt=chat_prompt_template)

print(chain.run("colorful socks"))

Rainbow Socks Co.

Part2怎么使用链2异步APILangChain通过利用asyncio库为Chains提供异步支持。目前LLMChain(通过arun、apredict、acall)和LLMMathChain(通过arun和acall)、ChatVectorDBChain和QA链都支持异步方法。对其他链的异步支持在路线图上。import asyncio

import time

from langchain.llms import OpenAI

from langchain.prompts import PromptTemplate

from langchain.chains import LLMChain

def generate_serially():

llm = OpenAI(temperature=0.9)

prompt = PromptTemplate(

input_variables=["product"],

template="What is a good name for a company that makes {product}?",

)

chain = LLMChain(llm=llm, prompt=prompt)

for _ in range(5):

resp = chain.run(product="toothpaste")

print(resp)

async def async_generate(chain):

resp = await chain.arun(product="toothpaste")

print(resp)

async def generate_concurrently():

llm = OpenAI(temperature=0.9)

prompt = PromptTemplate(

input_variables=["product"],

template="What is a good name for a company that makes {product}?",

)

chain = LLMChain(llm=llm, prompt=prompt)

tasks = [async_generate(chain) for _ in range(5)]

await asyncio.gather(*tasks)

s = time.perf_counter()

# If running this outside of Jupyter, use asyncio.run(generate_concurrently())

await generate_concurrently()

elapsed = time.perf_counter() - s

print("\033[1m" + f"Concurrent executed in {elapsed:0.2f} seconds." + "\033[0m")

s = time.perf_counter()

generate_serially()

elapsed = time.perf_counter() - s

print("\033[1m" + f"Serial executed in {elapsed:0.2f} seconds." + "\033[0m")

3不同的调用方法所有继承自Chain的类都提供了一些运行连锁逻辑的方法。最直接的一种是使用__call__:chat = ChatOpenAI(temperature=0)

prompt_template = "Tell me a {adjective} joke"

llm_chain = LLMChain(llm=chat, prompt=PromptTemplate.from_template(prompt_template))

llm_chain(inputs={"adjective": "corny"})

{'adjective': 'corny',

'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}

默认情况下,__call__同时返回输入和输出的键值。你可以通过设置 return_only_outputs 为 True,将其配置为只返回输出键值。llm_chain("corny", return_only_outputs=True)

{'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}

如果Chain只输出一个输出键(即它的output_keys中只有一个元素),你可以使用run方法。注意,run会输出一个字符串而不是一个字典。# llm_chain only has one output key, so we can use run

llm_chain.output_keys

['text']

llm_chain.run({"adjective": "corny"})

'Why did the tomato turn red? Because it saw the salad dressing!'

在有一个输入键的情况下,你可以直接输入字符串,而不必指定输入映射。# These two are equivalent

llm_chain.run({"adjective": "corny"})

llm_chain.run("corny")

# These two are also equivalent

llm_chain("corny")

llm_chain({"adjective": "corny"})

{'adjective': 'corny',

'text': 'Why did the tomato turn red? Because it saw the salad dressing!'}

提示: 你可以通过运行方法轻松地将链对象作为工具集成到你的Agent中。请看这里的一个例子。https://python.langchain.com/docs/modules/agents/tools/how_to/custom_tools.html4通用chain要实现你自己的自定义链,你可以对Chain进行子类化,并实现以下方法:from __future__ import annotations

from typing import Any, Dict, List, Optional

from pydantic import Extra

from langchain.base_language import BaseLanguageModel

from langchain.callbacks.manager import (

AsyncCallbackManagerForChainRun,

CallbackManagerForChainRun,

)

from langchain.chains.base import Chain

from langchain.prompts.base import BasePromptTemplate

class MyCustomChain(Chain):

"""

An example of a custom chain.

"""

prompt: BasePromptTemplate

"""Prompt object to use."""

llm: BaseLanguageModel

output_key: str = "text" #: :meta private:

class Config:

"""Configuration for this pydantic object."""

extra = Extra.forbid

arbitrary_types_allowed = True

@property

def input_keys(self) -> List[str]:

"""Will be whatever keys the prompt expects.

:meta private:

"""

return self.prompt.input_variables

@property

def output_keys(self) -> List[str]:

"""Will always return text key.

:meta private:

"""

return [self.output_key]

def _call(

self,

inputs: Dict[str, Any],

run_manager: Optional[CallbackManagerForChainRun] = None,

) -> Dict[str, str]:

# Your custom chain logic goes here

# This is just an example that mimics LLMChain

prompt_value = self.prompt.format_prompt(**inputs)

# Whenever you call a language model, or another chain, you should pass

# a callback manager to it. This allows the inner run to be tracked by

# any callbacks that are registered on the outer run.

# You can always obtain a callback manager for this by calling

# `run_manager.get_child()` as shown below.

response = self.llm.generate_prompt(

[prompt_value], callbacks=run_manager.get_child() if run_manager else None

)

# If you want to log something about this run, you can do so by calling

# methods on the `run_manager`, as shown below. This will trigger any

# callbacks that are registered for that event.

if run_manager:

run_manager.on_text("Log something about this run")

return {self.output_key: response.generations[0][0].text}

async def _acall(

self,

inputs: Dict[str, Any],

run_manager: Optional[AsyncCallbackManagerForChainRun] = None,

) -> Dict[str, str]:

# Your custom chain logic goes here

# This is just an example that mimics LLMChain

prompt_value = self.prompt.format_prompt(**inputs)

# Whenever you call a language model, or another chain, you should pass

# a callback manager to it. This allows the inner run to be tracked by

# any callbacks that are registered on the outer run.

# You can always obtain a callback manager for this by calling

# `run_manager.get_child()` as shown below.

response = await self.llm.agenerate_prompt(

[prompt_value], callbacks=run_manager.get_child() if run_manager else None

)

# If you want to log something about this run, you can do so by calling

# methods on the `run_manager`, as shown below. This will trigger any

# callbacks that are registered for that event.

if run_manager:

await run_manager.on_text("Log something about this run")

return {self.output_key: response.generations[0][0].text}

@property

def _chain_type(self) -> str:

return "my_custom_chain"

from langchain.callbacks.stdout import StdOutCallbackHandler

from langchain.chat_models.openai import ChatOpenAI

from langchain.prompts.prompt import PromptTemplate

chain = MyCustomChain(

prompt=PromptTemplate.from_template("tell us a joke about {topic}"),

llm=ChatOpenAI(),

)

chain.run({"topic": "callbacks"}, callbacks=[StdOutCallbackHandler()])

> Entering new MyCustomChain chain...

Log something about this run

> Finished chain.

'Why did the callback function feel lonely? Because it was always waiting for someone to call it back!'

5Debugging chains由于大多数Chain对象涉及到大量的输入提示预处理和LLM输出后处理,因此仅从输出中调试Chain对象是很难的。将verbose设置为True将打印出Chain对象运行时的一些内部状态。conversation = ConversationChain(

llm=chat,

memory=ConversationBufferMemory(),

verbose=True

)

conversation.run("What is ChatGPT?")

> Entering new ConversationChain chain...

Prompt after formatting:

The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

Current conversation:

Human: What is ChatGPT?

AI:

> Finished chain.

'ChatGPT is an AI language model developed by OpenAI. It is based on the GPT-3 architecture and is capable of generating human-like responses to text prompts. ChatGPT has been trained on a massive amount of text data and can understand and respond to a wide range of topics. It is often used for chatbots, virtual assistants, and other conversational AI applications.'

6从LangChainHub加载from langchain.chains import load_chain

chain = load_chain("lc://chains/llm-math/chain.json")

chain.run("whats 2 raised to .12")

> Entering new LLMMathChain chain...

whats 2 raised to .12

Answer: 1.0791812460476249

> Finished chain.

'Answer: 1.0791812460476249'

有时,链会要求额外的参数,而这些参数并没有和链一起被序列化。例如,一个在矢量数据库上做问题回答的链将需要一个矢量数据库。from langchain.embeddings.openai import OpenAIEmbeddings

from langchain.vectorstores import Chroma

from langchain.text_splitter import CharacterTextSplitter

from langchain import OpenAI, VectorDBQA

from langchain.document_loaders import TextLoader

loader = TextLoader("../../state_of_the_union.txt")

documents = loader.load()

text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)

texts = text_splitter.split_documents(documents)

embeddings = OpenAIEmbeddings()

vectorstore = Chroma.from_documents(texts, embeddings)

Running Chroma using direct local API.

Using DuckDB in-memory for database. Data will be transient.

chain = load_chain("lc://chains/vector-db-qa/stuff/chain.json", vectorstore=vectorstore)

query = "What did the president say about Ketanji Brown Jackson"

chain.run(query)

" The president said that Ketanji Brown Jackson is a Circuit Court of Appeals Judge, one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans, and will continue Justice Breyer's legacy of excellence."

7Adding memory (state)链可以用一个Memory对象来初始化,它将在对链的调用中持续保存数据。这使得链是有状态的。from langchain.chains import ConversationChain

from langchain.memory import ConversationBufferMemory

conversation = ConversationChain(

llm=chat,

memory=ConversationBufferMemory()

)

conversation.run("Answer briefly. What are the first 3 colors of a rainbow?")

# -> The first three colors of a rainbow are red, orange, and yellow.

conversation.run("And the next 4?")

# -> The next four colors of a rainbow are green, blue, indigo, and violet.

'The next four colors of a rainbow are green, blue, indigo, and violet.'

从本质上讲,BaseMemory定义了一个langchain如何存储内存的接口。它允许通过load_memory_variables方法读取存储数据,并通过save_context方法存储新数据。你可以在 "内存 "部分了解更多信息。8序列化这个笔记本涵盖了如何将链序列化到磁盘和从磁盘序列化。我们使用的序列化格式是json或yaml。目前,只有一些链支持这种类型的序列化。我们将随着时间的推移增加支持的链的数量。将一个链保存到磁盘首先,我们来看看如何将一个链保存到磁盘。这可以通过.save方法来完成,并指定一个带有json或yaml扩展名的文件路径。from langchain import PromptTemplate, OpenAI, LLMChain

template = """Question: {question}

Answer: Let's think step by step."""

prompt = PromptTemplate(template=template, input_variables=["question"])

llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0), verbose=True)

llm_chain.save("llm_chain.json")

cat llm_chain.json

{

"memory": null,

"verbose": true,

"prompt": {

"input_variables": [

"question"

],

"output_parser": null,

"template": "Question: {question}\n\nAnswer: Let's think step by step.",

"template_format": "f-string"

},

"llm": {

"model_name": "text-davinci-003",

"temperature": 0.0,

"max_tokens": 256,

"top_p": 1,

"frequency_penalty": 0,

"presence_penalty": 0,

"n": 1,

"best_of": 1,

"request_timeout": null,

"logit_bias": {},

"_type": "openai"

},

"output_key": "text",

"_type": "llm_chain"

}

从磁盘加载一个链from langchain.chains import load_chain

chain = load_chain("llm_chain.json")

chain.run("whats 2 + 2")

> Entering new LLMChain chain...

Prompt after formatting:

Question: whats 2 + 2

Answer: Let's think step by step.

> Finished chain.

' 2 + 2 = 4'

分开保存组件在上面的例子中,我们可以看到提示信息和llm配置信息与整个链条保存在同一个json中。另外,我们也可以把它们拆开,单独保存。这对于使保存的组件更加模块化通常是有用的。为了做到这一点,我们只需要指定llm_path而不是llm组件,以及prompt_path而不是prompt组件。llm_chain.prompt.save("prompt.json")

cat prompt.json

{

"input_variables": [

"question"

],

"output_parser": null,

"template": "Question: {question}\n\nAnswer: Let's think step by step.",

"template_format": "f-string"

}

llm_chain.llm.save("llm.json")

cat llm.json

{

"model_name": "text-davinci-003",

"temperature": 0.0,

"max_tokens": 256,

"top_p": 1,

"frequency_penalty": 0,

"presence_penalty": 0,

"n": 1,

"best_of": 1,

"request_timeout": null,

"logit_bias": {},

"_type": "openai"

}

config = {

"memory": None,

"verbose": True,

"prompt_path": "prompt.json",

"llm_path": "llm.json",

"output_key": "text",

"_type": "llm_chain",

}

import json

with open("llm_chain_separate.json", "w") as f:

json.dump(config, f, indent=2)

cat llm_chain_separate.json

{

"memory": null,

"verbose": true,

"prompt_path": "prompt.json",

"llm_path": "llm.json",

"output_key": "text",

"_type": "llm_chain"

}

chain = load_chain("llm_chain_separate.json")

chain.run("whats 2 + 2")

> Entering new LLMChain chain...

Prompt after formatting:

Question: whats 2 + 2

Answer: Let's think step by step.

> Finished chain.

' 2 + 2 = 4'

Part3基础9LLMLLMChain是一个简单的链,围绕语言模型增加了一些功能。它在整个LangChain中被广泛使用,包括在其他链和代理中。一个LLMChain由一个PromptTemplate和一个语言模型(LLM或聊天模型)组成。它使用所提供的输入键值(如果有的话,还有内存键值)来格式化提示模板,将格式化的字符串传递给LLM并返回LLM的输出。from langchain import PromptTemplate, OpenAI, LLMChain

prompt_template = "What is a good name for a company that makes {product}?"

llm = OpenAI(temperature=0)

llm_chain = LLMChain(

llm=llm,

prompt=PromptTemplate.from_template(prompt_template)

)

llm_chain("colorful socks")

{'product': 'colorful socks', 'text': '\n\nSocktastic!'}

运行LLM链的其他方式除了所有链对象共享的__call__和run方法外,LLMChain还提供了一些调用链逻辑的方法:应用允许你针对一个输入列表运行链:input_list = [

{"product": "socks"},

{"product": "computer"},

{"product": "shoes"}

]

llm_chain.apply(input_list)

[{'text': '\n\nSocktastic!'},

{'text': '\n\nTechCore Solutions.'},

{'text': '\n\nFootwear Factory.'}]

generate与apply类似,只是它返回一个LLMResult而不是字符串。LLMResult通常包含有用的生成,如令牌使用和完成原因。llm_chain.generate(input_list)

LLMResult(generations=[[Generation(text='\n\nSocktastic!', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nTechCore Solutions.', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nFootwear Factory.', generation_info={'finish_reason': 'stop', 'logprobs': None})]], llm_output={'token_usage': {'prompt_tokens': 36, 'total_tokens': 55, 'completion_tokens': 19}, 'model_name': 'text-davinci-003'})

predict与run方法类似,只是输入键被指定为关键字参数,而不是Python dict。# Single input example

llm_chain.predict(product="colorful socks")

'\n\nSocktastic!'

# Multiple inputs example

template = """Tell me a {adjective} joke about {subject}."""

prompt = PromptTemplate(template=template, input_variables=["adjective", "subject"])

llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0))

llm_chain.predict(adjective="sad", subject="ducks")

'\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.'

解析输出默认情况下,即使底层提示对象有输出解析器,LLMChain也不会对输出进行解析。如果你想在LLM的输出上应用该输出解析器,请使用predict_and_parse而不是predict,使用apply_and_parse而不是apply。使用predict:from langchain.output_parsers import CommaSeparatedListOutputParser

output_parser = CommaSeparatedListOutputParser()

template = """List all the colors in a rainbow"""

prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser)

llm_chain = LLMChain(prompt=prompt, llm=llm)

llm_chain.predict()

'\n\nRed, orange, yellow, green, blue, indigo, violet'

使用predict_and_parser:llm_chain.predict_and_parse()

['Red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

从字符串进行初始化我们也可以直接从一个字符串模板中构建一个LLMChain。template = """Tell me a {adjective} joke about {subject}."""

llm_chain = LLMChain.from_string(llm=llm, template=template)

llm_chain.predict(adjective="sad", subject="ducks")

'\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.'

10路由器本笔记本演示了如何使用RouterChain范式来创建一个链,为给定的输入动态地选择下一个链来使用。Router链由两个部分组成:RouterChain本身(负责选择要调用的下一条链)destination_chains: 路由器链可以路由到的链在本笔记本中,我们将重点介绍不同类型的路由链。我们将展示这些路由链在MultiPromptChain中的应用,以创建一个回答问题的链,选择与给定问题最相关的提示,然后使用该提示回答问题。from langchain.chains.router import MultiPromptChain

from langchain.llms import OpenAI

from langchain.chains import ConversationChain

from langchain.chains.llm import LLMChain

from langchain.prompts import PromptTemplate

physics_template = """You are a very smart physics professor. \

You are great at answering questions about physics in a concise and easy to understand manner. \

When you don't know the answer to a question you admit that you don't know.

Here is a question:

{input}"""

math_template = """You are a very good mathematician. You are great at answering math questions. \

You are so good because you are able to break down hard problems into their component parts, \

answer the component parts, and then put them together to answer the broader question.

Here is a question:

{input}"""

prompt_infos = [

{

"name": "physics",

"description": "Good for answering questions about physics",

"prompt_template": physics_template,

},

{

"name": "math",

"description": "Good for answering math questions",

"prompt_template": math_template,

},

]

llm = OpenAI()

destination_chains = {}

for p_info in prompt_infos:

name = p_info["name"]

prompt_template = p_info["prompt_template"]

prompt = PromptTemplate(template=prompt_template, input_variables=["input"])

chain = LLMChain(llm=llm, prompt=prompt)

destination_chains[name] = chain

default_chain = ConversationChain(llm=llm, output_key="text")

LLMRouterChain这条链使用LLM来决定如何进行路由。from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser

from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE

destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]

destinations_str = "\n".join(destinations)

router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)

router_prompt = PromptTemplate(

template=router_template,

input_variables=["input"],

output_parser=RouterOutputParser(),

)

router_chain = LLMRouterChain.from_llm(llm, router_prompt)

chain = MultiPromptChain(

router_chain=router_chain,

destination_chains=destination_chains,

default_chain=default_chain,

verbose=True,

)

print(chain.run("What is black body radiation?"))

> Entering new MultiPromptChain chain...

physics: {'input': 'What is black body radiation?'}

> Finished chain.

Black body radiation is the term used to describe the electromagnetic radiation emitted by a “black body”—an object that absorbs all radiation incident upon it. A black body is an idealized physical body that absorbs all incident electromagnetic radiation, regardless of frequency or angle of incidence. It does not reflect, emit or transmit energy. This type of radiation is the result of the thermal motion of the body's atoms and molecules, and it is emitted at all wavelengths. The spectrum of radiation emitted is described by Planck's law and is known as the black body spectrum.

print(

chain.run(

"What is the first prime number greater than 40 such that one plus the prime number is divisible by 3"

)

)

> Entering new MultiPromptChain chain...

math: {'input': 'What is the first prime number greater than 40 such that one plus the prime number is divisible by 3'}

> Finished chain.

?

The answer is 43. One plus 43 is 44 which is divisible by 3.

print(chain.run("What is the name of the type of cloud that rins"))

> Entering new MultiPromptChain chain...

None: {'input': 'What is the name of the type of cloud that rains?'}

> Finished chain.

The type of cloud that rains is called a cumulonimbus cloud. It is a tall and dense cloud that is often accompanied by thunder and lightning.

EmbeddingRouterChainEmbeddingRouterChain使用嵌入和相似性在目的地链之间进行路由。from langchain.chains.router.embedding_router import EmbeddingRouterChain

from langchain.embeddings import CohereEmbeddings

from langchain.vectorstores import Chroma

names_and_descriptions = [

("physics", ["for questions about physics"]),

("math", ["for questions about math"]),

]

router_chain = EmbeddingRouterChain.from_names_and_descriptions(

names_and_descriptions, Chroma, CohereEmbeddings(), routing_keys=["input"]

)

Using embedded DuckDB without persistence: data will be transient

chain = MultiPromptChain(

router_chain=router_chain,

destination_chains=destination_chains,

default_chain=default_chain,

verbose=True,

)

print(chain.run("What is black body radiation?"))

> Entering new MultiPromptChain chain...

physics: {'input': 'What is black body radiation?'}

> Finished chain.

Black body radiation is the emission of energy from an idealized physical body (known as a black body) that is in thermal equilibrium with its environment. It is emitted in a characteristic pattern of frequencies known as a black-body spectrum, which depends only on the temperature of the body. The study of black body radiation is an important part of astrophysics and atmospheric physics, as the thermal radiation emitted by stars and planets can often be approximated as black body radiation.

print(

chain.run(

"What is the first prime number greater than 40 such that one plus the prime number is divisible by 3"

)

)

> Entering new MultiPromptChain chain...

math: {'input': 'What is the first prime number greater than 40 such that one plus the prime number is divisible by 3'}

> Finished chain.

?

Answer: The first prime number greater than 40 such that one plus the prime number is divisible by 3 is 43.

11连续调用语言模型后的下一步是对语言模型进行一系列的调用。当你想把一个调用的输出作为另一个调用的输入时,这就特别有用。在这个笔记本中,我们将通过一些例子来说明如何做到这一点,使用顺序链。顺序链允许你连接多个链,并将它们组成管道,执行一些特定的场景。有两种类型的顺序链:SimpleSequentialChain: 顺序链的最简单形式,每个步骤都有一个单一的输入/输出,一个步骤的输出是下一个步骤的输入。顺序链(SequentialChain): 顺序链的一种更普遍的形式,允许有多个输入/输出。from langchain.llms import OpenAI

from langchain.chains import LLMChain

from langchain.prompts import PromptTemplate

# This is an LLMChain to write a synopsis given a title of a play.

llm = OpenAI(temperature=.7)

template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title.

Title: {title}

Playwright: This is a synopsis for the above play:"""

prompt_template = PromptTemplate(input_variables=["title"], template=template)

synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)

# This is an LLMChain to write a review of a play given a synopsis.

llm = OpenAI(temperature=.7)

template = """You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.

Play Synopsis:

{synopsis}

Review from a New York Times play critic of the above play:"""

prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)

review_chain = LLMChain(llm=llm, prompt=prompt_template)

# This is the overall chain where we run these two chains in sequence.

from langchain.chains import SimpleSequentialChain

overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True)

review = overall_chain.run("Tragedy at sunset on the beach")

> Entering new SimpleSequentialChain chain...

Tragedy at Sunset on the Beach is a story of a young couple, Jack and Sarah, who are in love and looking forward to their future together. On the night of their anniversary, they decide to take a walk on the beach at sunset. As they are walking, they come across a mysterious figure, who tells them that their love will be tested in the near future.

The figure then tells the couple that the sun will soon set, and with it, a tragedy will strike. If Jack and Sarah can stay together and pass the test, they will be granted everlasting love. However, if they fail, their love will be lost forever.

The play follows the couple as they struggle to stay together and battle the forces that threaten to tear them apart. Despite the tragedy that awaits them, they remain devoted to one another and fight to keep their love alive. In the end, the couple must decide whether to take a chance on their future together or succumb to the tragedy of the sunset.

Tragedy at Sunset on the Beach is an emotionally gripping story of love, hope, and sacrifice. Through the story of Jack and Sarah, the audience is taken on a journey of self-discovery and the power of love to overcome even the greatest of obstacles.

The play's talented cast brings the characters to life, allowing us to feel the depths of their emotion and the intensity of their struggle. With its compelling story and captivating performances, this play is sure to draw in audiences and leave them on the edge of their seats.

The play's setting of the beach at sunset adds a touch of poignancy and romanticism to the story, while the mysterious figure serves to keep the audience enthralled. Overall, Tragedy at Sunset on the Beach is an engaging and thought-provoking play that is sure to leave audiences feeling inspired and hopeful.

> Finished chain.

print(review)

Tragedy at Sunset on the Beach is an emotionally gripping story of love, hope, and sacrifice. Through the story of Jack and Sarah, the audience is taken on a journey of self-discovery and the power of love to overcome even the greatest of obstacles.

The play's talented cast brings the characters to life, allowing us to feel the depths of their emotion and the intensity of their struggle. With its compelling story and captivating performances, this play is sure to draw in audiences and leave them on the edge of their seats.

The play's setting of the beach at sunset adds a touch of poignancy and romanticism to the story, while the mysterious figure serves to keep the audience enthralled. Overall, Tragedy at Sunset on the Beach is an engaging and thought-provoking play that is sure to leave audiences feeling inspired and hopeful.

Sequential Chain当然,并不是所有的顺序链都像传递一个字符串作为参数,在链的所有步骤中得到一个字符串作为输出那样简单。在接下来的例子中,我们将尝试更复杂的链,涉及多个输入,也有多个最终输出。特别重要的是我们如何命名输入/输出变量名。在上面的例子中,我们不必考虑这个问题,因为我们只是把一个链的输出直接作为输入传给下一个链,但在这里我们必须担心这个问题,因为我们有多个输入。# This is an LLMChain to write a synopsis given a title of a play and the era it is set in.

llm = OpenAI(temperature=.7)

template = """You are a playwright. Given the title of play and the era it is set in, it is your job to write a synopsis for that title.

Title: {title}

Era: {era}

Playwright: This is a synopsis for the above play:"""

prompt_template = PromptTemplate(input_variables=["title", "era"], template=template)

synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="synopsis")

# This is an LLMChain to write a review of a play given a synopsis.

llm = OpenAI(temperature=.7)

template = """You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.

Play Synopsis:

{synopsis}

Review from a New York Times play critic of the above play:"""

prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)

review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")

# This is the overall chain where we run these two chains in sequence.

from langchain.chains import SequentialChain

overall_chain = SequentialChain(

chains=[synopsis_chain, review_chain],

input_variables=["era", "title"],

# Here we return multiple variables

output_variables=["synopsis", "review"],

verbose=True)

overall_chain({"title":"Tragedy at sunset on the beach", "era": "Victorian England"})

> Entering new SequentialChain chain...

> Finished chain.

{'title': 'Tragedy at sunset on the beach',

'era': 'Victorian England',

'synopsis': "\n\nThe play follows the story of John, a young man from a wealthy Victorian family, who dreams of a better life for himself. He soon meets a beautiful young woman named Mary, who shares his dream. The two fall in love and decide to elope and start a new life together.\n\nOn their journey, they make their way to a beach at sunset, where they plan to exchange their vows of love. Unbeknownst to them, their plans are overheard by John's father, who has been tracking them. He follows them to the beach and, in a fit of rage, confronts them. \n\nA physical altercation ensues, and in the struggle, John's father accidentally stabs Mary in the chest with his sword. The two are left in shock and disbelief as Mary dies in John's arms, her last words being a declaration of her love for him.\n\nThe tragedy of the play comes to a head when John, broken and with no hope of a future, chooses to take his own life by jumping off the cliffs into the sea below. \n\nThe play is a powerful story of love, hope, and loss set against the backdrop of 19th century England.",

'review': "\n\nThe latest production from playwright X is a powerful and heartbreaking story of love and loss set against the backdrop of 19th century England. The play follows John, a young man from a wealthy Victorian family, and Mary, a beautiful young woman with whom he falls in love. The two decide to elope and start a new life together, and the audience is taken on a journey of hope and optimism for the future.\n\nUnfortunately, their dreams are cut short when John's father discovers them and in a fit of rage, fatally stabs Mary. The tragedy of the play is further compounded when John, broken and without hope, takes his own life. The storyline is not only realistic, but also emotionally compelling, drawing the audience in from start to finish.\n\nThe acting was also commendable, with the actors delivering believable and nuanced performances. The playwright and director have successfully crafted a timeless tale of love and loss that will resonate with audiences for years to come. Highly recommended."}

Part4Memory in Sequential Chains有时你可能想传递一些上下文,在链的每一步或链的后面部分使用,但维护和链在一起的输入/输出变量会很快变得混乱。使用SimpleMemory是一个方便的方法来做管理和清理你的链。例如,使用之前的剧作家序列链,假设你想包括一些关于戏剧的日期、时间和地点的上下文,并使用生成的剧情简介和评论,创建一些社交媒体的帖子文本。你可以把这些新的上下文变量作为input_variables来添加,或者我们可以在链上添加一个SimpleMemory来管理这个上下文:from langchain.chains import SequentialChain

from langchain.memory import SimpleMemory

llm = OpenAI(temperature=.7)

template = """You are a social media manager for a theater company. Given the title of play, the era it is set in, the date,time and location, the synopsis of the play, and the review of the play, it is your job to write a social media post for that play.

Here is some context about the time and location of the play:

Date and Time: {time}

Location: {location}

Play Synopsis:

{synopsis}

Review from a New York Times play critic of the above play:

{review}

Social Media Post:

"""

prompt_template = PromptTemplate(input_variables=["synopsis", "review", "time", "location"], template=template)

social_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="social_post_text")

overall_chain = SequentialChain(

memory=SimpleMemory(memories={"time": "December 25th, 8pm PST", "location": "Theater in the Park"}),

chains=[synopsis_chain, review_chain, social_chain],

input_variables=["era", "title"],

# Here we return multiple variables

output_variables=["social_post_text"],

verbose=True)

overall_chain({"title":"Tragedy at sunset on the beach", "era": "Victorian England"})

> Entering new SequentialChain chain...

> Finished chain.

{'title': 'Tragedy at sunset on the beach',

'era': 'Victorian England',

'time': 'December 25th, 8pm PST',

'location': 'Theater in the Park',

'social_post_text': "\nSpend your Christmas night with us at Theater in the Park and experience the heartbreaking story of love and loss that is 'A Walk on the Beach'. Set in Victorian England, this romantic tragedy follows the story of Frances and Edward, a young couple whose love is tragically cut short. Don't miss this emotional and thought-provoking production that is sure to leave you in tears. #AWalkOnTheBeach #LoveAndLoss #TheaterInThePark #VictorianEngland"}

12变换这个笔记本展示了使用一个通用的转换链。作为一个例子,我们将创建一个假的转换,接收一个超长的文本,将文本过滤成只有前三段,然后将其传递给LLMChain来总结这些。from langchain.chains import TransformChain, LLMChain, SimpleSequentialChain

from langchain.llms import OpenAI

from langchain.prompts import PromptTemplate

with open("../../state_of_the_union.txt") as f:

state_of_the_union = f.read()

def transform_func(inputs: dict) -> dict:

text = inputs["text"]

shortened_text = "\n\n".join(text.split("\n\n")[:3])

return {"output_text": shortened_text}

transform_chain = TransformChain(

input_variables=["text"], output_variables=["output_text"], transform=transform_func

)

template = """Summarize this text:

{output_text}

Summary:"""

prompt = PromptTemplate(input_variables=["output_text"], template=template)

llm_chain = LLMChain(llm=OpenAI(), prompt=prompt)

sequential_chain = SimpleSequentialChain(chains=[transform_chain, llm_chain])

sequential_chain.run(state_of_the_union)

' The speaker addresses the nation, noting that while last year they were kept apart due to COVID-19, this year they are together again. They are reminded that regardless of their political affiliations, they are all Americans.'

Part5Documents13Stuffstuff文件链("stuff "是指 "to stuff "或 "to fill")是最直接的文件链。它接收一个文件列表,将它们全部插入一个提示,并将该提示传递给一个LLM。这条链非常适合于文件数量较少且大多数调用只传递几个文件的应用。14refine完善文档链通过循环输入文档和迭代更新其答案来构建一个响应。对于每个文档,它将所有非文档输入、当前文档和最新的中间答案传递给LLM链,以获得一个新的答案。由于Refine链每次只向LLM传递一个文档,所以它很适合于需要分析更多文档的任务,而这些文档在模型的上下文中并不适合。显而易见的是,这条链会比Stuff文档链等调用更多的LLM。也有一些任务是很难迭代完成的。例如,当文档之间经常相互参照,或者当一个任务需要许多文档的详细信息时,Refine链的表现就很差。15Map reducemap reduce文档链首先对每个文档单独应用LLM链(map步骤),将链的输出视为一个新的文档。然后,它将所有的新文档传递给一个单独的组合文档链,以获得一个单一的输出(Reduce步骤)。它可以选择首先压缩或折叠映射的文档,以确保它们适合于组合文档链(它通常会将它们传递给LLM)。如果有必要的话,这个压缩步骤会递归进行。16Map re-rankmap re-rank文件链对每个文件进行初始提示,不仅试图完成一项任务,而且对其答案的确定程度进行评分。得分最高的回答会被返回。Part6流行17API chainsAPIChain使使用LLM与API进行交互以检索相关信息。通过提供一个与所提供的API文档相关的问题来构建链。OpenMeteo Examplefrom langchain.chains.api import open_meteo_docs

chain_new = APIChain.from_llm_and_api_docs(llm, open_meteo_docs.OPEN_METEO_DOCS, verbose=True)

chain_new.run('What is the weather like right now in Munich, Germany in degrees Fahrenheit?')

> Entering new APIChain chain...

https://api.open-meteo.com/v1/forecast?latitude=48.1351&longitude=11.5820&temperature_unit=fahrenheit¤t_weather=true

{"latitude":48.14,"longitude":11.58,"generationtime_ms":0.33104419708251953,"utc_offset_seconds":0,"timezone":"GMT","timezone_abbreviation":"GMT","elevation":521.0,"current_weather":{"temperature":33.4,"windspeed":6.8,"winddirection":198.0,"weathercode":2,"time":"2023-01-16T01:00"}}

> Finished chain.

' The current temperature in Munich, Germany is 33.4 degrees Fahrenheit with a windspeed of 6.8 km/h and a wind direction of 198 degrees. The weathercode is 2.'

18检索QA这个例子展示了通过索引回答问题的情况。from langchain.chains import RetrievalQA

from langchain.document_loaders import TextLoader

from langchain.embeddings.openai import OpenAIEmbeddings

from langchain.llms import OpenAI

from langchain.text_splitter import CharacterTextSplitter

from langchain.vectorstores import Chroma

loader = TextLoader("../../state_of_the_union.txt")

documents = loader.load()

text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)

texts = text_splitter.split_documents(documents)

embeddings = OpenAIEmbeddings()

docsearch = Chroma.from_documents(texts, embeddings)

qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=docsearch.as_retriever())

query = "What did the president say about Ketanji Brown Jackson"

qa.run(query)

" The president said that she is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support, from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."

链的类型你可以很容易地指定不同的链类型,以便在RetrievalQA链中加载和使用。关于这些类型的详细介绍,请参见本笔记本。有两种方法来加载不同的链类型。首先,你可以在from_chain_type方法中指定链类型参数。这允许你传入你想使用的链类型的名称。例如,在下面我们将链类型改为map_reduce。qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="map_reduce", retriever=docsearch.as_retriever())

query = "What did the president say about Ketanji Brown Jackson"

qa.run(query)

" The president said that Judge Ketanji Brown Jackson is one of our nation's top legal minds, a former top litigator in private practice and a former federal public defender, from a family of public school educators and police officers, a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."

上述方法允许你真正简单地改变链_类型,但它没有为该链类型的参数提供大量的灵活性。如果你想控制这些参数,你可以直接加载链(就像你在这个笔记本中做的那样),然后用combined_documents_chain参数将其直接传递给RetrievalQA链。比如说from langchain.chains.question_answering import load_qa_chain

qa_chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff")

qa = RetrievalQA(combine_documents_chain=qa_chain, retriever=docsearch.as_retriever())

query = "What did the president say about Ketanji Brown Jackson"

qa.run(query)

" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."

通用的提示你可以传入自定义的提示语来做问题的回答。这些提示与你可以传入基本问题回答链的提示相同。from langchain.prompts import PromptTemplate

prompt_template = """Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.

{context}

Question: {question}

Answer in Italian:"""

PROMPT = PromptTemplate(

template=prompt_template, input_variables=["context", "question"]

)

chain_type_kwargs = {"prompt": PROMPT}

qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=docsearch.as_retriever(), chain_type_kwargs=chain_type_kwargs)

query = "What did the president say about Ketanji Brown Jackson"

qa.run(query)

" Il presidente ha detto che Ketanji Brown Jackson è una delle menti legali più importanti del paese, che continuerà l'eccellenza di Justice Breyer e che ha ricevuto un ampio sostegno, da Fraternal Order of Police a ex giudici nominati da democratici e repubblicani."

返回源文档此外,我们可以通过在构建链时指定一个可选的参数来返回用于回答问题的源文件。qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=docsearch.as_retriever(), return_source_documents=True)

query = "What did the president say about Ketanji Brown Jackson"

result = qa({"query": query})

result["result"]

" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice and a former federal public defender from a family of public school educators and police officers, and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."

result["source_documents"]

[Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0),

Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \n\nWe can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \n\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \n\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \n\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0),

Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. \n\nWhile it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. \n\nAnd soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. \n\nSo tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. \n\nFirst, beat the opioid epidemic.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0),

Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \n\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \n\nThat ends on my watch. \n\nMedicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. \n\nWe’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. \n\nLet’s pass the Paycheck Fairness Act and paid leave. \n\nRaise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. \n\nLet’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.', lookup_str='', metadata={'source': '../../state_of_the_union.txt'}, lookup_index=0)]

另外,如果我们的文档有一个 "源 "元数据键,我们可以使用RetrievalQAW withSourceChain来引用我们的来源:docsearch = Chroma.from_texts(texts, embeddings, metadatas=[{"source": f"{i}-pl"} for i in range(len(texts))])

from langchain.chains import RetrievalQAWithSourcesChain

from langchain import OpenAI

chain = RetrievalQAWithSourcesChain.from_chain_type(OpenAI(temperature=0), chain_type="stuff", retriever=docsearch.as_retriever())

chain({"question": "What did the president say about Justice Breyer"}, return_only_outputs=True)

{'answer': ' The president honored Justice Breyer for his service and mentioned his legacy of excellence.\n',

'sources': '31-pl'}

19对话检索QAConversationalRetrievalQA链建立在RetrievalQAChain的基础上,提供一个聊天历史组件。它首先将聊天历史(明确传入或从提供的内存中检索)和问题合并成一个独立的问题,然后从检索器中查找相关文档,最后将这些文档和问题传递给问题回答链以返回响应。要创建一个,你将需要一个检索器。在下面的例子中,我们将从一个矢量存储中创建一个,它可以从嵌入中创建。from langchain.embeddings.openai import OpenAIEmbeddings

from langchain.vectorstores import Chroma

from langchain.text_splitter import CharacterTextSplitter

from langchain.llms import OpenAI

from langchain.chains import ConversationalRetrievalChain

from langchain.document_loaders import TextLoader

loader = TextLoader("../../state_of_the_union.txt")

documents = loader.load()

# loaders = [....]

# docs = []

# for loader in loaders:

# docs.extend(loader.load())

text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)

documents = text_splitter.split_documents(documents)

embeddings = OpenAIEmbeddings()

vectorstore = Chroma.from_documents(documents, embeddings)

Using embedded DuckDB without persistence: data will be transient

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore.as_retriever(), memory=memory)

query = "What did the president say about Ketanji Brown Jackson"

result = qa({"question": query})

" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."

query = "Did he mention who she suceeded"

result = qa({"question": query})

result['answer']

' Ketanji Brown Jackson succeeded Justice Stephen Breyer on the United States Supreme Court.'

传入对话历史在上面的例子中,我们使用了一个Memory对象来跟踪聊天历史。我们也可以直接显式地传入它。为了做到这一点,我们需要初始化一个没有任何内存对象的链。qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore.as_retriever())下面是一个在没有聊天记录的情况下提出问题的例子chat_history = []

query = "What did the president say about Ketanji Brown Jackson"

result = qa({"question": query, "chat_history": chat_history})

result["answer"]

" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."

下面是一个用一些聊天记录提问的例子:chat_history = [(query, result["answer"])]

query = "Did he mention who she suceeded"

result = qa({"question": query, "chat_history": chat_history})

result['answer']

' Ketanji Brown Jackson succeeded Justice Stephen Breyer on the United States Supreme Court.'

使用不同的模式来凝练问题这个链条有两个步骤。首先,它将当前问题和聊天历史浓缩为一个独立的问题。这对于创建一个用于检索的独立向量是必要的。之后,它进行检索,然后使用单独模型的检索增强生成来回答问题。LangChain的声明性的部分力量在于,你可以很容易地为每个调用使用一个单独的语言模型。这对于使用一个更便宜、更快速的模型来完成浓缩问题的简单任务,然后使用一个更昂贵的模型来回答问题,是很有用的。下面是一个这样做的例子。from langchain.chat_models import ChatOpenAI

qa = ConversationalRetrievalChain.from_llm(

ChatOpenAI(temperature=0, model="gpt-4"),

vectorstore.as_retriever(),

condense_question_llm = ChatOpenAI(temperature=0, model='gpt-3.5-turbo'),

)

chat_history = []

query = "What did the president say about Ketanji Brown Jackson"

result = qa({"question": query, "chat_history": chat_history})

chat_history = [(query, result["answer"])]

query = "Did he mention who she suceeded"

result = qa({"question": query, "chat_history": chat_history})

返回源文档你也可以轻松地从ConversationalRetrievalChain返回源文件。当你想检查返回的文件时,这很有用。qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore.as_retriever(), return_source_documents=True)

chat_history = []

query = "What did the president say about Ketanji Brown Jackson"

result = qa({"question": query, "chat_history": chat_history})

result['source_documents'][0]

Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../state_of_the_union.txt'})

ConversationalRetrievalChain with search_distance如果你使用的是支持通过搜索距离进行过滤的矢量存储,你可以添加一个阈值参数。vectordbkwargs = {"search_distance": 0.9}

qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore.as_retriever(), return_source_documents=True)

chat_history = []

query = "What did the president say about Ketanji Brown Jackson"

result = qa({"question": query, "chat_history": chat_history, "vectordbkwargs": vectordbkwargs})

ConversationalRetrievalChain with map_reduce我们还可以使用不同类型的组合文件链与ConversationalRetrievalChain链。from langchain.chains import LLMChain

from langchain.chains.question_answering import load_qa_chain

from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT

llm = OpenAI(temperature=0)

question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)

doc_chain = load_qa_chain(llm, chain_type="map_reduce")

chain = ConversationalRetrievalChain(

retriever=vectorstore.as_retriever(),

question_generator=question_generator,

combine_docs_chain=doc_chain,

)

chat_history = []

query = "What did the president say about Ketanji Brown Jackson"

result = chain({"question": query, "chat_history": chat_history})

result['answer']

" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, from a family of public school educators and police officers, a consensus builder, and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."

ConversationalRetrievalChain with Question Answering with sources你也可以用这个链子来回答有来源的问题。from langchain.chains.qa_with_sources import load_qa_with_sources_chain

llm = OpenAI(temperature=0)

question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)

doc_chain = load_qa_with_sources_chain(llm, chain_type="map_reduce")

chain = ConversationalRetrievalChain(

retriever=vectorstore.as_retriever(),

question_generator=question_generator,

combine_docs_chain=doc_chain,

)

chat_history = []

query = "What did the president say about Ketanji Brown Jackson"

result = chain({"question": query, "chat_history": chat_history})

result['answer']

" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, from a family of public school educators and police officers, a consensus builder, and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \nSOURCES: ../../state_of_the_union.txt"

ConversationalRetrievalChain with streaming to stdout在这个例子中,链的输出将被流向stdout的token,逐个token。from langchain.chains.llm import LLMChain

from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler

from langchain.chains.conversational_retrieval.prompts import CONDENSE_QUESTION_PROMPT, QA_PROMPT

from langchain.chains.question_answering import load_qa_chain

# Construct a ConversationalRetrievalChain with a streaming llm for combine docs

# and a separate, non-streaming llm for question generation

llm = OpenAI(temperature=0)

streaming_llm = OpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=0)

question_generator = LLMChain(llm=llm, prompt=CONDENSE_QUESTION_PROMPT)

doc_chain = load_qa_chain(streaming_llm, chain_type="stuff", prompt=QA_PROMPT)

qa = ConversationalRetrievalChain(

retriever=vectorstore.as_retriever(), combine_docs_chain=doc_chain, question_generator=question_generator)

chat_history = []

query = "What did the president say about Ketanji Brown Jackson"

result = qa({"question": query, "chat_history": chat_history})

The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.

chat_history = [(query, result["answer"])]

query = "Did he mention who she suceeded"

result = qa({"question": query, "chat_history": chat_history})

Ketanji Brown Jackson succeeded Justice Stephen Breyer on the United States Supreme Court.

get_chat_history Function你还可以指定一个get_chat_history函数,它可以用来格式化chat_history字符串。def get_chat_history(inputs) -> str:

res = []

for human, ai in inputs:

res.append(f"Human:{human}\nAI:{ai}")

return "\n".join(res)

qa = ConversationalRetrievalChain.from_llm(OpenAI(temperature=0), vectorstore.as_retriever(), get_chat_history=get_chat_history)

chat_history = []

query = "What did the president say about Ketanji Brown Jackson"

result = qa({"question": query, "chat_history": chat_history})

result['answer']

" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."

20SQL这个略过了。21摘要总结链可以用来总结多个文档。一种方法是输入多个较小的文档,在它们被分成几块后,用MapReduceDocumentsChain对它们进行操作。你也可以选择用StuffDocumentsChain或RefineDocumentsChain来做总结。准备数据首先,我们准备数据。在这个例子中,我们从一个长的文件中创建了多个文件,但这些文件可以以任何方式获取(这个笔记本的重点是强调在你获取文件之后要做什么)。from langchain import OpenAI, PromptTemplate, LLMChain

from langchain.text_splitter import CharacterTextSplitter

from langchain.chains.mapreduce import MapReduceChain

from langchain.prompts import PromptTemplate

llm = OpenAI(temperature=0)

text_splitter = CharacterTextSplitter()

with open("../../state_of_the_union.txt") as f:

state_of_the_union = f.read()

texts = text_splitter.split_text(state_of_the_union)

from langchain.docstore.document import Document

docs = [Document(page_content=t) for t in texts[:3]]

快速开始如果你只是想尽快开始,这是推荐的方式:from langchain.chains.summarize import load_summarize_chain

chain = load_summarize_chain(llm, chain_type="map_reduce")

chain.run(docs)

' In response to Russian aggression in Ukraine, the United States and its allies are taking action to hold Putin accountable, including economic sanctions, asset seizures, and military assistance. The US is also providing economic and humanitarian aid to Ukraine, and has passed the American Rescue Plan and the Bipartisan Infrastructure Law to help struggling families and create jobs. The US remains unified and determined to protect Ukraine and the free world.'

如果你想对正在发生的事情有更多的控制和了解,请看以下信息。The stuff Chain这一部分展示了使用stuff链做总结的结果。chain = load_summarize_chain(llm, chain_type="stuff")

chain.run(docs)

' In his speech, President Biden addressed the crisis in Ukraine, the American Rescue Plan, and the Bipartisan Infrastructure Law. He discussed the need to invest in America, educate Americans, and build the economy from the bottom up. He also announced the release of 60 million barrels of oil from reserves around the world, and the creation of a dedicated task force to go after the crimes of Russian oligarchs. He concluded by emphasizing the need to Buy American and use taxpayer dollars to rebuild America.'

Custom Prompts你也可以使用你自己的提示语与这个链条。在这个例子中,我们将用意大利语回答。prompt_template = """Write a concise summary of the following:

{text}

CONCISE SUMMARY IN ITALIAN:"""

PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])

chain = load_summarize_chain(llm, chain_type="stuff", prompt=PROMPT)

chain.run(docs)

"\n\nIn questa serata, il Presidente degli Stati Uniti ha annunciato una serie di misure per affrontare la crisi in Ucraina, causata dall'aggressione di Putin. Ha anche annunciato l'invio di aiuti economici, militari e umanitari all'Ucraina. Ha anche annunciato che gli Stati Uniti e i loro alleati stanno imponendo sanzioni economiche a Putin e stanno rilasciando 60 milioni di barili di petrolio dalle riserve di tutto il mondo. Inoltre, ha annunciato che il Dipartimento di Giustizia degli Stati Uniti sta creando una task force dedicata ai crimini degli oligarchi russi. Il Presidente ha anche annunciato l'approvazione della legge bipartitica sull'infrastruttura, che prevede investimenti per la ricostruzione dell'America. Questo porterà a creare posti"

The map_reduce Chainchain = load_summarize_chain(llm, chain_type="map_reduce")

chain.run(docs)

" In response to Russia's aggression in Ukraine, the United States and its allies have imposed economic sanctions and are taking other measures to hold Putin accountable. The US is also providing economic and military assistance to Ukraine, protecting NATO countries, and releasing oil from its Strategic Petroleum Reserve. President Biden and Vice President Harris have passed legislation to help struggling families and rebuild America's infrastructure."

我们还可以返回map_reduce链的中间步骤,如果我们想检查它们的话。这是通过return_map_steps变量实现的。chain = load_summarize_chain(OpenAI(temperature=0), chain_type="map_reduce", return_intermediate_steps=True)

chain({"input_documents": docs}, return_only_outputs=True)

{'map_steps': [" In response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains.",

' The United States and its European allies are taking action to punish Russia for its invasion of Ukraine, including seizing assets, closing off airspace, and providing economic and military assistance to Ukraine. The US is also mobilizing forces to protect NATO countries and has released 30 million barrels of oil from its Strategic Petroleum Reserve to help blunt gas prices. The world is uniting in support of Ukraine and democracy, and the US stands with its Ukrainian-American citizens.',

" President Biden and Vice President Harris ran for office with a new economic vision for America, and have since passed the American Rescue Plan and the Bipartisan Infrastructure Law to help struggling families and rebuild America's infrastructure. This includes creating jobs, modernizing roads, airports, ports, and waterways, replacing lead pipes, providing affordable high-speed internet, and investing in American products to support American jobs."],

'output_text': " In response to Russia's aggression in Ukraine, the United States and its allies have imposed economic sanctions and are taking other measures to hold Putin accountable. The US is also providing economic and military assistance to Ukraine, protecting NATO countries, and passing legislation to help struggling families and rebuild America's infrastructure. The world is uniting in support of Ukraine and democracy, and the US stands with its Ukrainian-American citizens."}

你也可以使用你自己的提示语与这个链条。在这个例子中,我们将用意大利语回答。prompt_template = """Write a concise summary of the following:

{text}

CONCISE SUMMARY IN ITALIAN:"""

PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])

chain = load_summarize_chain(OpenAI(temperature=0), chain_type="map_reduce", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=PROMPT)

chain({"input_documents": docs}, return_only_outputs=True)

{'intermediate_steps': ["\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Gli Stati Uniti e i loro alleati stanno ora imponendo sanzioni economiche a Putin e stanno tagliando l'accesso della Russia alla tecnologia. Il Dipartimento di Giustizia degli Stati Uniti sta anche creando una task force dedicata per andare dopo i crimini degli oligarchi russi.",

"\n\nStiamo unendo le nostre forze con quelle dei nostri alleati europei per sequestrare yacht, appartamenti di lusso e jet privati di Putin. Abbiamo chiuso lo spazio aereo americano ai voli russi e stiamo fornendo più di un miliardo di dollari in assistenza all'Ucraina. Abbiamo anche mobilitato le nostre forze terrestri, aeree e navali per proteggere i paesi della NATO. Abbiamo anche rilasciato 60 milioni di barili di petrolio dalle riserve di tutto il mondo, di cui 30 milioni dalla nostra riserva strategica di petrolio. Stiamo affrontando una prova reale e ci vorrà del tempo, ma alla fine Putin non riuscirà a spegnere l'amore dei popoli per la libertà.",

"\n\nIl Presidente Biden ha lottato per passare l'American Rescue Plan per aiutare le persone che soffrivano a causa della pandemia. Il piano ha fornito sollievo economico immediato a milioni di americani, ha aiutato a mettere cibo sulla loro tavola, a mantenere un tetto sopra le loro teste e a ridurre il costo dell'assicurazione sanitaria. Il piano ha anche creato più di 6,5 milioni di nuovi posti di lavoro, il più alto numero di posti di lavoro creati in un anno nella storia degli Stati Uniti. Il Presidente Biden ha anche firmato la legge bipartitica sull'infrastruttura, la più ampia iniziativa di ricostruzione della storia degli Stati Uniti. Il piano prevede di modernizzare le strade, gli aeroporti, i porti e le vie navigabili in"],

'output_text': "\n\nIl Presidente Biden sta lavorando per aiutare le persone che soffrono a causa della pandemia attraverso l'American Rescue Plan e la legge bipartitica sull'infrastruttura. Gli Stati Uniti e i loro alleati stanno anche imponendo sanzioni economiche a Putin e tagliando l'accesso della Russia alla tecnologia. Stanno anche sequestrando yacht, appartamenti di lusso e jet privati di Putin e fornendo più di un miliardo di dollari in assistenza all'Ucraina. Alla fine, Putin non riuscirà a spegnere l'amore dei popoli per la libertà."}

The custom MapReduceChainMulti input prompt你也可以使用多输入的提示。在这个例子中,我们将使用一个MapReduce链来回答关于我们代码的具体问题。from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain

from langchain.chains.combine_documents.stuff import StuffDocumentsChain

map_template_string = """Give the following python code information, generate a description that explains what the code does and also mention the time complexity.

Code:

{code}

Return the the description in the following format:

name of the function: description of the function

"""

reduce_template_string = """Given the following python function names and descriptions, answer the following question

{code_description}

Question: {question}

Answer:

"""

MAP_PROMPT = PromptTemplate(input_variables=["code"], template=map_template_string)

REDUCE_PROMPT = PromptTemplate(input_variables=["code_description", "question"], template=reduce_template_string)

llm = OpenAI()

map_llm_chain = LLMChain(llm=llm, prompt=MAP_PROMPT)

reduce_llm_chain = LLMChain(llm=llm, prompt=REDUCE_PROMPT)

generative_result_reduce_chain = StuffDocumentsChain(

llm_chain=reduce_llm_chain,

document_variable_name="code_description",

)

combine_documents = MapReduceDocumentsChain(

llm_chain=map_llm_chain,

combine_document_chain=generative_result_reduce_chain,

document_variable_name="code",

)

map_reduce = MapReduceChain(

combine_documents_chain=combine_documents,

text_splitter=CharacterTextSplitter(separator="\n##\n", chunk_size=100, chunk_overlap=0),

)

code = """

def bubblesort(list):

for iter_num in range(len(list)-1,0,-1):

for idx in range(iter_num):

if list[idx]>list[idx+1]:

temp = list[idx]

list[idx] = list[idx+1]

list[idx+1] = temp

return list

##

def insertion_sort(InputList):

for i in range(1, len(InputList)):

j = i-1

nxt_element = InputList[i]

while (InputList[j] > nxt_element) and (j >= 0):

InputList[j+1] = InputList[j]

j=j-1

InputList[j+1] = nxt_element

return InputList

##

def shellSort(input_list):

gap = len(input_list) // 2

while gap > 0:

for i in range(gap, len(input_list)):

temp = input_list[i]

j = i

while j >= gap and input_list[j - gap] > temp:

input_list[j] = input_list[j - gap]

j = j-gap

input_list[j] = temp

gap = gap//2

return input_list

"""

map_reduce.run(input_text=code, question="Which function has a better time complexity?")

Created a chunk of size 247, which is longer than the specified 100

Created a chunk of size 267, which is longer than the specified 100

'shellSort has a better time complexity than both bubblesort and insertion_sort, as it has a time complexity of O(n^2), while the other two have a time complexity of O(n^2).'

The refine Chainchain = load_summarize_chain(llm, chain_type="refine")

chain.run(docs)

"\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains. We are joining with our European allies to find and seize the assets of Russian oligarchs, including yachts, luxury apartments, and private jets. The U.S. is also closing off American airspace to all Russian flights, further isolating Russia and adding an additional squeeze on their economy. The U.S. and its allies are providing support to the Ukrainians in their fight for freedom, including military, economic, and humanitarian assistance. The U.S. is also mobilizing ground forces, air squadrons, and ship deployments to protect NATO countries. The U.S. and its allies are also releasing 60 million barrels of oil from reserves around the world, with the U.S. contributing 30 million barrels from its own Strategic Petroleum Reserve. In addition, the U.S. has passed the American Rescue Plan to provide immediate economic relief for tens of millions of Americans, and the Bipartisan Infrastructure Law to rebuild America and create jobs. This investment will"

Intermediate Steps我们还可以返回精炼链的中间步骤,如果我们想检查它们的话。这可以通过return_refine_steps变量来实现。chain = load_summarize_chain(OpenAI(temperature=0), chain_type="refine", return_intermediate_steps=True)

chain({"input_documents": docs}, return_only_outputs=True)

{'refine_steps': [" In response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains.",

"\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains. We are joining with our European allies to find and seize the assets of Russian oligarchs, including yachts, luxury apartments, and private jets. The U.S. is also closing off American airspace to all Russian flights, further isolating Russia and adding an additional squeeze on their economy. The U.S. and its allies are providing support to the Ukrainians in their fight for freedom, including military, economic, and humanitarian assistance. The U.S. is also mobilizing ground forces, air squadrons, and ship deployments to protect NATO countries. The U.S. and its allies are also releasing 60 million barrels of oil from reserves around the world, with the U.S. contributing 30 million barrels from its own Strategic Petroleum Reserve. Putin's war on Ukraine has left Russia weaker and the rest of the world stronger, with the world uniting in support of democracy and peace.",

"\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains. We are joining with our European allies to find and seize the assets of Russian oligarchs, including yachts, luxury apartments, and private jets. The U.S. is also closing off American airspace to all Russian flights, further isolating Russia and adding an additional squeeze on their economy. The U.S. and its allies are providing support to the Ukrainians in their fight for freedom, including military, economic, and humanitarian assistance. The U.S. is also mobilizing ground forces, air squadrons, and ship deployments to protect NATO countries. The U.S. and its allies are also releasing 60 million barrels of oil from reserves around the world, with the U.S. contributing 30 million barrels from its own Strategic Petroleum Reserve. In addition, the U.S. has passed the American Rescue Plan to provide immediate economic relief for tens of millions of Americans, and the Bipartisan Infrastructure Law to rebuild America and create jobs. This includes investing"],

'output_text': "\n\nIn response to Russia's aggression in Ukraine, the United States has united with other freedom-loving nations to impose economic sanctions and hold Putin accountable. The U.S. Department of Justice is also assembling a task force to go after the crimes of Russian oligarchs and seize their ill-gotten gains. We are joining with our European allies to find and seize the assets of Russian oligarchs, including yachts, luxury apartments, and private jets. The U.S. is also closing off American airspace to all Russian flights, further isolating Russia and adding an additional squeeze on their economy. The U.S. and its allies are providing support to the Ukrainians in their fight for freedom, including military, economic, and humanitarian assistance. The U.S. is also mobilizing ground forces, air squadrons, and ship deployments to protect NATO countries. The U.S. and its allies are also releasing 60 million barrels of oil from reserves around the world, with the U.S. contributing 30 million barrels from its own Strategic Petroleum Reserve. In addition, the U.S. has passed the American Rescue Plan to provide immediate economic relief for tens of millions of Americans, and the Bipartisan Infrastructure Law to rebuild America and create jobs. This includes investing"}

Custom Prompts你也可以使用你自己的提示语与这个链条。在这个例子中,我们将用意大利语回答。prompt_template = """Write a concise summary of the following:

{text}

CONCISE SUMMARY IN ITALIAN:"""

PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])

refine_template = (

"Your job is to produce a final summary\n"

"We have provided an existing summary up to a certain point: {existing_answer}\n"

"We have the opportunity to refine the existing summary"

"(only if needed) with some more context below.\n"

"------------\n"

"{text}\n"

"------------\n"

"Given the new context, refine the original summary in Italian"

"If the context isn't useful, return the original summary."

)

refine_prompt = PromptTemplate(

input_variables=["existing_answer", "text"],

template=refine_template,

)

chain = load_summarize_chain(OpenAI(temperature=0), chain_type="refine", return_intermediate_steps=True, question_prompt=PROMPT, refine_prompt=refine_prompt)

chain({"input_documents": docs}, return_only_outputs=True)

{'intermediate_steps': ["\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia e bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi.",

"\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare,",

"\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare."],

'output_text': "\n\nQuesta sera, ci incontriamo come democratici, repubblicani e indipendenti, ma soprattutto come americani. La Russia di Putin ha cercato di scuotere le fondamenta del mondo libero, ma ha sottovalutato la forza della gente ucraina. Insieme ai nostri alleati, stiamo imponendo sanzioni economiche, tagliando l'accesso della Russia alla tecnologia, bloccando i suoi più grandi istituti bancari dal sistema finanziario internazionale e chiudendo lo spazio aereo americano a tutti i voli russi. Il Dipartimento di Giustizia degli Stati Uniti sta anche assemblando una task force dedicata per andare dopo i crimini degli oligarchi russi. Stiamo fornendo più di un miliardo di dollari in assistenza diretta all'Ucraina e fornendo assistenza militare."}

Part7另外的这里包含了各种链,可先了解下,真正用哪个再来看。https://python.langchain.com/docs/modules/chains/additional/Part8总结到此为止,你已经了解了什么是链,并用一些基本的例子加深了你对它的了解。我们可以通过组合不同的链,来完成各种各种的需求。当然,其中还涉及到其它组件相关的一些知识,包括数据的加载和切割,提示的构建等。我们要将目前已经所学到的结合起来,也不用死记硬背,用到什么了解什么。编辑于 2023-06-30 17:22・IP 属地广东LangChain​赞同 17​​2 条评论​分享​喜欢​收藏​申请转载​文章被以下专栏收录langchain记录langchain学习中的相关

langchain学习笔记(2)——Chains - 知乎

langchain学习笔记(2)——Chains - 知乎切换模式写文章登录/注册langchain学习笔记(2)——ChainsCheers学生一、Chains将LLM和Prompts结合在多步骤的工作流中,使用LLMChain 有许多链式搜索的应用程序可以查看哪些最适合您的用例。 下面的连接包含了很多使用chain的应用 https://python.langchain.com/en/latest/modules/chains/how_to_guides.html1.1 简单链## 导入基础库

from langchain.llms import OpenAI

from langchain.chains import LLMChain

from langchain.prompts import PromptTemplate

from langchain.chains import SimpleSequentialChain

llm = OpenAI(temperature=1, openai_api_key=openai_api_key)

## 建立模板

template = '''你的任务是根据用户所提供的地区给出相应的菜肴

% USER LOCATION

{user_location}

你的回复:

'''

prompt_template = PromptTemplate(input_variables=["user_location"], template=template)

# 建立location的chain

location_chain = LLMChain(llm=llm, prompt=prompt_template)

## 接下来获取chain的返回结果输入到下一个chain中

mealtemplate = '''给你一个菜肴,请告诉我如何在家做那道菜,给出具体的步骤来、

% MEAL

{user_meal}

您的回复:

'''

prompt_template = PromptTemplate(input_variables=["user_meal"], template=mealtemplate)

location_chain = LLMChain(llm=llm, prompt=prompt_template)

# 建立meal的chain

meal_chain = LLMChain(llm=llm, prompt=prompt_template)

# 建立简单链

overall_chain = SimpleSequentialChain(chains=[location_chain, meal_chain], verbose=True)

review = overall_chain.run("陕西")代码使用SimpleSequentialChain类创建一个表示任务链的对象。对象接受一个链列表和一个详细参数作为参数。verbose参数是一个布尔值,控制对象是否打印关于链执行的一些信息。如果verbose为True,对象将打印每个链的名称以及每个任务的输入和输出变量。如果verbose为False,对象将不输出任何内容。1.2 总结链很容易运行通过长期大量的文档,并得到一个摘要。检查这个视频的其他链类型除了 map-reduce# 导入基础库

from langchain.chains.summarize import load_summarize_chain

from langchain.document_loaders import TextLoader

from langchain.text_splitter import RecursiveCharacterTextSplitter

# 导入文档

loader = TextLoader('data/PaulGrahamEssays/disc.txt')

documents = loader.load()

# 拆分文档内容

text_splitter = RecursiveCharacterTextSplitter(chunk_size=700, chunk_overlap=50)

texts = text_splitter.split_documents(documents)

# There is a lot of complexity hidden in this one line. I encourage you to check out the video above for more detail

chain = load_summarize_chain(llm, chain_type="map_reduce", verbose=True)

chain.run(texts)1.3 定制链LangChain 提供了很多现成的链接,但是有时候您可能想要为您的特定用例创建一个自定义链接。我们将创建一个自定义链,用于连接2个 LLMChains 的输出。 定制链的步骤 1. Chain 类的子类化,类的方法重写 2. 填写 input _ key 和 output _ key 属性 3. 添加显示如何执行链的 _ call 方法from langchain.chains import LLMChain

from langchain.chains.base import Chain

from typing import Dict, List

class ConcatenateChain(Chain):

chain_1: LLMChain

chain_2: LLMChain

@property

def input_keys(self) -> List[str]:

# 两个input_key的并集

all_input_vars = set(self.chain_1.input_keys).union(set(self.chain_2.input_keys))

return list(all_input_vars)

@property

def output_keys(self) -> List[str]:

return ['concat_output']

def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:

output_1 = self.chain_1.run(inputs)

output_2 = self.chain_2.run(inputs)

return {'concat_output': output_1 + output_2}

prompt_1 = PromptTemplate(

input_variables=["product"],

template="请给我生产 {product} 的公司的名称?",

)

chain_1 = LLMChain(llm=llm, prompt=prompt_1)

prompt_2 = PromptTemplate(

input_variables=["product"],

template="请给我生产制作{product}的公司的口号?",

)

chain_2 = LLMChain(llm=llm, prompt=prompt_2)

## 连接chain

concat_chain = ConcatenateChain(chain_1=chain_1, chain_2=chain_2)

concat_output = concat_chain.run("彩色的袜子")

print(f"Concatenated output:\n{concat_output}") Concatenated output: Rainbow Socks Co. "Step Into Colorful Comfort!"二、集成ChainLLM math,集成python,调用python来进行数学运算,返回相应的结果# 调用LLMMath

from langchain import OpenAI, LLMMathChain

llm = OpenAI(temperature=0)

llm_math = LLMMathChain(llm=llm, verbose=True)

llm_math.run("What is 13 raised to the .3432 power?")结果如下所示> Entering new LLMMathChain chain...

What is 13 raised to the .3432 power?

import math

print(math.pow(13, .3432))

Answer: 2.4116004626599237

> Finished chain.调用python很好的解决了chatgpt较弱的数理能力,上述过程也可以理解为chatgpt的插件模式 以下是一些常见的集成链及其功能。 LLM Math:结合Python解释器完成数据计算 SQLDatabaseChain:集合sqlite数据库完成查询 qa_with_sources:基于多个文档进行问答(底层用到Netwokx) LLMRequestChain:请求指定url查询结果,并用llm解释 PALChain:生成代码并运行得出结果 APIChain:根据api文档生成api请求 networkx是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行复杂网络数据分析、仿真建模等工作。发布于 2023-04-12 10:41・IP 属地上海LangChainGPT-4​赞同 7​​添加评论​分享​喜欢​收藏​申请

chains中文_chains是什么意思

chains中文_chains是什么意思

繁體版

English

Hindi日本語DefinitionIndonesia한국어РусскийไทยViệt

登录 注册

网站工具

设为首页

收藏本站

英语翻译

日语翻译

法语翻译

俄语翻译

韩语翻译

阿拉伯语翻译

印尼语翻译

汉语词典

造句

发音

句子翻译

当前位置:在线翻译 > 英语翻译 > chains

chains中文是什么意思

发音:  用"chains"造句"chains"怎么读"chains" in a sentence"chains"的同义词

中文翻译手机版缝条/链联营企业锁链"chain"中文翻译    n. 1.链子,链条;项圈;表链。 2.连锁;连续,一系 ..."in chains" 中文翻译 :    上着镣铐,在囚禁中; 在囚禁中"in chains bound with chains" 中文翻译 :    用链锁住的"tow chains and safety chains" 中文翻译 :    拖链安全链"alice in chains" 中文翻译 :    艾丽丝囚徒; 牢中艾利斯合唱团"anteisobranched chains" 中文翻译 :    反异支链"antiparallel chains" 中文翻译 :    反向平行链; 逆平行链"automobile chains" 中文翻译 :    汽车链"bad chains" 中文翻译 :    无效的链接"barchan chains" 中文翻译 :    新月形沙丘链"be put in chains" 中文翻译 :    被囚禁"by breaking these chains" 中文翻译 :    冲破这些枷锁"carbon chains" 中文翻译 :    碳链"cattle chains" 中文翻译 :    拴牲畜的链子"chains and rings" 中文翻译 :    链和环"chains certificate" 中文翻译 :    锚链合格证书"chains for dogs" 中文翻译 :    狗用项圈"chains of evidence" 中文翻译 :    证据链"chains of gold" 中文翻译 :    金锁链"chains of honor" 中文翻译 :    荣耀之链"chains of ice" 中文翻译 :    冰之链"chains of islands" 中文翻译 :    岛群"chains of metal" 中文翻译 :    金属铰链"chains of representation" 中文翻译 :    代表的连续性"chains of title" 中文翻译 :    所有权的连续性

例句与用法In a spasm of rapture he tears off his chains .他狂喜之下挣断锁链。More reds now swarmed over the chains .更多的红军蜂拥爬上了铁索。Is there any bend in the seamount chain ?海山链有弯曲的地方吗?Chain is a business that has several outlets .连锁是拥有若干分号的企业。The dog was chained , so how did it get free ?狗拴着,是怎么挣脱开的呢?The chained men sat frozen with terror .铁链锁着的人坐在那里,吓得发呆。The dog is fastened to post by an iron chain .那条狗用铁索拴在柱子上了。She wore a locket hanging on a silver chain .她戴着银项链儿,坠着个挂盒。I was just going out to chain up the dogs .我正打算把狗拴上。I'm chained to my desk in london .我被套在伦敦的办公室里了。更多例句:  1  2  3  4  5用"chains"造句  

英文解释metal shackles; for hands or legs同义词:irons,

其他语种chains in Hindichains 意味chains meaningchains artinyachains 뜻chains переводchainsとは意味{映画} : ストリート?ウォリアーズ/戦え!血の一滴まで◆米1990

相关词汇chain 中文,   chaines 中文,   chained 中文,   chaining 中文,   chainotte 中文,   chainpipe 中文,   chainpump 中文,   chainpur 中文,   chainreactor 中文,   chains (anti-skid ) 中文,   chains and metal accessories 中文,   chains and rings 中文,   chains certificate 中文,   

相邻词汇chainotte 中文chainpipe 中文chainpump 中文chainpur 中文chainreactor 中文chains (anti-skid ) 中文chains and metal accessories 中文chains and rings 中文chains certificate 中文

精彩推荐

这款特殊的“口红”关键时刻能救命!(双语)

男子高铁涉嫌猥亵女儿,警方却终止调查! (双语版)

中秋节祝福语 (中英双语)

chains的中文翻译,chains是什么意思,怎么用汉语翻译chains,chains的中文意思,chains的中文,chains in Chinese,chains的中文,chains怎么读,发音,例句,用法和解释由查查在线词典提供,版权所有违者必究。

英语翻译    日语翻译    法语翻译    韩语翻译    俄语翻译    汉语词典    Hindi

关于查查    联系我们    人才招聘    意见反馈    友情链接

Copyright © 词泰科技有限公司 (京ICP备13021324号) www.ichacha.net All rights reserved

英文学习技巧

1

(双语)这款特殊的“口红”关键时刻能救命!

2

(双语版)男子高铁涉嫌猥亵女儿,警方却终止调查!

3

(中英双语)中秋节祝福语

4

(双语)这一大国居然一条河流都没有,你知道是哪个国家吗?

5

(双语)过年千万别送这10种礼物

6

(双语)昨天,他偷了架飞机,做了件震惊世界的事!

7

(双语)光吃不胖?不是梦!

8

(双语)我们可以长生不老吗?

全文翻译

英语→汉语

汉语→英语

App Store

Android

© WordTech

LangChain大型语言模型(LLM)应用开发(三):Chains - 知乎

LangChain大型语言模型(LLM)应用开发(三):Chains - 知乎切换模式写文章登录/注册LangChain大型语言模型(LLM)应用开发(三):Chains- 派神 -每天进步一点点LangChain是一个基于大语言模型(如ChatGPT)用于构建端到端语言模型应用的 Python 框架。它提供了一套工具、组件和接口,可简化创建由大型语言模型 (LLM) 和聊天模型提供支持的应用程序的过程。LangChain 可以轻松管理与语言模型的交互,将多个组件链接在一起,以便在不同的应用程序中使用。今天我们来学习DeepLearning.AI的在线课程:LangChain for LLM Application Development的第三门课:Chains,该门课程主要讲解LangChain的核心组件:链,即Chain, chain可以将大型语言模型(LLM)和提示语(prompt)结合在一起, 你还可以创建多种不同功能的Chain,然后将这些chain组合在一起,对文本或其他数据执行一系列操作。目录LLMChainSequential Chains SimpleSequentialChain SequentialChainRouter Chain下面我们导入本地环境配置文件.env, 在.env文件中我们存放了opai的api key 。import os

from dotenv import load_dotenv, find_dotenv

_ = load_dotenv(find_dotenv()) # read local .env file接下来我们导入一个csv文件,该文件存放了用户对产品的评论信息。import pandas as pd

df = pd.read_csv('Data.csv')

dfLLMChainLLMChain是最基本的chain,他将LLM和prompt组合在一起,下面我们要实现一个让LLM给生产不同产品的公司取名字的功能:from langchain.chat_models import ChatOpenAI

from langchain.prompts import ChatPromptTemplate

from langchain.chains import LLMChain

#定义大型语言模型

llm = ChatOpenAI(temperature=0.9)

prompt = ChatPromptTemplate.from_template(

"描述生产{product}的公司的一个最佳名称是什么?"

)

#将llm和prompt组合在一起创建一个LLMChain的实例

chain = LLMChain(llm=llm, prompt=prompt)

#执行chain

product = "床上用品"

chain.run(product)这里我们定义llm时使用的温度参数temperature为0.9,该参数的取值范围为0-1,之所以这里要设置为0.9,因为temperature的值越大,那么llm返回结果的随机性就越大,这里我们要实现的功能是给公司取名字的功能,因此我们需要LLM具有较大的灵活性和多样性,所以llm每次返回的结果可能都会不一样,这也就是我们希望llm实现的功能。Sequential ChainsSequential chain 是另一种类型的chain。它可以将多个chain组合在一起,其中前一个chain的输出是后一个chain的输入。SimpleSequentialChainSimpleSequentialChain是最基本的一种Sequential Chains,因为它只有一个输入和一个输出,其中前一个chain的输出为后一个chain的输入,如下图所示:下面我们看个例子,在这个例子中我们除了要执行之前LLMChain的给公司取名的功能外,我们还要需要llm生成20个字左右的公司名称的描述信息,所以,在这里需要创建两个chain, 一个chain负责给公司取名字,另一个chain负责就公司的名字生成20个字左右的描述信息,最后我们需要将这两个chain组合在一起,创建一个新的chain,对于这个新的chain它只有一个输入和一个输出,输入就是公司生产的产品,输出则是对公司名称的20字左右的描述信息。from langchain.chains import SimpleSequentialChain

llm = ChatOpenAI(temperature=0.9)

# prompt template 1

first_prompt = ChatPromptTemplate.from_template(

"描述生产{product}的公司的一个最佳名称是什么?"

)

# Chain 1

chain_one = LLMChain(llm=llm, prompt=first_prompt)

# prompt template 2

second_prompt = ChatPromptTemplate.from_template(

"为以下公司编写 20 个字的描述:{company_name}”"

)

# chain 2

chain_two = LLMChain(llm=llm, prompt=second_prompt)

# 将chain1和chain2组合在一起生成一个新的chain.

overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],

verbose=True

)

#执行新的chain

overall_simple_chain.run(product)

SequentialChainSequentialChain与SimpleSequentialChain的区别在于它可以有多个输入和输出,而SimpleSequentialChain只有一个输入和输出,如下图所示:在下面的例子中我对官方课件的代码做了修改,原来官方的代码只有4个chain, 而我在此基础上增加了一个chain,这样的修改主要是让大家更好的理解该案例中涉及的prompt的含义,原先的prompt使用的都是英语,我都将其翻译成了中文,这样大家就比较能看懂这些prompt了,该案例主要功能是要让llm对前面导入的用户评语进行分析,并给出回复,因为用户的评语可能使用的是多种不同的语言,为此我们需要让chain能够识别用户评语使用的是那种语言,并将其翻译成中文,最后给出回复,具体来说包含以下功能和步骤:将用户评论翻译成中文用一句话概括用户评论识别出用户评论使用的语言按原始评论语言生成回复将回复翻译成中文from langchain.chains import SequentialChain

#定义llm

llm = ChatOpenAI(temperature=0.9)

# prompt template 1: 将评论翻译成中文

first_prompt = ChatPromptTemplate.from_template(

"将下面的评论翻译成中文:"

"\n\n{Review}"

)

# chain 1: input= Review and output= Chinese_Review

chain_one = LLMChain(llm=llm, prompt=first_prompt,

output_key="Chinese_Review"

)

#概括评论

second_prompt = ChatPromptTemplate.from_template(

"你能用 1 句话概括以下评论吗:"

"\n\n{Chinese_Review}"

)

# chain 2: input= Chinese_Review and output= summary

chain_two = LLMChain(llm=llm, prompt=second_prompt,

output_key="summary"

)

# prompt template 3: 识别评论使用的语言

third_prompt = ChatPromptTemplate.from_template(

"下面的评论使用的是什么语言?:\n\n{Review}"

)

# chain 3: input= Review and output= language

chain_three = LLMChain(llm=llm, prompt=third_prompt,

output_key="language"

)

# prompt template 4: 生成回复信息

fourth_prompt = ChatPromptTemplate.from_template(

"使用指定语言编写对以下摘要的后续回复:"

"\n\n摘要:{summary}\n\n语言:{language}"

)

# chain 4: input= summary, language and output= followup_message

chain_four = LLMChain(llm=llm, prompt=fourth_prompt,

output_key="followup_message"

)

# prompt template 5: 将回复信息翻译成中文

five_prompt = ChatPromptTemplate.from_template(

"将下面的评论翻译成中文:"

"\n\n{followup_message}"

)

# chain 5: input= followup_message and output= Chinese_followup_message

chain_five = LLMChain(llm=llm, prompt=five_prompt,

output_key="Chinese_followup_message"

)

# overall_chain: input= Review

# output= language,Chinese_Review,summary, followup_message,

#Chinese_followup_message

overall_chain = SequentialChain(

chains=[chain_one, chain_two, chain_three, chain_four,chain_five],

input_variables=["Review"],

output_variables=["language","Chinese_Review", "summary",

"followup_message","Chinese_followup_message"],

verbose=True

)这里我们看到我们在定义最后的overall_chain 时设置了输入变量和输出变量,因此这些输入和输出变量最后会作为中间结果被输出。下面我们看一下用户的评语:review = df.Review[5]

print(review)接下来我们执行SequentialChain:overall_chain(review) Router Chain有一种应用场景就是我们有时候希望根据信息的内容将其传送到不同的chain,而每个chain的职能是只擅长回答自己所属领域的问题,那么在这种场景下我们就需要一种具有"路由器"功能的chain来将信息传输到不同职能的chain.在下面的例子中,我们有多个不同职能的chain,它们负责回复关于不同学科领域的用户问题,比如数学chain,历史chain,物理chain,计算机chain,每个chain都只擅长回复自己专业领域的问题,这里我们还有一个路由chain, 它的作用是识别用户所提问题属于哪个领域,然后将问题传输给那个领域的chain,让其来完成回答用户问题的功能。下面我们首先定义4个专业领域的prompt模板,在这些模板中我们将告知llm它的职责与定位:physics_template="""你是一位非常聪明的物理学教授。\

你擅长以简洁易懂的方式回答有关物理的问题。 \

当你不知道某个问题的答案时,你就承认你不知道。

这里有一个问题:

{input}"""

math_template="""你是一位非常优秀的数学家。\

你很擅长回答数学问题。 \

你之所以如此出色,是因为你能够将难题分解为各个组成部分,\

回答各个组成部分,然后将它们组合起来回答更广泛的问题。

这里有一个问题:

{input}"""

history_template = """你是一位非常优秀的历史学家。\

你对各个历史时期的人物、事件和背景有深入的了解和理解。 \

你有能力思考、反思、辩论、讨论和评价过去。 \

你尊重历史证据,并有能力利用它来支持你的解释和判断。

这里有一个问题:

{input}"""

computerscience_template="""你是一位成功的计算机科学家。\

你有创造力,协作精神,前瞻性思维,自信,有很强的解决问题的能力,\

对理论和算法的理解,以及出色的沟通能力。\

你很擅长回答编程问题。

你是如此优秀,因为你知道如何通过描述一个机器可以很容易理解的命令步骤来解决问题,\

你知道如何选择一个解决方案,在时间复杂度和空间复杂度之间取得良好的平衡。

这里有一个问题:

{input}"""接下来我们还还需要对这些模板功能进行结构化的解释说明这样便于后面的路由chain能找到它们,为此我们要定义一个模板的索引结构:prompt_infos = [

{

"name": "physics",

"description": "擅长回答有关物理方面的问题",

"prompt_template": physics_template

},

{

"name": "math",

"description": "擅长回答有关数学方面的问题",

"prompt_template": math_template

},

{

"name": "history",

"description": "擅长回答有关历史方面的问题",

"prompt_template": history_template

},

{

"name": "computer science",

"description": "擅长回答有关计算机科学方面的问题",

"prompt_template": computerscience_template

}

]接下来我们还需要定义一个目标chain的集合,所谓的目标chain就是指回答单一领域问题的chai成,它们都是基本的LLMChain:from langchain.chains import LLMChain

from langchain.chains.router import MultiPromptChain

from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser

from langchain.prompts import PromptTemplate

from langchain.prompts import ChatPromptTemplate

from langchain.chat_models import ChatOpenAI

#定义llm

llm = ChatOpenAI(temperature=0)

#创建目标chain

destination_chains = {}

for p_info in prompt_infos:

name = p_info["name"]

prompt_template = p_info["prompt_template"]

prompt = ChatPromptTemplate.from_template(template=prompt_template)

chain = LLMChain(llm=llm, prompt=prompt)

destination_chains[name] = chain

destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]

destinations_str = "\n".join(destinations)

print(destinations_str)这里我们还生成了一个目标字符串destinations_str,它会在后面别嵌入到路由chain的prompt模板中来为定位目标chain提供索引。default_prompt = ChatPromptTemplate.from_template("{input}")

default_chain = LLMChain(llm=llm, prompt=default_prompt)这里我们看到default_prompt 中只包含了一个变量{input},没有包含任何的前缀信息,这是因为default_chain回答的是哪些无法被识别的属于领域的问题,所以这里就让LLM自由发挥了。MULTI_PROMPT_ROUTER_TEMPLATE = """给定一个原始文本输入到\

一个语言模型并且选择最适合输入的模型提示语。\

你将获得可用的提示语的名称以及该提示语最合适的描述。\

如果你认为修改原始输入最终会导致语言模型得到更好的响应,你也可以修改原始输入。

<< FORMATTING >>

返回一个 Markdown 代码片段,其中 JSON 对象的格式如下:

```json

{{{{

"destination": string \ 要使用的提示语的名称或"DEFAULT"

"next_inputs": string \ 原始输入的可能修改版本

}}}}

```

记住:"destination"必须是下面指定的候选提示语中的一种,\

如果输入语句不适合任何候选提示语,则它就是"DEFAULT"。

记住:"next_inputs"可以只是原始输入,如果你认为不需要做任何修改的话。

<< CANDIDATE PROMPTS >>

{destinations}

<< INPUT >>

{{input}}

<< OUTPUT (remember to include the ```json)>>"""这上面的模板里,我们允许LLM修改用户的原始输入,如果修改后的输入能产生更好的输出效果的话,也就是说LLM会先判断是否需要修改用户的prompt,如果觉得有必要修改用户的prompt,那么就会把修改过的prompt传送给后续处理特定领域问题的chain,如果没必要修改,那么就直接把用户的prompt传送给后续的chain。下面还需要在路由prompt模板中嵌入destinations_str,它是为识别领域chain提供索引:router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(

destinations=destinations_str

)

print(router_template)接下来我们要定义最核心的MultiPromptChain,它的三个主要参数为路由chain, 领域chain(集合),默认chain。由这3个主要的参数,我们也能猜测出MultiPromptChain的主要处理逻辑:首先让路由chain来识别用户prompt,并将其传送给特定领域chain,如果没找到合适的领域chain,则由默认chain来处理用户prompt,这里我们给MultiPromptChain的verbose设置为True,这样MultiPromptChain在处理用户prompt的时候会输出一些中间结果,这些中间结果有助于我们观察llm的思维过程是否和我们给它的设定的业务逻辑是一致的。如果不想显示中间结果可以把verbose参数设置为False:router_chain = LLMRouterChain.from_llm(llm, router_prompt)

chain = MultiPromptChain(router_chain=router_chain,

destination_chains=destination_chains,

default_chain=default_chain, verbose=True

)下面我们来设计一些简单的问题,这些问题可能涉及到不同的领域,我们看看llm是怎么来回答用户问题的:response = chain.run("2+2等于几?")

print(response)这里我们可以看到LLM能按照我们的router_template模板内的要求识别出该问题属于"math"领域,然后由该领域的chain来回答这个问题,并最后返回了正确的答案。response = chain.run("成吉思汗是谁?")

print(response)对于“成吉思汗是谁?”这个问题,我们发现LLM对问题进行了修改,它把用户的问题改成了:“成吉思汗是哪个历史时期的重要人物?”,可能是LLM觉得修改后的prompt更有助于后续的领域chain来回答这个问题吧。response = chain.run("什么是黑体辐射?")

print(response)response = chain.run("为什么学习机器学习都要使用python语言?")

print(response)response = chain.run("天上一共有多少颗星星?")

print(response)对于“天上一共有多少颗星星?”这个问题,我们看到LLM并没有识别出来它属于哪个领域,因此它返回的领域值为None, 然后该问题交由默认chain来回答。总结今天我们学习了Langchain的核心组件chain。主要分为LLMChain,Sequential Chains,Router Chain,其中LLMChain是最基本的chain它简单的组合了LLM和promt, Sequential Chains主要包含SimpleSequentialChain和SequentialChain,对于SimpleSequentialChain来说它只是简单的将多个LLMChain串联在一起,前一个chain的输出是后一个chain的输入,所以总体上来说SimpleSequentialChain只有一个输入和一个输出,而SequentialChain则具体多个输入或输出。而Router Chain则是具有路由功能的chain ,它可以将用户的问题进行分类,从而将问题传递给特定的chain。参考资料https://learn.deeplearning.ai/langchain/lesson/4/chains发布于 2023-07-06 15:38・IP 属地上海应用开发LLM#ChatGPT​赞同 7​​添加评论​分享​喜欢​收藏​申请

CHAIN | English meaning - Cambridge Dictionary

CHAIN | English meaning - Cambridge Dictionary

Dictionary

Translate

Grammar

Thesaurus

+Plus

Cambridge Dictionary +Plus

Shop

Cambridge Dictionary +Plus

My profile

+Plus help

Log out

Cambridge Dictionary +Plus

My profile

+Plus help

Log out

Log in

/

Sign up

English (UK)

Search

Search

English

Meaning of chain in English

chainnoun uk

Your browser doesn't support HTML5 audio

/tʃeɪn/ us

Your browser doesn't support HTML5 audio

/tʃeɪn/

chain noun

(CONNECTED THINGS)

Add to word list

Add to word list

[ C ] a series of things of the same type connected in a line, or a series of people standing in a line: The synthetic polymer is a plastic composed of long chains of molecules. As part of the centenary celebrations a chain of beacons was lit across the country. Peace campaigners formed a chain around the military base.

[ C ] a line of connected mountains: The Rockies are a mountain chain in North America. These peaks are all part of the same Himalaya chain.

B2 [ C ] a set of connected events, usually where one causes the next: chain of events His resignation was followed by a remarkable chain of events. In the story, a chain of cause and effect leads us on an emotional journey of two families.break a chain Intervention like this can break the chain of debt and worry.

See also

blockchain

carbon chain

cold chain

food chain

Keychain

supply chain

More examplesFewer examplesVolunteers formed a chain to pass buckets of water along.If just one of the servers on that long chain is out of action, the whole system fails.Fiji is a small nation composed of a chain of islands.Colombia is intersected by three parallel Andean mountain chains.Greece's Peloponnese peninsula has a chain of mountain ranges dominated by Mount Taygetus. This type of attack triggers an unending chain of actions and reactions. The lawyers have to establish a chain of causation by which the specific acts of specific people led to this incident.

SMART Vocabulary: related words and phrases

Things collected in lines or rings

column

crocodile

file

interrow

line

queue

rank

ring

rope

row

single file

string

thread

tier

train

two-tier

You can also find related words, phrases, and synonyms in the topics:

Geography: hills & mountains

Events and occurrences

chain noun

(BUSINESSES)

[ C ] a group of shops, restaurants, hotels, or other businesses owned by the same company : The supermarket chain announced that it was cutting the cost of all its fresh and frozen meat. She has built up a chain of 180 bookshops across the country. I prefer to shop at independent shops rather than chains.

More examplesFewer examplesThey are not only the world's biggest fast-food chain, but also the industry's trendsetter.Jonson has done the whole range of hotel work, from porter to owner of a large chain of hotels.I know it's a chain, but the food is good.

SMART Vocabulary: related words and phrases

Enterprises

acquiree

acquirer

acquiror

agency

agribusiness

answering service

clicks and mortar idiom

conglomerate

consortium

firm

flyer

franchise

franchisee

franchiser

packer

parent company

partner up

partnership

plc

private company

See more results »

chain noun

(RINGS)

A2 [ C or U ] (a length of) rings usually made of metal that are connected together and used for fastening, pulling, supporting, or limiting freedom, or as jewellery: The gates were locked with a padlock and a heavy steel chain. Put the chain on the door if you are alone in the house. Mary was wearing a beautiful silver chain around her neck. See also

key chain

 

PM Images/DigitalVision/GettyImages

 chains

[ plural ] another word for

snow chains : Bear in mind that you can only use chains where snow or ice protects the road surface from damage.

[ plural ] a series of metal rings that are attached to two posts, used in American football to measure the distance between two points on the field : The referees had to bring out the chains to determine if the ball carrier got a first down.

See more  in chains

tied with chains: The hostages were kept in chains for 23 hours a day.

See more

[ plural ] a fact or situation that limits a person's freedom: At last the country has freed itself from the chains of the authoritarian regime.

SMART Vocabulary: related words and phrases

Cords, ropes, cables & string

bell pull

bowline

bungee

cable

catgut

cord

fibre

halter

halyard

harness

landline

lanyard

lariat

lasso

rein

shackles

shock cord

stringed

stringy

tether

See more results »

You can also find related words, phrases, and synonyms in the topics:

Limiting and restricting

chain noun

(HOUSE SALE)

[ C ] UK a situation in which someone selling a house cannot complete the sale because the person who wants to buy it needs to sell their house first: Some sellers refuse to exchange contracts with buyers who are in a chain.

SMART Vocabulary: related words and phrases

Mortgages & real estate

blockbusting

brick

bricks and mortar idiom

BTL

buy-to-let

commercial property

equity

landlady

letting

mortgagee

planning blight

real estate broker

real estate office

Realtor

realty

realty office

refinance

remortgage

repo

repossess

See more results »

Idioms

off the chain

move the chains

chainverb [ T usually + adv/prep ] uk

Your browser doesn't support HTML5 audio

/tʃeɪn/ us

Your browser doesn't support HTML5 audio

/tʃeɪn/

chain verb [T usually + adv/prep]

(PUT IN CHAINS)

to fasten someone or something using a chain: chain something up It's so cruel to keep a pony chained up like that all the time.chain someone/something/yourself to something They chained themselves to lampposts in protest at the judge's decision.

SMART Vocabulary: related words and phrases

Fastening and tying

be locked together idiom

belay

bind

board something up

bound

bowline

clamp

gag

half hitch

harness

hobble

hogtie

knotted

stake

strap

strap someone in

strap something up

strop

tack

tape something up

See more results »

chain verb [T usually + adv/prep]

(LINK)

[ often passive ] (also chain together) to join objects together so that they form one long connected object: The beads are chained together in 7-foot lengths. He succeeded in chaining together a long string of synthetic genes to re-create a portion of the DNA of a simple bacterium.

[ often passive ] (also chain together) to connect things so that they happen together, one after another: The system allows you to send individual commands or chain them together. These filters can be chained to each other to create sequences of filters.be chained with The second operation may be chained with the first operation, or performed separately.

More examplesFewer examplesUSB allows all your devices such as a keyboard, mouse, printer, etc. to be chained together and connected to a single USB port.The frames are containers for text that can be chained together to contain a single story. Make subtle changes to parts of the drum sequence by altering positions and rhythms, and chain them in a random order.The team managed to chain together some magical passages of play.

SMART Vocabulary: related words and phrases

Connecting and combining

abut

additive

adjoin

affix something to something

agglomerate

converge

convergence

cor

couple something together

couple something with something

isthmic

jointed

junction

kludge

knit

unify

unintegrated

union

unseparated

wad

See more results »

You can also find related words, phrases, and synonyms in the topics:

Linking and relating

Phrasal verb

chain someone to something

(Definition of chain from the Cambridge Advanced Learner's Dictionary & Thesaurus © Cambridge University Press)

chain | American Dictionary

chainnoun [ C ] us

Your browser doesn't support HTML5 audio

/tʃeɪn/

chain noun [C]

(CONNECTED RINGS)

Add to word list

Add to word list

a length of metal rings that are connected together and used for fastening or supporting, and in machinery: She looped the chain around her bike and locked it to the fence.

A chain is also a length of connected rings worn as jewelry: Mary wore a silver chain around her neck.

chain noun [C]

(RELATED THINGS)

a set of connected or related things: a mountain chain a chain of supermarkets That set in motion a chain of events that changed her life forever.

chainverb [ T ] us

Your browser doesn't support HTML5 audio

/tʃeɪn/

chain verb [T]

(ATTACH)

to tie or connect together with a chain: An old bicycle was chained to a post near the front door.

If you are chained to something, you work for long periods with it: I had no intention of spending my day chained to the stove.

(Definition of chain from the Cambridge Academic Content Dictionary © Cambridge University Press)

chain | Business English

chainnoun [ C ] uk

Your browser doesn't support HTML5 audio

/tʃeɪn/ us

Your browser doesn't support HTML5 audio

Add to word list

Add to word list

COMMERCE a group of similar businesses, such as restaurants or hotels, which are all owned and controlled by the same organization: hotel/supermarket/fast-food chain The well-known fast-food chain has expanded to over 20,000 restaurants in 17 countries. chain restaurants/stores/retailers a chain of supermarkets/bookstores/department stores

a system of people, processes, or organizations that work together in a particular order: This unit examines the stages in the chain of production of tea, from the leaves in Sri Lanka to the cup in the UK.chain of command/power/authority Employee complaints were taken all the way up the corporate chain of command.

PROPERTY

  UK a situation in which someone cannot complete the sale of their house because the person who wants to buy it needs to sell their house first: Some house sellers refuse to exchange contracts with buyers who are in a chain

See also

distribution chain

production chain

supply chain

value chain

(Definition of chain from the Cambridge Business English Dictionary © Cambridge University Press)

Examples of chain

chain

Text that is no longer spoken by a mouth to be heard by an ear marks one of the limits of the theory of chains.

From the Cambridge English Corpus

He would put an end to "damnations" with the promise of a decade in chains.

From the Cambridge English Corpus

I shall first do my best to link together the chains of this argument.

From the Cambridge English Corpus

Here the amplified beams of both chains are superposed automatically due to the optical properties of the phase conjugated signal.

From the Cambridge English Corpus

By using "these powerladen exotics" as gifts, core elites could create patron- client chains similar to the compadre networks referred to earlier.

From the Cambridge English Corpus

Now, having this in mind, we may consider the maximal chains of consecutively overlapping truly maximal subwords of u having the k-factorization property.

From the Cambridge English Corpus

The high degree of heterogeneity means indistinguishable strains are likely to represent chains of recent transmission [5].

From the Cambridge English Corpus

One such application area is the coordination of production and distribution in supply chains.

From the Cambridge English Corpus

Arguments can be chained by regarding data also as claims, for which further data can be provided.

From the Cambridge English Corpus

Cyanopolyynes: carbon chains formation in a carbon arc mimicking the formation of carbon chains in the circumstellar medium.

From the Cambridge English Corpus

The aliphatic content indicates the presence of longer or less branched aliphatic chains that those observed in the interstellar medium.

From the Cambridge English Corpus

In (15a) who satisfies the wh-criterion (which is now stated in terms of chains).

From the Cambridge English Corpus

In (10) and (11) (see next section), pronounced positions of the derivational chains are indicated by italicization.

From the Cambridge English Corpus

If my feet are in chains, my heart is free.

From the Cambridge English Corpus

A subset of a pointed cpo is admissible if it is pointed and closed under sups of chains.

From the Cambridge English Corpus

See all examples of chain

These examples are from corpora and from sources on the web. Any opinions in the examples do not represent the opinion of the Cambridge Dictionary editors or of Cambridge University Press or its licensors.

Collocations with chain

chain

These are words often used in combination with chain.Click on a collocation to see more examples of it.

bicycle chainLet us take the illustration of the young man who used the bicycle chain.

From the Hansard archive

Example from the Hansard archive. Contains Parliamentary information licensed under the Open Parliament Licence v3.0

 

broken chainTherefore, it is necessary to involve the state, the education system and the social services to restore this broken chain.

From the Hansard archive

Example from the Hansard archive. Contains Parliamentary information licensed under the Open Parliament Licence v3.0

 

causal chainNote that if either of these perspectives is taken, the causal chain has effectively been shortened and has acquired new beginning and end points.

From the Cambridge English Corpus  

These examples are from corpora and from sources on the web. Any opinions in the examples do not represent the opinion of the Cambridge Dictionary editors or of Cambridge University Press or its licensors.

See all collocations with chain

What is the pronunciation of chain?

 

B2,A2

Translations of chain

in Chinese (Traditional)

有聯繫的事, 一連串,一系列(的事物), 鏈條…

See more

in Chinese (Simplified)

有联系的事, 一连串,一系列(的事物), 链条…

See more

in Spanish

cadena, encadenar, cadena [feminine]…

See more

in Portuguese

série (de acontecimentos), cadeia, corrente…

See more

in more languages

in Marathi

in Japanese

in Turkish

in French

in Catalan

in Dutch

in Tamil

in Hindi

in Gujarati

in Danish

in Swedish

in Malay

in German

in Norwegian

in Urdu

in Ukrainian

in Russian

in Telugu

in Arabic

in Bengali

in Czech

in Indonesian

in Thai

in Vietnamese

in Polish

in Korean

in Italian

साखळी…

See more

鎖, チェーン, (レストラン、店の)チェーン…

See more

zincir, halka, mağazalar/lokantalar zinciri…

See more

chaîne [feminine], série [feminine], suite [feminine]…

See more

cadena, sèrie, encadenar…

See more

ketting, reeks, ketenen…

See more

இணைக்கப்பட்ட அல்லது தொடர்புடைய விஷயங்களின் தொகுப்பு, (ஒரு நீளம்) மோதிரங்கள் பொதுவாக உலோகத்தால் ஆனது, அவை ஒன்றாக இணைக்கப்பட்டு கட்டுதல்…

See more

श्रृंखला, सिलसिला, ज़ंजीर…

See more

ચેન, શ્રેણી, સિલસિલો…

See more

kæde, lænke, række…

See more

kedja, kätting, följd…

See more

rantai, rentetan, merantaikan…

See more

die Kette, anketten…

See more

lenke [masculine], kjetting [masculine], kjede [masculine]…

See more

لمبا سلسلہ, کسی بھی چیز کا وسیع دائرہ, متعلقہ واقعات کا سلسلہ…

See more

ланцюг, цеп, ланцюжок…

See more

цепь, сеть, прикреплять цепью…

See more

ముడివడి ఉన్న లేక పరస్పర సంబంధం ఉన్న వస్తువుల వర్గం/ శ్రేణి/వరుస, గొలుసు/సంకెల…

See more

سِلْسِلة, يُكَبّل, يُقَيّد…

See more

একই মালিকানায় একাধিক ব্যবসায়িক সংস্থা, শিকল, শৃঙ্খল…

See more

řetěz, řetízek, uvázat na řetěz…

See more

rantai, rangkaian, merantai…

See more

โซ่, เหตุการณ์ที่เกิดต่อเนื่องกัน, ล่ามโซ่…

See more

dây xích, chuỗi, xích lại…

See more

łańcuch, łańcuszek, sieć…

See more

체인, 사슬, 체인점…

See more

catena, incatenare, serie…

See more

Need a translator?

Get a quick, free translation!

Translator tool

 

Browse

Chagas disease

chagrin

chagrined

chai

chain

chain drive

BETA

chain gang

chain letter

chain mail

More meanings of chain

All

chain of command

chain reaction

chain saw

food chain

key chain

chain drive

chain gang

See all meanings

Phrasal Verbs

chain someone to something

See all phrasal verb meanings

Idioms and phrases

off the chain idiom

Word of the Day

flexitarian

A flexitarian way of eating consists mainly of vegetarian food but with some meat.

About this

Blog

Forget doing it or forget to do it? Avoiding common mistakes with verb patterns (2)

March 06, 2024

Read More

New Words

stochastic parrot

March 04, 2024

More new words

has been added to list

To top

Contents

EnglishAmericanBusinessExamplesCollocationsTranslations

© Cambridge University Press & Assessment 2024

Learn

Learn

Learn

New Words

Help

In Print

Word of the Year 2021

Word of the Year 2022

Word of the Year 2023

Develop

Develop

Develop

Dictionary API

Double-Click Lookup

Search Widgets

License Data

About

About

About

Accessibility

Cambridge English

Cambridge University Press & Assessment

Consent Management

Cookies and Privacy

Corpus

Terms of Use

© Cambridge University Press & Assessment 2024

Cambridge Dictionary +Plus

My profile

+Plus help

Log out

Dictionary

Definitions

Clear explanations of natural written and spoken English

English

Learner’s Dictionary

Essential British English

Essential American English

Translations

Click on the arrows to change the translation direction.

Bilingual Dictionaries

English–Chinese (Simplified)

Chinese (Simplified)–English

English–Chinese (Traditional)

Chinese (Traditional)–English

English–Dutch

Dutch–English

English–French

French–English

English–German

German–English

English–Indonesian

Indonesian–English

English–Italian

Italian–English

English–Japanese

Japanese–English

English–Norwegian

Norwegian–English

English–Polish

Polish–English

English–Portuguese

Portuguese–English

English–Spanish

Spanish–English

English–Swedish

Swedish–English

Semi-bilingual Dictionaries

English–Arabic

English–Bengali

English–Catalan

English–Czech

English–Danish

English–Gujarati

English–Hindi

English–Korean

English–Malay

English–Marathi

English–Russian

English–Tamil

English–Telugu

English–Thai

English–Turkish

English–Ukrainian

English–Urdu

English–Vietnamese

Translate

Grammar

Thesaurus

Pronunciation

Cambridge Dictionary +Plus

Shop

Cambridge Dictionary +Plus

My profile

+Plus help

Log out

Log in /

Sign up

English (UK)  

Change

English (UK)

English (US)

Español

Русский

Português

Deutsch

Français

Italiano

中文 (简体)

正體中文 (繁體)

Polski

한국어

Türkçe

日本語

Tiếng Việt

Nederlands

Svenska

Dansk

Norsk

हिंदी

বাঙ্গালি

मराठी

ગુજરાતી

தமிழ்

తెలుగు

Українська

Follow us

Choose a dictionary

Recent and Recommended

Definitions

Clear explanations of natural written and spoken English

English

Learner’s Dictionary

Essential British English

Essential American English

Grammar and thesaurus

Usage explanations of natural written and spoken English

Grammar

Thesaurus

Pronunciation

British and American pronunciations with audio

English Pronunciation

Translation

Click on the arrows to change the translation direction.

Bilingual Dictionaries

English–Chinese (Simplified)

Chinese (Simplified)–English

English–Chinese (Traditional)

Chinese (Traditional)–English

English–Dutch

Dutch–English

English–French

French–English

English–German

German–English

English–Indonesian

Indonesian–English

English–Italian

Italian–English

English–Japanese

Japanese–English

English–Norwegian

Norwegian–English

English–Polish

Polish–English

English–Portuguese

Portuguese–English

English–Spanish

Spanish–English

English–Swedish

Swedish–English

Semi-bilingual Dictionaries

English–Arabic

English–Bengali

English–Catalan

English–Czech

English–Danish

English–Gujarati

English–Hindi

English–Korean

English–Malay

English–Marathi

English–Russian

English–Tamil

English–Telugu

English–Thai

English–Turkish

English–Ukrainian

English–Urdu

English–Vietnamese

Dictionary +Plus

Word Lists

Choose your language

English (UK)  

English (US)

Español

Русский

Português

Deutsch

Français

Italiano

中文 (简体)

正體中文 (繁體)

Polski

한국어

Türkçe

日本語

Tiếng Việt

Nederlands

Svenska

Dansk

Norsk

हिंदी

বাঙ্গালি

मराठी

ગુજરાતી

தமிழ்

తెలుగు

Українська

Contents

English 

 

Noun 

chain (CONNECTED THINGS)

chain (BUSINESSES)

chain (RINGS)

chains

in chains

chain (HOUSE SALE)

Verb 

chain (PUT IN CHAINS)

chain (LINK)

American 

 

Noun 

chain (CONNECTED RINGS)

chain (RELATED THINGS)

Verb 

chain (ATTACH)

Business 

 Noun

Examples

Collocations

Translations

Grammar

All translations

My word lists

Add chain to one of your lists below, or create a new one.

More

Go to your word lists

Tell us about this example sentence:

The word in the example sentence does not match the entry word.

The sentence contains offensive content.

Cancel

Submit

The word in the example sentence does not match the entry word.

The sentence contains offensive content.

Cancel

Submit

Necklace Chains and Chain Jewelry | Tiffany & Co.

Necklace Chains and Chain Jewelry | Tiffany & Co.

BannerItem 1

Introducing our first exhibition at The Landmark, brought to life in partnership with Peter Marino. Book now.

center

BannerItem 2

Find the perfect gift within our selection under $1,500. Shop now.

center

BannerItem 3

Enjoy complimentary shipping and returns on all orders. Shop now.

center

Purchases made on this site will ship to U.S. addresses only. Do you want to shop the U.S. site?

Shop the U.S. site

Or

Choose location

Americas

United States

Canada (English)

Canada (Francais)

México

Brazil

Europe & Middle East

United Kingdom

Austria

Belgium

France

Deutschland

Ireland

Italy

Netherlands

España

Россия

United Arab Emirates (UAE)

Asia / Pacific

日本

中国大陆

香港/澳門特別行政區

台灣

India

한국

Australia

Malaysia

Singapore

All Other Locations

International

Contact us

Jewelry

Shop by Category

Necklaces & Pendants

Earrings

Bracelets

Rings

Fine Watches

Brooches

Men's Jewelry

Explore All Categories

Curated Shops

Gifts for Her

Most Popular Jewelry

New Jewelry

High Jewelry

Bold Silver Jewelry

Dainty Jewelry

Hoop Earrings

Stacking Rings

Shop by Metal

Gold Jewelry

Rose Gold Jewelry

Platinum Jewelry

Sterling Silver Jewelry

Shop by Gemstone

Diamond Jewelry

Pearl Jewelry

Aquamarine Jewelry

Colored Gemstone Jewelry

Featured Collections

Tiffany Lock

Tiffany T

Tiffany HardWear

Tiffany Knot

Jean Schlumberger by Tiffany

Tiffany Victoria®

Return to Tiffany®

Elsa Peretti®

Paloma Picasso®

Explore All Collections

Gifts

Gifts for...

Her

Him

Baby

The Home

The Couple

Explore All Gifts

Discover

Gifts $1,500 & Under

Online Exclusives

Tiffany Blue® Gifts

Gifts to Personalize

Wedding Gifts

Anniversary Gifts

Birthday Gifts

Business Gifts

Gifts for Her

Shop Now

Love & Engagement

Engagement

Engagement Rings

Men’s Engagement Rings

Book an Appointment

Wedding

Women's Wedding Bands

Men's Wedding Bands

Wedding Band Sets

Couples' Rings

Begin Your Journey

The Tiffany Difference

The Guide to Diamonds

A Lifetime of Service

A Tiffany Ring

Responsible Sourcing

How to Choose an Engagement Ring

How to Choose a Wedding Band

Shop by Shape

Round

Oval

Emerald

Princess

Tiffany True®

Cushion

Shop by Setting

Solitaire

Halo

Three Stone

Engagement Ring Collections

The Tiffany® Setting

Tiffany True®

Tiffany Harmony®

Tiffany Soleste®

Tiffany Novo®

Jean Schlumberger by Tiffany

Wedding Band Collections

Tiffany Together

Tiffany Forever

T&CO.®

Fine Watches

Shop By Category

Women’s Watches

Men’s Watches

Patek Philippe

All Fine Watches

Curated Shops

Diamond Watches

Tiffany Blue Watches

Explore Fine Watches

Shop By Collection

Atlas®

Tiffany 1837® Makers

Tiffany Eternity

Tiffany CT60®

Tiffany East West®

It's About Time

Shop All Fine Watches

Home & Accessories

For the Table

Tableware

Glassware & Barware

Flatware & Trays

Coffee & Tea

For the Home

Decor

Blankets & Cushions

Baby

Candles

Explore All Home

Leather Goods

Bags

Small Leather Goods

Accessories

Scarves & Stoles

Belts

Sunglasses

Stationery, Games & Unique Objects

Key Rings

Explore All Leather Goods & Accessories

Curated Shops

Women's Accessories

Table by Tiffany

Wedding Gifts

Housewarming Gifts

Elsa Peretti Home

Table Linens

A House Icon, Re-envisioned

Shop New Eyewear

Fragrance

Shop by Collection

Tiffany Rose Gold

Tiffany Signature

Tiffany & Love

Shop All Fragrance

Discover Our Scents

Fragrance Gifts

Shop Now

Men’s

Shop by Category

Necklaces & Pendants

Bracelets

Rings

Accessories

Watches

Bar & Drinkware

Games & Novelties

Explore All Men's

Discover

Gifts for Him

Men's Engagement Rings

Tiffany & Sports

The Modern Man's Guide to Wearing Jewelry

For the Modern Man

Shop Men's Jewelry

Stories

Now Trending

Bird on a Rock

Blue Book: Out of the Blue

The Landmark

Discover Tiffany Lock

Table by Tiffany

The Return to Tiffany® x Beyoncé Collection

View All Stories

The House of Tiffany & Co.

The World of Tiffany

High Jewelry

The Tiffany Diamond

Tiffany & Sports

Jewelry Design and Innovation Workshop

Sustainability

Our Diamond Traceability Story

A House Icon: The Jean Schlumberger by Tiffany Bird on a Rock

Discover Now

Jewelry

Jewelry

Shop by Category

Necklaces & Pendants

Earrings

Bracelets

Rings

Fine Watches

Brooches

Men's Jewelry

Explore All Categories

Curated Shops

Gifts for Her

Most Popular Jewelry

New Jewelry

High Jewelry

Bold Silver Jewelry

Dainty Jewelry

Hoop Earrings

Stacking Rings

Shop by Metal

Gold Jewelry

Rose Gold Jewelry

Platinum Jewelry

Sterling Silver Jewelry

Shop by Gemstone

Diamond Jewelry

Pearl Jewelry

Aquamarine Jewelry

Colored Gemstone Jewelry

Featured Collections

Tiffany Lock

Tiffany T

Tiffany HardWear

Tiffany Knot

Jean Schlumberger by Tiffany

Tiffany Victoria®

Return to Tiffany®

Elsa Peretti®

Paloma Picasso®

Explore All Collections

Necklaces & Pendants

Shop Now

Gifts

Gifts

Gifts for...

Her

Him

Baby

The Home

The Couple

Explore All Gifts

Discover

Gifts $1,500 & Under

Online Exclusives

Tiffany Blue® Gifts

Gifts to Personalize

Wedding Gifts

Anniversary Gifts

Birthday Gifts

Business Gifts

Gifts for Her

Shop Now

Love & Engagement

Love & Engagement

Engagement

Engagement Rings

Men’s Engagement Rings

Book an Appointment

Wedding

Women's Wedding Bands

Men's Wedding Bands

Wedding Band Sets

Couples' Rings

Begin Your Journey

The Tiffany Difference

The Guide to Diamonds

A Lifetime of Service

A Tiffany Ring

Responsible Sourcing

How to Choose an Engagement Ring

How to Choose a Wedding Band

Shop by Shape

Round

Oval

Emerald

Princess

Tiffany True®

Cushion

Shop by Setting

Solitaire

Halo

Three Stone

Engagement Ring Collections

The Tiffany® Setting

Tiffany True®

Tiffany Harmony®

Tiffany Soleste®

Tiffany Novo®

Jean Schlumberger by Tiffany

Wedding Band Collections

Tiffany Together

Tiffany Forever

T&CO.®

About Love

Explore Love & Engagement

Fine Watches

Fine Watches

Shop By Category

Women’s Watches

Men’s Watches

Patek Philippe

All Fine Watches

Curated Shops

Diamond Watches

Tiffany Blue Watches

Explore Fine Watches

Shop By Collection

Atlas®

Tiffany 1837® Makers

Tiffany Eternity

Tiffany CT60®

Tiffany East West®

It's About Time

Shop All Fine Watches

Home & Accessories

Home & Accessories

For the Table

Tableware

Glassware & Barware

Flatware & Trays

Coffee & Tea

For the Home

Decor

Blankets & Cushions

Baby

Candles

Explore All Home

Leather Goods

Bags

Small Leather Goods

Accessories

Scarves & Stoles

Belts

Sunglasses

Stationery, Games & Unique Objects

Key Rings

Explore All Leather Goods & Accessories

Curated Shops

Women's Accessories

Table by Tiffany

Wedding Gifts

Housewarming Gifts

Elsa Peretti Home

Table Linens

A House Icon, Re-envisioned

Shop New Eyewear

Fragrance

Fragrance

Shop by Collection

Tiffany Rose Gold

Tiffany Signature

Tiffany & Love

Shop All Fragrance

Discover Our Scents

Fragrance Gifts

Shop Now

Men’s

Men’s

Shop by Category

Necklaces & Pendants

Bracelets

Rings

Accessories

Watches

Bar & Drinkware

Games & Novelties

Explore All Men's

Discover

Gifts for Him

Men's Engagement Rings

Tiffany & Sports

The Modern Man's Guide to Wearing Jewelry

For the Modern Man

Shop Men's Jewelry

Stories

Stories

Now Trending

Bird on a Rock

Blue Book: Out of the Blue

The Landmark

Discover Tiffany Lock

Table by Tiffany

The Return to Tiffany® x Beyoncé Collection

View All Stories

The House of Tiffany & Co.

The World of Tiffany

High Jewelry

The Tiffany Diamond

Tiffany & Sports

Jewelry Design and Innovation Workshop

Sustainability

Our Diamond Traceability Story

A House Icon: The Jean Schlumberger by Tiffany Bird on a Rock

Discover Now

Contact us

Book an Appointment

My Account

Store Locator

Chain Necklaces

Whether worn solo or layered together, chains are a jewelry must-have. Discover yellow gold chains, rose gold chains and sterling silver chains.

Home

Designer Jewelry

Chain Necklaces

Unable to complete your search.

 

Please try again, or call 800 843 3269.

Filter By

Materials

Gold

Platinum

Rose Gold

Sterling Silver

White Gold

Gemstones

Diamonds

No Gemstones

Pearls

Designers & Collections

Elsa Peretti®

Tiffany 1837®

Return to Tiffany®

Tiffany HardWear

Tiffany Forge

Categories

Jewelry

Price Ranges

$1,000 - $2,000

$2,000 - $5,000

$5,000 & Over

$500 & Under

$500 - $1,000

Unmapped Categories

Shop All Necklaces & Pendants

Browse more in Necklaces & Pendants

Sterling Silver Chains with Diamonds

Sterling Silver Chains with Pearls

Bold Necklaces

Layering Necklaces

Everyday Diamond Necklaces

Chain Necklaces and Cords

A showcase for the House’s legendary craftsmanship, our collection of chain necklaces stands out for its exceptional attention to detail. Discover small and medium link designs that can be stylishly layered or paired with charms, or large link necklaces that are a sculptural statement on their own. For timeless style, add one of our unique sterling silver or 18k gold chain necklaces to your jewelry box, thoughtfully made by Tiffany artisans. Our short and long chain necklaces feature a variety of classic link styles, such as beaded chains, graduated links and curb chains. Looking for a bold statement? Our signature gauge link necklace inspired by the energy and architecture of New York City, crafted with or without our legendary diamonds, is a timeless piece to wear for years to come. Try a double wrap link necklace for a striking statement or a chain necklace with pearls for a modern take on a classic design.

Shop Long Necklaces

Shop Layering Necklaces

Shop Chain Bracelets

Sign out of Sales Service Mode

Client Care

Contact Us

Product Care & Repair

Track Your Order

Book an Appointment

Frequently Asked Questions

Gift Cards

Sign up for Tiffany Emails

Website Accessibility

Our Company

World of Tiffany

Sustainability

California Privacy

Tiffany Careers

Website Policies

Do Not Sell or Share My Info

Opt-Out of Targeted Advertising

Related Tiffany Sites

Wedding & Gift Registry

Business Accounts

Tiffany for the Press

The Tiffany & Co. Foundation

Tiffany Alertline

Site Index

Client Care

Contact Us

Track Your Order

Product Care & Repair

Book an Appointment

Frequently Asked Questions

Gift Cards

Website Accessibility

Our Company

World of Tiffany

Sustainability

California Privacy

Tiffany Careers

Website Policies

Do Not Sell or Share My Personal Information

Opt-Out of Targeted Advertising

Related Tiffany Sites

Wedding & Gift Registry

Business Accounts

Tiffany for the Press

The Tiffany & Co. Foundation

Tiffany Alertline

Site Index

Latest from Tiffany

Be the first to know about exciting new designs, special events, store openings and much more.

Email

Sign up

Change Location: United States

Americas

United States

Canada (English)

Canada (Français)

Mexico

Brazil

Europe & Middle East

United Kingdom

Austria

Belgium

France

Deutschland

Ireland

Italia

Netherlands

España

Россия

United Arab Emirates (UAE)

Asia/Pacific

中国大陆

日本

香港/澳門特別行政區

台湾

한국

Australia

India

Malaysia

Singapore

All other locations

International

© T&CO. 2024

© T&CO. 2024

in chains是什么意思_in chains的翻译_音标_读音_用法_例句_爱词霸在线词典

hains是什么意思_in chains的翻译_音标_读音_用法_例句_爱词霸在线词典首页翻译背单词写作校对词霸下载用户反馈专栏平台登录in chains是什么意思_in chains用英语怎么说_in chains的翻译_in chains翻译成_in chains的中文意思_in chains怎么读,in chains的读音,in chains的用法,in chains的例句翻译人工翻译试试人工翻译翻译全文in chains英 释义adv.在囚禁中点击 人工翻译,了解更多 人工释义实用场景例句全部The prisoners are in chains.囚犯上了镣铐.《现代英汉综合大词典》They were brought to the police station in chains.他们被戴上手铐,送往警察局.辞典例句Magellan also put more than 30 other mutineers, including several noblemen, in chains, working hard labour.麦哲伦还镇压了30多名反叛者, 包括几个贵族, 让他们带上镣铐干苦力.英汉非文学 - 文明史Last night we were put in chains , creating a precedent for political prisoners.并于昨夜上了镣, 开政治犯从未上镣之纪录.汉英文学 - 现代散文Born a free man, he was now in chains.他生来本是个自由人, 现在却戴上镣铐.互联网Man was born free, and everywhere he is in chains.人是生而自由的, 却处处受到束缚.互联网Greed eventually let to his becoming a criminal covered in chains.贪婪终于使他沦为了披枷戴锁的罪犯.互联网The captured criminals were paraded in chains through the streets.抓获的罪犯带着镣铐列队游街示众.互联网I must be put in chains. Must I then also lament?我一定会被拴上锁链的. 我也必定要哀怨 吗 ?互联网Homer tells us also that Sisyphus had put Death in chains.荷马也告诉我们,西西弗斯曾一度给死神套上了镣铐.互联网We hanged Bruce in chains for a show.我们把布鲁斯置于铁枷之中示众.互联网The conqueror rode in a triumphal chariot, the dazed prisoners walking in chains before him.凯旋将领乘坐战车, 面色茫然的囚徒用铁链禁锢着走在前面.互联网Gathered nobility filled the Great Hall, where Ryel knelt in chains at his brother's feet.贵族们都聚集在大厅里, Ryel身上挂着枷锁,跪在他弟弟的脚下.互联网In the Tower of London, prisoners used to languish in chains, cold, and darkness.过去, 在伦敦塔里的囚犯受到镣铐 、 寒冷和阴暗的折磨.互联网We live our lives in chains and we never even know we have the key.我们被锁链,锁链束缚,却从来不知道钥匙在自己手中.互联网收起实用场景例句英英释义Adjective1. bound with chains;"enchained demons strained in anger to gnaw on his bones""prisoners in chains"收起英英释义释义实用场景例句英