ReAct: Treating Thought as an Action So a Language Model Can Reason and Act in One Trace
ReAct भाषा मॉडल को 'सोच' को भी एक क्रिया बना देता है: सोच, क्रिया, अवलोकन की बारी-बारी ट्रेस में तर्क करते हुए search व lookup बुलाता है — केवल 1 से 6 examples, पैरामीटर नहीं बदले। यह लेख paper की तालिकाएँ पुनर्गणना करता है और नकली विकी पर Qwen3-4B से चार prompts तुलना करता है।
इस पृष्ठ पर
- यह paper क्यों पढ़ने योग्य है
- पृष्ठभूमि: केवल-तर्क और केवल-क्रिया में क्या कमी
- विधि: ‘सोच’ को एक क्रिया के रूप में
- Action space में एक और खाना
- केवल prompt, पैरामीटर नहीं
- चार कार्य
- Fine-tuning
- Paper के experiments और निष्कर्ष
- ज्ञान-सघन कार्य: HotpotQA और Fever
- निर्णय कार्य: ALFWorld और WebShop
- तालिकाएँ पढ़ते समय ध्यान
- हाथ से जाँच: paper की तालिकाओं की पुनर्गणना
- हाथ का प्रयोग: नकली विकी पर चार prompts
- Experiment design
- नतीजे
- यह प्रयोग क्या बता सकता है, क्या नहीं
- सीमाएँ और आगे की राह
- इस paper में सबसे ज़रूरी बातें
- Further reading
- अक्सर पूछे जाने वाले सवाल
ReAct: Synergizing Reasoning and Acting in Language Models (Yao आदि; Princeton और Google Research; ICLR 2023; आगे ReAct paper) का बदलाव एक वाक्य में लिखा जा सकता है: ‘सोच’ को भी एक क्रिया बना दो। मॉडल हर कदम या tool बुलाता है (क्रिया) या एक खुला टेक्स्ट लिखता है (सोच); सोच बाहरी environment नहीं बदलती, observation नहीं देती, केवल context में जुड़ती है और आगे के तर्क-क्रिया में मदद करती है। ट्रेस इस प्रकार ‘सोच, क्रिया, अवलोकन’ की बारी बन जाती है। Paper ने frozen PaLM-540B को केवल 1–6 मानव-लिखे examples दिए, और QA (HotpotQA, Fever) व अंतःक्रियात्मक निर्णय (ALFWorld, WebShop) दोनों में ‘केवल तर्क’ और ‘केवल क्रिया’ से तुलना की: ALFWorld पर सर्वश्रेष्ठ prompt group की success दर 71%, केवल-क्रिया सर्वश्रेष्ठ 45%, imitation learning वाला BUTLER 37%; WebShop पर success 40.0%, IL 29.1%। पर इस paper का निष्कर्ष “ReAct सब जगह बेहतर” नहीं: HotpotQA पर ReAct (27.4) CoT (29.4) से थोड़ा नीचे; सर्वश्रेष्ठ दोनों का मिश्रण।
इस लेख ने paper समझाने के बाद दो काम किए। जाँच: paper की पाँचों तालिकाएँ script में उतारकर दोहराईं; कथन लगभग खड़े रहे, तीन बातें ध्यान रखनी हैं: तालिका 1 के छोटे अंतरों के error bars नहीं; तालिका 3 की “best of 6” पंक्तियाँ और “overall” column एक पैमाने के नहीं; तालिका 5 व तालिका 1 उसी विधि के लिए 2.0 का अंतर देती हैं। छोटा पुनरुत्पादन: नकली विकी पर Qwen3-4B से चार prompts (72 प्रश्न, दो worlds)। Standard और CoT ने केवल 11 व 9 सही — सब 18 द्विविकल्प तुलनाओं में से, लगभग यादृच्छिक अनुमान; Act 36 सही (50.0%), ReAct 50 सही (69.4%); प्रति-प्रश्न paired sign test p = 0.007। ReAct की बढ़त मुख्यतः Lookup से ही पढ़ी जा सकने वाले उत्तरों वाले प्रश्नों से: ऐसे 37 में ReAct ने 36 पर Lookup उपयोग किया, Act केवल 21 पर। कीमत: प्रति प्रश्न 165.8 नए tokens (Act 49.6), और keyword ग़लत चुन लेने पर दोहराए खोज के चक्र — paper की विफलता विश्लेषण की “reasoning error” और “search result error” यही हैं। 72 प्रश्न, एक 4B मॉडल — केवल दिशा; नीचे जो बताया जा सकता है और जो नहीं, अलग लिखा है।
यह लेख का प्रयोग चीनी संस्करण में चला: नकली विकी के नाम व संवाद चीनी में थे। नीचे कोड और नमूना आउटपुट उसी मूल रन के अंग्रेज़ी अनुवाद हैं — नाम romanized किए गए, सारे संख्याएँ अपरिवर्तित; चीनी संस्करण की original run से ही आँकड़े आए हैं।
यह paper क्यों पढ़ने योग्य है
- आज के लगभग सब Agent loops का न्यूनतम रूप। मॉडल अगला कदम तय करता है, environment चलाकर नतीजा देता है, नतीजा context में, मॉडल फिर तय करता है। बाद के function calling, browser agents, code agents — बदला केवल interface format, चक्र नहीं।
- “सोच क्या करती है” को अलग-अलग मापा। Paper केवल ReAct बनाम बेसलाइन का कुल स्कोर नहीं: सोच हटाई (Act), क्रिया हटाई (CoT), सोच को environment feedback की पुनरावृत्ति से बदला (ReAct-IM); हर तुलना एक ठोस प्रश्न का उत्तर।
- निष्कर्ष एकतरफ़ा नहीं। ReAct HotpotQA में CoT से हारा; लेखकों ने स्वयं विफलता विश्लेषण किया, उसी से hybrid सुझाया। हार मानना और कारण समझाना — सर्वत्र विजय की तालिका से अधिक सूचना।
- इस साइट के पास। Agent engineering विवरण Agents और tool calling में; function calling का format structured output व function calling में; chain-of-thought CoT व्याख्या और Toolformer Toolformer व्याख्या में।
पृष्ठभूमि: केवल-तर्क और केवल-क्रिया में क्या कमी
2022 के शुरू में बड़े मॉडलों के दो उपयोग लगभग अलग राहों पर। एक तर्क: chain-of-thought (CoT) मॉडल को बीच के कदम लिखवाकर उत्तर देता है, गणित व सामान्य ज्ञान में प्रभावी; पर पूरी तरह parameters में याद ज्ञान पर — तथ्य ग़लत याद हुआ तो हर अगला कदम उस ग़लती पर, और लिखा तर्क वैसा ही आत्मविश्वासी दिखता है। दूसरी क्रिया: मॉडल क्रियाओं की शृंखला बनाकर environment चलाए या tools बुलाए — WebGPT browser से उत्तर, SayCan robot planning। इनमें मॉडल सीधे क्रिया देता है; कोई कदम “क्यों, कहाँ तक पहुँचा” नहीं लिखता; स्थिति मॉडल के भीतर अप्रत्यक्ष।
Paper का चित्र 1 दो विफल उदाहरणों से दोनों कमियाँ दिखाता है: केवल-क्रिया मॉडल HotpotQA में तीन search results पढ़कर उन्हें अंतिम Finish में नहीं जोड़ पाया; ALFWorld में उसे “sink 1 में pepper नहीं” समझ नहीं आया, वह वही निष्फल क्रिया दोहराता रहा। दोनों में कमी एक ही: दो क्रियाओं के बीच भाषा में वर्तमान स्थिति सारांशित कर अगला कदम तय करने की क्षमता।
विधि: ‘सोच’ को एक क्रिया के रूप में
Action space में एक और खाना
साधारण agent सेटिंग में कदम पर observation मिलता है, policy से क्रिया चुनते हैं; context अब तक का पूरा इतिहास:
जब “context से क्रिया” का mapping अप्रत्यक्ष हो और पूरे इतिहास पर जटिल तर्क चाहिए, यह policy सीखना कठिन — ऊपर के दोनों विफल उदाहरण वैसे ही। ReAct action space को कर देता है, भाषा की space। में गिरने वाली “क्रिया” ही सोच: environment नहीं बदलती, observation नहीं देती, केवल context में जुड़ती है:
Paper सोच के उपयोग गिनाता है: लक्ष्य खंडित कर योजना, कार्य-संबंधी सामान्य ज्ञान का इंजेक्शन, observations से मुख्य सूचना निकालना, प्रगति दर्ज कर योजना बदलना, असामान्यता सँभालकर योजना समायोजित।
केवल prompt, पैरामीटर नहीं
Paper की मुख्य सेटिंग frozen PaLM-540B: 1–6 मानव-लिखी ट्रेसों के examples, मॉडल उन्हीं की नकल में आगे लिखता है। Examples की सोच annotators की सीधी प्राकृत भाषा; paper ज़ोर देता है — कोई विशेष format, सोच या examples की चयन-प्रक्रिया नहीं। दो प्रयोग शैली: ज्ञान-सघन तर्क कार्यों में सोच व क्रिया कड़ी बारी में (“dense thought”); क्रिया-बहुल निर्णय कार्यों में सोच केवल सबसे निर्णायक स्थानों पर, मॉडल ख़ुद तय करे कब सोचे (“sparse thought”)।
Paper की तुलनित prompts (HotpotQA व Fever के विवरण):
| Prompt | ट्रेस में क्या |
|---|---|
| Standard | प्रश्न, सीधा उत्तर |
| CoT | प्रश्न, एक तर्क, उत्तर (ReAct ट्रेस से क्रिया-अवलोकन हटे) |
| CoT-SC | 21 CoT नमूना (temperature 0.7), बहुमत का उत्तर |
| Act | प्रश्न, क्रिया-अवलोकन की बारी, अंत में Finish (ReAct ट्रेस से सोच हटी) |
| ReAct | प्रश्न, सोच-क्रिया-अवलोकन की बारी, अंत में सोच प्लस Finish |
| ReAct→CoT-SC | ReAct निर्धारित कदमों (HotpotQA 7, Fever 5) में उत्तर न दे तो CoT-SC की ओर वापसी |
| CoT-SC→ReAct | 21 CoT-SC samples में बहुमत उत्तर आधे से कम आए तो ReAct की ओर वापसी |
Paper कहता है इन्हीं कदम सीमाओं पर रुकना क्योंकि अधिक कदम ReAct सुधारते नहीं; footnote का आधार: सही ट्रेसों में 7 कदम (HotpotQA) व 5 कदम (Fever) उपयोग करने वाले केवल 0.84% व 1.33%।
चार कार्य
| कार्य | क्रियाएँ | Examples | मापदंड |
|---|---|---|---|
| HotpotQA, multi-hop QA | search, lookup, finish (Wikipedia interface) | 6 | Exact match (EM) |
| Fever, तथ्य जाँच | वही | 3 | Accuracy |
| ALFWorld, टेक्स्ट-रूप घरेलू खेल | go to, take, use आदि टेक्स्ट क्रियाएँ | हर प्रकार पर 3 annotated, उनमें से 2 के 6 क्रमचय = 6 prompt groups | 134 अनदेखी खेलों की success दर |
| WebShop, ऑनलाइन ख़रीदारी (11.8 लाख वास्तविक सामग्री) | खोज, चयन, विकल्प, ख़रीद | 1 | 500 test निर्देशों का score व success दर |
HotpotQA और Fever का Wikipedia interface केवल तीन क्रियाओं का, paper ने जानबूझकर अत्यंत कमज़ोर बनाया: search[entity] प्रविष्टि के पहले 5 वाक्य, न होने पर 5 समान प्रविष्टियाँ; lookup[string] वर्तमान पृष्ठ में उस स्ट्रिंग वाला अगला वाक्य — browser के Ctrl+F जैसा; finish[answer] कार्य समाप्त। Paper की भाषा: यह अत्याधुनिक lexical या neural retrievers से कहीं कमज़ोर है; उद्देश्य मानव के Wikipedia उपयोग का अनुकरण और मॉडल को स्पष्ट भाषा तर्क से retrieval पर मजबूर करना। यही तीन क्रियाएँ इस लेख के छोटे प्रयोग की prototype।
Fine-tuning
हाथ से लिखी ट्रेसें scale नहीं लेतीं; paper ने bootstrapping भी: ReAct (व अन्य बेसलाइनों) से बनी 3,000 सही ट्रेसों से PaLM-8B व 62B fine-tune — प्रश्न दिया हो तो पूरी ट्रेस decode करें।
Paper के experiments और निष्कर्ष
ज्ञान-सघन कार्य: HotpotQA और Fever
Paper तालिका 1: PaLM-540B prompts के नतीजे।
| विधि | HotpotQA EM | Fever accuracy |
|---|---|---|
| Standard | 28.7 | 57.1 |
| CoT | 29.4 | 56.3 |
| CoT-SC | 33.4 | 60.4 |
| Act | 25.7 | 58.9 |
| ReAct | 27.4 | 60.9 |
| CoT-SC→ReAct | 34.2 | 64.6 |
| ReAct→CoT-SC | 35.1 | 62.0 |
| Supervised सर्वश्रेष्ठ | 67.5 | 89.5 |
Paper की तीन पठन रेखाएँ:
- ReAct दोनों कार्यों में Act से बेहतर — सोच का अंतिम उत्तर जोड़ने में योगदान; fine-tuning भी यही कहता है।
- ReAct Fever में CoT से ऊपर (60.9 बनाम 56.3), HotpotQA में थोड़ा नीचे (27.4 बनाम 29.4)। Paper की व्याख्या: Fever में SUPPORTS और REFUTES का अंतर महीन हो सकता है — सटीक व ताज़ा ज्ञान retrieval ज़रूरी।
- दोनों hybrids सर्वश्रेष्ठ: HotpotQA में ReAct→CoT-SC, Fever में CoT-SC→ReAct। Paper चित्र 2 दिखाता है: केवल 3–5 CoT-SC samples से CoT-SC के 21 samples जितना स्तर।
HotpotQA में ReAct CoT से क्यों हारा, जानने के लिए paper ने सही व ग़लत के ReAct व CoT ट्रेसों में से यादृच्छिक 50-50 (कुल 200) लेकर मानव रूप से सफलता-विफलता के प्रकार अंकित किए:
Paper तालिका 2: HotpotQA की सफलता-विफलता के प्रकार (मानव annotated)।
| प्रकार | अर्थ | ReAct | CoT |
|---|---|---|---|
| सफल: true positive | तर्क व तथ्य दोनों सही | 94% | 86% |
| सफल: false positive | तर्क या तथ्य गढ़ा | 6% | 14% |
| विफल: reasoning error | तर्क ग़लत, दोहराए चक्र सहित | 47% | 16% |
| विफल: search result error | Search खाली या निरर्थक | 23% | लागू नहीं |
| विफल: hallucination | तर्क या तथ्य गढ़ा | 0% | 56% |
| विफल: label ambiguity | भविष्यवाणी सही पर label से पूर्ण मेल नहीं | 29% | 28% |
Paper के तीन प्रेक्षण: hallucination CoT की बड़ी समस्या (विफलताओं में 56%; सही में भी 14% गढ़े); ReAct बाहरी ज्ञान पहुँच से ट्रेसें अधिक ठोस व विश्वसनीय; बारी की संरचना तर्क की लचीलापन सीमित — ReAct के reasoning errors अधिक, और उसका एक विशेष पैटर्न: पिछली सोच-क्रिया बार-बार दोहराना, चक्र से बाहर न निकल पाना (paper उसे greedy decoding से जोड़ता है); search का उपयोगी सामग्री लाना ReAct के लिए निर्णायक — निरर्थक search उसकी विफलताओं का 23%, तर्क पटरी से उतर जाता है और वापस कठिन।
Fine-tuning (paper चित्र 3): 3,000 ट्रेसों से PaLM-8B व 62B fine-tune करने से पहले ReAct दोनों आकारों में चार विधियों में सबसे ख़राब — केवल examples से तर्क व क्रिया एक साथ सिखाना कठिन; fine-tune के बाद ReAct चारों में सर्वश्रेष्ठ: fine-tuned 8B ReAct ने सब 62B prompt विधियों को पार किया; fine-tuned 62B ReAct ने सब 540B prompt विधियों को। Standard या CoT का fine-tune स्पष्ट ख़राब; paper की व्याख्या: पहला मॉडल को (hallucinated हो सकने वाले) तथ्य रटाता है, दूसरा सूचना पाने के लिए (तर्क करके) क्रिया करना सिखाता है — अधिक सामान्य क्षमता।
निर्णय कार्य: ALFWorld और WebShop
Paper तालिका 3: ALFWorld की task-type दर से success (%)।
| विधि | Pick | Clean | Heat | Cool | Look | Pick2 | समग्र |
|---|---|---|---|---|---|---|---|
| Act, 6 groups में सर्वश्रेष्ठ | 88 | 42 | 74 | 67 | 72 | 41 | 45 |
| ReAct, औसत | 65 | 39 | 83 | 76 | 55 | 24 | 57 |
| ReAct, 6 groups में सर्वश्रेष्ठ | 92 | 58 | 96 | 86 | 78 | 41 | 71 |
| ReAct-IM, औसत | 55 | 59 | 60 | 55 | 23 | 24 | 48 |
| ReAct-IM, 6 groups में सर्वश्रेष्ठ | 62 | 68 | 87 | 57 | 39 | 33 | 53 |
| BUTLERg, 8 में सर्वश्रेष्ठ | 33 | 26 | 70 | 76 | 17 | 12 | 22 |
| BUTLER, 8 में सर्वश्रेष्ठ | 46 | 39 | 74 | 100 | 22 | 24 | 37 |
BUTLER एक agent है जो हर task-type पर 105 expert ट्रेसों से imitation learning करता है (beam search; बाकी सब greedy); आँकड़े ALFWorld मूल paper से। Paper का कथन: सर्वश्रेष्ठ ReAct trial की समग्र success 71% — सर्वश्रेष्ठ Act (45%) और BUTLER (37%) से स्पष्ट ऊपर; सबसे ख़राब ReAct trial (48%) भी दोनों के सर्वश्रेष्ठ से ऊपर; 6 groups में ReAct का Act पर सापेक्ष सुधार 33%–90%, औसत 62%। गुणात्मक रूप से: बिना सोच वाला Act लक्ष्य को sub-goals में नहीं तोड़ पाता, या environment की चालू स्थिति का पीछा खो देता है।
ReAct-IM Inner Monologue (IM) का नियंत्रित प्रतिरूप: सोच को IM शैली के dense बाहरी feedback से बदलना — content केवल environment की चालू स्थिति और लक्ष्य से कितनी दूरी; कोई उच्च-स्तरीय लक्ष्य खंडन नहीं, सामान्य ज्ञान तर्क नहीं। ReAct समग्र success 71 बनाम 53 से स्पष्ट जीता; छह task-types में पाँच बेहतर; paper देखता है ReAct-IM प्रायः sub-goal पूरा हुआ या नहीं, अगला sub-goal क्या — ग़लत आँकता है, और सामग्री कहाँ होगी अनुमान भी कठिन।
Paper तालिका 4: WebShop का score व success (%)।
| विधि | Score | Success |
|---|---|---|
| Act | 62.3 | 30.1 |
| ReAct | 66.6 | 40.0 |
| IL | 59.9 | 29.1 |
| IL+RL | 62.4 | 28.7 |
| मानव expert | 82.1 | 59.6 |
IL ने 1,012 मानव-अंकित ट्रेसें लीं; IL+RL ने अतिरिक्त 10,587 training निर्देश (आँकड़े WebShop मूल paper से)। Paper की पठन: एकल example वाला Act पहले ही IL, IL+RL के बराबर; sparse तर्क जोड़ने पर ReAct की success पिछले सर्वश्रेष्ठ से निरपेक्ष 10 प्रतिशत अंक ऊपर; पर मानव expert से बहुत दूर — मानव अधिक product exploration व query रूपांतरण करता है।
तालिकाएँ पढ़ते समय ध्यान
- PaLM-540B सार्वजनिक नहीं। Paper Appendix A.1 में GPT-3 (text-davinci-002, greedy) से ReAct prompts दोहराए: HotpotQA 30.8, ALFWorld 78.4 — PaLM-540B के 29.4 व 70.9 (paper तालिका 5) से ऊपर; लेखकों का अनुमान GPT-3 के instruction fine-tuning से।
- Paper PaLM प्रयोगों की evaluation set आकार व runs नहीं बताता; तालिका 1 में error bars नहीं। केवल Appendix A.1 की तालिका 5 बताती है: HotpotQA यादृच्छिक 500 validation प्रश्न। इसलिए तालिका 1 के एक-दो अंकों का अंतर noise है या नहीं, पाठक तय नहीं कर सकता; अगले भाग में मानी हुई 500 पर अनुमान।
- “सर्वश्रेष्ठ” एकल trial का स्कोर नहीं। तालिका 3 में Act, ReAct, ReAct-IM की “सर्वश्रेष्ठ” पंक्तियों के per-task आँकड़े अलग-अलग अधिकतम दिखते हैं जबकि “समग्र” column सबसे अच्छे एक trial का; अगले भाग की भारित पुनर्गणना इस अनुमान को संगत दिखाती है — paper स्पष्ट नहीं लिखता।
- BUTLER का “समग्र” छह task-types का भारित औसत नहीं। ALFWorld मूल paper में प्रत्येक type के आँकड़े प्रति-type प्रशिक्षित agents के; “समग्र” उसी policy का सब 3,553 कार्यों पर प्रशिक्षित नतीजा।
- सब prompt विधियाँ supervised से बहुत नीचे। तालिका 1 में सर्वश्रेष्ठ prompt विधि HotpotQA पर supervised सर्वश्रेष्ठ से 30 अंकों से अधिक नीचे; paper स्वयं मानता है, और अधिक मानव data से fine-tune को ReAct की क्षमता खोलने का बेहतर रास्ता मानता है।
हाथ से जाँच: paper की तालिकाओं की पुनर्गणना
नीचे का script GPU नहीं माँगता, मिलीसेकंडों में। Paper की तालिकाओं 1–5 के आँकड़े dictionary में उतारकर (PDF के टेक्स्ट से अंकित, पाठ से जाँचे) पाँच प्रकार पुनर्गणित: तालिका 1 के विधियों के बीच अंतर; तालिका 2 की हर column का योग; तालिका 3 को ALFWorld अनदेखी set की task संख्याओं (24, 31, 23, 21, 18, 17; कुल 134) से भारित कर समग्र दर; abstract व टेक्स्ट के कुछ अंतर; तालिका 5 बनाम तालिका 1 उसी विधि के आँकड़े।
पूर्ण कोड (लगभग 76 पंक्तियाँ)
"""Check the ReAct paper's tables and abstract: only the paper's own numbers"""
import math
T1 = { # method: (HotpotQA EM, Fever accuracy)
"Standard": (28.7, 57.1), "CoT": (29.4, 56.3), "CoT-SC": (33.4, 60.4),
"Act": (25.7, 58.9), "ReAct": (27.4, 60.9),
"CoT-SC -> ReAct": (34.2, 64.6), "ReAct -> CoT-SC": (35.1, 62.0),
"Supervised SoTA": (67.5, 89.5)}
T2 = { # shares of success/failure types (%): (ReAct, CoT)
"success": {"true positive": (94, 86), "false positive": (6, 14)},
"failure": {"reasoning error": (47, 16), "search result error": (23, 0),
"hallucination": (0, 56), "label ambiguity": (29, 28)}}
W = {"Pick": 24, "Clean": 31, "Heat": 23, "Cool": 21, "Look": 18, "Pick2": 17}
T3 = { # per row: success rates of the 6 task types, last entry is All
"Act (best of 6)": (88, 42, 74, 67, 72, 41, 45),
"ReAct (avg)": (65, 39, 83, 76, 55, 24, 57),
"ReAct (best of 6)": (92, 58, 96, 86, 78, 41, 71),
"ReAct-IM (avg)": (55, 59, 60, 55, 23, 24, 48),
"ReAct-IM (best of 6)": (62, 68, 87, 57, 39, 33, 53),
"BUTLERg (best of 8)": (33, 26, 70, 76, 17, 12, 22),
"BUTLER (best of 8)": (46, 39, 74, 100, 22, 24, 37)}
T4 = { # WebShop: (score, success rate)
"Act": (62.3, 30.1), "ReAct": (66.6, 40.0), "IL": (59.9, 29.1),
"IL+RL": (62.4, 28.7), "Human expert": (82.1, 59.6)}
def se(p, n):
"""standard error (percentage points) of a rate p (%) over n samples"""
return 100 * math.sqrt(p / 100 * (1 - p / 100) / n)
print("Table 1: HotpotQA and Fever (PaLM-540B prompts)")
NAMES = ("HotpotQA", "Fever")
rows = [("ReAct", "Act", (0, 1)), ("ReAct", "CoT", (0, 1)),
("ReAct -> CoT-SC", "CoT-SC", (0,)), ("CoT-SC -> ReAct", "ReAct", (1,))]
for a, b, cols in rows:
diffs = ", ".join(f"{NAMES[i]} {T1[a][i] - T1[b][i]:+.1f}" for i in cols)
print(f" {a} - {b}: {diffs}")
best = [max(v[i] for m, v in T1.items() if m != "Supervised SoTA")
for i in (0, 1)]
sota = T1["Supervised SoTA"]
print(f" Supervised SoTA - best prompt: HotpotQA {sota[0] - best[0]:+.1f}, "
f"Fever {sota[1] - best[1]:+.1f}")
print(f" if the eval set is 500 questions (the paper states this only for\n"
f" the GPT-3 experiments), the SE of EM near 30% is {se(30, 500):.1f} pp")
print("\nTable 2: sum of the shares in each column (%)")
for kind, rows in T2.items():
sums = [sum(v[i] for v in rows.values()) for i in (0, 1)]
print(f" {kind}: ReAct {sums[0]}, CoT {sums[1]}")
print("\nTable 3: re-weight All by the unseen-set task counts "
"(24/31/23/21/18/17, total 134)")
print(f" {'row':<22}{'weighted':>9}{'printed':>9}{'diff':>7}")
for row, v in T3.items():
wavg = sum(x * n for x, n in zip(v[:6], W.values())) / sum(W.values())
print(f" {row:<22}{wavg:9.1f}{v[6]:9d}{wavg - v[6]:+7.1f}")
print(f" SE: ReAct's All=57 over 134 games is about {se(57, 134):.1f} pp")
print("\nnumbers in the abstract and the text")
print(f" ALFWorld: ReAct best 71 - BUTLER 37 = {71 - 37}")
print(f" ALFWorld: worst ReAct trial 48 > best Act trial 45: {48 > 45}")
print(f" WebShop: success rate {T4['ReAct'][1]} - {T4['IL'][1]} = "
f"{T4['ReAct'][1] - T4['IL'][1]:.1f}")
print(f" WebShop: score {T4['ReAct'][0]} - {T4['IL+RL'][0]} = "
f"{T4['ReAct'][0] - T4['IL+RL'][0]:.1f}")
print(f" WebShop: Act - IL success rate = {T4['Act'][1] - T4['IL'][1]:+.1f}")
print(f" WebShop: Human expert - ReAct success rate = "
f"{T4['Human expert'][1] - T4['ReAct'][1]:.1f}")
print(f" WebShop 500 items: SE of success rate 40.0 is {se(40, 500):.1f};\n"
f" the 1.0-pp gap between Act and IL is within the noise")
print("\nTable 5: PaLM-540B vs GPT-3 (text-davinci-002)")
print(f" HotpotQA: {30.8 - 29.4:+.1f}; ALFWorld: {78.4 - 70.9:+.1f}")
gap = 29.4 - T1["ReAct"][0]
print(f" Table 5's PaLM-540B HotpotQA is 29.4,\n"
f" the same method in table 1 is {T1['ReAct'][0]}, a gap of {gap:.1f}")
आउटपुट (चीनी संस्करण की original run से; labels अंग्रेज़ी में अनूदित):
Table 1: HotpotQA and Fever (PaLM-540B prompts)
ReAct - Act: HotpotQA +1.7, Fever +2.0
ReAct - CoT: HotpotQA -2.0, Fever +4.6
ReAct -> CoT-SC - CoT-SC: HotpotQA +1.7
CoT-SC -> ReAct - ReAct: Fever +3.7
Supervised SoTA - best prompt: HotpotQA +32.4, Fever +24.9
if the eval set is 500 questions (the paper states this only for
the GPT-3 experiments), the SE of EM near 30% is 2.0 pp
Table 2: sum of the shares in each column (%)
success: ReAct 100, CoT 100
failure: ReAct 99, CoT 100
Table 3: re-weight All by the unseen-set task counts (24/31/23/21/18/17, total 134)
row weighted printed diff
Act (best of 6) 63.6 45 +18.6
ReAct (avg) 57.3 57 +0.3
ReAct (best of 6) 75.5 71 +4.5
ReAct-IM (avg) 48.6 48 +0.6
ReAct-IM (best of 6) 60.1 53 +7.1
BUTLERg (best of 8) 39.7 22 +17.7
BUTLER (best of 8) 51.6 37 +14.6
SE: ReAct's All=57 over 134 games is about 4.3 pp
numbers in the abstract and the text
ALFWorld: ReAct best 71 - BUTLER 37 = 34
ALFWorld: worst ReAct trial 48 > best Act trial 45: True
WebShop: success rate 40.0 - 29.1 = 10.9
WebShop: score 66.6 - 62.4 = 4.2
WebShop: Act - IL success rate = +1.0
WebShop: Human expert - ReAct success rate = 19.6
WebShop 500 items: SE of success rate 40.0 is 2.2,
the 1.0-pp gap between Act and IL is within the noise
Table 5: PaLM-540B vs GPT-3 (text-davinci-002)
HotpotQA: +1.4; ALFWorld: +7.5
Table 5's PaLM-540B HotpotQA is 29.4,
the same method in table 1 is 27.4, a gap of 2.0
मद-दर-मद:
- तालिका 1 के अंतर paper के कथनों से मेल। ReAct Act से +1.7 (HotpotQA) व +2.0 (Fever); CoT से HotpotQA −2.0, Fever +4.6; दोनों hybrids अपनी वापसी वाली विधियों से +1.7 (ReAct→CoT-SC बनाम CoT-SC, HotpotQA) व +3.7 (CoT-SC→ReAct बनाम ReAct, Fever); supervised सर्वश्रेष्ठ सर्वश्रेष्ठ prompt से +32.4 व +24.9। Paper का कोई कथन बढ़ा-चढ़ा नहीं।
- पर तालिका 1 के छोटे अंतर कितने भरोसेमंद — paper निर्णय का आधार नहीं देता। Evaluation set 500 हो (paper केवल GPT-3 प्रयोगों में गिनता) तो EM का 30% के पास standard error 2.0 प्रतिशत अंक — ReAct-बनाम-Act के 1.7 के उसी पैमाने का। इसलिए paper का निष्कर्ष अधिक भर ALFWorld जैसे बड़े अंतरों, fine-tuning और विफलता विश्लेषण पर खड़ा है, तालिका 1 के एक-दो अंकों पर नहीं।
- तालिका 2 आत्मसंगत। सफलता columns के योग दोनों 100; विफलता में ReAct 99 (rounding), CoT 100।
- तालिका 3 की “औसत” पंक्तियाँ भारित पुनर्गणना से मेल, “सर्वश्रेष्ठ” नहीं — इसमें ही सूचना। ReAct औसत पुनर्गणना 57.3, paper 57 छापता है; ReAct-IM 48.6 बनाम 48। तीनों “सर्वश्रेष्ठ” पंक्तियों की पुनर्गणना छापे समग्र से स्पष्ट ऊँची: Act 63.6 बनाम 45, ReAct 75.5 बनाम 71, ReAct-IM 60.1 बनाम 53। यह “हर task अपना अधिकतम, समग्र सर्वश्रेष्ठ एक trial” पठन से मेल (भिन्न tasks के सर्वश्रेष्ठ प्रायः भिन्न prompts से)। BUTLER की दो पंक्तियाँ और दूर (51.6 बनाम 37; 39.7 बनाम 22) — उनका समग्र दूसरा cross-task प्रशिक्षित policy है (ऊपर देखें)। Paper स्पष्ट नहीं लिखता — यह आँकड़ों से मेल खाने वाली व्याख्या है, paper का विवरण नहीं।
- Prompt की पसंद स्वयं बड़ा चर। ReAct की समग्र success 6 groups में 48% से 71%; 134 खेलों पर 57% का standard error केवल 4.3 प्रतिशत अंक — यह फैलाव नमूना त्रुटि से बहुत बड़ा। Paper का औसत व सर्वश्रेष्ठ दोनों रिपोर्ट करना सही; केवल एक group का निष्कर्ष अस्थिर।
- Abstract व टेक्स्ट के आँकड़े मेल। 71 − 37 = 34, abstract का “34%”; सबसे ख़राब ReAct trial (48) सच में सर्वश्रेष्ठ Act trial (45) से ऊँचा (48 केवल टेक्स्ट में, तालिका में नहीं — इसलिए केवल “>45” जाँचा जा सका); WebShop success 40.0 − 29.1 = 10.9, abstract का “10%” rounding; score IL+RL से +4.2; Act IL से केवल +1.0, और 500 निर्देशों पर success 40.0 का standard error 2.2 — paper का “Act और IL बराबर” सटीक; मानव expert ReAct से +19.6।
- तालिका 5 और तालिका 1 मेल नहीं। तालिका 5 में PaLM-540B का HotpotQA 29.4, तालिका 1 में उसी विधि 27.4 — 2.0 का अंतर; paper व्याख्या नहीं। तालिका 5 का caption यादृच्छिक 500 प्रश्न subset कहता है; सबसे संभव भिन्न evaluation subset, पर यह अनुमान ही। GPT-3 PaLM से HotpotQA में +1.4, ALFWorld में +7.5।
हाथ का प्रयोग: नकली विकी पर चार prompts
Paper का PaLM-540B सार्वजनिक नहीं, और HotpotQA के तथ्य प्रायः छोटे मॉडलों के parameters में हो चुके होते हैं; इसलिए यह भाग paper के आँकड़े दोहराता नहीं, बल्कि एक संकीर्ण प्रश्न: उत्तर parameters में न हो, tools से ही निकलना पड़े तो ‘सोच’ क्या बदलती है? तरीका: एक नकली Wikipedia बनाना — नाम, कंपनियाँ, शहरें, देश सब यादृच्छिक गढ़े; मॉडल उन्हें नहीं जानता, कोई भी सही उत्तर निकाले हुए पृष्ठों से आना चाहिए। इससे Standard व CoT निचली सीमा बन जाते हैं; तुलना लायक Act और ReAct।
Experiment design
- Worlds। हर world में 40 व्यक्ति, 16 कंपनियाँ, 14 शहर, 6 देश — स्थित random seeds (दो worlds; seeds 1 व 2)। हर प्रविष्टि template वाक्यों से: व्यक्ति 7 वाक्य (वृत्ति, जन्म-स्थान, कार्यस्थल, गुरु, प्लस पुरस्कार, पुस्तकें, शौक — तीन असंबद्ध), कंपनी 6 वाक्य (प्रकार, मुख्यालय, स्थापना-वर्ष, संस्थापक, प्लस कर्मचारी संख्या व निर्यात देश संख्या), शहर 3 वाक्य, देश 2 वाक्य। पहला वाक्य स्थिर, बाकी फेंटे — इसलिए व्यक्ति पृष्ठ में हर तथ्य Search के पहले 5 से बाहर होने की प्रायिकता एक-तिहाई, कंपनी पृष्ठ में पाँचवाँ भाग; पढ़ने के लिए Lookup ज़रूरी।
- क्रियाएँ। Paper की तीन क्रियाओं से समरूप:
Search[entity]प्रविष्टि के पहले 5 वाक्य, न होने पर 5 सबसे समान प्रविष्टियाँ;Lookup[keyword]वर्तमान पृष्ठ में उस keyword वाला अगला वाक्य “(result i/n)” चिह्नित; और न हो तो “no more results”;Finish[answer]समाप्त। यहाँ का Lookup literal match — समानार्थी नहीं समझता; यह बात आगे काटेगी। - प्रश्न। हर world 36, चार श्रेणियों में 9-9: 1-hop (जन्म-शहर, कार्य कंपनी), 2-hop (स्थापना-वर्ष, जन्म-देश, संस्थापक), 3-hop (कंपनी के मुख्यालय का देश; गुरु की कंपनी की स्थापना-वर्ष), तुलना (दो व्यक्ति एक ही शहर में जन्मे? दो कंपनियों में कौन पहले? — सब द्विविकल्प, यादृच्छिक अनुमान की आधी सफलता)। हर world में 6 प्रश्नों में पहला नाम एक अक्षर दोहराया (misspelled); मूल नाम समान प्रविष्टियों में सबसे समान गारंटी — समान प्रविष्टियों से वापसी संभव। 72 में 37 प्रश्नों में कम-से-कम एक आवश्यक वाक्य पहले 5 से बाहर।
- Prompts। चारों prompts वही 4 हाथ-लिखे examples। Examples का अपना छोटा world, नाम किसी test world में नहीं: एक distractor वाला 2-hop, एक “misspelled नाम फिर Lookup” 1-hop, एक तुलना, एक 2-hop देश। कोई 3-hop example नहीं, कोई हाँ/नहीं example नहीं। Standard केवल प्रश्न-उत्तर; CoT examples की कदम-सोच को एक पैराग्राफ जोड़कर उत्तर; Act केवल क्रिया-अवलोकन; ReAct सोच-क्रिया-अवलोकन। चारों के prefixes क्रमशः 85, 354, 652 व 972 tokens (Qwen3 tokenizer)।
- Decoding व कदम। Greedy decoding, अधिकतम 7 कदम (paper की HotpotQA सीमा); example prefix का KV cache एक बार। मॉडल Qwen3-4B (आधिकारिक post-training संस्करण, Base नहीं), यहाँ साधारण continuation मॉडल की तरह: chat template नहीं, इसलिए उसकी thinking mode नहीं चलती।
- निर्णय व विफलता प्रकार। Exact match (lowercase, punctuation हटाकर अक्षर-दर-अक्षर), paper से मेल। ग़लत Act व ReAct ट्रेसें स्वतः वर्गीकृत: 7 कदम ख़त्म उत्तर नहीं (
no_finish); आवश्यक प्रविष्टि खोले बिना उत्तर (unopened); प्रविष्टि खोली पर आवश्यक वाक्य कभी observation में न आया (unseen); आवश्यक वाक्य दिखे पर भी उत्तर ग़लत (misread)। तीन और चिह्न: एक ही क्रिया दोहराना (loop), Search प्रविष्टि नहीं मिली (miss), अमान्य क्रिया format (invalid) — ये तीन पूरे 72 पर।
Paper से अंतर पहले साफ़:
| Paper | यह प्रयोग | |
|---|---|---|
| मॉडल | PaLM-540B, अप्रकाशित | Qwen3-4B, Apache-2.0 |
| Data | HotpotQA व Fever के वास्तविक प्रश्न | स्व-गढ़ी नकली विकी, 72 प्रश्न (दो worlds × 36) |
| Examples | HotpotQA 6 | 4, चारों prompts साझा |
| Environment | वास्तविक Wikipedia API | Template वाक्य; Lookup literal match |
| Parameters में उत्तर? | हो सकता (pretraining में Wikipedia) | नहीं (नाम गढ़े) |
वातावरण: Apple M2 Max (MPS), Python 3.14.3, PyTorch 2.10.0, transformers 5.3.0; Qwen3-4B float32 में लोड, greedy decoding। 288 उत्तर (72 × 4 prompts) 37 मिनट; script अंत में पहले 4 प्रश्नों का ReAct फिर चलाता है — ट्रेसें अक्षर-दर-अक्षर एक। Greedy decoding उसी वातावरण में पुनरुत्पादनीय; hardware या library versions बदलने पर कुछ ट्रेसें भिन्न हो सकती हैं। सांख्यिकी script केवल run से सहेजी react_runs.json पढ़ता है, मॉडल नहीं बुलाता।
Prompt व नियमों का इतिहास बताना ज़रूरी: script विकास में बार-बार बदला; एक बार शुरू होने के लगभग दो मिनट में मैंने रोका — उसका आउटपुट सहेजा नहीं; इसलिए examples की भाषा एक बार में नहीं बनी, पर prompts पर कोई तुलना या खोज नहीं की। 288 उत्तर एक ही पूरे रन से; रन शुरू होने के बाद script नहीं बदला। निर्णय नियमों में रन के बाद एक “लचीला निर्णय” नियंत्रित पंक्ति जोड़ी (नीचे देखें); मुख्य तालिका exact match ही।
नीचे कोड चीनी संस्करण के original script का अंग्रेज़ी अनुवाद है (नाम romanized; templates व prompts अंग्रेज़ी में रेंडर किए); वास्तविक रन चीनी नामों व चीनी templates के साथ हुआ, सारे संख्याएँ उसी रन की।
पूर्ण कोड (लगभग 447 पंक्तियाँ): नकली विकी, चार prompts और run script
"""Mini reproduction of ReAct: four prompting styles on a fictional wiki
(Qwen3-4B, greedy decoding). English rendering of the Chinese original."""
import copy
import difflib
import json
import random
import re
import string
import sys
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache
from transformers.utils import logging as hf_logging
hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
NAME, DEV, MAX_STEPS = "Qwen/Qwen3-4B", "mps", 7
T, A, O, Q, ANS = ("Thought", "Action", "Observation", "Question", "Answer")
NOT_FOUND = "not found"
INVALID = "Invalid action. Use Search[...], Lookup[...] or Finish[...]."
# --- fictional world ---
GIV = "hao shu yan heng lin lan yuan yu jin xi".split()
SUR = "cen qi gan miao wei ruan feng li ke qiu".split()
SYL = "ta er nuo wei ke la si bei ku ao mi luo".split()
IND = "machinery food shipping instruments glass textile software shipbuild".split()
JOB = "potter composer geologist architect astronomer botanist".split()
PRZ = "amber egret bronze galaxy turquoise ginkgo".split()
SIGHT = "lighthouse clock tower harbor market stone bridge".split()
HOBBY = "chess sailing gardening photography hiking".split()
S = dict( # sentence templates on the pages
job="{p} is a {x}.",
born="{p} was born in {x}.",
works="{p} works at {x}.",
mentor="{p}'s mentor is {x}.",
prize="{p} won the {x} Prize in {y}.",
books="{p} has written {y} books.",
hobby="{p} loves {x}.",
kind="{p} is a {x} company.",
hq="{p} is headquartered in {x}.",
year="{p} was founded in {x}.",
founder="{p} was founded by {x}.",
staff="{p} has about {y} employees.",
sells="{p} sells products to {y} countries.",
city="{p} is a city known for its {x}.",
land="{p} is located in {x}.",
pop="{p} has a population of about {y}.",
cap="{x} is the capital of {p}.",
)
QT = dict( # question templates
born="In which city was {p} born?",
works="At which company does {p} work?",
year="In which year was {p}'s company founded?",
country="In which country was {p} born?",
founder="Who founded the company where {p} works?",
hqc="In which country is the headquarters of {p}'s company?",
myear="In which year was the company of {p}'s mentor founded?",
same="Were {p} and {x} born in the same city?",
early="Which was founded earlier, {p} or {x}?",
)
YES, NO = ("yes", "no")
def build_world(seed, n_people=40, n_comp=16, n_city=14, n_country=6):
rng, used = random.Random(seed), set()
def uniq(make):
while True:
s = make()
if s not in used:
used.add(s)
return s
def stem(k):
return "".join(rng.choice(SYL) for _ in range(k)).title()
def person():
return rng.choice(SUR) + rng.choice(GIV) + rng.choice(GIV)
country = [uniq(lambda: stem(3) + " Country") for _ in range(n_country)]
city = {uniq(lambda: stem(3)): rng.choice(country) for _ in range(n_city)}
comp = {uniq(lambda: stem(2) + " " + rng.choice(IND)): None
for _ in range(n_comp)}
ppl = [uniq(person) for _ in range(n_people)]
for c in comp:
comp[c] = dict(hq=rng.choice(list(city)), year=rng.randint(1950, 2012),
founder=rng.choice(ppl))
who = {p: dict(born=rng.choice(list(city)), works=rng.choice(list(comp)),
mentor=rng.choice([q for q in ppl if q != p])) for p in ppl}
pages = {}
def page(name, first, facts, fillers):
rest = facts + fillers
rng.shuffle(rest) # first sentence fixed, the rest shuffled
pages[name] = [first] + rest
for p, f in who.items():
page(p, S["job"].format(p=p, x=rng.choice(JOB)),
[S[k].format(p=p, x=f[k]) for k in ("born", "works", "mentor")],
[S["prize"].format(p=p, x=rng.choice(PRZ),
y=rng.randint(1980, 2020)),
S["books"].format(p=p, y=rng.randint(2, 12)),
S["hobby"].format(p=p, x=rng.choice(HOBBY))])
for c, f in comp.items():
page(c, S["kind"].format(p=c, x=c.split()[-1]),
[S["hq"].format(p=c, x=f["hq"]),
S["year"].format(p=c, x=f["year"]),
S["founder"].format(p=c, x=f["founder"])],
[S["staff"].format(p=c, y=rng.randint(40, 9000)),
S["sells"].format(p=c, y=rng.randint(2, 30))])
for x, k in city.items():
page(x, S["city"].format(p=x, x=rng.choice(SIGHT)),
[S["land"].format(p=x, x=k)],
[S["pop"].format(p=x, y=rng.randint(20, 900) * 1000)])
for k in country:
cap = rng.choice([x for x in city if city[x] == k] or list(city))
page(k, S["land"].format(p=k, x="a distant continent"),
[S["cap"].format(p=k, x=cap)], [])
return dict(pages=pages, who=who, comp=comp, city=city, ppl=ppl, rng=rng)
def misspell(name, pages):
"""duplicate one character; the original name stays the unique closest
entry"""
for i in sorted(range(len(name)), key=lambda i: abs(i - len(name) // 2)):
t = name[:i] + name[i] + name[i:]
r = sorted((difflib.SequenceMatcher(None, t, x).ratio(), x)
for x in pages)
if t not in pages and name[i] != " " and r[-1][1] == name \
and r[-1][0] > r[-2][0]:
return t
raise ValueError(name)
def make_questions(w):
"""9 questions of each of 4 kinds: 1-hop, 2-hop, 3-hop, comparison;
need lists the (entry, sentence) pairs the answer rests on"""
rng, who, comp = w["rng"], w["who"], w["comp"]
city, ppl, out = w["city"], w["ppl"], []
def fact(page, key, x):
return page, S[key].format(p=page, x=x)
def add(kind, key, gold, need, typo=False, **kw):
if typo: # misspell the first name in the question
kw["p"] = misspell(kw["p"], w["pages"])
out.append(dict(kind=kind, q=QT[key].format(**kw), gold=str(gold),
need=need, typo=typo))
for i, p in enumerate(rng.sample(ppl, 9)):
k = "born" if i < 5 else "works"
add(1, k, who[p][k], [fact(p, k, who[p][k])],
typo=i in (1, 3, 8), p=p)
for i, p in enumerate(rng.sample(ppl, 9)):
c, b = who[p]["works"], who[p]["born"]
if i % 3 == 0:
add(2, "year", comp[c]["year"],
[fact(p, "works", c), fact(c, "year", comp[c]["year"])],
typo=i == 0, p=p)
elif i % 3 == 1:
add(2, "country", city[b],
[fact(p, "born", b), fact(b, "land", city[b])],
typo=i == 4, p=p)
else:
add(2, "founder", comp[c]["founder"],
[fact(p, "works", c), fact(c, "founder", comp[c]["founder"])],
typo=i == 8, p=p)
for i, p in enumerate(rng.sample(ppl, 9)):
c, m = who[p]["works"], who[p]["mentor"]
if i < 5:
h = comp[c]["hq"]
add(3, "hqc", city[h], [fact(p, "works", c), fact(c, "hq", h),
fact(h, "land", city[h])], p=p)
else:
mc = who[m]["works"]
add(3, "myear", comp[mc]["year"],
[fact(p, "mentor", m), fact(m, "works", mc),
fact(mc, "year", comp[mc]["year"])], p=p)
pairs = [(a, b) for a in ppl for b in ppl if a < b]
same = [(a, b) for a, b in pairs if who[a]["born"] == who[b]["born"]]
diff = [(a, b) for a, b in pairs if who[a]["born"] != who[b]["born"]]
for a, b in rng.sample(same, 3) + rng.sample(diff, 2):
add(4, "same", YES if who[a]["born"] == who[b]["born"] else NO,
[fact(a, "born", who[a]["born"]),
fact(b, "born", who[b]["born"])], p=a, x=b)
for _ in range(4):
a, b = rng.sample(sorted(comp), 2)
while comp[a]["year"] == comp[b]["year"]:
a, b = rng.sample(sorted(comp), 2)
add(4, "early", a if comp[a]["year"] < comp[b]["year"] else b,
[fact(a, "year", comp[a]["year"]),
fact(b, "year", comp[b]["year"])], p=a, x=b)
rng.shuffle(out)
return out
class Wiki:
"""the same three actions as section 3.1 of the paper"""
def __init__(self, pages):
self.pages, self.cur, self.kw, self.pos = pages, None, None, 0
self.visited, self.flags, self.acts = [], set(), []
self.shown = set() # sentences that appeared in observations
def search(self, name):
key = {t.lower(): t for t in self.pages}.get(name.strip().lower())
if key is None:
sim = difflib.get_close_matches(name, list(self.pages), n=5,
cutoff=0.0)
return f"{NOT_FOUND}[{name}]. similar entries: {sim}"
self.cur, self.kw = key, None
self.visited.append(key)
self.shown.update(self.pages[key][:5])
return " ".join(self.pages[key][:5])
def lookup(self, kw):
if self.cur is None:
return "no page open yet; use Search first."
hits = [s for s in self.pages[self.cur] if kw.lower() in s.lower()]
if kw != self.kw:
self.kw, self.pos = kw, 0
if self.pos >= len(hits):
return "no more results."
self.pos += 1
self.shown.add(hits[self.pos - 1])
return f"(result {self.pos}/{len(hits)}) {hits[self.pos - 1]}"
def act(self, text):
"""execute one action string; return (action kind, observation)"""
m = re.match(r"\s*(Search|Lookup|Finish)\[(.*?)\]", text)
if not m:
self.flags.add("invalid")
return None, INVALID
kind, arg = m.groups()
if kind == "Finish":
return kind, arg # the second item is the answer here
if text.strip() in self.acts:
self.flags.add("loop")
self.acts.append(text.strip())
obs = self.search(arg) if kind == "Search" else self.lookup(arg)
if obs.startswith(NOT_FOUND):
self.flags.add("miss")
return kind, obs
# --- prompts ---
EXW = { # the examples' own small world; names in no test world
"Shao Yuanzhou": [
"Shao Yuanzhou is a glass artisan.",
"Shao Yuanzhou won the Amber Prize in 1994.",
"Shao Yuanzhou works at Alan Glass.",
"Shao Yuanzhou has written 3 books.", "Shao Yuanzhou loves chess.",
"Shao Yuanzhou was born in Duowei.",
"Shao Yuanzhou's mentor is Yideli."],
"Alan Glass": [
"Alan Glass is a glass company.", "Alan Glass has about 900 employees.",
"Alan Glass is headquartered in Duowei.",
"Alan Glass was founded in 1971.", "Alan Glass was founded by Yideli."],
"Kunzo Instruments": [
"Kunzo Instruments is an instrument company.",
"Kunzo Instruments has about 300 employees.",
"Kunzo Instruments is headquartered in Kaiwa.",
"Kunzo Instruments was founded in 1983.",
"Kunzo Instruments was founded by Natara."],
"He Malan": [
"He Malan is a composer.", "He Malan has written 5 books.",
"He Malan works at Kunzo Instruments.",
"He Malan won the Egret Prize in 2003.",
"He Malan's mentor is Natara.", "He Malan was born in Kaiwa."],
"Yideli": [
"Yideli is a botanist.", "Yideli was born in Kaiwa.",
"Yideli has written 8 books.", "Yideli works at Alan Glass.",
"Yideli won the Egret Prize in 1999.", "Yideli loves sailing.",
"Yideli's mentor is Natara."],
"He Malan2": ["He Malan2 is an astronomer."],
"Kaiwa": [
"Kaiwa is a city known for its lighthouse.",
"Kaiwa has a population of about 310000.",
"Kaiwa is located in Oster Country."],
}
# 4 examples, each: question and steps (thought, action); observations
# come from the environment
SHOTS = [
("In which year was the company of Shao Yuanzhou founded?", [
("I need to find which company Shao Yuanzhou works at, then look up "
"when that company was founded.", "Search[Shao Yuanzhou]"),
("Shao Yuanzhou works at Alan Glass. Next, look up when Alan Glass "
"was founded.", "Search[Alan Glass]"),
("Alan Glass was founded in 1971 (the 1994 on the previous page is "
"the year of a prize, unrelated to the question), so the answer is "
"1971.", "Finish[1971]")]),
("In which city was He Malan2 born?", [
("I need to look up He Malan2's birth city.", "Search[He Malan2]"),
("No such entry; the name may be misspelled. Among the similar "
"entries 'He Malan' looks closest, so I look it up.",
"Search[He Malan]"),
("This page does not state the birthplace. I use Lookup to find "
"'born' on the page.", "Lookup[born]"),
("He Malan was born in Kaiwa, so the answer is Kaiwa.",
"Finish[Kaiwa]")]),
("Which was founded earlier, Alan Glass or Kunzo Instruments?", [
("I need the founding years of both companies, then compare.",
"Search[Alan Glass]"),
("Alan Glass was founded in 1971. Now look up Kunzo Instruments.",
"Search[Kunzo Instruments]"),
("Kunzo Instruments was founded in 1983. 1971 is earlier than 1983, "
"so Alan Glass is earlier.", "Finish[Alan Glass]")]),
("In which country was Yideli born?", [
("I need Yideli's birth city first, then the country of that city.",
"Search[Yideli]"),
("Yideli was born in Kaiwa. Next, look up which country Kaiwa is in.",
"Search[Kaiwa]"),
("Kaiwa is in Oster Country, so the answer is Oster Country.",
"Finish[Oster Country]")]),
]
TOOLS = ("There are three actions: Search[entity] returns the first few "
"sentences of an entry, or similar entries if absent; "
"Lookup[keyword] returns the next sentence on the current page "
"containing the word; Finish[answer] gives the answer and ends.")
HEAD = dict(
std="Answer the question.",
act="Answer the question using only 'Action, Observation'." + TOOLS,
react="Answer the question by alternating 'Thought, Action, "
"Observation'. Thought is for reasoning." + TOOLS,
)
HEAD["cot"] = HEAD["std"]
def render_shot(method, q, steps):
env, out = Wiki(EXW), f"{Q}: {q}\n"
for i, (th, act) in enumerate(steps, 1):
kind, obs = env.act(act)
if method == "react":
out += f"{T} {i}: {th}\n"
if method in ("act", "react"):
out += f"{A} {i}: {act}\n"
out += f"{O} {i}: {obs}\n" if kind != "Finish" else ""
if method == "cot":
out += f"{T}: {' '.join(th for th, _ in steps)}\n"
if method in ("std", "cot"):
out += f"{ANS}: {obs}\n" # the last step is Finish; obs is the answer
return out + "\n"
def prefix_for(method):
shots = "".join(render_shot(method, q, s) for q, s in SHOTS)
return HEAD[method] + "\n\n" + shots
# --- model and loop ---
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME, dtype=torch.float32).to(DEV)
CACHE = {}
def gen(method, text, max_new, stop):
"""greedy decoding; the examples' prefix KV cache computed once"""
pre = prefix_for(method)
if method not in CACHE:
ids = tok(pre, return_tensors="pt").input_ids.to(DEV)
cache = DynamicCache()
with torch.no_grad():
model(input_ids=ids, past_key_values=cache, use_cache=True)
CACHE[method] = (ids, cache)
pids, pcache = CACHE[method]
ids = tok(pre + text, return_tensors="pt").input_ids.to(DEV)
assert torch.equal(ids[0, :pids.shape[1]], pids[0]), "prefix tokens moved"
out = model.generate(
input_ids=ids, attention_mask=torch.ones_like(ids),
max_new_tokens=max_new, do_sample=False, temperature=None,
top_p=None, top_k=None, past_key_values=copy.deepcopy(pcache),
stop_strings=stop, tokenizer=tok)
new = out[0, ids.shape[1]:]
torch.mps.empty_cache()
return tok.decode(new, skip_special_tokens=True), int(new.shape[0])
def norm(s):
s = re.sub(r"\b(a|an|the)\b", " ", (s or "").lower())
drop = string.punctuation + ",:;!?()[]{}-_'\". "
return " ".join("".join(c for c in s if c not in drop).split())
def closed_book(method, q):
lead = f"{T}:" if method == "cot" else f"{ANS}:"
txt, n = gen(method, f"{Q}: {q}\n{lead}", 120 if method == "cot" else 16,
["\n\n", f"\n{Q}"])
txt = txt.split(f"{ANS}:")[-1] if method == "cot" else txt
return txt.strip().split("\n")[0], n, [txt.strip()]
def agent(method, q, env):
"""(thought ->) action -> observation, until Finish or out of steps"""
hist, toks, log = f"{Q}: {q}\n", 0, []
for i in range(1, MAX_STEPS + 1):
lead = f"{T} {i}:" if method == "react" else f"{A} {i}:"
txt, n = gen(method, hist + lead, 150 if method == "react" else 48,
[f"\n{O}"])
toks += n
m = re.search(rf"{A} {i}:[ ]*([^\n]*)", lead + txt)
act = m.group(1).strip() if m else ""
thought = (lead + txt)[len(f"{T} {i}:"):m.start()].strip() if m else ""
kind, obs = env.act(act)
if kind == "Finish":
log.append(f"{i} {thought} | {act}")
return obs, toks, log
log.append(f"{i} {thought} | {act} -> {obs}")
hist += f"{T} {i}: {thought}\n" if method == "react" else ""
hist += f"{A} {i}: {act}\n{O} {i}: {obs}\n"
env.flags.add("no_finish")
return None, toks, log
def run(method, item, world):
t0, env = time.time(), Wiki(world["pages"])
if method in ("std", "cot"):
ans, toks, log = closed_book(method, item["q"])
else:
ans, toks, log = agent(method, item["q"], env)
ok = norm(ans) == norm(item["gold"])
why = ""
if not ok and method in ("act", "react"):
if ans is None:
why = "no_finish" # ran out of steps without answering
elif not {pg for pg, _ in item["need"]} <= set(env.visited):
why = "unopened" # never opened a required entry
elif not {sen for _, sen in item["need"]} <= env.shown:
why = "unseen" # opened it, but the needed sentence never showed
else:
why = "misread" # saw all needed sentences, still wrong
# does a needed sentence hide beyond the first 5 (Lookup required)?
hidden = any(s not in world["pages"][pg][:5] for pg, s in item["need"])
return dict(method=method, kind=item["kind"], typo=item["typo"],
hidden=hidden, q=item["q"], gold=item["gold"], ans=ans,
ok=ok, calls=len(env.acts), toks=toks,
flags=sorted(env.flags), why=why, log=log,
secs=round(time.time() - t0, 1))
if __name__ == "__main__":
seeds, runs, t_all = (1, 2), [], time.time()
limit = int(sys.argv[1]) if len(sys.argv) > 1 else 36
for seed in seeds:
world = build_world(seed)
for item in make_questions(world)[:limit]:
for method in ("std", "cot", "act", "react"):
runs.append(dict(run(method, item, world), world=seed))
with open("react_runs.json", "w", encoding="utf-8") as f:
json.dump(runs, f, ensure_ascii=False)
print("prompt prefix token counts: " + ", ".join(
f"{k} {CACHE[k][0].shape[1]}" for k in ("std", "cot", "act", "react")))
mins = (time.time() - t_all) / 60
print(f"{len(runs)} answers in total, {mins:.0f} minutes")
# determinism check: rerun ReAct on the same questions, traces should
# be identical
world = build_world(seeds[0])
base = [r for r in runs if r["world"] == seeds[0]
and r["method"] == "react"][:4]
again = [run("react", it, world) for it in make_questions(world)[:4]]
same = sum(a["log"] == b["log"] for a, b in zip(base, again))
print(f"determinism check: reran {len(base)} questions, {same} traces "
f"identical")
Run script के अंत का आउटपुट (चीनी संस्करण की original run से; टेक्स्ट अंग्रेज़ी में अनूदित):
prompt prefix token counts: std 85, cot 354, act 652, react 972
288 answers in total, 37 minutes
determinism check: reran 4 questions, 4 traces identical
पूर्ण कोड (लगभग 193 पंक्तियाँ): सांख्यिकी script
"""Summarize react_runs.json: accuracy, cost and failure types of the four
prompting styles (English rendering of the Chinese original)"""
import json
import math
from collections import Counter
runs = json.load(open("react_runs.json", encoding="utf-8"))
METHODS = ("std", "cot", "act", "react")
LABEL = dict(std="Standard", cot="CoT", act="Act", react="ReAct")
T, A, O = ("Thought", "Action", "Observation")
GOLD, MODEL = ("gold answer", "model answer")
def pick(m, f=lambda r: True):
return [r for r in runs if r["method"] == m and f(r)]
def score(rows):
return sum(r["ok"] for r in rows), len(rows)
def wilson(k, n, z=1.96):
"""Wilson 95% confidence interval (percentage points)"""
p, d = k / n, 1 + z * z / n
c = (p + z * z / (2 * n)) / d
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
return 100 * (c - h), 100 * (c + h)
def show(rows):
k, n = score(rows)
return f"{k}/{n}" if n else "-"
N = len(pick("std"))
print(f"1. accuracy (exact match), {N} questions")
print(f" {'':<10}{'all':>9}{'95% CI':>12}{'world 1':>9}{'world 2':>9}")
for m in METHODS:
k, n = score(pick(m))
lo, hi = wilson(k, n)
w = [show(pick(m, lambda r: r["world"] == i)) for i in (1, 2)]
print(f" {LABEL[m]:<10}{k:>3}/{n} {100 * k / n:4.1f}%"
f" [{lo:3.0f},{hi:3.0f}]{w[0]:>9}{w[1]:>9}")
def first_word(ans):
"""yes/no questions: read the start of the answer; negatives count as no"""
a = (ans or "").strip().lower()
if a.startswith(("no", "not", "never")):
return "no"
return "yes" if a.startswith(("yes", "right")) else a
YN = ("yes", "no")
print("\n lenient scoring: answers to yes/no questions starting with "
"'no/not/never' also count as no")
for m in ("act", "react"):
rows = pick(m)
lenient = [r["ok"] or (r["gold"] in YN
and first_word(r["ans"]) == r["gold"])
for r in rows]
changed = sum(a and not r["ok"] for a, r in zip(lenient, rows))
print(f" {LABEL[m]:<10}{sum(lenient):>3}/{len(rows)}"
+ f", {changed} answers rejudged")
print("\n2. by question kind (correct / total)")
KINDS = {1: "1-hop", 2: "2-hop", 3: "3-hop", 4: "comparison"}
print(" " + " " * 10 + "".join(f"{v:>9}" for v in KINDS.values()))
for m in METHODS:
cells = [show(pick(m, lambda r: r["kind"] == k)) for k in KINDS]
print(f" {LABEL[m]:<10}" + "".join(f"{c:>9}" for c in cells))
print("\n3. by question property (correct / total)")
PROPS = [("misspelled name", lambda r: r["typo"]),
("name correct", lambda r: not r["typo"]),
("needs Lookup", lambda r: r["hidden"]),
("no Lookup needed", lambda r: not r["hidden"])]
print(f" {'':<18}{'Act':>8}{'ReAct':>8}")
for name, f in PROPS:
print(f" {name:<18}{show(pick('act', f)):>8}{show(pick('react', f)):>8}")
print("\n4. cost (average per question)")
print(f" {'':<10}{'tool calls':>11}{'new tokens':>12}{'seconds':>9}")
for m in METHODS:
rows = pick(m)
mean = lambda key: sum(r[key] for r in rows) / len(rows)
print(f" {LABEL[m]:<10}{mean('calls'):>11.1f}{mean('toks'):>12.1f}"
f"{mean('secs'):>9.1f}")
print("\n5. reasons and behavior flags of wrong Act and ReAct answers (count)")
print(" first four columns count wrong answers only; loop, miss, invalid "
"count all")
WHY = ("no_finish", "unopened", "unseen", "misread")
print(f" {'':<10}" + "".join(f"{w:>10}" for w in WHY)
+ f"{'loop':>6}{'miss':>6}{'invalid':>9}")
for m in ("act", "react"):
rows = pick(m)
why = Counter(r["why"] for r in rows if not r["ok"])
flags = Counter(f for r in rows for f in r["flags"])
print(f" {LABEL[m]:<10}" + "".join(f"{why[w]:>10}" for w in WHY)
+ f"{flags['loop']:>6}{flags['miss']:>6}{flags['invalid']:>9}")
print("\n6. use of Lookup")
print(" used / correct: among questions needing Lookup, how many used it "
"and how many were correct")
print(" calls / empty: among all questions, Lookup calls and calls with "
"no result")
print(f" {'':<10}{'used':>8}{'correct':>9}{'calls':>7}{'empty':>7}")
EMPTY = "no more results"
for m in ("act", "react"):
hid = pick(m, lambda r: r["hidden"])
used = [r for r in hid if any("Lookup[" in x for x in r["log"])]
calls = [x for r in pick(m) for x in r["log"] if "Lookup[" in x]
empty = [x for x in calls if EMPTY in x]
right = sum(r["ok"] for r in used)
print(f" {LABEL[m]:<10}{len(used):>4}/{len(hid)}{right:>9}"
f"{len(calls):>7}{len(empty):>7}")
print("\n7. paired per-question comparison of Act and ReAct (same question)")
act = {(r["world"], r["q"]): r["ok"] for r in pick("act")}
rea = {(r["world"], r["q"]): r["ok"] for r in pick("react")}
both = sum(act[k] and rea[k] for k in act)
only_rea = sum(rea[k] and not act[k] for k in act)
only_act = sum(act[k] and not rea[k] for k in act)
n_diff = only_rea + only_act
tail = sum(math.comb(n_diff, i) for i in range(min(only_rea, only_act) + 1))
p_val = min(1.0, 2 * tail / 2 ** n_diff) if n_diff else 1.0
print(f" both right {both}, only ReAct right {only_rea}, "
f"only Act right {only_act}, both wrong {len(act) - both - n_diff}")
print(f" exact binomial (sign) test, two-sided p = {p_val:.3f}")
by = {m: {(r["world"], r["q"]): r for r in pick(m)} for m in ("act", "react")}
for tag, win, lose in (
("only ReAct right", "react", "act"),
("only Act right", "act", "react")):
ks = [k for k in act if by[win][k]["ok"] and not by[lose][k]["ok"]]
kinds = Counter(by[win][k]["kind"] for k in ks)
why = Counter(by[lose][k]["why"] for k in ks)
hid = sum(by[win][k]["hidden"] for k in ks)
print(f" {tag} ({len(ks)} questions): "
+ ", ".join(f"{KINDS[i]} {kinds[i]}" for i in KINDS)
+ f"; needed sentence beyond the first 5 in {hid}")
print(" failure types of the losing side: "
+ ", ".join(f"{w} {why[w]}" for w in WHY))
def steps(log):
"""split a log line into (thought, action, observation)"""
out = []
for line in log:
_, rest = line.split(" ", 1)
thought, rest = rest.split(" | ", 1)
act, _, obs = rest.partition(" -> ")
out.append((thought, act, obs))
return out
def trace(title, r):
print(f"\n [{title}] {r['q']}")
print(f" {GOLD}: {r['gold']} | {MODEL}: {r['ans']}")
for i, (th, a, ob) in enumerate(steps(r["log"]), 1):
if th:
print(f" {T} {i}: {th}")
print(f" {A} {i}: {a}")
if ob:
print(f" {O} {i}: {ob[:80]}" + ("..." if len(ob) > 80 else ""))
print("\n8. traces (first item of each kind by a fixed rule; not cherry-picked)")
first = lambda rows: next(iter(rows), None)
react = pick("react")
ok3 = first([r for r in react if r["ok"] and r["kind"] == 3 and r["hidden"]])
bad = {w: first([r for r in react if not r["ok"] and r["why"] == w])
for w in WHY}
if ok3:
trace("ReAct success: 3-hop and needs Lookup", ok3)
for w in ("unseen", "misread", "no_finish"):
if bad[w]:
trace(f"ReAct, {w}", bad[w])
for w in ("unopened", "unseen"):
act_bad = first([r for r in pick("act")
if not r["ok"] and r["why"] == w])
if act_bad:
trace(f"Act, {w}", act_bad)
print("\n9. names that exist only in the examples, written by the model into "
"its own thoughts or actions")
EXAMPLE_ONLY = ("Shao Yuanzhou", "Alan Glass", "Kunzo Instruments", "He Malan",
"Yideli", "He Malan2", "Kaiwa", "Oster Country", "Duowei",
"Natara")
for m in ("act", "react"):
rows = pick(m)
leaky = [r for r in rows
if any(n in f"{t} {a}" for t, a, _ in steps(r["log"])
for n in EXAMPLE_ONLY)]
wrong = sum(not r["ok"] for r in leaky)
frac = f"{len(leaky)}/{len(rows)}"
print(f" {LABEL[m]:<10}" + f"{frac} questions, {wrong} of them wrong")
सांख्यिकी script का आउटपुट (चीनी संस्करण की original run से; ट्रेस टेक्स्ट अंग्रेज़ी में अनूदित, नाम romanized; धारा 8 की ट्रेसें स्थिर नियम से हर प्रकार की पहली, कोई चयन नहीं):
1. accuracy (exact match), 72 questions
all 95% CI world 1 world 2
Standard 11/72 15.3% [ 9, 25] 6/36 5/36
CoT 9/72 12.5% [ 7, 22] 4/36 5/36
Act 36/72 50.0% [ 39, 61] 21/36 15/36
ReAct 50/72 69.4% [ 58, 79] 23/36 27/36
lenient scoring: yes/no answers starting with no/not/never also count as no
Act 36/72, 0 answers rejudged
ReAct 52/72, 2 answers rejudged
2. by question kind (correct / total)
1-hop 2-hop 3-hop comparison
Standard 0/18 0/18 0/18 11/18
CoT 0/18 0/18 0/18 9/18
Act 12/18 7/18 5/18 12/18
ReAct 14/18 13/18 7/18 16/18
3. by question property (correct / total)
Act ReAct
misspelled name 6/12 9/12
name correct 30/60 41/60
needs Lookup 10/37 19/37
no Lookup needed 26/35 31/35
4. cost (average per question)
tool calls new tokens seconds
Standard 0.0 5.2 1.0
CoT 0.0 59.7 4.9
Act 2.5 49.6 6.2
ReAct 3.2 165.8 18.9
5. reasons and behavior flags of wrong Act and ReAct answers (count)
first four columns count wrong answers only; loop, miss, invalid count all
no_finish unopened unseen misread loop miss invalid
Act 0 21 15 0 5 14 0
ReAct 7 12 1 2 15 20 0
6. use of Lookup
used / correct: among questions needing Lookup, how many used it and how many were correct
calls / empty: among all questions, Lookup calls and calls with no result
used correct calls empty
Act 21/37 8 31 11
ReAct 36/37 19 45 19
7. paired per-question comparison of Act and ReAct (same question)
both right 31, only ReAct right 19, only Act right 5, both wrong 17
exact binomial (sign) test, two-sided p = 0.007
only ReAct right (19 questions): 1-hop 2, 2-hop 6, 3-hop 5, comparison 6; needed sentence beyond the first 5 in 12
failure types of the losing side: no_finish 0, unopened 8, unseen 11, misread 0
only Act right (5 questions): 1-hop 0, 2-hop 0, 3-hop 3, comparison 2; needed sentence beyond the first 5 in 3
failure types of the losing side: no_finish 0, unopened 3, unseen 0, misread 2
8. traces (first item of each kind by a fixed rule; not cherry-picked)
[ReAct success: 3-hop and needs Lookup] In which year was the company of Wei Haoyan's mentor founded?
gold answer: 1951 | model answer: 1951
Thought 1: I need to find Wei Haoyan's mentor first, then that mentor's company.
Action 1: Search[Wei Haoyan]
Observation 1: Wei Haoyan is a geologist. Wei Haoyan works at Weiluo Food. Wei Haoyan's mentor is Wei Yuanlin. Wei Haoyan was born in Lasi City. Wei Haoyan won the Turquoise Prize in 2016.
Thought 2: Wei Haoyan's mentor is Wei Yuanlin. Next, look up Wei Yuanlin's company.
Action 2: Search[Wei Yuanlin]
Observation 2: Wei Yuanlin is an astronomer. Wei Yuanlin works at Aoke Shipbuilding. Wei Yuanlin loves sailing. Wei Yuanlin has written 5 books. Wei Yuanlin was born in Luobei.
Thought 3: Wei Yuanlin works at Aoke Shipbuilding. Next, look up its founding year.
Action 3: Search[Aoke Shipbuilding]
Observation 3: Aoke Shipbuilding is a shipbuilding company. Aoke Shipbuilding is headquartered in Vitano. Aoke Shipbuilding sells products to 4 countries. Aoke Shipbuilding has about 5110 employees. Aoke Shipbuilding was founded by Qi Hengshu.
Thought 4: The founding year of Aoke Shipbuilding is not stated directly. I use Lookup to find 'founded' on the page.
Action 4: Lookup[founded]
Observation 4: (result 1/1) Aoke Shipbuilding was founded in 1951.
Thought 5: Aoke Shipbuilding was founded in 1951, so the answer is 1951.
Action 5: Finish[1951]
[ReAct, unseen] At which company does Cen Xiheng work?
gold answer: Kemi Machinery | model answer: cannot determine
Thought 1: I need to find Cen Xiheng's company.
Action 1: Search[Cen Xiheng]
Observation 1: Cen Xiheng is a composer. Cen Xiheng has written 7 books. Cen Xiheng loves gardening. Cen Xiheng's mentor is Ruan Haojin. Cen Xiheng was born in Kumiwei.
Thought 2: This page does not say which company Cen Xiheng works at. I use Lookup to find 'company' on the page.
Action 2: Lookup[company]
Observation 2: no more results.
Thought 3: No company information found. I look at similar entries.
Action 3: Search[Cen Xiheng similar]
Observation 3: not found[Cen Xiheng similar]. similar entries: ['Cen Xiheng', 'Cen Hengyan', 'Wei Henglin', 'Ruan Xijin', 'Ruan Yuxi']
Thought 4: No company information found. I look up the company of his mentor Ruan Haojin.
Action 4: Search[Ruan Haojin]
Observation 4: Ruan Haojin is an architect. Ruan Haojin has written 2 books. Ruan Haojin loves sailing. Ruan Haojin works at Beta Glass. Ruan Haojin won the Turquoise Prize in 1990.
Thought 5: Ruan Haojin works at Beta Glass, but the question asks about Cen Xiheng's company, so it cannot be determined.
Action 5: Finish[cannot determine]
[ReAct, misread] Were Qiu Yuyan and Qi Xiyan born in the same city?
gold answer: no | model answer: no
Thought 1: I need both birthplaces, then compare.
Action 1: Search[Qiu Yuyan]
Observation 1: Qiu Yuyan is a botanist. Qiu Yuyan has written 3 books. Qiu Yuyan was born in Keerluo. Qiu Yuyan loves chess. Qiu Yuyan's mentor is Qi Xiyan.
Thought 2: Qiu Yuyan was born in Keerluo. Now the birthplace of Qi Xiyan.
Action 2: Search[Qi Xiyan]
Observation 2: Qi Xiyan is a botanist. Qi Xiyan loves hiking. Qi Xiyan won the Ginkgo Prize in 2002. Qi Xiyan's mentor is Feng Xilan. Qi Xiyan was born in Weisluo.
Thought 3: Qiu Yuyan was born in Keerluo, Qi Xiyan in Weisluo. The cities differ, so the answer is no.
Action 3: Finish[no]
[ReAct, no_finish] At which company does Qiu Yuyan work?
gold answer: Kuwei Machinery | model answer: None
Thought 1: I need to find Qiu Yuyan's company.
Action 1: Search[Qiu Yuyan]
Observation 1: Qiu Yuyan is a botanist. Qiu Yuyan has written 3 books. Qiu Yuyan was born in Keerluo. Qiu Yuyan loves chess. Qiu Yuyan's mentor is Qi Xiyan.
Thought 2: This page does not say which company Qiu Yuyan works at. I use Lookup to find 'company' on the page.
Action 2: Lookup[company]
Observation 2: no more results.
Thought 3: No company information found. I look at similar entries.
Action 3: Search[Qiu Yuyan similar]
Observation 3: not found[Qiu Yuyan similar]. similar entries: ['Qiu Yuyan', 'Wei Linyan', 'Wei Yulan', 'Ruan Yuxi', 'Miao Jinyu']
Thought 4: No company information found. I try other possible keywords.
Action 4: Search[Qiu Yuyan company]
Observation 4: not found[Qiu Yuyan company]. similar entries: ['Qiu Yuyan', 'Wei Linyan', 'Wei Yulan', 'Ruan Yuxi', 'Miao Jinyu']
Thought 5: No company information found. I try other possible keywords.
Action 5: Search[Qiu Yuyan work]
Observation 5: not found[Qiu Yuyan work]. similar entries: ['Qiu Yuyan', 'Wei Linyan', 'Wei Yulan', 'Ruan Yuxi', 'Miao Jinyu']
Thought 6: No company information found. I try other possible keywords.
Action 6: Search[Qiu Yuyan employed]
Observation 6: not found[Qiu Yuyan employed]. similar entries: ['Qiu Yuyan', 'Wei Linyan', 'Wei Yulan', 'Ruan Yuxi', 'Miao Jinyu']
Thought 7: No company information found. I try other possible keywords.
Action 7: Search[Qiu Yuyan employed at]
Observation 7: not found[Qiu Yuyan employed at]. similar entries: ['Qiu Yuyan', 'Wei Linyan', 'Wei Yulan', 'Ruan Yuxi', 'Miao Jinyu']
[Act, unopened] In which country was Feng Xixilin born?
gold answer: Siaota Country | model answer: Kutasi
Action 1: Search[Feng Xixilin]
Observation 1: not found[Feng Xixilin]. similar entries: ['Feng Xilin', 'Ke Xixi', 'Feng Xilan', 'Feng Haolin', 'Wei Linyan']
Action 2: Search[Feng Xilin]
Observation 2: Feng Xilin is a botanist. Feng Xilin has written 8 books. Feng Xilin loves gardening. Feng Xilin was born in Kutasi. Feng Xilin's mentor is Ruan Haojin.
Action 3: Finish[Kutasi]
[Act, unseen] At which company does Qiu Yuyan work?
gold answer: Kuwei Machinery | model answer: cannot determine
Action 1: Search[Qiu Yuyan]
Observation 1: Qiu Yuyan is a botanist. Qiu Yuyan has written 3 books. Qiu Yuyan was born in Keerluo. Qiu Yuyan loves chess. Qiu Yuyan's mentor is Qi Xiyan.
Action 2: Search[Qi Xiyan]
Observation 2: Qi Xiyan is a botanist. Qi Xiyan loves hiking. Qi Xiyan won the Ginkgo Prize in 2002. Qi Xiyan's mentor is Feng Xilan. Qi Xiyan was born in Weisluo.
Action 3: Finish[cannot determine]
9. names that exist only in the examples, written by the model into its own thoughts or actions
Act 0/72 questions, 0 of them wrong
ReAct 1/72 questions, 1 of them wrong
नतीजे
- समग्र (धारा 1)। Standard व CoT केवल 11 व 9 सही (15.3%, 12.5%) — सब 18 द्विविकल्प तुलनाओं से; यादृच्छिक अनुमान भी 9 देता; इसलिए 1–3 hop का 0/18 ही design की अपेक्षा: नाम गढ़े, parameters में उत्तर नहीं। Act 36 सही (50.0%), ReAct 50 (69.4%)। उसी प्रश्न पर paired (धारा 7): दोनों सही 31, केवल ReAct सही 19, केवल Act सही 5; sign test p = 0.007।
- अंतर असमान, p मान आशावादी। World 1 में ReAct केवल +2 (23 बनाम 21); world 2 में +12 (27 बनाम 15)। दोनों worlds व्यक्ति व कंपनियाँ साझा करते हैं — एक ही व्यक्ति कई प्रश्नों में, प्रश्न स्वतंत्र नहीं। जो कहा जा सकता है: दिशा सुसंगत; “ReAct Act से कितने प्रतिशत अंक ऊपर” इस पैमाने पर अर्थहीन।
- अंतर कहाँ (धारा 2, 3)। Hop के अनुसार: 1-hop पर ReAct बनाम Act 14 बनाम 12; 2-hop पर 13 बनाम 7 — सबसे बड़ा; 3-hop पर 7 बनाम 5, दोनों नीचे। गुण के अनुसार: अंतर मुख्यतः Lookup माँगने वाले प्रश्नों से — 19/37 बनाम 10/37; Lookup की ज़रूरत न होने वाले 31/35 बनाम 26/35। Misspelled नाम के 12 में 9 बनाम 6 — sample छोटा, व्याख्या नहीं।
- सोच ने क्रिया कैसे बदली (धारा 6)। Lookup माँगने वाले उन 37 में ReAct ने 36 पर Lookup लिया, Act केवल 21; ReAct की ट्रेस में observation में आवश्यक सूचना कम पड़ते ही सोच “यह पृष्ठ … नहीं कहता; मैं Lookup से पृष्ठ में खोजूँगा” लिखती है, उसके बाद Lookup (धारा 8 की पहली ट्रेस पूरा उदाहरण)। Act में यह कदम नहीं: प्रायः दो पृष्ठ पढ़कर सीधे Finish — “मुझे और क्या चाहिए” कहीं नहीं लिखा। Act के examples में Lookup भी दिखाया गया — अंतर यह नहीं कि उसे क्रिया का पता नहीं। Example की सोच एक ही समय तर्क भी है और “कब Lookup बदलना है” का प्रशिक्षण भी — prompt में दोनों अलग नहीं होते।
- Act की विफलताएँ (धारा 5; ट्रेसें धारा 8)। 36 ग़लतों में 21 आवश्यक प्रविष्टि खोले बिना, 15 खोली पर आवश्यक वाक्य कभी नहीं दिखा; कोई
no_finish, कोईmisreadनहीं। ठेठ चरण: जल्दी समाप्ति — “किसी का जन्म किस देश में” पर व्यक्ति पृष्ठ खोजकर सीधेFinish[Kutasi]— पहली hop का शहर ही उत्तर मान लिया, शहर पृष्ठ नहीं देखा; “किसी की कंपनी कौन-सी” पर उसका व गुरु का पृष्ठ खोजकर आवश्यक वाक्य न देखकरFinish[cannot determine]। - ReAct की विफलताएँ तर्क की विफलता जैसी (धारा 5)। 22 ग़लतों में 7 बार 7 कदम ख़त्म उत्तर नहीं (
no_finish), 12 आवश्यक प्रविष्टि नहीं खोली, 1unseen, 2misread; 15 प्रश्नों में दोहराई क्रिया, 20 में Search प्रविष्टि नहीं मिली। ठेठ चक्र:Lookup[company]निरर्थक (पृष्ठ “works at …” लिखता है, “company” शब्द नहीं), फिर हर कदम की सोच “नहीं मिला; दूसरे keyword आज़माता हूँ”, क्रियाएँSearch[Qiu Yuyan company],Search[Qiu Yuyan work],Search[Qiu Yuyan employed]… जब तक कदम ख़त्म (धारा 8 कीno_finishट्रेस)। Lookup कुल 45 बुलावे, 19 निरर्थक। Paper तालिका 2 की “reasoning error (दोहराए चक्र सहित)” व “search result error” यही श्रेणियाँ; यहाँ कारण और स्पष्ट: Lookup का keyword प्रश्न के शब्दों से, पृष्ठ दूसरी भाषा उपयोग करता है। - कदम छोड़ दो तो गढ़ता है। 12
unopenedमें एक प्रकार: “कंपनी के मुख्यालय का देश” पर Lookup से मुख्यालय शहर “Kutasi” मिलने के बाद सोच सीधे “Kutasi Oster Country में है” लिख देती है — शहर पृष्ठ नहीं खोला; और “Oster Country” संयोग से examples में आया देश-नाम है, test world के उस शहर के देश से असंगत। यही paper तालिका 2 की CoT hallucination: एक retrieval कदम छोड़ दो तो ReAct भी न देखा तथ्य गढ़ देता है, और examples की सामग्री को world ज्ञान मान लेता है (धारा 9: केवल examples में मौजूद नाम ReAct के 72 उत्तरों में 1 बार उसकी सोच में; Act में शून्य)। - निर्णयकर्ता की एक खामी (धारा 1 का लचीला निर्णय)। ग़लत ट्रेसें पढ़ते हुए मिला: 2 तुलना प्रश्नों में ReAct ने “no” उत्तर लिखा, gold “no” (दोनों अंग्रेज़ी रेंडरिंग में एक जैसे गिर जाते हैं; मूल चीनी में दो भिन्न शब्द थे — “बु” बनाम “फ़ौ”)। Examples में हाँ/नहीं वाले प्रश्न नहीं, उत्तर format सिखाया नहीं गया। मैंने नियम बदलकर पुनर्चालन नहीं किया; मुख्य तालिका exact match ही (ReAct 50/72); साथ लचीले निर्णय की पंक्ति (नकारात्मक प्रारंभ भी “नहीं” गिने जाएँ): ReAct 52/72, Act 36/72 (Act का कोई उत्तर नहीं बदला)। यह समायोजन दोनों का क्रम नहीं बदलता।
- लागत (धारा 4)। ReAct प्रति प्रश्न औसत 3.2 tool बुलावे, 165.8 नए tokens, 18.9 सेकंड (M2 Max); Act 2.5, 49.6, 6.2। ReAct का prefix भी सबसे लंबा (972 tokens)। सटीकता generation की मात्रा से ख़रीदी गई।
यह प्रयोग क्या बता सकता है, क्या नहीं
- बता सकता है: “उत्तर retrieval से ही मिल सकता है” सेटिंग में क्रिया से पहले की सोच लिखवाना मॉडल के निर्णय बदलता है — मुख्यतः “आगे खोजूँ या नहीं, किस क्रिया से”; सोच से उपजी विफलताएँ paper के विश्लेषण से मेल (चक्र, निरर्थक search से भटकना, कदम छोड़कर गढ़ना); CoT शैली की hallucination इस सेटिंग में ReAct में “कदम छोड़कर गढ़ने” के रूप में आती है।
- नहीं बता सकता: Paper में ReAct-Act का अंतर (HotpotQA 27.4 बनाम 25.7; ALFWorld 71% बनाम 45%) इतना ही होगा या नहीं; यहाँ ReAct ने Act से +14 (50 बनाम 36) — parameters का ज्ञान बंद करने और template वाक्यों वाले पृष्ठों की सेटिंग में। Paper में Standard का HotpotQA 28.7 है — बहुत प्रश्न 540B parameters से ही हल हो जाते; यहाँ वह राह बंद, इसलिए यहाँ का अंतर paper की संख्याओं से आकार में तुलना नहीं।
- पैमाना: 72 प्रश्न, एक 4B मॉडल, दो worlds, चार examples, एक prompt सेट; paper तालिका 3 में ReAct की success 6 prompt groups में 48% से 71% — prompt की पसंद विधि के अंतर से बड़ी हो सकती है, और यहाँ एक भी prompt नहीं बदला। वही प्रयोग अंग्रेज़ी prompts व अंग्रेज़ी नकली विकी से स्वतंत्र एक और रन (स्वतंत्र पूर्ण चालन, आँकड़े अलग जाँचे): ReAct ने Act से केवल +4 (48 बनाम 44), और अंतर Lookup की ज़रूरत न होने वाले प्रश्नों में — यहाँ से उलटा। केवल prompt भाषा व नकली नाम भिन्न दो संस्करणों ने +14 व +4 दिए — यह गिरावट ऊपर के किसी भी p मान से बड़ा noise-प्रमाण है।
- Environment का सरलीकरण: पृष्ठ template वाक्य; कोई विभेदन, समानार्थी, noise या पुरानी सूचना नहीं; Lookup literal match — वास्तविक retrieval से कठोर, वास्तविक पृष्ठों से सरल भविष्यवाणी।
- Greedy decoding: Paper चक्र को greedy से जोड़ता है; यहाँ sampling नहीं आज़माया — चक्र prompt की देन है या decoding की, नहीं छाँटा जा सका।
सीमाएँ और आगे की राह
Paper की अपनी सीमाएँ: केवल prompt पर ReAct छोटे मॉडलों के लिए सबसे कठिन (8B व 62B पर ReAct prompts चार विधियों में सबसे ख़राब; fine-tune के बाद ही सर्वश्रेष्ठ); retrieval गुणवत्ता उसकी ऊपरी सीमा तय करती है; HotpotQA पर CoT से नीचे। Paper का निष्कर्ष यहीं रुकता है: hybrids व fine-tuning उसके दिए रास्ते; अधिक मानव data बेहतर रास्ता हो सकता है।
ऊपर की जाँच से कुछ और: paper PaLM प्रयोगों की evaluation set आकार व runs नहीं बताता; तालिका 1 के error bars नहीं — एक-दो अंकों का निर्णय असंभव; तालिका 3 की “सर्वश्रेष्ठ” पंक्तियाँ हर task का अधिकतम, एकल trial नहीं; तालिका 5 और तालिका 1 में उसी विधि का 2.0 अंतर, व्याख्या नहीं।
आगे के कामों ने इस paper की स्थिति बदल दी:
- Tool calling अब केवल prompt नहीं। Toolformer व्याख्या की self-supervised विधि से मॉडल data से सीखे कब tool बुलाए; आज के मॉडल function calling सीधे क्षमता के रूप में प्रशिक्षित, क्रियाएँ structured interface से (देखें structured output व function calling)।
- ‘सोच’ मॉडल में प्रशिक्षित। Reasoning मॉडलों का अपना सोच चरण; tool calling सोच के भीतर; “पहले सोचो फिर करो” examples के format से सिखाना ज़रूरी नहीं (देखें तर्क सुदृढ़ीकरण अधिगम)।
- विफलता के बाद प्रतिबिंब। Reflexion (arXiv 2303.11366) agents को विफलता के बाद भाषा में प्रतिबिंब लिखवाकर अगली कोशिश के context में — ठीक ReAct के चक्र व निरर्थक खोज के विरुद्ध।
- मूल्यांकन: एकल success दर काफ़ी नहीं; Agent मूल्यांकन स्थिरता व ट्रेस देखता है (देखें Agents और tool calling में pass^k व ट्रेस मूल्यांकन)।
इस paper में सबसे ज़रूरी बातें
- सोच action space का एक अतिरिक्त खाना। ReAct का पूरा बदलाव action space को “क्रिया प्लस भाषा” करना: सोच environment नहीं बदलती, context बदलती है — योजना, स्थिति पीछा, असामान्यता सँभालने के लिए।
- तुलनाएँ खोलकर मापो। Paper ने अलग सोच हटाई (Act), क्रिया हटाई (CoT), सोच को environment feedback से बदला (ReAct-IM); पुनरुत्पादन में भी केवल “सोच है या नहीं” बदला। एक कुल स्कोर से सोच ने ठीक क्या बदला, नहीं दिखता।
- ReAct हर जगह बेहतर नहीं। HotpotQA में CoT से हारा; paper का उत्तर hybrids व fine-tuning; किसी prompt विधि का मूल्यांकन करने से पहले पूछो: उसकी विफलताएँ क्या स्वीकार्य हैं?
- विफलता की शैली कुल स्कोर से अधिक सूचनात्मक। CoT की विफलता hallucination; ReAct की चक्र व निरर्थक खोज से भटकना; Act की जल्दी समाप्ति; इस लेख के छोटे प्रयोग में भी यही तीन, प्लस ReAct का कदम छोड़कर गढ़ना।
- त्रुटि की चेतना रखो। Paper तालिका 1 के error bars नहीं; इस लेख के 72 प्रश्नों में हर प्रश्न लगभग 1/72; अंतर noise से छोटा तो व्याख्या न करें; prompt groups के बीच का फ़र्क़ प्रायः विधियों के बीच के अंतर से बड़ा।
Further reading
- Paper: ReAct (arXiv 2210.03629); यह लेख v3 (10 मार्च 2023) पर; लेखकों का project पृष्ठ react-lm.github.io।
- Paper के datasets व environments: HotpotQA (arXiv 1809.09600), FEVER (arXiv 1803.05355), ALFWorld (arXiv 2010.03768), WebShop (arXiv 2207.01206)।
- Paper की तुलना व उद्धृत विधियाँ: chain-of-thought (arXiv 2201.11903), self-consistency (arXiv 2203.11171), WebGPT (arXiv 2112.09332), SayCan (arXiv 2204.01691), Inner Monologue (arXiv 2207.05608)।
- आगे का काम: Reflexion (arXiv 2303.11366)।
- इस साइट: Agents और tool calling, structured output व function calling, Prompt Engineering, CoT व्याख्या, Toolformer व्याख्या।
अक्सर पूछे जाने वाले सवाल
- ReAct क्या है? CoT (chain-of-thought) से क्या अंतर?
- ReAct (Reasoning and Acting) 'सोच' को भी एक क्रिया बनाता है: मॉडल 'सोच, क्रिया, अवलोकन' के बीच बारी रखता है; क्रिया बाहरी tools बुलाती है (जैसे search और पृष्ठ-भीतर lookup); सोच केवल context में लिखी जाती है, environment नहीं बदलती। CoT में केवल तर्क, कोई क्रिया नहीं — सब parameters में याद ज्ञान पर; तथ्य ग़लत याद हुआ तो हर अगला कदम ग़लती पर। Paper में ReAct तथ्य-जाँच Fever पर CoT से बेहतर (60.9 बनाम 56.3), multi-hop HotpotQA पर थोड़ा नीचे (27.4 बनाम 29.4); दोनों का मिश्रण सर्वश्रेष्ठ।
- क्या ReAct हमेशा chain-of-thought से बेहतर?
- हमेशा नहीं। Paper के ही HotpotQA नतीजों में ReAct का exact match (27.4) CoT (29.4) से नीचे: बारी की संरचना तर्क की लचीलापन सीमित करती है, और निरर्थक search results उसे एक ही सोच-क्रिया के चक्र में फँसा देते हैं। Paper के सर्वश्रेष्ठ स्कोर दोनों को एक-दूसरे की वापसी बनाने वाले hybrids से (HotpotQA पर ReAct→CoT-SC 35.1; Fever पर CoT-SC→ReAct 64.6), और 3,000 ट्रेसों से fine-tune किए ReAct से।
- ReAct का prompt कैसा होता है? Fine-tuning चाहिए?
- मुख्य सेटिंग में fine-tuning नहीं। हर example एक पूरी ट्रेस: पहले प्रश्न, फिर 'Thought i, Action i, Observation i' दोहराते, अंत में Finish[उत्तर]; क्रियाएँ स्थिर format (HotpotQA में Search[entity], Lookup[string], Finish[answer]); observations environment भरता है; examples की सोच annotators की सीधी प्राकृत भाषा। Frozen PaLM-540B को 1–6 मानव examples; fine-tuning दूसरा प्रयोग — 3,000 सही ट्रेसों से PaLM-8B व 62B।
- ReAct की आम विफलताएँ क्या हैं?
- Paper के मानव annotations में ReAct की विफलताएँ मुख्यतः reasoning errors (47%, एक ही सोच-क्रिया के चक्र सहित) और search ने उपयोगी सामग्री न निकाली (23%); CoT की मुख्य विफलता hallucination (56%)। इस लेख के नकली विकी प्रयोग में वही पैटर्न: Lookup का keyword पृष्ठ की शब्दावली से न मिले तो ReAct तरह-तरह से फिर खोजता रहता है जब तक कदम ख़त्म; एक कदम छोड़ दे तो न देखा तथ्य भी गढ़ देता है (गढ़ा देश का नाम examples में आया ही था)।
- आज के function calling और Agents से ReAct का संबंध?
- ReAct का चक्र (मॉडल अगला कदम तय करे, environment चलाकर observation दे, observation context में, मॉडल फिर तय करे) आज लगभग सब Agent loops का न्यूनतम रूप है। अब मॉडल क्रियाएँ function calling interface से कहते हैं, reasoning मॉडलों में सोच का चरण अंतर्निहित, tool calling सीधे क्षमता के रूप में प्रशिक्षित — prompt-निर्भर नहीं; पर 'सोच, क्रिया, अवलोकन' की बारी की संरचना वही है।