跳到主要內容
Open In ColabOpen on GitHub

ADS4GPTs

將 AI 原生廣告整合到您的 Agentic 應用程式中。

總覽

本筆記本概述如何直接在 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)
API 參考文件:ChatOpenAI
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 和工具的資訊

  • 工具概念指南
  • 工具操作指南

此頁面有幫助嗎?