Skip to content
Merged
146 changes: 94 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,25 @@ from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()])

# Stream text responses in real-time
stream = ai.generate_stream(
model="googleai/gemini-flash-latest",
prompt="Stream a 2-line poem about space.",
)
async for chunk in stream:
print(chunk.text, end="")

# Access final response metadata
response = await stream.response
async def main() -> None:
# 1. Stream text as the model writes it
stream = ai.generate_stream(
model="googleai/gemini-flash-latest",
prompt="Stream a 2-line poem about space.",
)
async for chunk in stream:
print(chunk.text, end="")
print()

# 2. Await the final response for usage and finish reason
response = await stream.response
print(response.finish_reason)
# => stop


if __name__ == "__main__":
ai.run_main(main())
```

### 2. Streaming Tool Calling & Structured Output
Expand All @@ -47,50 +56,70 @@ from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()])

# Define a tool with Pydantic type annotations

# 1. Define a tool with a Pydantic input
class WeatherInput(BaseModel):
city: str = Field(description="Target city name")


@ai.tool(description="Get current weather for a location")
async def get_weather(input: WeatherInput) -> str:
return f"Sunny, 72°F in {input.city}"

# Define structured output schema

# 2. Define the structured output schema
class ActivityPlan(BaseModel):
activities: list[str]
outfit: str

# Stream response with automatic tool execution and structured output
stream = ai.generate_stream(
model="googleai/gemini-flash-latest",
prompt="Suggest activities for Seattle today.",
tools=[get_weather],
output_schema=ActivityPlan,
)
async for chunk in stream:
if chunk.text:
print(chunk.text, end="")

# Access validated Pydantic output object
response = await stream.response
print(response.output)
# => ActivityPlan(activities=['Kayak on Lake Union', 'Discovery Park'], outfit='Light jacket')
async def main() -> None:
# 3. Stream; Genkit runs the tool calls and parses the output
stream = ai.generate_stream(
model="googleai/gemini-flash-latest",
prompt="Suggest activities for Seattle today.",
tools=[get_weather],
output_schema=ActivityPlan,
)
async for chunk in stream:
if chunk.text:
print(chunk.text, end="")
print()

# 4. Read the validated Pydantic object
response = await stream.response
print(response.output)
# => activities=['Kayak on Lake Union', 'Discovery Park'] outfit='Light jacket'


if __name__ == "__main__":
ai.run_main(main())
```

### 3. Tool Approval Middleware & Restarts

```python
from genkit import Genkit
from pydantic import BaseModel
from genkit.exp import Genkit
from genkit_google_genai import GoogleAI
from genkit_middleware import Middleware, ToolApproval

ai = Genkit(plugins=[GoogleAI(), Middleware()])
tool_approval = ToolApproval(allowed_tools=[])


# 1. A tool takes one input, so group the fields in a model
class Transfer(BaseModel):
amount: float
to_account: str


@ai.tool(description="Transfer money to an account")
async def transfer_money(amount: float, to_account: str) -> str:
return f"Transferred ${amount} to {to_account}"
async def transfer_money(transfer: Transfer) -> str:
return f"Transferred ${transfer.amount} to {transfer.to_account}"


# 2. Every tool call pauses for approval (allowed_tools=[])
agent = ai.define_agent(
name="bankingAgent",
model="googleai/gemini-flash-latest",
Expand All @@ -99,15 +128,23 @@ agent = ai.define_agent(
use=[tool_approval],
)

chat = agent.chat()
out1 = await chat.send("Transfer $100 to account 999.")
# => Returns INTERRUPTED status because transfer_money requires approval

# Approve pending tool interrupts and resume execution
restarts = [intr.restart(resumed_metadata={"tool_approved": True}) for intr in out1.interrupts]
out2 = await chat.resume(restart=restarts)
print(out2.text)
# => "$100 has been successfully transferred to account 999."
async def main() -> None:
# 3. The turn stops at the pending transfer
chat = agent.chat()
out1 = await chat.send("Transfer $100 to account 999.")
print(out1.finish_reason)
# => interrupted

# 4. Approve the pending calls and resume
restarts = [intr.restart(resumed_metadata={"tool_approved": True}) for intr in out1.interrupts]
out2 = await chat.resume(restart=restarts)
print(out2.text)
# => $100 has been transferred to account 999.


if __name__ == "__main__":
ai.run_main(main())
```

