在使用Playwright设置Langchain代理时遇到的问题
我没法让这个工作起来:
from langchain_community.agent_toolkits import PlayWrightBrowserToolkit
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
import asyncio
import nest_asyncio
nest_asyncio.apply()
from langchain_community.tools.playwright.utils import (
create_sync_playwright_browser,
)
def main():
sync_browser = create_sync_playwright_browser(headless=False)
toolkit = PlayWrightBrowserToolkit.from_browser(sync_browser=sync_browser)
tools = toolkit.get_tools()
model = ChatOpenAI(model="gpt-4o", temperature=0)
agent_chain = create_agent(model=model, tools=tools)
result = agent_chain.invoke(
{"messages": [("user", "What are the headers on langchain.com?")]}
)
print(result)
if __name__ == "__main__":
main()
我遇到的错误是
File "C:\Users\paulo\anaconda3\envs\estee\Lib\site-packages\playwright_impl_sync_base.py",
line 113, in _sync self._dispatcher_fiber.switch() greenlet.error:
Cannot switch to a different thread Current:
<greenlet.greenlet object at 0x000001CA8AE7F900
(otid=0x000001CA89E17180) current active started main>
Expected:
<greenlet.greenlet object at 0x000001CA89E42100
(otid=0x000001CA8A3BC060) suspended active started main>
我的目标只是让langchain和 playwright有一个能运行的Hello World示例;浏览器是同步还是异步对我来说都无所谓,我只想要一个最基本的可正常工作的实现。我一开始尝试了异步浏览器,但也没成功。
能不能请人帮忙?
解决方案
我拿到了你的代码,并把它转换成 async 版本,在 Linux Mint 上对我可用(基于 Ubuntu 24.02),使用 langchain 1.2.x,不是 0.3.x。
如果在你的电脑上运行不起来,可能只是Windows的问题。
我用 Ollama 代替 OpenAI 进行了测试。
我在终端里把它作为脚本运行(使用Python 3.13),而不是在Jupyter中作为代码运行。
它没有抛出任何错误,能从代理那里得到响应,但它说在langchain.com上找不到头部信息。
# --- info ---
import langchain
import langchain_community
print("langchain:", langchain.__version__)
print("langchain_community:", langchain_community.__version__)
# --- code ---
from langchain_community.agent_toolkits import PlayWrightBrowserToolkit
from langchain_community.tools.playwright.utils import create_async_playwright_browser
from langchain.agents import create_agent
# from langchain_openai import ChatOpenAI
from langchain_ollama import ChatOllama
# it needs it to run async browser
import nest_asyncio
nest_asyncio.apply()
async def main(): # <-- async
async_browser = create_async_playwright_browser()
toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)
tools = toolkit.get_tools()
print("--- tools ---")
for item in tools:
print(item.name)
# model = ChatOpenAI(model="gpt-4o", temperature=0)
model = ChatOllama(model="llama3.2", temperature=0)
agent_chain = create_agent(model=model, tools=tools)
result = await agent_chain.ainvoke( # <-- await, ainvoke
{"messages": [("user", "What are the headers on langchain.com?")]}
)
print("--- result ---")
print(result)
print("--- messages ---")
for item in result["messages"]:
print("type:", item.type)
print("name:", item.name)
print("content:", item.content)
print("---")
if __name__ == "__main__":
# main()
import asyncio
asyncio.run(main())
结果:
langchain: 1.2.13
langchain_community: 0.4.1
--- tools ---
click_element
navigate_browser
previous_webpage
extract_text
extract_hyperlinks
get_elements
current_webpage
--- result ---
{'messages': [HumanMessage(content='What are the headers on langchain.com?', additional_kwargs={}, response_metadata={}, id='c2575d91-99d8-48bf-afea-7c24d6b1fc16'), AIMessage(content='', additional_kwargs={}, response_metadata={'model': 'llama3.2', 'created_at': '2026-03-31T20:28:18.548216398Z', 'done': True, 'done_reason': 'stop', 'total_duration': 8932239195, 'load_duration': 121650058, 'prompt_eval_count': 425, 'prompt_eval_duration': 7491245727, 'eval_count': 16, 'eval_duration': 1289860413, 'logprobs': None, 'model_name': 'llama3.2', 'model_provider': 'ollama'}, id='lc_run--019d4595-0e0b-79d2-ac5e-623fcbf23c14-0', tool_calls=[{'name': 'get_elements', 'args': {'selector': '*'}, 'id': '516c49b6-28c1-427f-b0da-2d66274d7d50', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 425, 'output_tokens': 16, 'total_tokens': 441}), ToolMessage(content='[]', name='get_elements', id='0a4f9c45-f3eb-43ee-b182-ae610d903450', tool_call_id='516c49b6-28c1-427f-b0da-2d66274d7d50'), AIMessage(content="Based on the output from the tool call, it appears that the headers on langchain.com are not explicitly listed. The tool call `get_elements` with the selector `*` returns an empty list, indicating that the headers are not available or are not present on the page.\n\nHowever, I can suggest that you try checking the website's documentation or contact support for more information on the available headers or API endpoints.", additional_kwargs={}, response_metadata={'model': 'llama3.2', 'created_at': '2026-03-31T20:28:27.005448701Z', 'done': True, 'done_reason': 'stop', 'total_duration': 8350693341, 'load_duration': 153406746, 'prompt_eval_count': 93, 'prompt_eval_duration': 1321625016, 'eval_count': 84, 'eval_duration': 6851252575, 'logprobs': None, 'model_name': 'llama3.2', 'model_provider': 'ollama'}, id='lc_run--019d4595-315d-70b0-b9f3-8c5595de86bf-0', tool_calls=[], invalid_tool_calls=[], usage_metadata={'input_tokens': 93, 'output_tokens': 84, 'total_tokens': 177})]}
--- messages ---
type: human
name: None
content: What are the headers on langchain.com?
---
type: ai
name: None
content:
---
type: tool
name: get_elements
content: []
---
type: ai
name: None
content: Based on the output from the tool call, it appears that the headers on langchain.com are not explicitly listed. The tool call `get_elements` with the selector `*` returns an empty list, indicating that the headers are not available or are not present on the page.
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。