chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1 @@
"""Runnable Dify Agent client examples."""
@@ -0,0 +1,51 @@
"""Small CLI for listing or copying Dify Agent examples."""
from __future__ import annotations
import argparse
import shutil
import sys
from pathlib import Path
EXAMPLE_MODULES = (
"run_pydantic_ai_agent",
"run_server_consumer",
"run_server_sse_consumer",
"run_server_sync_client",
)
def cli() -> None:
parser = argparse.ArgumentParser(
prog="dify_agent_examples",
description="List or copy Dify Agent runtime examples.",
)
parser.add_argument("--copy-to", metavar="DEST", help="Copy example files to a new directory")
args = parser.parse_args()
examples_dir = Path(__file__).parent
if args.copy_to:
copy_to(examples_dir, Path(args.copy_to))
return
for module_name in EXAMPLE_MODULES:
print(f"python -m dify_agent_examples.{module_name}")
def copy_to(examples_dir: Path, destination: Path) -> None:
if destination.exists():
print(f'Error: destination path "{destination}" already exists', file=sys.stderr)
sys.exit(1)
destination.mkdir(parents=True)
copied = 0
for source in examples_dir.glob("*.py"):
if source.name == "__init__.py":
continue
shutil.copy2(source, destination / source.name)
copied += 1
print(f'Copied {copied} Dify Agent example files to "{destination}"')
if __name__ == "__main__":
cli()
@@ -0,0 +1,85 @@
"""Run a Pydantic AI agent through the Dify API LLM gateway.
Prerequisites:
- Sync the server runtime dependencies first: `uv sync --project dify-agent --extra server`.
- Run the Dify API with its inner Agent LLM endpoint enabled.
- Fill `dify-agent/.env` with a real tenant, user, app, plugin, provider, and model.
This example is meant to be run from a source checkout because
`dify_agent_examples` is not part of the published package.
Example from the repository root:
PYTHONPATH=dify-agent/src:dify-agent/examples/dify_agent \
uv run --project dify-agent python -m dify_agent_examples.run_pydantic_ai_agent
"""
from __future__ import annotations
import asyncio
import os
from pathlib import Path
from uuid import uuid4
import httpx
from pydantic_ai import Agent
from dify_agent.adapters.llm import DifyApiLLMProvider, DifyLLMAdapterModel
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
PROJECT_ROOT = Path(__file__).resolve().parents[3]
def load_env_file(path: Path) -> None:
"""Load simple KEY=VALUE lines without adding a dotenv dependency."""
if not path.exists():
return
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
def required_env(name: str) -> str:
value = os.environ.get(name)
if value:
return value
raise RuntimeError(f"Missing required environment variable: {name}")
async def main() -> None:
load_env_file(PROJECT_ROOT / ".env")
async with httpx.AsyncClient(timeout=600, trust_env=False) as http_client:
provider = DifyApiLLMProvider(
plugin_id=required_env("DIFY_AGENT_PLUGIN_ID"),
inner_api_url=required_env("DIFY_INNER_API_URL"),
inner_api_key=required_env("DIFY_INNER_API_KEY"),
execution_context=DifyExecutionContextLayerConfig(
tenant_id=required_env("DIFY_AGENT_TENANT_ID"),
user_id=required_env("DIFY_AGENT_USER_ID"),
user_from="account",
app_id=required_env("DIFY_AGENT_APP_ID"),
agent_mode="single_step",
invoke_from="debugger",
),
agent_run_id=str(uuid4()),
http_client=http_client,
)
model = DifyLLMAdapterModel(
required_env("DIFY_AGENT_MODEL_NAME"),
provider,
model_provider=required_env("DIFY_AGENT_PROVIDER"),
)
agent = Agent(model=model)
async with agent.run_stream("Explain the theory of relativity") as run:
async for piece in run.stream_output():
print(piece, end="", flush=True)
print(run.usage)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,133 @@
"""Async Python client example for the Dify Agent run server.
Requires Redis and a running API server. Before starting the server, sync the
server runtime dependencies with `uv sync --project dify-agent --extra server`
or install `dify-agent[server]`. The server schedules runs in-process, for
example:
uv run --project dify-agent uvicorn dify_agent.server.app:app --reload
The request carries Dify plugin model configuration in registered modules. This
script prints the created run and every event observed through cursor polling.
``Client.create_run`` performs one POST attempt only; use polling or SSE replay to
recover after client-side uncertainty.
"""
import asyncio
from dify_agent.layers.prompt import Config as PromptConfig
from dify_agent.client import Client
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
from dify_agent.layers.dify_plugin import (
DifyPluginLLMLayerConfig,
)
from dify_agent.protocol import DIFY_AGENT_MODEL_LAYER_ID, CreateRunRequest, RunComposition, RunLayerSpec
API_BASE_URL = "http://localhost:8000"
TENANT_ID = "replace-with-tenant-id"
USER_ID = "replace-with-user-id"
APP_ID = "replace-with-app-id"
PLUGIN_ID = "langgenius/openai"
PLUGIN_PROVIDER = "openai"
MODEL_NAME = "gpt-4o-mini"
async def main() -> None:
async with Client(base_url=API_BASE_URL) as client:
run = await client.create_run(
CreateRunRequest(
composition=RunComposition(
layers=[
RunLayerSpec(
name="prompt",
config=(
PromptConfig(
prefix="You are a concise assistant.",
user="Say hello from the Dify Agent API server example.",
)
).model_dump(mode="json"),
),
RunLayerSpec(
name="execution_context",
config=(
DifyExecutionContextLayerConfig(
tenant_id=TENANT_ID,
user_id=USER_ID,
user_from="account",
app_id=APP_ID,
agent_mode="workflow_run",
invoke_from="service-api",
)
).model_dump(mode="json"),
),
RunLayerSpec(
name=DIFY_AGENT_MODEL_LAYER_ID,
config=(
DifyPluginLLMLayerConfig(
plugin_id=PLUGIN_ID, model_provider=PLUGIN_PROVIDER, model=MODEL_NAME
)
).model_dump(mode="json"),
),
# Minimal plugin-tools example. API callers should pass
# prepared parameters + JSON schema instead of relying on
# dify-agent to fetch and merge daemon declarations.
# from dify_agent.layers.dify_plugin import (
# DifyPluginToolConfig,
# DifyPluginToolParameter,
# DifyPluginToolParameterForm,
# DifyPluginToolParameterType,
# DifyPluginToolsLayerConfig,
# )
# RunLayerSpec(
# name="tools",
# config=DifyPluginToolsLayerConfig(
# execution_context="execution_context",
# tools=[
# DifyPluginToolConfig(
# plugin_id="langgenius/search",
# plugin_unique_identifier="langgenius/search:1.0.0@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
# provider="search",
# tool_name="web_search",
# credential_type="api-key",
# credentials={"api_key": "replace-with-tool-key"},
# runtime_parameters={"site": "docs.dify.ai"},
# parameters=[
# DifyPluginToolParameter(
# name="query",
# type=DifyPluginToolParameterType.STRING,
# form=DifyPluginToolParameterForm.LLM,
# required=True,
# llm_description="Search query",
# ),
# ],
# parameters_json_schema={
# "type": "object",
# "properties": {
# "query": {"type": "string", "description": "Search query"}
# },
# "required": ["query"],
# },
# )
# ]
# ).model_dump(mode="json"),
# ),
],
),
)
)
print("created run", run)
cursor = "0-0"
while True:
page = await client.get_events(run.run_id, after=cursor)
cursor = page.next_cursor or cursor
for event in page.events:
print("event", event)
if event.type in {"run_succeeded", "run_failed"}:
return
await asyncio.sleep(0.5)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,25 @@
"""Async SSE client example for the Dify Agent run server.
Create a run with ``run_server_consumer.py`` or any HTTP client, then set RUN_ID
below and run this script while the server is available. The Python client parses
SSE frames into typed protocol events and reconnects with the latest event id by
default. Malformed frames and HTTP 4xx responses fail without reconnecting.
"""
import asyncio
from dify_agent.client import Client
API_BASE_URL = "http://localhost:8000"
RUN_ID = "replace-with-run-id"
async def main() -> None:
async with Client(base_url=API_BASE_URL, stream_timeout=None) as client:
async for event in client.stream_events(RUN_ID):
print(event)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,118 @@
"""Synchronous Python client example for the Dify Agent run server.
Requires the same running FastAPI server as the async examples. Before starting
that server, sync the server runtime dependencies with
`uv sync --project dify-agent --extra server` or install
`dify-agent[server]`. ``create_run_sync`` does not retry ``POST /runs``; if a
timeout occurs, inspect server state or create a new run explicitly rather than
assuming the original request was not accepted.
"""
from dify_agent.layers.prompt import Config as PromptConfig
from dify_agent.client import Client
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
from dify_agent.layers.dify_plugin import (
DifyPluginLLMLayerConfig,
)
from dify_agent.protocol import DIFY_AGENT_MODEL_LAYER_ID, CreateRunRequest, RunComposition, RunLayerSpec
API_BASE_URL = "http://localhost:8000"
TENANT_ID = "replace-with-tenant-id"
USER_ID = "replace-with-user-id"
APP_ID = "replace-with-app-id"
PLUGIN_ID = "langgenius/openai"
PLUGIN_PROVIDER = "openai"
MODEL_NAME = "gpt-4o-mini"
def main() -> None:
with Client(base_url=API_BASE_URL) as client:
run = client.create_run_sync(
CreateRunRequest(
composition=RunComposition(
layers=[
RunLayerSpec(
name="prompt",
config=(
PromptConfig(
prefix="You are a concise assistant.",
user="Say hello from the synchronous Dify Agent client example.",
)
).model_dump(mode="json"),
),
RunLayerSpec(
name="execution_context",
config=(
DifyExecutionContextLayerConfig(
tenant_id=TENANT_ID,
user_id=USER_ID,
user_from="account",
app_id=APP_ID,
agent_mode="workflow_run",
invoke_from="service-api",
)
).model_dump(mode="json"),
),
RunLayerSpec(
name=DIFY_AGENT_MODEL_LAYER_ID,
config=(
DifyPluginLLMLayerConfig(
plugin_id=PLUGIN_ID, model_provider=PLUGIN_PROVIDER, model=MODEL_NAME
)
).model_dump(mode="json"),
),
# Minimal plugin-tools example. API callers should pass
# prepared parameters + JSON schema instead of relying on
# dify-agent to fetch and merge daemon declarations.
# from dify_agent.layers.dify_plugin import (
# DifyPluginToolConfig,
# DifyPluginToolParameter,
# DifyPluginToolParameterForm,
# DifyPluginToolParameterType,
# DifyPluginToolsLayerConfig,
# )
# RunLayerSpec(
# name="tools",
# config=DifyPluginToolsLayerConfig(
# execution_context="execution_context",
# tools=[
# DifyPluginToolConfig(
# plugin_id="langgenius/search",
# plugin_unique_identifier="langgenius/search:1.0.0@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
# provider="search",
# tool_name="web_search",
# credential_type="api-key",
# credentials={"api_key": "replace-with-tool-key"},
# runtime_parameters={"site": "docs.dify.ai"},
# parameters=[
# DifyPluginToolParameter(
# name="query",
# type=DifyPluginToolParameterType.STRING,
# form=DifyPluginToolParameterForm.LLM,
# required=True,
# llm_description="Search query",
# ),
# ],
# parameters_json_schema={
# "type": "object",
# "properties": {
# "query": {"type": "string", "description": "Search query"}
# },
# "required": ["query"],
# },
# )
# ]
# ).model_dump(mode="json"),
# ),
],
),
)
)
print("created run", run)
terminal = client.wait_run_sync(run.run_id, poll_interval_seconds=0.5)
print("terminal status", terminal)
if __name__ == "__main__":
main()