Metadata-Version: 2.4
Name: gemi
Version: 0.1.0
Summary: 🤖 gemi — the simplest Python library for Google Gemini web app
Author: xlastfire
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives.
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and included
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work; and
        
              (d) If the Work includes a "NOTICE" text file, as part of your
                  distribution, you must include a readable copy of the
                  attribution notices contained within such NOTICE file.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied. You are solely responsible for determining the appropriateness
              of using or reproducing the Work and assume any risks associated
              with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              shall any Contributor be liable for damages, including any direct,
              indirect, special, incidental, or exemplary damages of any character
              arising as a result of this License or out of the use or inability
              to use the Work (including but not limited to damages for loss of
              goodwill, work stoppage, computer failure or malfunction, or all
              other commercial damages or losses).
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer
              additional warranty, liability, or other obligations. However, in
              accepting such obligations, You may offer such conditions only on
              Your own behalf and on Your sole responsibility.
        
           END OF TERMS AND CONDITIONS
        
Project-URL: Homepage, https://github.com/xlastfire/gemi
Project-URL: Repository, https://github.com/xlastfire/gemi
Project-URL: Issues, https://github.com/xlastfire/gemi/issues
Project-URL: Documentation, https://github.com/xlastfire/gemi#readme
Keywords: gemini,google,AI,LLM,chatbot,generative-ai,async,reverse-engineered
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: curl-cffi~=0.14.0
Requires-Dist: loguru~=0.7.3
Requires-Dist: orjson~=3.11.7
Requires-Dist: pydantic~=2.12.5
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: browser
Requires-Dist: browser-cookie3; extra == "browser"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Dynamic: license-file

# 🤖 gemi

The **simplest** Python library for Google Gemini — no API key, no `asyncio`, just your browser cookies.

