wencai.py
Overview
The wencai.py file implements an interface to interact with WenCai (iwencai), a Chinese financial data and stock selection platform powered by AI technologies. The WenCai platform provides comprehensive and timely financial information, including news, announcements, research reports, and quantitative stock/fund selection tools. This file encapsulates the parameters, invocation logic, and response processing required to query WenCai's services using the third-party pywencai Python package.
Key functionalities include:
Defining tool parameters and validation for WenCai queries.
Executing queries to the WenCai platform with retry and timeout management.
Processing and formatting the complex response objects (dataframes, dicts, strings) into markdown reports.
Providing an interface for integration with a larger agent-based system, following standardized ToolBase conventions.
Classes and Functions
WenCaiParam
class WenCaiParam(ToolParamBase):
Description
WenCaiParam encapsulates the configuration parameters for querying the WenCai platform. It extends the generic ToolParamBase class, adding WenCai-specific parameters and validation.
Attributes
meta(ToolMeta): Metadata describing the tool's name ("iwencai"), a detailed description of the WenCai platform, and the input parameters schema.top_n(int): Number of top results to retrieve from the query. Default is 10.query_type(str): The financial instrument category to query. Allowed values include'stock','zhishu','fund','hkstock','usstock','threeboard','conbond','insurance','futures','lccp', and'foreign_exchange'. Default is'stock'.
Methods
init(self)Initializes the parameter object with default values and metadata.
check(self)Validates the parameters:
Ensures
top_nis a positive integer.Ensures
query_typeis one of the allowed values.
get_input_form(self) -> dict[str, dict]Returns a dictionary describing the expected input form for the tool:
{ "query": { "name": "Query", "type": "line" } }This defines that the tool expects a single line string input named "Query".
Usage Example
param = WenCaiParam()
param.top_n = 5
param.query_type = "fund"
param.check() # Validates parameters, raises if invalid
input_form = param.get_input_form()
print(input_form)
WenCai
class WenCai(ToolBase, ABC):
Description
WenCai is the main tool class that implements the logic to query the WenCai platform and process its results. It inherits from ToolBase and Python's ABC (abstract base class), integrating with the agent framework.
Class Attributes
component_name(str): Set to"WenCai", identifies the component name.
Methods
_invoke(self, **kwargs)The core method that executes the query. It is decorated with a
timeoutdecorator, which limits the execution time based on theCOMPONENT_EXEC_TIMEOUTenvironment variable (default 12 seconds).Parameters:
kwargs: Should contain at least a"query"key with the search string.
Behavior:
If no query is provided, it sets an empty report output and returns immediately.
Attempts to query WenCai up to
max_retries + 1times (max_retriesis a parameter fromself._param).Uses
pywencai.get()to fetch data, passing:query: the query string,query_type: from parameters,perpage: number of results (top_n).
Processes the response:
If response is a Pandas DataFrame, converts it to markdown.
If response is a dict, iterates through items and converts each to markdown or string accordingly, skipping keys like
"meta"or dataframes with"image_url".
Joins all processed parts into a single markdown string and sets it as output under
"report".Logs exceptions and retries after a delay (
self._param.delay_after_error).If all retries fail, sets an error output
_ERRORwith the exception message.
Returns:
The markdown string report on success.
Error string on failure.
thoughts(self) -> strReturns a human-readable string describing the current operation, e.g.,
Pulling live financial data for `{query}`.where
{query}is the current query input.
Usage Example
wencai_tool = WenCai()
wencai_tool._param = WenCaiParam()
wencai_tool._param.top_n = 5
wencai_tool._param.query_type = "stock"
result = wencai_tool._invoke(query="AAPL stock price")
print(result) # Markdown formatted financial data report
Important Implementation Details
Timeout Handling: The
_invokemethod is decorated with a timeout to ensure it does not hang indefinitely due to network or server issues.Retry Logic: Implements retry mechanism controlled by
max_retries(configurable via parameters inherited fromToolParamBase) to improve robustness.Response Processing: The
pywencai.get()API returns heterogeneous data types (DataFrame, dict, string). The code carefully inspects the type of each returned item and converts it to markdown or simple string format to create a unified textual report.Skipping Certain Data: Some keys like
"meta"or dataframes containing"image_url"are ignored during processing to avoid irrelevant or non-text data.Integration: Uses
set_output()andoutput()methods from the base class to manage outputs, fitting into a larger agent or tool orchestration framework.Logging: Exceptions during querying are logged with full traceback for debugging.
Integration with the Larger System
This file depends on:
pywencai: External library to query the WenCai platform.pandas: For data manipulation and markdown formatting.agent.tools.base: Provides base classes (ToolParamBase,ToolMeta,ToolBase) to integrate with a modular agent framework.api.utils.api_utils.timeout: Decorator to control execution time of component calls.
It is designed to be a plugin/tool module that can be invoked by an agent or workflow engine when a user or system requests financial data retrieval or stock/fund selection analysis.
The input is typically a free-text query string describing the desired financial data or stock selection criteria.
Outputs are markdown reports that can be rendered in UI components, logs, or further processed by other system parts.
Visual Diagram
classDiagram
class WenCaiParam {
+meta: ToolMeta
+top_n: int
+query_type: str
+__init__()
+check()
+get_input_form() dict
}
class WenCai {
+component_name: str
+_invoke(kwargs) str
+thoughts() str
}
WenCaiParam <|-- WenCai : uses parameter object
WenCai ..|> ToolBase
WenCai ..|> ABC
Summary
The wencai.py file provides a robust and well-structured integration point with the WenCai financial platform. It cleanly separates parameter configuration from execution logic, handles diverse response formats gracefully, and ensures resilience through retries and timeouts. Its design supports seamless embedding into larger AI agents or financial analytics systems, enabling users to query rich live financial data and receive neatly formatted analysis reports.