This topic describes how to integrate the Information Query Service OpenAPI (HTTP version) with agent platforms such as Platform for AI (PAI), Model Studio, and Dify, and agent development frameworks compatible with OpenAI APIs.
Agent platforms
PAI integration
Platform for AI (PAI) is an all-in-one machine learning platform from Alibaba Cloud designed for developers.
-
To quickly build an agent with web search capabilities, follow the instructions in Build a DeepSeek Web Search Application with LangStudio and Information Query Service.
-
PAI-EAS Spot is a cost-effective deployment solution for online inference services. When deploying a service using PAI-EAS Spot, follow the instructions in Best Practices for Building an AI Q&A System with RAG and Web Search Integration to integrate the Information Query Service.
Model Studio integration
-
In the Model Studio console, create a custom plug-in.
Set the Plugin name to Information Query Service, the Plugin description to "The 'Information Query Service' is a powerful real-time search API that provides structured data from multiple search engines and knowledge bases.", and the Plugin URL to https://cloud-iqs.aliyuncs.com/search. Turn on the Enable authentication switch. For Authentication type, select Service-level authentication. For Location, select Header. For Type, select bearer. In the Token field, enter your IQS API key.
-
Create a tool based on the Web Search (Text Search) API. The following steps use Lite Search as an example.
-
Tool name: common-search
-
Tool description:
The universal search API provides enhanced, real-time search capabilities across the open web. It leverages large model optimization and multi-source data fusion to deliver clean, accurate, diverse, and high-quality results. -
Tool path: https://cloud-iqs.aliyuncs.com/search/unified
-
Input parameters:
-
query: The search query (required)
-
engineType: The search engine type (optional, passthrough). Refer to the documentation to configure this parameter.
-
-
Set the Request method to POST and the Content type to application/json. Set the parameter mapping for the query parameter to Recognized by LLM and for the engineType parameter to Business passthrough. Configure the output parameter: set the Parameter name to pageItems, the Parameter description to Search Results, and the Type to String.
-
After you finish testing, publish the plug-in. You can then use the 'Information Query Service' plug-in in your Model Studio applications and configure its business parameters as needed.
On the Application configuration page, in the Skills area, click the + icon next to Plugins to add the required plug-in. Then, in the toolbar at the top of the Conversation preview panel on the right, click the Bar chart icon to configure business parameters.
On the Application debugging interface, click Input parameter configuration. In the dialog box that appears, find the engineType field for the common-search tool, enter GenericAdvanced, and click Confirm.
Dify integration
Custom tools in Dify
-
Create a custom tool using the API definition from the OpenAPI Specification.
Click Create Custom Tool. In the dialog box that appears, enter a Name for the tool and paste the OpenAPI 3.1.0-formatted JSON definition into the Schema area. You can also import it by clicking the Import from URL button. The system then automatically parses the schema and lists the tool's name, description, request method, and path in the Available tools table.
-
Configure the authentication method.
In the Authentication method dialog box, select API key as the authentication type. For Authentication header prefix, select Custom. Enter X-API-Key for the Key and your API key for the Value. Click Save.
-
Test the API.
In the custom tool list, select the target tool (for example, Tongxiao). This opens the Test GetGenericSearch dialog box. Select API key as the authentication method. In the parameters area, enter a parameter name (such as query) and its corresponding value, and then click Test. The API then returns the structured search results below in JSON format.
Workflows in Dify
-
Create an 'Information Query Service' workflow.
In the Create blank app dialog box, select Workflow as the application type, enter a name and description, and then click Create.
-
Add a 'query' workflow variable.
Set the field type to Text and the maximum length to 100, select the required checkbox, and then click Save.
-
Add an 'HTTP Request' node.
Configure the HTTP Request node: select GET as the request method and enter the target API endpoint. In the HEADERS section, add X-API-Key and enter your API key. In the PARAMS section, bind the query workflow variable as a query parameter. Set the timeout and retry policy as needed.
-
Add a 'Code Execution' node to transform the HTTP request output variable.
Configure the Code Execution node: map the input variable body from the HTTP request's body (String type). Use Python 3 code with import json to parse the body into JSON and assign it to the output variable search_result (Object type).
-
Add a 'Template Transform' node to convert the results into text for the large model.
{%- if search_result and search_result.pageItems -%}
{% for pageItem in search_result.pageItems %}
---
- Title:
{{ pageItem.title }}
- URL:
{{ pageItem.link }}
- Snippet:
{{ pageItem.snippet }}
Text:
{{ pageItem.mainText }}
---
{% endfor %}
{% endif %}
-
Add an 'End' node.
In the configuration panel for the End node, add an output variable named search_result. Set its source to the output of the Template Transform node and its type to String.
-
Test and publish as a tool.
Click the Run button in the upper-right corner of the canvas to start the test. Review the execution trace and output for each node to ensure the workflow runs correctly before you publish it as a tool.
Click the Publish button in the upper-right corner to open the drop-down menu, and select Publish as tool.
In the Publish as tool dialog box, set the Name to "Tongxiao" and the Tool invocation name to generic_search. Set the Tool description to "'Tongxiao' is a powerful real-time search API that provides structured data from multiple search engines and knowledge bases." In the Tool input parameters table, set the parameter name to query, the type to text-input, and the method to Fill by LLM. Set the description to query to search. Fill in the Tags and Privacy policy fields as needed. Click Save to finish publishing.
Development integration
Before running the following code, ensure that Python and its required dependencies are installed in your environment.
OpenAI
Example call
This example shows how to use function calling through an OpenAI-compatible API to build a smart search agent.
from openai import OpenAI
from datetime import datetime
import json
import os
import requests
class TongxiaoSearch:
def __init__(self):
self.BACKEND = "https://cloud-iqs.aliyuncs.com"
self.headers = {
"X-API-Key": os.getenv('TONGXIAO_API_KEY')
}
self.timeout = 5
def generic_search(self, query: str):
url = f"{self.BACKEND}/search/genericSearch?query={query}"
try:
response = requests.get(url, headers=self.headers, timeout=self.timeout)
if response.status_code != requests.codes.ok:
raise RuntimeError(
f"GenericSearch request failed with status code: {response.status_code}"
)
search_resp = json.loads(response.text)
return search_resp["pageItems"]
except requests.HTTPError as e:
raise RuntimeError(f"Request to {url} failed: {e}")
# Define the tool list. The model uses the name and description to decide which tool to call.
tools = [
{
"type": "function",
"function": {
"name": "generic_search",
"description": "Provides real-time search capabilities for the open domain.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query (length: >=2 and <=100)"
}
}
},
"required": [
"query"
]
}
}
]
# Information Query Service - standard search
def generic_search(query: str):
page_items = TongxiaoSearch().generic_search(query)
page_results = []
for page_item in page_items:
if page_item.get('publishTime'):
publish_date = datetime.fromtimestamp(page_item.get('publishTime') / 1000.0).date()
else:
publish_date = ''
page_result = (
f"Title: {page_item.get('title', '')}\n"
f"URL: {page_item.get('link', '')}\n"
f"Published Date: {publish_date}\n"
f"Snippet: {page_item.get('snippet', '')}\n"
f"Text: {page_item.get('mainText', '')}\n\n"
)
page_results.append(page_result)
return "---\n".join(page_results)
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
def get_response(messages):
completion = client.chat.completions.create(
model="qwen-plus", # The qwen-plus model is used as an example. You can replace it with another model as needed. For a list of models, see https://help.aliyun.com/document_detail/2596482.html
messages=messages,
tools=tools
)
return completion.model_dump()
def call_with_messages():
messages = [
{"role": "system", "content": "You are an AI-powered web search engine designed to help users find and summarize information on the internet. Avoid unnecessary chatter and focus on the content.\n"
"Before you answer, you must use the search tool (generic_search) to get information.\n"
f"Today's date: {datetime.now().strftime('%a, %b %d, %Y')}"},
{"role": "user", "content": "Alibaba"}
]
# The first model call
i = 1
first_response = get_response(messages)
assistant_output = first_response['choices'][0]['message']
print(f"\nRound {i} model output: {first_response}\n")
if assistant_output['content'] is None:
assistant_output['content'] = ""
messages.append(assistant_output)
if assistant_output['tool_calls'] is None: # If a tool call is not required, print the reply directly.
print(f"No tool call is needed. I can reply directly: {assistant_output['content']}")
return
# If a tool call is needed, make multiple calls to the model until it determines that no more tool calls are necessary.
while assistant_output['tool_calls'] is not None:
tool_name = assistant_output['tool_calls'][0]['function']['name']
if tool_name == 'generic_search':
tool_info = {"name": "generic_search", "role":"tool"}
# Extract argument information
query = json.loads(assistant_output['tool_calls'][0]['function']['arguments'])['query']
tool_info['content'] = generic_search(query)
else:
tool_info = {"role":"tool", "name": tool_name, "content": ""}
print(f"Tool output:\n{tool_info['content']}\n")
messages.append(tool_info)
assistant_output = get_response(messages)['choices'][0]['message']
if assistant_output['content'] is None:
assistant_output['content'] = ""
messages.append(assistant_output)
i += 1
print(f"Round {i} model output: {assistant_output}\n")
print(f"Final answer: {assistant_output['content']}")
if __name__ == '__main__':
call_with_messages()