跳到主要内容
将 AI 原生广告集成到您的代理应用程序中。

概览

本笔记本概述了如何直接在 LangChain 中使用 ADS4GPTs 工具和工具包。但在您的 LangGraph 应用程序中,您很可能会使用我们预构建的 LangGraph 代理。

设置

安装 ADS4GPTs 包

使用 pip 安装 ADS4GPTs 包。
# Install ADS4GPTs Package
# Install the ADS4GPTs package using pip
!pip install ads4gpts-langchain
设置用于 API 身份验证的环境变量(获取 API 密钥)。
# Setup environment variables
# Prompt the user to enter their ADS4GPTs API key securely
if not os.environ.get("ADS4GPTS_API_KEY"):
    os.environ["ADS4GPTS_API_KEY"] = getpass("Enter your ADS4GPTS API key: ")

实例化

导入必要的库,包括 ADS4GPTs 工具和工具包。 初始化 ADS4GPTs 工具,例如 Ads4gptsInlineSponsoredResponseTool。我们将使用一个工具,因为其他所有工具的过程都是相同的。
# Import Required Libraries

import os
from getpass import getpass

from ads4gpts_langchain import Ads4gptsInlineSponsoredResponseTool, Ads4gptsToolkit
# Initialize ADS4GPTs Tools
# Initialize the Ads4gptsInlineSponsoredResponseTool
inline_sponsored_response_tool = Ads4gptsInlineSponsoredResponseTool(
    ads4gpts_api_key=os.environ["ADS4GPTS_API_KEY"],
)

工具包实例化

使用所需的参数初始化 Ads4gptsToolkit。
# Toolkit Initialization
# Initialize the Ads4gptsToolkit with the required parameters
toolkit = Ads4gptsToolkit(
    ads4gpts_api_key=os.environ["ADS4GPTS_API_KEY"],
)

# Retrieve tools from the toolkit
tools = toolkit.get_tools()

# Print the initialized tools
for tool in tools:
    print(f"Initialized tool: {tool.__class__.__name__}")
Initialized tool: Ads4gptsInlineSponsoredResponseTool
Initialized tool: Ads4gptsSuggestedPromptTool

调用

运行 ADS4GPTs 工具并使用示例输入显示结果。
# Run ADS4GPTs Tools
# Sample input data for the tools
sample_input = {
    "id": "test_id",
    "user_gender": "female",
    "user_age": "25-34",
    "user_persona": "test_persona",
    "ad_recommendation": "test_recommendation",
    "undesired_ads": "test_undesired_ads",
    "context": "test_context",
    "num_ads": 1,
    "style": "neutral",
}

# Run Ads4gptsInlineSponsoredResponseTool
inline_sponsored_response_result = inline_sponsored_response_tool._run(
    **sample_input, ad_format="INLINE_SPONSORED_RESPONSE"
)
print("Inline Sponsored Response Result:", inline_sponsored_response_result)
Inline Sponsored Response Result: {'ad_text': '<- Promoted Content ->\n\nLearn the sartorial ways and get your handmade tailored suit by the masters themselves with Bespoke Tailors. [Subscribe now](https://youtube.com/@bespoketailorsdubai?si=9iH587ujoWKkueFa)\n\n<->'}

异步运行 ADS4GPTs 工具

异步运行 ADS4GPTs 工具并使用示例输入显示结果。
import asyncio


# Define an async function to run the tools asynchronously
async def run_ads4gpts_tools_async():
    # Run Ads4gptsInlineSponsoredResponseTool asynchronously
    inline_sponsored_response_result = await inline_sponsored_response_tool._arun(
        **sample_input, ad_format="INLINE_SPONSORED_RESPONSE"
    )
    print("Async Inline Sponsored Response Result:", inline_sponsored_response_result)
Async Inline Sponsored Response Result: {'ad_text': '<- Promoted Content ->\n\nGet the best tailoring content from Jonathan Farley. Learn to tie 100 knots and more! [Subscribe now](https://www.youtube.com/channel/UCx5hk4LN3p02jcUt3j_cexQ)\n\n<->'}

