-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Allow applying gr.cache() to intermediate functions directly
#13322
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
abidlabs
wants to merge
10
commits into
main
Choose a base branch
from
cachee2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
949f266
changes
abidlabs 7690707
add changeset
gradio-pr-bot 56febd1
Apply suggestion from @abidlabs
abidlabs dc58e43
changes
abidlabs 5b430c6
changes
abidlabs 3ac9bc8
changes
abidlabs 3c33cb2
changes
abidlabs a6aa372
changes
abidlabs 94ab1f0
changes
abidlabs 5ae37bc
changes
abidlabs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "gradio": minor | ||
| --- | ||
|
|
||
| feat:Allow applying `gr.cache()` to intermediate functions directly | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| """Demo showcasing runtime gr.cache(fn)(...) for an intermediate helper call.""" | ||
|
|
||
| import re | ||
| import time | ||
|
|
||
| import gradio as gr | ||
|
|
||
| POLICIES = { | ||
| "Billing": [ | ||
| { | ||
| "title": "Refund windows", | ||
| "text": "Customers can request a refund within 30 days of purchase. " | ||
| "Annual subscriptions can be prorated if the request arrives after the " | ||
| "first 30 days but before day 90.", | ||
| }, | ||
| { | ||
| "title": "Invoice corrections", | ||
| "text": "Billing agents can correct invoice email addresses, company " | ||
| "names, and tax identifiers, but cannot alter the purchase date.", | ||
| }, | ||
| { | ||
| "title": "Duplicate charges", | ||
| "text": "If two charges appear within 24 hours for the same plan and " | ||
| "customer account, billing should confirm card fingerprint and issue a " | ||
| "same-day reversal.", | ||
| }, | ||
| ], | ||
| "IT": [ | ||
| { | ||
| "title": "Password resets", | ||
| "text": "IT can revoke all active sessions and force a password reset " | ||
| "after verifying the employee through the HR directory.", | ||
| }, | ||
| { | ||
| "title": "VPN access", | ||
| "text": "New VPN access is approved only for employees with manager " | ||
| "approval and a registered MFA device.", | ||
| }, | ||
| { | ||
| "title": "Laptop replacement", | ||
| "text": "Broken laptops should be tagged with the device asset number " | ||
| "and shipped to the repair center before a replacement is issued.", | ||
| }, | ||
| ], | ||
| "HR": [ | ||
| { | ||
| "title": "Parental leave", | ||
| "text": "Full-time employees are eligible for 16 weeks of paid parental " | ||
| "leave after six months of employment.", | ||
| }, | ||
| { | ||
| "title": "Address changes", | ||
| "text": "Employees should update their home address in the HR portal " | ||
| "before payroll closes on the 20th of each month.", | ||
| }, | ||
| { | ||
| "title": "Interview scheduling", | ||
| "text": "Recruiters should provide interview panels at least 48 hours " | ||
| "to review candidate materials before the session starts.", | ||
| }, | ||
| ], | ||
| } | ||
|
|
||
| TONE_PREFIX = { | ||
| "Concise": "Give a short answer.", | ||
| "Friendly": "Give a warm, helpful answer.", | ||
| "Formal": "Give a professional and policy-focused answer.", | ||
| } | ||
|
|
||
|
|
||
| def _tokens(text: str) -> set[str]: | ||
| return set(re.findall(r"[a-z0-9]+", text.lower())) | ||
|
|
||
|
|
||
| def retrieve_passages(question: str, team: str) -> list[dict[str, str | int]]: | ||
| """Pretend retrieval is the expensive deterministic step.""" | ||
| time.sleep(2) | ||
| query_tokens = _tokens(question) | ||
| ranked = [] | ||
| for doc in POLICIES[team]: | ||
| combined_text = f"{doc['title']} {doc['text']}" | ||
| score = len(query_tokens & _tokens(combined_text)) | ||
| ranked.append( | ||
| { | ||
| "title": doc["title"], | ||
| "text": doc["text"], | ||
| "score": score, | ||
| } | ||
| ) | ||
|
|
||
| ranked.sort(key=lambda item: item["score"], reverse=True) | ||
| return ranked[:2] | ||
|
|
||
|
|
||
| def draft_answer(question: str, team: str, tone: str) -> tuple[str, str, str]: | ||
| start = time.time() | ||
|
|
||
| passages = gr.cache(retrieve_passages)(question, team) | ||
| top_match = passages[0] | ||
| bullets = "\n".join( | ||
| f"- {match['title']}: {match['text']}" for match in passages | ||
| ) | ||
|
|
||
| answer = ( | ||
| f"{TONE_PREFIX[tone]}\n\n" | ||
| f"For a {team.lower()} request about '{question}', the strongest match is " | ||
| f"**{top_match['title']}**.\n\n" | ||
| f"Suggested reply: Based on the current {team.lower()} policy, {top_match['text']}" | ||
| ) | ||
| debug = ( | ||
| f"Retrieved {len(passages)} passages in {time.time() - start:.2f}s.\n" | ||
| "Try the same question twice, or change only the tone. " | ||
| "The retrieval helper should be reused from cache." | ||
| ) | ||
| return answer, bullets, debug | ||
|
|
||
|
|
||
| with gr.Blocks(title="Intermediate gr.cache() Demo") as demo: | ||
| gr.Markdown( | ||
| "# Intermediate `gr.cache()` Demo\n" | ||
| "This simulates a support assistant where the **retrieval** step is expensive " | ||
| "but deterministic, while the final answer still recomputes. " | ||
| "Submit the same question twice, or change only the tone, and watch Gradio " | ||
| "show the `used cache` badge when the cached helper is reused." | ||
| ) | ||
|
|
||
| with gr.Row(): | ||
| with gr.Column(): | ||
| team = gr.Dropdown( | ||
| choices=list(POLICIES.keys()), | ||
| value="Billing", | ||
| label="Team", | ||
| ) | ||
| tone = gr.Dropdown( | ||
| choices=["Concise", "Friendly", "Formal"], | ||
| value="Friendly", | ||
| label="Answer style", | ||
| ) | ||
| question = gr.Textbox( | ||
| label="Customer question", | ||
| lines=3, | ||
| value="Can this customer get a refund after being charged twice?", | ||
| ) | ||
| draft = gr.Markdown() | ||
| retrieved = gr.Markdown() | ||
| debug = gr.Textbox(label="Debug", lines=3) | ||
| gr.Button("Draft reply").click( | ||
| draft_answer, | ||
| [question, team, tone], | ||
| outputs=[draft, retrieved, debug], | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| demo.launch() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The changeset summary line is missing a space after
feat:; most tooling that parses conventional commits expectsfeat: ...(with a space). Updating this improves changelog readability and consistency.