[![Python](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org)
[![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](LICENSE)

```python
from gemi import Gemini

g = Gemini()
print(g.ask("What is the capital of France?"))
```

---

## ✨ Features

- **No `asyncio` required** — everything works in regular Python scripts
- **Zero-config auth** — reads cookies from env vars, `.env`, JSON file, or browser
- **Simple `ask()`** — returns a `Response` with `.text`, `.images`, `.thoughts`
- **Streaming** — `g.stream()` yields text as it arrives
- **Multi-turn chat** — `g.chat()` remembers context across messages
- **Gems** — create, list, update, and delete system prompt presets
- **Chat management** — list, read, and delete your Gemini history
- **Deep Research** — `g.research("topic")` → full web-browsed report
- **Image generation** — `g.generate_image("a cat")` + `.save_images()`
- **CLI tool** — `gemi ask "What is 2+2?"`
- **Async support** — `async_ask()`, `async_stream()` available too

---

## 📦 Installation

```bash
pip install gemi
```

With automatic browser cookie detection:

```bash
pip install "gemi[browser]"
```

> Requires Python 3.10+

---

## 🔑 Authentication

You need your Gemini session cookies. There are several ways to provide them:

### Option A — Environment Variables (recommended)

```bash
export GEMINI_PSID="your __Secure-1PSID value"
export GEMINI_PSIDTS="your __Secure-1PSIDTS value"
```

Or in a `.env` file in your project directory:

```env
GEMINI_PSID=your_value_here
GEMINI_PSIDTS=your_value_here
```

Then just use `Gemini()` — it auto-discovers them.

### Option B — Direct

```python
g = Gemini(psid="...", psidts="...")
```

### Option C — JSON Cookie File

```python
g = Gemini(cookies_json="cookies.json")
```

Supports browser export formats (array of objects, flat dict, `{"cookies": [...]}` wrapper).

### Option D — Auto Browser (needs `[browser]` extra)

```bash
pip install "gemi[browser]"
```

Just be logged in to [gemini.google.com](https://gemini.google.com) in your browser.

### How to get your cookies

1. Go to [gemini.google.com](https://gemini.google.com) and log in
2. Press `F12` → **Network** tab → refresh the page
3. Click any request → **Cookies** tab
4. Copy `__Secure-1PSID` and `__Secure-1PSIDTS`

---

## 🚀 Usage

### Ask a question

```python
from gemi import Gemini

g = Gemini()

response = g.ask("What is the capital of France?")
print(response.text)   # "Paris"
print(response)        # same — str(response) returns the text
```

### Streaming

```python
for chunk in g.stream("Write a poem about the ocean"):
    print(chunk, end="", flush=True)
print()
```

### Multi-turn Chat

```python
chat = g.chat(model="flash")

chat.say("My name is Alex and I love astronomy.")
reply = chat.say("What books would you recommend for me?")
print(reply)

# View conversation history
for role, text in chat.history:
    print(f"[{role}] {text[:80]}")

# Save to file
chat.save("conversation.txt")

# Keep the chat ID to resume later
print(chat.chat_id)  # → "c_abc123..."
```

### Resume a Previous Chat

```python
chat = g.resume_chat("c_abc123")
chat.say("Continue from where we left off.")
```

### Attach Files (Images, PDFs, Documents)

```python
response = g.ask(
    "Summarize this document and describe the image",
    files=["report.pdf", "diagram.png"]
)
print(response.text)
```

### Choose a Model

```python
g.ask("Hello!", model="flash")
g.ask("Solve this math problem: ...", model="thinking")
g.ask("Write a detailed essay", model="pro")
```

| Alias | Model |
|---|---|
| `flash` | gemini-3-flash |
| `pro` | gemini-3-pro |
| `thinking` | gemini-3-flash-thinking |
| `flash-plus` | gemini-3-flash-plus |
| `pro-plus` | gemini-3-pro-plus |
| `thinking-plus` | gemini-3-flash-thinking-plus |
| `flash-advanced` | gemini-3-flash-advanced |
| `pro-advanced` | gemini-3-pro-advanced |
| `thinking-advanced` | gemini-3-flash-thinking-advanced |

### Thinking Models

```python
response = g.ask("What is 17 × 23?", model="thinking")
print(response.thoughts)  # reasoning steps
print(response.text)      # final answer
```

### Images

```python
# Get web images in a response
response = g.ask("Show me pictures of the Eiffel Tower")
for img in response.web_images:
    print(img.title, img.url)

# Generate AI images
response = g.generate_image("a futuristic city at sunset")
paths = response.save_images("./generated/")
print(paths)  # ['/path/to/generated/gemi_0.png']

# One-liner: generate and auto-save
g.generate_image("a cute robot", save_to="./robots/")
```

### Chat Management

```python
# List recent conversations
for chat in g.list_chats():
    print(chat["id"], chat["title"])

# Read a chat's full history
turns = g.read_chat("c_abc123")
for turn in turns:
    print(f"[{turn['role']}] {turn['text'][:80]}")

# Delete one chat
g.delete_chat("c_abc123")

# Delete multiple chats at once
results = g.delete_chats(["c_abc", "c_def", "c_ghi"])
print(results)  # {'c_abc': True, 'c_def': True, 'c_ghi': True}
```

### Gems (System Prompt Presets)

```python
# List all gems
for gem in g.get_gems():
    kind = "system" if gem["predefined"] else "custom"
    print(f"[{kind}] {gem['name']} → {gem['id']}")

# Find a specific gem by name
gem = g.get_gem(name="Coding partner")

# Use a gem in a one-shot ask
response = g.ask("Review my code", gem=gem["id"])

# Use a gem in a multi-turn chat
chat = g.chat(gem=gem["id"])
chat.say("Help me write a Python function")

# Create a custom gem
my_gem = g.create_gem(
    name="Python Teacher",
    prompt="You are a patient Python teacher. Explain with simple examples.",
    description="For learning Python",
)
print(my_gem["id"])

# Update a gem
g.update_gem(
    gem_id=my_gem["id"],
    name="Advanced Python Teacher",
    prompt="You are an expert Python engineer. Focus on best practices.",
)

# Delete a gem
g.delete_gem(my_gem["id"])
```

### Deep Research

```python
# One-liner — returns the full report as a string
report = g.research("Impact of large language models on software engineering")
print(report)

# With progress callback and save to file
def show_progress(status):
    print(f"  [{status['state']}]", end="\r", flush=True)

report = g.research(
    "Climate change adaptation strategies 2025",
    timeout=600,
    on_status=show_progress,
)

with open("report.md", "w") as f:
    f.write(report)
```

### List Available Models

```python
for m in g.list_models():
    status = "✓" if m["available"] else "✗"
    print(f"[{status}] {m['name']}: {m['display_name']}")

# Or just get available names
print(g.models)
```

### Temporary Conversations (not saved to history)

```python
response = g.ask("Secret question", temporary=True)
```

### Context Manager

```python
with Gemini() as g:
    print(g.ask("Hello!"))
# client closes cleanly
```

### Async Usage (for async code / Jupyter notebooks)

```python
import asyncio
from gemi import Gemini

async def main():
    g = Gemini()
    async with g:
        response = await g.async_ask("Hello!")
        print(response.text)

        async for chunk in g.async_stream("Tell me a story"):
            print(chunk, end="", flush=True)

asyncio.run(main())
```

### Account Diagnostics

```python
info = g.inspect()
print("Deep Research:", info["deep_research_available"])
print("Status:", info["account_status"])
```

---

## 🖥️ CLI

After installing you get the `gemi` command:

```bash
# Ask a question
gemi ask "What is quantum entanglement?"

# Stream a response
gemi stream "Write a haiku about code"

# Interactive chat REPL
gemi chat

# Resume an existing chat
gemi chat c_abc123

# List recent conversations
gemi chats

# Read a chat's message history
gemi read c_abc123

# Delete one or more chats
gemi delete c_abc123 c_def456

# List available models
gemi models

# List gems
gemi gems

# Create a custom gem
gemi gem-create --name "Chef" --prompt "You are a master chef."

# Update a gem
gemi gem-update GEM_ID --name "Chef Pro" --prompt "Updated prompt"

# Delete a gem
gemi gem-delete GEM_ID

# Run a deep research task
gemi research "AI trends in 2025" --output report.md

# Check account feature availability
gemi inspect
```

### CLI Authentication

```bash
# Via environment variables (recommended)
export GEMINI_PSID="..."
export GEMINI_PSIDTS="..."
gemi ask "Hello"

# Via JSON cookie file
gemi --cookies cookies.json ask "Hello"

# Via direct flags
gemi --psid "..." --psidts "..." ask "Hello"

# Via proxy
gemi --proxy http://127.0.0.1:8080 ask "Hello"

# Enable debug output
GEMINI_DEBUG=1 gemi ask "Hello"
```

---

## 📁 Project Structure

```
gemi/
├── src/
│   └── gemi/
│       ├── __init__.py     # Public API
│       ├── client.py       # Gemini class (main entry point)
│       ├── chat.py         # Chat class (multi-turn conversations)
│       ├── response.py     # Response wrapper
│       ├── cookies.py      # Cookie discovery from multiple sources
│       ├── exceptions.py   # Re-exported exceptions
│       └── cli.py          # CLI (installed as `gemi` command)
├── pyproject.toml
├── README.md
└── LICENSE
```

---

## ❗ Notes

- Uses **browser session cookies** — unofficial reverse-engineered API
- Cookie tokens expire; re-export them if you get an `AuthError`
- Deep Research and image generation depend on your Google account type and region
- Some features require **Gemini Advanced** (paid subscription)

---

## 📄 License

Apache License 2.0. See [LICENSE](LICENSE).