工具包调用

使用 Ads4gptsToolkit 获取并运行工具。
# Sample input data for the tools
sample_input = {
    "id": "test_id",
    "user_gender": "female",
    "user_age": "25-34",
    "user_persona": "test_persona",
    "ad_recommendation": "test_recommendation",
    "undesired_ads": "test_undesired_ads",
    "context": "test_context",
    "num_ads": 1,
    "style": "neutral",
}

# Run one tool and print the result
tool = tools[0]
result = tool._run(**sample_input)
print(f"Result from {tool.__class__.__name__}:", result)


# Define an async function to run the tools asynchronously
async def run_toolkit_tools_async():
    result = await tool._arun(**sample_input)
    print(f"Async result from {tool.__class__.__name__}:", result)


# Execute the async function
await run_toolkit_tools_async()
Result from Ads4gptsInlineSponsoredResponseTool: {'ad_text': '<- Promoted Content ->\n\nLearn the sartorial ways and get your handmade tailored suit by the masters themselves with Bespoke Tailors. [Subscribe now](https://youtube.com/@bespoketailorsdubai?si=9iH587ujoWKkueFa)\n\n<->'}
Async result from Ads4gptsInlineSponsoredResponseTool: {'ad_text': '<- Promoted Content ->\n\nGet the best tailoring content from Jonathan Farley. Learn to tie 100 knots and more! [Subscribe now](https://www.youtube.com/channel/UCx5hk4LN3p02jcUt3j_cexQ)\n\n<->'}

链接

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass("Enter your OPENAI_API_KEY API key: ")
import os

from langchain_openai import ChatOpenAI

openai_model = ChatOpenAI(model="gpt-4o", openai_api_key=os.environ["OPENAI_API_KEY"])
model = openai_model.bind_tools(tools)
model_response = model.invoke(
    "Get me an ad for clothing. I am a young man looking to go out with friends."
)
print("Tool call:", model_response)
Tool call: content='' additional_kwargs={'tool_calls': [{'id': 'call_XLR5UjF8JhylVHvrk9mTjhj8', 'function': {'arguments': '{"id":"unique_user_id_001","user_gender":"male","user_age":"18-24","ad_recommendation":"Stylish and trendy clothing suitable for young men going out with friends.","undesired_ads":"formal wear, women\'s clothing, children\'s clothing","context":"A young man looking for clothing to go out with friends","num_ads":1,"style":"youthful and trendy","ad_format":"INLINE_SPONSORED_RESPONSE"}', 'name': 'ads4gpts_inline_sponsored_response'}, 'type': 'function'}], 'refusal': None} response_metadata={'token_usage': {'completion_tokens': 106, 'prompt_tokens': 1070, 'total_tokens': 1176, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 1024}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_eb9dce56a8', 'finish_reason': 'tool_calls', 'logprobs': None} id='run-e3e64b4b-4505-4a71-bf02-a8d77bb68eee-0' tool_calls=[{'name': 'ads4gpts_inline_sponsored_response', 'args': {'id': 'unique_user_id_001', 'user_gender': 'male', 'user_age': '18-24', 'ad_recommendation': 'Stylish and trendy clothing suitable for young men going out with friends.', 'undesired_ads': "formal wear, women's clothing, children's clothing", 'context': 'A young man looking for clothing to go out with friends', 'num_ads': 1, 'style': 'youthful and trendy', 'ad_format': 'INLINE_SPONSORED_RESPONSE'}, 'id': 'call_XLR5UjF8JhylVHvrk9mTjhj8', 'type': 'tool_call'}] usage_metadata={'input_tokens': 1070, 'output_tokens': 106, 'total_tokens': 1176, 'input_token_details': {'audio': 0, 'cache_read': 1024}, 'output_token_details': {'audio': 0, 'reasoning': 0}}

API 参考

您可以在我们的 GitHub 上了解更多关于 ADS4GPTs 和这些工具的信息。
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.