### 4. Agent Loops & Persistent Sessions
Expand All @@ -125,23 +162,29 @@ from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()])

# Persist multi-turn session history in Cloud Firestore
# 1. Persist multi-turn session history in Cloud Firestore
store = FirestoreSessionStore()

# Define an agent with persistent session memory
# 2. Define an agent backed by the store
agent = ai.define_agent(
name="supportAgent",
model="googleai/gemini-flash-latest",
system="You are a helpful customer support agent.",
store=store,
)

# Multi-turn chat with automatic persistent session state
chat = agent.chat()
res1 = await chat.send("Hi, my name is Alex.")
res2 = await chat.send("What was my name again?")
print(res2.text)
# => "Your name is Alex!"

async def main() -> None:
# 3. Each turn is saved; the next one sees the history
chat = agent.chat()
await chat.send("Hi, my name is Alex.")
res = await chat.send("What was my name again?")
print(res.text)
# => Your name is Alex.


if __name__ == "__main__":
ai.run_main(main())
```

---
Expand All @@ -151,11 +194,11 @@ print(res2.text)
<table>
<tr>
<td><strong>Type-Safe by Design</strong></td>
<td>Leverage native Python type annotations and Pydantic models for structured inputs, outputs, and automatic tool schema generation.</td>
<td>Native Python type annotations and Pydantic models drive structured inputs, outputs, and tool schemas.</td>
</tr>
<tr>
<td><strong>Unified Model API</strong></td>
<td>Switch effortlessly between Google Gemini, Anthropic Claude, OpenAI, Ollama, and Vertex AI using a single consistent interface.</td>
<td>Switch between Google Gemini, Anthropic Claude, OpenAI, Ollama, and Vertex AI with one interface.</td>
</tr>
<tr>
<td><strong>Integrated Observability</strong></td>
Expand All @@ -171,7 +214,7 @@ print(res2.text)

## Developer Tools & Dev UI

Accelerate AI development with the local Genkit Developer UI and CLI.
Run flows, prompts and tools locally with the Genkit Developer UI and CLI.

```bash
genkit start -- uv run main.py
Expand All @@ -180,28 +223,27 @@ genkit start -- uv run main.py
Key features:
- **Playground**: Run and experiment with Genkit flows, prompts, and tools in dedicated playgrounds.
- **Trace Inspector**: Analyze detailed execution traces, including step-by-step breakdowns of complex flows.
- **Evaluations**: Review performance metrics and evaluate model outputs over time.

<img src="docs/resources/readme-ui-traces-screenshot.png" width="700" alt="Screenshot of Genkit Developer UI showing traces">

---

## Exploring Samples & Onboarding

Jumpstart your app with copy-pasteable reference implementations in [`samples/`](samples/):
Reference implementations live in [`samples/`](samples/):

- **[Basic Flows](samples/basic-flows)**: Text generation, real-time streaming, structured Pydantic schemas, and type-safe tools
- **[Basic Flows](samples/basic-flows)**: Typed flows, named `ai.run` steps, streaming, and serving over FastAPI. No model or API key needed
- **[Agents](samples/agents)**: Autonomous multi-turn agents, session state persistence, and memory
- **[Multimodal & Advanced Gemini](samples/google-genai-media)**: Multimodal media processing, context caching, and code execution
- **[Model Evaluation](samples/evaluators)**: Automated quality evaluation, scoring metrics, and assertion suites
- **[Tool Interrupts](samples/tool-interrupts)**: Pausing tool calls for human approval and resuming the turn

### Running Samples Locally

Clone the repository and launch any sample with the interactive Dev UI:

```bash
cd samples/<sample-name>
genkit start -- uv run main.py
genkit start -- uv run src/main.py
```

---
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# API Reference

