返回提交历史
Modified
docs/pydantic_ai.md
+37
-4
Modified
g4f/Provider/PollinationsAI.py
+1
-1
Modified
g4f/gui/client/demo.html
+31
-2
Added
g4f/integration/langchain.py
+41
-0
Added
g4f/integration/pydantic_ai.py
+72
-0
Modified
g4f/tools/langchain.py
+4
-4
Modified
g4f/tools/pydantic_ai.py
+1
-72
XFEstudio/gpt4free
Add LangChain Documenation Example
510d9d9b
代码差异
7 个文件
+187
-83
@@ -21,10 +21,10 @@ pip install g4f pydantic_ai
21
21
22
22
### 1. Patch PydanticAI to Use G4F Models
23
23
24
In order to use PydanticAI with G4F models, you need to apply the necessary patch to the client. This can be done by importing `patch_infer_model` from `g4f.tools.pydantic_ai`. The `api_key` parameter is optional, so if you have one, you can provide it. If not, the system will proceed without it.
24
In order to use PydanticAI with G4F models, you need to apply the necessary patch to the client. This can be done by importing `patch_infer_model` from `g4f.integration.pydantic_ai`. The `api_key` parameter is optional, so if you have one, you can provide it. If not, the system will proceed without it.
25
25
26
26
```python
27
from g4f.tools.pydantic_ai import patch_infer_model
27
from g4f.integration.pydantic_ai import patch_infer_model
28
28
29
29
patch_infer_model(api_key="your_api_key_here") # Optional
30
30
```
@@ -89,7 +89,7 @@ For example, you can process your query or interact with external systems before
89
89
90
90
```python
91
91
from pydantic_ai import Agent
92
from g4f.tools.pydantic_ai import AIModel
92
from g4f.integration.pydantic_ai import AIModel
93
93
94
94
agent = Agent(
95
95
AIModel("gpt-4o"),
@@ -109,7 +109,7 @@ This example shows how to initialize an agent with a specific model (`gpt-4o`) a
109
109
from pydantic import BaseModel
110
110
from pydantic_ai import Agent
111
111
from pydantic_ai.models import ModelSettings
112
from g4f.tools.pydantic_ai import patch_infer_model
112
from g4f.integration.pydantic_ai import patch_infer_model
113
113
114
114
patch_infer_model("your_api_key")
115
115
@@ -129,6 +129,39 @@ This example demonstrates the use of a custom Pydantic model (`MyModel`) to capt
129
129
130
130
---
131
131
132
## LangChain Integration Example
133
134
For users working with LangChain, here is an example demonstrating how to integrate G4F models into a LangChain environment:
135
136
```python
137
from g4f.integration.langchain import ChatAI
138
import g4f.debug
139
140
# Enable debugging logs
141
g4f.debug.logging = True
142
143
llm = ChatAI(
144
model="llama3-70b-8192",
145
provider="Groq",
146
api_key="" # Optionally add your API key here
147
)
148
149
messages = [
150
{"role": "user", "content": "2 🦜 2"},
151
{"role": "assistant", "content": "4 🦜"},
152
{"role": "user", "content": "2 🦜 3"},
153
{"role": "assistant", "content": "5 🦜"},
154
{"role": "user", "content": "3 🦜 4"},
155
]
156
157
response = llm.invoke(messages)
158
assert(response.content == "7 🦜")
159
```
160
161
This example shows how to use LangChain's `ChatAI` integration to create a conversational agent with a G4F model. The interaction takes place with the given messages and the agent processes them step-by-step to return the expected output.
162
163
---
164
132
165
## Conclusion
133
166
134
167
By following these steps, you have successfully integrated PydanticAI models into the G4F client, created an agent, and enabled debugging. This allows you to conduct conversations with the language model, pass system prompts, and retrieve responses synchronously.
@@ -262,7 +262,7 @@ class PollinationsAI(AsyncGeneratorProvider, ProviderModelMixin):
262
262
"seed": seed,
263
263
"cache": cache
264
264
})
265
if "gemimi" in model:
265
if "gemini" in model:
266
266
data.pop("seed")
267
267
async with session.post(cls.text_api_endpoint, json=data) as response:
268
268
await raise_for_status(response)
@@ -101,7 +101,7 @@
101
101
border: none;
102
102
}
103
103
104
#background {
104
#background, #image-feed {
105
105
height: 100%;
106
106
position: absolute;
107
107
z-index: -1;
@@ -201,6 +201,7 @@
201
201
</head>
202
202
<body>
203
203
<iframe id="background"></iframe>
204
<img id="image-feed" alt="Image Feed">
204
205
205
206
<!-- Gradient Background Circle -->
206
207
<div class="gradient"></div>
@@ -313,7 +314,7 @@
313
314
<script>
314
315
(async () => {
315
316
const today = new Date().toJSON().slice(0, 10);
316
const max = 5;
317
const max = 6;
317
318
const cache_id = Math.floor(Math.random() * max);
318
319
let prompt;
319
320
if (cache_id % 2 == 0) {
@@ -328,6 +329,34 @@
328
329
background.src = `data:text/html;charset=utf-8,${encodeURIComponent(text)}`;
329
330
const gradient = document.querySelector('.gradient');
330
331
gradient.classList.add('hidden');
332
333
const url = "https://image.pollinations.ai/feed";
334
const eventSource = new EventSource(url);
335
const imageFeed = document.getElementById("image-feed");
336
const images = []
337
eventSource.onmessage = (event) => {
338
const data = JSON.parse(event.data);
339
if (data.nsfw || !data.nologo || data.width < 1024 || !data.imageURL) {
340
return;
341
}
342
const lower = data.prompt.toLowerCase();
343
const tags = ["logo", "infographic", "warts","prostitute", "curvy", "breasts", "written", "bodies", "naked", "classroom", "malone", "dirty", "shoes", "shower", "banner", "fat", "nipples", "couple", "sexual", "sandal", "supplier", "overlord", "succubus", "platinum", "cracy", "crazy", "lamic", "ropes", "cables", "wires", "dirty", "messy", "cluttered", "chaotic", "disorganized", "disorderly", "untidy", "unorganized", "unorderly", "unsystematic", "disarranged", "disarrayed", "disheveled", "disordered", "jumbled", "muddled", "scattered", "shambolic", "sloppy", "unkept", "unruly"];
344
for (i in tags) {
345
if (lower.indexOf(tags[i]) != -1) {
346
console.log("Skipping image with tag: " + tags[i]);
347
return;
348
}
349
}
350
images.push(data.imageURL);
351
};
352
eventSource.onerror = (event) => {
353
eventSource.close();
354
}
355
setInterval(() => {
356
if (images.length > 0) {
357
imageFeed.src = images.shift();
358
}
359
}, 7000);
331
360
})();
332
361
</script>
333
362
</body>
@@ -0,0 +1,41 @@
1
from __future__ import annotations
2
3
from typing import Any, Dict
4
from langchain_community.chat_models import openai
5
from langchain_community.chat_models.openai import ChatOpenAI, BaseMessage, convert_message_to_dict
6
from pydantic import Field
7
from g4f.client import AsyncClient, Client
8
from g4f.client.stubs import ChatCompletionMessage
9
10
def new_convert_message_to_dict(message: BaseMessage) -> dict:
11
message_dict: Dict[str, Any]
12
if isinstance(message, ChatCompletionMessage):
13
message_dict = {"role": message.role, "content": message.content}
14
if message.tool_calls is not None:
15
message_dict["tool_calls"] = [{
16
"id": tool_call.id,
17
"type": tool_call.type,
18
"function": tool_call.function
19
} for tool_call in message.tool_calls]
20
if message_dict["content"] == "":
21
message_dict["content"] = None
22
else:
23
message_dict = convert_message_to_dict(message)
24
return message_dict
25
26
openai.convert_message_to_dict = new_convert_message_to_dict
27
28
class ChatAI(ChatOpenAI):
29
model_name: str = Field(default="gpt-4o", alias="model")
30
31
@classmethod
32
def validate_environment(cls, values: dict) -> dict:
33
client_params = {
34
"api_key": values["api_key"] if "api_key" in values else None,
35
"provider": values["model_kwargs"]["provider"] if "provider" in values["model_kwargs"] else None,
36
}
37
values["client"] = Client(**client_params).chat.completions
38
values["async_client"] = AsyncClient(
39
**client_params
40
).chat.completions
41
return values
@@ -0,0 +1,72 @@
1
from __future__ import annotations
2
3
from typing import Optional
4
from functools import partial
5
from dataclasses import dataclass, field
6
7
from pydantic_ai.models import Model, KnownModelName, infer_model
8
from pydantic_ai.models.openai import OpenAIModel, OpenAISystemPromptRole
9
10
import pydantic_ai.models.openai
11
pydantic_ai.models.openai.NOT_GIVEN = None
12
13
from ..client import AsyncClient
14
15
@dataclass(init=False)
16
class AIModel(OpenAIModel):
17
"""A model that uses the G4F API."""
18
19
client: AsyncClient = field(repr=False)
20
system_prompt_role: OpenAISystemPromptRole | None = field(default=None)
21
22
_model_name: str = field(repr=False)
23
_provider: str = field(repr=False)
24
_system: Optional[str] = field(repr=False)
25
26
def __init__(
27
self,
28
model_name: str,
29
provider: str | None = None,
30
*,
31
system_prompt_role: OpenAISystemPromptRole | None = None,
32
system: str | None = 'openai',
33
**kwargs
34
):
35
"""Initialize an AI model.
36
37
Args:
38
model_name: The name of the AI model to use. List of model names available
39
[here](https://github.com/openai/openai-python/blob/v1.54.3/src/openai/types/chat_model.py#L7)
40
(Unfortunately, despite being ask to do so, OpenAI do not provide `.inv` files for their API).
41
system_prompt_role: The role to use for the system prompt message. If not provided, defaults to `'system'`.
42
In the future, this may be inferred from the model name.
43
system: The model provider used, defaults to `openai`. This is for observability purposes, you must
44
customize the `base_url` and `api_key` to use a different provider.
45
"""
46
self._model_name = model_name
47
self._provider = provider
48
self.client = AsyncClient(provider=provider, **kwargs)
49
self.system_prompt_role = system_prompt_role
50
self._system = system
51
52
def name(self) -> str:
53
if self._provider:
54
return f'g4f:{self._provider}:{self._model_name}'
55
return f'g4f:{self._model_name}'
56
57
def new_infer_model(model: Model | KnownModelName, api_key: str = None) -> Model:
58
if isinstance(model, Model):
59
return model
60
if model.startswith("g4f:"):
61
model = model[4:]
62
if ":" in model:
63
provider, model = model.split(":", 1)
64
return AIModel(model, provider=provider, api_key=api_key)
65
return AIModel(model)
66
return infer_model(model)
67
68
def patch_infer_model(api_key: str | None = None):
69
import pydantic_ai.models
70
71
pydantic_ai.models.infer_model = partial(new_infer_model, api_key=api_key)
72
pydantic_ai.models.AIModel = AIModel
@@ -2,12 +2,12 @@ from __future__ import annotations
2
2
3
3
from typing import Any, Dict
4
4
from langchain_community.chat_models import openai
5
from langchain_community.chat_models.openai import convert_message_to_dict
5
from langchain_community.chat_models.openai import ChatOpenAI, BaseMessage, convert_message_to_dict
6
6
from pydantic import Field
7
7
from g4f.client import AsyncClient, Client
8
8
from g4f.client.stubs import ChatCompletionMessage
9
9
10
def new_convert_message_to_dict(message: openai.BaseMessage) -> dict:
10
def new_convert_message_to_dict(message: BaseMessage) -> dict:
11
11
message_dict: Dict[str, Any]
12
12
if isinstance(message, ChatCompletionMessage):
13
13
message_dict = {"role": message.role, "content": message.content}
@@ -25,14 +25,14 @@ def new_convert_message_to_dict(message: openai.BaseMessage) -> dict:
25
25
26
26
openai.convert_message_to_dict = new_convert_message_to_dict
27
27
28
class ChatAI(openai.ChatOpenAI):
28
class ChatAI(ChatOpenAI):
29
29
model_name: str = Field(default="gpt-4o", alias="model")
30
30
31
31
@classmethod
32
32
def validate_environment(cls, values: dict) -> dict:
33
33
client_params = {
34
34
"api_key": values["g4f_api_key"] if "g4f_api_key" in values else None,
35
"provider": values["provider"] if "provider" in values else None,
35
"provider": values["g4f_provider"] if "g4f_provider" in values else None,
36
36
}
37
37
values["client"] = Client(**client_params).chat.completions
38
38
values["async_client"] = AsyncClient(
@@ -1,72 +1 @@
1
from __future__ import annotations
2
3
from typing import Optional
4
from functools import partial
5
from dataclasses import dataclass, field
6
7
from pydantic_ai.models import Model, KnownModelName, infer_model
8
from pydantic_ai.models.openai import OpenAIModel, OpenAISystemPromptRole
9
10
import pydantic_ai.models.openai
11
pydantic_ai.models.openai.NOT_GIVEN = None
12
13
from ..client import AsyncClient
14
15
@dataclass(init=False)
16
class AIModel(OpenAIModel):
17
"""A model that uses the G4F API."""
18
19
client: AsyncClient = field(repr=False)
20
system_prompt_role: OpenAISystemPromptRole | None = field(default=None)
21
22
_model_name: str = field(repr=False)
23
_provider: str = field(repr=False)
24
_system: Optional[str] = field(repr=False)
25
26
def __init__(
27
self,
28
model_name: str,
29
provider: str | None = None,
30
*,
31
system_prompt_role: OpenAISystemPromptRole | None = None,
32
system: str | None = 'openai',
33
**kwargs
34
):
35
"""Initialize an AI model.
36
37
Args:
38
model_name: The name of the AI model to use. List of model names available
39
[here](https://github.com/openai/openai-python/blob/v1.54.3/src/openai/types/chat_model.py#L7)
40
(Unfortunately, despite being ask to do so, OpenAI do not provide `.inv` files for their API).
41
system_prompt_role: The role to use for the system prompt message. If not provided, defaults to `'system'`.
42
In the future, this may be inferred from the model name.
43
system: The model provider used, defaults to `openai`. This is for observability purposes, you must
44
customize the `base_url` and `api_key` to use a different provider.
45
"""
46
self._model_name = model_name
47
self._provider = provider
48
self.client = AsyncClient(provider=provider, **kwargs)
49
self.system_prompt_role = system_prompt_role
50
self._system = system
51
52
def name(self) -> str:
53
if self._provider:
54
return f'g4f:{self._provider}:{self._model_name}'
55
return f'g4f:{self._model_name}'
56
57
def new_infer_model(model: Model | KnownModelName, api_key: str = None) -> Model:
58
if isinstance(model, Model):
59
return model
60
if model.startswith("g4f:"):
61
model = model[4:]
62
if ":" in model:
63
provider, model = model.split(":", 1)
64
return AIModel(model, provider=provider, api_key=api_key)
65
return AIModel(model)
66
return infer_model(model)
67
68
def patch_infer_model(api_key: str | None = None):
69
import pydantic_ai.models
70
71
pydantic_ai.models.infer_model = partial(new_infer_model, api_key=api_key)
72
pydantic_ai.models.AIModel = AIModel
1
from ..integration.pydantic_ai import AIModel, patch_infer_model