Repository navigation
Conversation
3lf
left a comment
There was a problem hiding this comment.
Independent review of the #33 to #39 stack at 7465e1e: needs changes, priority high.
The history summarizer re-summarizes the whole history every turn, so it does not cut cost (WRAP-004). With langchain-openai>=1.6.3, .content is a list of blocks, not text (WRAP-005).
Size: this PR takes README.md from 521,762 to 530,726 bytes (+8,964). The README panel on the repo page only renders about the first 512,000 bytes, and main was already over that. Details and options in the #33 review, under "Stack level".
Line numbers inside the findings refer to the stack head (b779ae9) unless another commit is named; each link points to the line in this PR.
4 findings are inline threads on this diff.
The 11 findings below are nits, or on lines this PR does not change but within its topic:
Minor
- WRAP-030 · README.md:1666 · pre-existing
In Claude Opus 5.5, thinking is always on andmax_tokenscaps thinking and answer text together. Withmax_tokens=1024and a Persian answer, the reply may be cut off midway or contain no text block at all. The code at lines 1687 to 1689 and the streaming example at lines 1942 to 1950 don't checkstop_reason, so they print truncated text as if it were a complete answer. This contradicts the book's own warning at line 1253 (a low cap can run out before the final text) and the PR #35 warning at line 1973 (the text you see isn't necessarily the complete answer). The basic OpenAI examples (lines 1641 to 1650) and the OpenAI streaming example (lines 1917 to 1931) also ignorefinish_reason; onlyread_complete_textat line 1760 checks it.
Suggested fix: In both Anthropic examples, raisemax_tokensto e.g.4096and add this after the response:if message.stop_reason != "end_turn": print("\n[جواب کامل نشد: ", message.stop_reason, "]"). In the Anthropic streaming example, addfinal = stream.get_final_message()after the loop and the samestop_reasoncheck. Also add one sentence under the note at line 1692: «تو این مدلهاmax_tokensسقف فکر و متن با همه؛ سقف رو خیلی کم نگیر و دلیل پایان رو چک کن.» - WRAP-031 · README.md:1915 · pre-existing
The warning at line 1973 (PR #35) rightly says the program must tell a successful finish apart from a dropped connection, a refused request or hitting the output cap, and must mark unfinished text as «ناتمام» ("unfinished"). But the streaming loop right above that warning never readsfinish_reason, so a stream that ended withlengthorcontent_filterfinishes exactly like a complete answer, and the reader never sees the warning put into practice. Also, if the reader enablesstream_options={"include_usage": True}to log token counts (habit 4, line 1979), the last chunk has emptychoicesandchunk.choices[0]crashes withIndexError. The code is unchanged frommain; PR #35 only added the text warning.
Suggested fix: Change the loop to this (only a few extra lines):For the Anthropic example, add this after the loop:finish_reason = None for chunk in stream: if not chunk.choices: # مثلاً تیکه آخر گزارش مصرف continue choice = chunk.choices[0] if choice.delta.content: print(choice.delta.content, end="", flush=True) if choice.finish_reason: finish_reason = choice.finish_reason if finish_reason != "stop": print(f"\n[جواب ناتمام موند: {finish_reason}]")
if stream.get_final_message().stop_reason == "max_tokens": print("\n[جواب به سقف توکن خورد]"). - WRAP-033 · README.md:2498 · pre-existing
This sentence has the model running code itself. It never does: it writes the code, and the provider's infrastructure runs it in a sandbox. That contradicts the chapter's main message, which the PRs reinforced (line 2494: «برنامه اون رو بررسی و اجرا میکنه», "the program checks and runs it"), and step 2 of the same list (line 2527) correctly says «این کد در محیط ایزوله سمت سرور اجرا میشه» ("this code runs in an isolated server-side environment"). The heading «Server-side Tools / Code Execution» also equates server-side tools with code execution, while web search and web fetch are server-side tools too.
Suggested fix: Change the sentence to «اینجا مدل کد رو مینویسه و زیرساخت ارائهدهنده همونجا (توی یه محیط ایزوله یا Sandbox) اجراش میکنه؛ برنامه تو لازم نیست خودش اجراش کنه.» and the heading to «ابزارهای سمت سرور (Server-side Tools، مثل اجرای کد یا جستجوی وب)». - WRAP-035 · README.md:3003 · pre-existing
The agent chapter teaches the loop with no stop condition other than «حل شد» ("solved"): no step limit, no cost or time budget, and nothing on what to do when the agent is stuck. Figure vis-15 only has «کافیه؟» ("enough?"). In the coding-agent section, step 4 (line 3475) says «تا سبز شدن ادامه میده» ("keeps going until green") and vis-37 shows an uncapped «همه سبز» ("all green") loop as well, with no warning that the agent must not delete or weaken tests to get to green. The same book caps the validation loop (line 2673) and prompt optimization (line 2448), and chapter 17 (line 4546) counts «شرط توقف» ("stop condition") as a cause of failure, yet the place that teaches the agent loop says nothing about it.
Suggested fix: After the detective-loop list, add: «تو برنامه واقعی، حلقه رو بیسقف ول نکن: حداکثر تعداد قدم، بودجه هزینه یا زمان بذار و اگه به سقف رسید، کار رو با گزارش «تموم نشد» به انسان بسپار.» Also change step 4 of the coding agent to: «... و تا سبز شدن یا رسیدن به سقف تلاش ادامه میده؛ حذف یا ضعیفکردن تست برای سبز شدن قبول نیست.»
Nits (7)
- WRAP-098 · README.md:1779 · pre-existing
The comments at lines 1788, 1791 and 1794 state the model's behavior as fact, as if it were real output, with no "sample" or "hypothetical" label. PR #38 added such labels to the café example (line 1006) and the streaming timings (line 1955), but not here. Readers may think «قیمه بادمجون» is the output of a real run.
Suggested fix: Suggested comments, in order: «# جواب نمونه (فرضی): قیمه بادمجون! مواد لازم: ...», «# چون تاریخچه همراه درخواست میره، مدل میتونه بفهمه منظورت همون غذاست» and «# انتظار داریم هنوز درباره نسخه بدون گوشت حرف بزنه». - WRAP-099 · README.md:2529 · pre-existing
The phrase «سمت تقویم Google نشسته» ("sits on the Google Calendar side") suggests Google itself hosts the MCP server; usually an MCP server is a separate program (on your own machine or another server) that talks to the calendar API. Line 2554 also says «میزبان مغز متفکره» ("the host is the thinking brain"), while a few lines later (line 2578) the model is called «مغز» ("the brain"), so there are two brain metaphors. The glossary (line 6575) also defines MCP as «استاندارد اتصال ابزارها به مدلها» ("a standard for connecting tools to models"), whereas the correct text at line 2543 says it connects applications to tools and data. PR #39 changed line 2552 only to fix the spelling of Google.
Suggested fix: Line 2552: «برنامهای که به تقویم Google وصل میشه (روی سیستم خودت یا یه سرور دیگه اجرا میشه) و ابزارها و دادهها رو در دسترس میذاره». Line 2554: «میزبان هماهنگکنندهست (مدل هم داخل همینه)، سرور دستها رو در اختیار میذاره...». Line 6575: «استاندارد اتصال اپلیکیشنهای مبتنی بر LLM به ابزارها و دادهها». - WRAP-100 · README.md:2652 · pre-existing
Figure vis-14 shows the «نامعتبر ← تلاش دوباره ← مدل» (invalid → retry → model) path with no cap and no "report error" exit, while the text right above it (line 2673, rewritten in PR #38) states a cap of 3 attempts and an error report. A reader who only looks at the figure learns an endless loop.
Suggested fix: In the figure, add a «حداکثر ۳ بار» ("at most 3 times") label next to «تلاش دوباره» and a «گزارش خطا» exit. If the figure won't change, change the caption to: «... اعتبارسنجی خروجی خراب رو قبل از رسیدن به کد متوقف میکنه؛ تلاش دوباره سقف داره و بعدش خطا گزارش میشه.» - WRAP-101 · README.md:3062 · pre-existing
The figure's third panel is titled «طرحریزی و اجرا», but the section heading (line 3069), the alt text and the caption say «برنامهریزی و اجرا» (two different words for "planning"). The panel also has a «بازبینی» ("review") box with an arrow back to «نقشه» ("plan"), i.e. replanning, while the text at line 3073 only explains «اول نقشه کامل، بعد اجرا» ("full plan first, then execute").
Suggested fix: Either change the figure label to «برنامهریزی و اجرا», or add to the text at line 3073: «اگه وسط کار نتیجه با نقشه نخوند، نقشه رو بازبینی و دوباره اجرا میکنه.» - WRAP-102 · README.md:3130 · pre-existing
The nearest «نمونه بالا» ("example above") is the multi-agent system figure (line 3145), not the LangChain agent (line 3093) the text means.mainhad the same ambiguity with «حلقهای که بالا دیدیم» ("the loop we saw above"); PR #35 rewrote the sentence but didn't make the reference clear.
Suggested fix: Change «تو نمونه بالا» to «تو مثال LangChain همین فصل (ایجنت نرخ ارز)». - WRAP-103 · README.md:3164 · pre-existing
Spelling varies within one section: «موس» (lines 3173, 3176) vs «ماوس» (lines 3187, 3189) for "mouse", and «تایید» (lines 3184, 3187, 3483) vs «تأیید» (lines 3197, 3226) for "confirm", without and with hamza. PR #39, which is about Persian consistency, didn't unify them, and its own line 3483 uses «تایید»; PR #38 also added «تامین» (line 2451, also without hamza). CONTRIBUTING only makes the hamza-less «سوال» a rule and has none for the others, so this is an inconsistency, not a rule violation.
Suggested fix: Pick one form (e.g. «تأیید» and «ماوس», or the hamza-less spellings and «موس»), record it in CONTRIBUTING, then unify every occurrence. - WRAP-104 · README.md:6022 · new in #35
The new captions use the formal «اگر» ("if"): line 6085 from PR #35, and line 6516 from PR #39, which was itself the "Persian polish" PR. The rest of the prose uses the colloquial «اگه». Next to «میشه», «میکنن» and «داری» in the same sentences, «اگر» is out of tone.
Suggested fix: Line 6085: «اگه ابزار ابری، لاگ بیرونی یا قابلیت آنلاین هم به برنامه وصل کرده باشی، ...». Line 6516: «اگه لازم شد، از خلاصهسازی یا بازیابی کمک بگیر.»
| summary = get_summary_from_llm(summary_prompt + old_text) | ||
| return read_complete_text(response) | ||
|
|
||
| def summarize_history(messages, keep_turns=2): |
There was a problem hiding this comment.
Major (new in #35) · WRAP-004
With the PR #35 redesign, the full history always stays in messages, and summarize_history only runs when each request is built. So every turn resends all old turns to the summarizer: its input grows with each turn, and each turn costs an extra paid request. Since old + recent is the whole history, the total input tokens per turn (summarizer plus main request) are never lower than simply sending the whole history, and the summarizer prompt and the summary text come on top. So this "solution" does not fix the «انباشت توکن» (token accumulation, line 1799) that the section exists to solve; it only keeps the main request's context bounded. The summary is also rebuilt from scratch every turn and can change between turns. The text at line 1877 only calls summarization «یه درخواست جدا با هزینه» (a separate, paid request) and says nothing about the summarizer's input growing. The main version replaced the old messages with the summary and returned a compacted list.
Suggested fix: Keep the summary and only fold the turns that have just left the window into the previous summary. To avoid a new global variable (which line 1797 itself rules out for real code), keep the state in a factory function and pass that to prepare_history. For example, def make_summarizer(keep_turns=2): holds state = {"summary": "", "done": 0} and an inner function prepare(messages) that splits off the old part with split_history, sends only old[state["done"]:] together with state["summary"] to the summarizer, then sets state["done"] = len(old) and returns system + recent with the summary. Usage: chat("...", prepare_history=make_summarizer()). Suggested text under the code: «این نمونه خلاصه رو هر بار از نو نمیسازه؛ فقط نوبتهایی که تازه از پنجره بیرون افتادن به خلاصه قبلی اضافه میشن. اگه هر بار کل بخش قدیمی رو خلاصه کنی، ورودی خلاصهساز هم مثل تاریخچه رشد میکنه و صرفهجویی توکن از بین میره.» A cheaper model could also be suggested for the summarizer.
| > ⚠️ **متن دیدهشده لزوماً جواب کامل نیست:** برنامه باید پایان موفق پاسخ رو از قطع اتصال، رد درخواست یا رسیدن به سقف خروجی جدا کنه. اگر استریم وسط کار قطع شد، متن قبلی رو «ناتمام» نشون بده. تلاش دوباره ممکنه جواب تازهای بسازه؛ اون رو به ادامه متن قبلی نچسبون و هزینه تلاشهای قبلی رو هم حساب کن. | ||
|
|
||
| > 🧰 **چهار عادت حرفهای برای کد پروداکشن:** | ||
| > ۱. **تلاش دوباره (Retry) با فاصلههای فزاینده (Exponential Backoff):** APIها گاهی شلوغن (ارور 429 یا 503). به جای کرش، چند بار با فاصلههای فزاینده دوباره تلاش کن. (نمونه کدش رو تو [پروژه عملی](#پروژه-عملی-ساخت-دستیار-پرسشوپاسخ-فارسی-) همین راهنما داریم.) |
There was a problem hiding this comment.
Minor (pre-existing) · WRAP-032
This professional habit sits exactly where the reader works with the raw SDK, but it doesn't mention that the official OpenAI and Anthropic SDKs already retry twice by default with increasing delays. Anyone who wraps client.chat.completions.create in their own retry loop multiplies the requests (3 x 3 = 9), which raises cost and latency. It also treats every 429 as "the server is busy", while a 429 for exhausted credit won't be fixed by retrying. The practical project (lines 6186 and 6223) handles this correctly with max_retries=0, but the core lesson at this line is still incomplete.
Suggested fix: Rewrite habit 1 as: «۱. تلاش دوباره (Retry) با فاصلههای فزاینده (Exponential Backoff): بعضی خطاها موقتیان، مثل 503 یا ۴۲۹ِ محدودیت نرخ. SDKهای رسمی OpenAI و Anthropic خودشون بهطور پیشفرض دو بار دوباره تلاش میکنن؛ اگه حلقه تلاش خودت رو مینویسی، تکرار SDK رو با max_retries=0 خاموش کن تا تلاشها ضرب نشن. خطای کلید، درخواست نامعتبر یا تمومشدن اعتبار با تلاش دوباره درست نمیشه. (نمونه کدش رو تو پروژه عملی همین راهنما داریم.)»
| </div> | ||
|
|
||
| بیا یه مثال **واقعی و کامل** ببینیم که تو عمل چطور کار میکنه. فرض کن یه اپلیکیشن داری که کاربر ازش میپرسه «هوای تهران چطوره؟» و مدل باید ابزار آبوهوا رو صدا بزنه، جواب بگیره و به زبان آدمیزاد توضیح بده: | ||
| بیا مسیر یه دور فراخوانی ابزار رو با **داده آموزشی** ببینیم. تابع واقعاً اجرا میشه، ولی عددهای آبوهوا رو خودمون تو کد گذاشتیم و زنده نیستن. برای داده روز، باید داخل همین تابع به سرویس آبوهوا وصل بشی: |
There was a problem hiding this comment.
Minor (new in #35) · WRAP-034
In a book about LLMs, «داده آموزشی» means training data, but here the intended meaning is made-up demo weather data. The example's own code (the docstring at line 2697 and the user message) calls it «داده نمونه» ("sample data"), and line 4688 correctly uses «داده آموزشی» for model training data. Readers may think these numbers come from the model's training data.
Suggested fix: Suggested wording: «بیا مسیر یه دور فراخوانی ابزار رو با داده نمونه (ساختگی) ببینیم. تابع واقعاً اجرا میشه، ولی عددهای آبوهوا رو خودمون تو کد گذاشتیم و زنده نیستن.»
| @@ -2675,7 +2713,7 @@ if ai_response.tool_calls: | |||
| # ۷. مدل حالا با نتیجه ابزار، جواب نهایی رو میسازه | |||
| final_response = llm_with_tools.invoke(messages) | |||
| print(f"جواب نهایی: {final_response.content}") | |||
There was a problem hiding this comment.
Major (pre-existing) · WRAP-005
The book itself (lines 2292 and 2625) requires langchain-openai 1.6.3 or later so that GPT-6 with tools goes through the Responses API. On that path AIMessage.content is not a string but a list of blocks. So the four print calls in these chapters print a Python list like [{'type': 'text', 'text': '...\u200c...', 'annotations': [], 'id': '...'}] instead of a Persian sentence, and the half-space shows up as \u200c. The comment at line 2739 (rewritten by PR #35) promises a clean sentence. The code doesn't crash, but a reader who copies it sees output that doesn't match the book and may think their code is broken.
Suggested fix: Use .text instead of .content in all four places: print(f"جواب نهایی: {final_response.text}"), print(f"جواب مدل: {ai_response.text}"), print(f"جواب نهایی: {result['messages'][-1].text}") and print(result["messages"][-1].text). Also add one sentence to the note at line 2292: «تو این مسیر، محتوای پیام مدل ممکنه یه لیست از بلوکها باشه؛ برای گرفتن متن ساده از .text استفاده کن.»
1c5ffc0 to
bbe8ff1
Compare
7465e1e to
7488f61
Compare
bbe8ff1 to
88d6a7a
Compare
7488f61 to
d4f1369
Compare
Make conversation state local and transactional: summarize the previous summary plus newly evicted turns, and commit history and summary together after a complete answer. Keep the summary as user data, print plain text from block messages, identify incomplete or empty responses, and handle usage-only stream chunks. Supply the immediate LangChain dependencies used by the examples.
Clarify retry ownership, server-side tool execution, MCP roles, demo data and bounded agent loops; align the validation, agent, replanning and coding-workflow figures. Add committed README-extracted keyless tests, a fence-aware source helper, pinned SDK test dependencies and Python 3.12 CI. This draft depends on #34 and targets
docs/base-generation-prompting.d4f13699468559cad765970f16387896f729a271: 79 Node tests, source/anchor QA, volatile-data checks and workflow lint. CI..textoutput expressions; no live model requests are made.This update keeps the existing PR Draft. No merge or release is included.