!!! note
Full Genkit documentation is available at [genkit.dev](https://genkit.dev/python/docs/get-started/)
Full Genkit documentation is available at [genkit.dev](https://genkit.dev/docs/python/get-started/)

## genkit

Expand Down
23 changes: 14 additions & 9 deletions docs/migrating-from-0.12.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ If you're a coding agent, replace each enum member with its string value. The va

Every removed name, and what to use instead:

- **Model enums** (`KnownGemini*`, `KnownGpt`, `KnownClaude`, `*Version`, `GeminiEmbeddingModels`, `VertexEmbeddingModels`): pass the model name as a string, such as `'openai/gpt-4o'`.
- **Model enums** (`KnownGeminiModels`, `KnownGemini*`, `KnownGpt`, `KnownClaude`, `*Version`, `GeminiEmbeddingModels`, `VertexEmbeddingModels`): pass a typed ref such as `GoogleAI.gemini('gemini-flash-latest')` or `OpenAI.gpt('gpt-4o')`, or the model name as a string, such as `'openai/gpt-4o'`.
- **Name helpers** (`bedrock_name`, `anthropic_name`, `ollama_name`, `openai_model`, `genkit_eval_name`, `package_name`): use the full `'plugin/model'` string.
- **`Candidate`**: use the response's `message`.
- **`Document.data`, `Document.data_type`, `Document.from_data()`**: build a `Document` with its constructor.
Expand Down Expand Up @@ -404,7 +404,7 @@ async def run(n: int, ctx: ActionRunContext) -> str:
```python
from genkit import FlowContext

@ai.flow()
@ai.flow
async def run(n: int, ctx: FlowContext[Status]) -> str:
ctx.send_chunk(Status(step='search'))
```
Expand All @@ -427,7 +427,7 @@ async def prepare(dish: str, ctx: ToolRunContext) -> str: ...
```python
from genkit import ToolContext

@ai.tool()
@ai.tool
async def prepare(dish: str, ctx: ToolContext[Progress]) -> str:
ctx.send_chunk(Progress(stage='searing', percent=40))
```
Expand Down Expand Up @@ -472,7 +472,7 @@ async def slow(x: dict, ctx: ToolRunContext) -> dict:
**New:**

```python
@ai.tool()
@ai.tool
async def slow(x: dict) -> dict:
while not done:
await step() # cancellation raises asyncio.CancelledError here
Expand All @@ -485,7 +485,7 @@ task = asyncio.create_task(ai.generate(prompt=p))
task.cancel()
```

To stop a stream early, use `async with` (or call `aclose()`). A bare `break` without it leaves the flow running.
To stop a stream early, use `async with` (or call `aclose()`). After a bare `break`, the flow keeps running until the stream object is garbage-collected.

```python
stream = my_flow.stream(x)
Expand All @@ -498,7 +498,7 @@ async with stream:
Cancellation can now land at any `await` in your tool, so put cleanup for partial work in `finally`. If you catch `asyncio.CancelledError` yourself, re-raise it.

```python
@ai.tool()
@ai.tool
async def book_trip(trip: Trip) -> Booking:
hold = await reserve_seats(trip)
try:
Expand Down Expand Up @@ -660,7 +660,7 @@ async def get_order(order_id: str) -> Order:
```python
from genkit import PublicError

@ai.flow()
@ai.flow
async def get_order(order_id: str) -> Order:
order = await db.find(order_id)
if order is None:
Expand Down Expand Up @@ -783,7 +783,10 @@ model = openai_model('gpt-4o')
**New:**

```python
model = 'openai/gpt-4o'
from genkit_openai import OpenAI

model = OpenAI.gpt('gpt-4o') # typed ref; autocompletes and binds OpenAIConfig
model = 'openai/gpt-4o' # plain string also works
```

## Ollama
Expand Down Expand Up @@ -912,9 +915,11 @@ from genkit.middleware import Middleware, MiddlewareContext
@ai.middleware
class PiiRedact(Middleware[Cfg]):
name = 'pii_redact'
async def model(self, params, ctx: MiddlewareContext, next_fn): ...
async def wrap_model(self, params, ctx: MiddlewareContext, next_fn): ...
```

Hooks are now `wrap_generate`, `wrap_model`, and `wrap_tool`. A method still named `model` is never called; the class inherits the pass-through `wrap_model` and the request goes to the provider unchanged, with no error.

`tools()` returns `Tool` handles. `GenerateMiddleware`, `MiddlewareRef`, `MiddlewarePlugin` and `new_middleware` are removed.

### Defining models and embedders
Expand Down
Loading
Loading