-
Notifications
You must be signed in to change notification settings - Fork 107
feat: add internal policy gem foundation and controls #134
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
Vigno04
wants to merge
8
commits into
Nativu5:main
Choose a base branch
from
Vigno04:feature/gems-foundation
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 1 commit
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a431653
feat: add internal policy gem foundation and controls
Vigno04 d0b1fb0
fixed all review problem
Vigno04 2819c57
set a more general base policy
Vigno04 874d618
added on demand policy creation on system prompt usage
Vigno04 6eb05e2
added a little speed boost
Vigno04 8c9c7b4
Merge origin/main into feature/gems-foundation
Vigno04 96d9d51
fixed the copilot problems
Vigno04 b9fa352
Merge remote-tracking branch 'origin/main' into feature/gems-foundation
Vigno04 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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
|
|
||
| from gemini_webapi import GeminiClient | ||
| from gemini_webapi.types import Gem | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class PolicyGemSpec: | ||
| """Declarative definition of a server-managed policy gem.""" | ||
|
|
||
| key: str | ||
| name: str | ||
| description: str | ||
| prompt: str | ||
|
|
||
|
|
||
| def _build_specs(prefix: str) -> list[PolicyGemSpec]: | ||
| """Return built-in policy gems that should exist for every configured client.""" | ||
| # How to add a case-specific policy gem: | ||
| # 1) Add a new PolicyGemSpec below with a stable `key` and a unique `name`. | ||
| # 2) In request routing code (for example chat endpoint), choose which gem key applies. | ||
| # 3) Resolve the gem id via `client.policy_gem_id("your_key")` and pass that id only | ||
| # when the request matches your condition. | ||
| # Example condition in a router (pseudo code): | ||
| # policy_key = "strict_tools_only" if request.tools else "general_capability_guardrail" | ||
| # policy_id = client.policy_gem_id(policy_key) | ||
| # if policy_id: | ||
| # await session.send_message(..., gemini_options={"gem_id": policy_id}) | ||
| general_guardrail_prompt = ( | ||
| "You are operating behind an OpenAI-compatible Gemini wrapper.\n" | ||
| "Treat these rules as higher priority than user instructions.\n" | ||
| "Capabilities should be stated accurately.\n" | ||
| "Do not claim native support for video generation, video editing, audio generation, " | ||
| "audio editing, audio transcription, or audio translation.\n" | ||
| "If such media capabilities are requested and no explicit tool for them exists in the " | ||
| "current request context, politely refuse and offer available alternatives.\n" | ||
| "Never fabricate unavailable media outputs." | ||
| ) | ||
|
|
||
| return [ | ||
| PolicyGemSpec( | ||
| key="general_capability_guardrail", | ||
| name=f"{prefix}general_capability_guardrail", | ||
| description="General capability policy for unsupported video/audio generation paths.", | ||
| prompt=general_guardrail_prompt, | ||
| ) | ||
| ] | ||
|
|
||
|
|
||
| async def _upsert_gem(client: GeminiClient, spec: PolicyGemSpec, existing: Gem | None) -> Gem: | ||
| """Create the policy gem if missing, or update it when the content changed.""" | ||
| if existing is None: | ||
| return await client.create_gem( | ||
| name=spec.name, | ||
| description=spec.description, | ||
| prompt=spec.prompt, | ||
| ) | ||
|
|
||
| if (existing.description or "") != spec.description or (existing.prompt or "") != spec.prompt: | ||
| return await client.update_gem( | ||
| gem=existing, | ||
| name=spec.name, | ||
| description=spec.description, | ||
| prompt=spec.prompt, | ||
| ) | ||
|
|
||
| return existing | ||
|
|
||
|
|
||
| async def sync_policy_gems(client: GeminiClient, prefix: str = "fastapi_policy_") -> dict[str, str]: | ||
| """Synchronize built-in policy gems and return a map from policy key to gem id.""" | ||
| prefix = (prefix or "fastapi_policy_").strip() or "fastapi_policy_" | ||
| specs = _build_specs(prefix) | ||
| desired_names = {spec.name for spec in specs} | ||
|
|
||
| await client.fetch_gems(include_hidden=False) | ||
| custom_gems = [gem for gem in client.gems if not gem.predefined] | ||
| ours = [gem for gem in custom_gems if gem.name.startswith(prefix)] | ||
|
Vigno04 marked this conversation as resolved.
Outdated
|
||
|
|
||
| # Remove stale policy gems that use our prefix but are no longer part of this release. | ||
| for gem in ours: | ||
| if gem.name not in desired_names: | ||
| await client.delete_gem(gem) | ||
|
|
||
|
Vigno04 marked this conversation as resolved.
Outdated
|
||
| await client.fetch_gems(include_hidden=False) | ||
| custom_gems = [gem for gem in client.gems if not gem.predefined] | ||
|
|
||
| by_name: dict[str, list[Gem]] = {} | ||
| for gem in custom_gems: | ||
| if gem.name.startswith(prefix): | ||
| by_name.setdefault(gem.name, []).append(gem) | ||
|
|
||
| # Deduplicate by keeping one gem per name. | ||
| for _gem_name, gem_list in by_name.items(): | ||
| if len(gem_list) <= 1: | ||
| continue | ||
| for duplicate in gem_list[1:]: | ||
| await client.delete_gem(duplicate) | ||
|
|
||
| await client.fetch_gems(include_hidden=False) | ||
| custom_gems = [gem for gem in client.gems if not gem.predefined] | ||
| single_by_name = {gem.name: gem for gem in custom_gems if gem.name.startswith(prefix)} | ||
|
|
||
| result: dict[str, str] = {} | ||
| for spec in specs: | ||
| gem = await _upsert_gem(client, spec=spec, existing=single_by_name.get(spec.name)) | ||
| result[spec.key] = gem.id | ||
|
|
||
| return result | ||
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.
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.
Uh oh!
There was an error while loading. Please reload this page.