File size: 13,152 Bytes
860fd4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""Machine-readable discovery for the ideaX library API."""
from pathlib import Path


def agent_prompt(base_url=None, requires_key=False):
    base_url = base_url or '本说明所在服务的根地址(从 /llms.txt URL 去掉 /llms.txt)'
    auth = ('所有 /api/v1 请求需要 Authorization: Bearer <API_KEY>;使用服务所有者提供的凭据。'
            if requires_key else '当前公开可读,无需 API key。')
    auth += ' 所有接口只读,不接受任意 SQL、创建、更新或删除;本服务不提供执行研究生成的 HTTP 接口。'
    template = Path(__file__).with_name('library_api_agent_prompt.md').read_text(encoding='utf-8')
    return template.replace('{{BASE_URL}}', base_url).replace('{{AUTH_NOTE}}', auth)


def llms_text(requires_key=False):
    auth = 'All /api/v1 routes require Authorization: Bearer <API_KEY>.\n' if requires_key else 'This instance permits public, read-only access.\n'
    return '# Copyable prompt for agents / 可直接交给其他 agent 的提示词\n\n' + agent_prompt(requires_key=requires_key) + '''

# ideaX / litgraph research domains API

Read /openapi.json for parameter and response schemas.
''' + auth + '''
1. GET /api/v1/domains?q=distillation&limit=20 finds research domains by name or ID.
   Omit q to browse all domains; use page.next_offset as offset for the next page.
2. GET /api/v1/domains/knowledge-distillation returns domain details and counts.
3. GET /api/v1/domains/knowledge-distillation/insights?limit=20
   GET /api/v1/domains/knowledge-distillation/problems?limit=20
   list the domain's insights and problems. Add q for lexical search within the domain.
   Add sort=paper_count&limit=N for the N entries with the most distinct supporting
   papers. paper_count is the deduplicated size of supporting_papers, NOT external
   citation counts or a quality/novelty score. Ties use entry ID ascending.
   q may filter matches before ranking. Use page.next_offset for ranked pagination;
   after is not accepted with sort=paper_count. Each page supports 1–100 entries.
   When exploring a chosen domain, read its insights broadly: start without q
   with sort=paper_count&limit=50 (or all available if fewer), then paginate as
   domain size and context budget allow. Compare mechanisms, assumptions, and
   failure conditions; inspect promising entries and source papers, and connect
   them to the domain's problems. Follow with targeted searches for relevant
   lower-support entries. Keep entry IDs, reading counts, and coverage gaps.
4. GET /api/v1/domains/knowledge-distillation/papers?limit=20
   lists ALL papers assigned to the domain, including papers without extracted
   source cards. source_card_available=false distinguishes those records.
   Use page.next_after as after for subsequent pages. Optional q searches titles.
5. GET /api/v1/search?q=on-policy%20distillation&kind=problem&mode=all&limit=10
   searches problem statements, mechanisms, scopes, and technique names.
   kind=insight searches transferable insights. Omit kind to search both.
   fields=techniques searches named techniques; fields=statement,mechanism narrows
   the searched fields. Use mode=any for broader recall or Chinese search terms.
   unit=knowledge-distillation restricts the research domain.
6. GET /api/v1/entries/{entry_id} returns the complete entry, member evidence,
   source paper IDs, and technique names. Read it before applying a mechanism.
7. GET /api/v1/papers/{paper_id} returns paper metadata and its structured source
   card when available, plus the paper's domain memberships.
   These numeric IDs are NOT the W-prefixed IDs used in the separate lineage DB.
8. GET /api/v1/papers/by-arxiv?id=2605.07865 returns matching papers.
9. POST /api/v1/papers/batch with JSON {"ids":[203336,172353]} reads up to 50
   source cards. This POST only reads data; missing_ids lists absent IDs.
10. GET /api/v1/entries?kind=insight&limit=100 browses entries. Continue using
   page.next_after as after. Search and paper_count-ranked pages use page.next_offset as offset.
11. GET /api/v1/stats reports the snapshot counts. GET /health is a liveness check.

Responses use {"ok":true,"data":...}; list/search responses also contain page.
Errors use {"ok":false,"error":{"code":"...","message":"..."}}.
Search uses lexical field-specific BM25, with Chinese bigram tokenization.
The score is a ranking value (lower ranks first), not confidence or applicability.
This API does not provide embedding/vector search, arbitrary SQL, or mutations.

Evidence limits:
- Entries and source cards are extracted/merged research materials, not paper PDFs
  or full text. Source coverage and extraction quality vary; inspect evidence.
- Supporting papers support the source entry, not a new hypothesis you derive.
- Results have NOT been masked. Do not use this live corpus as a date-safe or
  result-blind benchmark without a separately prepared snapshot.
- A failed search does not establish novelty. Search both Chinese and English,
  inspect source cards, and verify the closest original papers independently.
'''


def openapi(requires_key=False):
    success = {'description': 'Read succeeded', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/Envelope'}}}}
    error = {'description': 'Request rejected or resource unavailable', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/Error'}}}}

    def operation(summary, parameters=None):
        value = {'summary': summary, 'responses': {'200': success, '400': error, '404': error, '503': error}}
        if parameters:
            value['parameters'] = parameters
        if requires_key:
            value['security'] = [{'BearerAuth': []}]
            value['responses']['401'] = error
        return value

    def query(name, schema, description='', required=False):
        return {'name': name, 'in': 'query', 'required': required, 'schema': schema, 'description': description}

    parameters = [
        query('q', {'type': 'string', 'minLength': 1, 'maxLength': 500}, 'Lexical query; Chinese or English.'),
        query('kind', {'type': 'string', 'enum': ['problem', 'insight']}),
        query('unit', {'type': 'string'}, 'Research domain ID returned by /units.'),
        query('fields', {'type': 'string', 'default': 'statement,mechanism,scope,techniques'}, 'Comma-separated subset of statement,mechanism,scope,techniques.'),
        query('mode', {'type': 'string', 'enum': ['all', 'any'], 'default': 'all'}, 'Require every token or match any token.'),
        query('sort', {'type': 'string', 'enum': ['id', 'relevance', 'paper_count']},
              'Default: relevance with q, otherwise id. paper_count sorts distinct supporting-paper count descending, then entry ID ascending; not external citations. q filters before sorting. relevance requires q.'),
        query('limit', {'type': 'integer', 'minimum': 1, 'maximum': 100, 'default': 20}),
        query('offset', {'type': 'integer', 'minimum': 0, 'maximum': 10000, 'default': 0}, 'Search or paper_count pagination; use page.next_offset. Prefer after for ID-ordered browsing.'),
        query('after', {'type': 'string'}, 'ID-ordered browsing only; cannot combine with q, paper_count sorting, or nonzero offset.'),
    ]
    search_parameters = [dict(p, required=True) if p['name'] == 'q' else p for p in parameters if p['name'] != 'after']
    batch = operation('Read up to 50 source paper cards; no database writes')
    batch['x-read-only'] = True
    batch_schema = {
        'type': 'object', 'required': ['ids'], 'additionalProperties': False,
        'properties': {'ids': {'type': 'array', 'minItems': 1, 'maxItems': 50,
                               'items': {'oneOf': [{'type': 'integer', 'minimum': 0}, {'type': 'string', 'pattern': '^[0-9]{1,20}$'}]}}}}
    batch['requestBody'] = {'required': True, 'content': {'application/json': {'schema': batch_schema}}}
    paths = {
        '/health': {'get': {'summary': 'Liveness', 'responses': {'200': success}}},
        '/api/v1/stats': {'get': operation('Snapshot counts')},
        '/api/v1/units': {'get': operation('Research domains and per-kind counts')},
        '/api/v1/domains': {'get': operation('Browse or search litgraph research domains', [
            query('q', {'type': 'string'}, 'Matches domain name and ID.'),
            query('limit', {'type': 'integer', 'minimum': 1, 'maximum': 100, 'default': 50}),
            query('offset', {'type': 'integer', 'minimum': 0, 'maximum': 10000, 'default': 0})])},
        '/api/v1/search': {'get': operation('Search problem, insight, and technique fields', search_parameters)},
        '/api/v1/entries': {'get': operation('Browse or search entries', parameters)},
        '/api/v1/entries/{entry_id}': {'get': operation('Complete entry and provenance', [
            {'name': 'entry_id', 'in': 'path', 'required': True, 'schema': {'type': 'string'}, 'example': 'knowledge-distillation-P0062'}])},
        '/api/v1/papers/{paper_id}': {'get': operation('Structured source paper card', [
            {'name': 'paper_id', 'in': 'path', 'required': True, 'schema': {'type': 'string', 'pattern': '^[0-9]{1,20}$'}, 'example': '203336'}])},
        '/api/v1/papers/by-arxiv': {'get': operation('Source cards matching an arXiv ID', [
            query('id', {'type': 'string'}, 'Version suffixes and arXiv URLs are accepted.', True)])},
        '/api/v1/papers/batch': {'post': batch},
    }
    domain_param = {'name': 'domain_id', 'in': 'path', 'required': True, 'schema': {'type': 'string'}, 'example': 'knowledge-distillation'}
    paths['/api/v1/domains/{domain_id}'] = {'get': operation('Domain details and counts', [domain_param])}
    for resource in ('insights', 'problems'):
        paths['/api/v1/domains/{domain_id}/' + resource] = {'get': operation(
            'Browse or search this domain\'s ' + resource,
            [domain_param] + [p for p in parameters if p['name'] not in ('unit', 'kind')])}
    paths['/api/v1/domains/{domain_id}/papers'] = {'get': operation('All papers assigned to this domain, including metadata-only papers', [
        domain_param, query('q', {'type': 'string'}, 'Search paper titles.'),
        query('limit', {'type': 'integer', 'minimum': 1, 'maximum': 100, 'default': 20}),
        query('after', {'type': 'string'}, 'Paper ID returned as page.next_after.')])}
    for path, item in paths.items():
        if path in ('/api/v1/search', '/api/v1/entries', '/api/v1/entries/{entry_id}') or path.endswith(('/insights', '/problems')):
            data_schema = {'$ref': '#/components/schemas/Entry'}
            if path != '/api/v1/entries/{entry_id}':
                data_schema = {'type': 'array', 'items': data_schema}
            item['get']['responses']['200'] = {'description': 'Entries include paper_count (distinct supporting papers)',
                'content': {'application/json': {'schema': {'allOf': [
                    {'$ref': '#/components/schemas/Envelope'},
                    {'type': 'object', 'properties': {'data': data_schema}}]}}}}
    return {
        'openapi': '3.0.3',
        'info': {'title': 'ideaX / litgraph Read-only Domains API', 'version': '1.1.0',
                 'description': 'Research domains, their insights/problems, all member papers, and source cards. Read /llms.txt for evidence limits. Results are not masked.'},
        'paths': paths,
        'components': {
            'securitySchemes': {'BearerAuth': {'type': 'http', 'scheme': 'bearer'}},
            'schemas': {
                'Entry': {'type': 'object', 'required': ['id', 'paper_count'], 'properties': {
                    'id': {'type': 'string'}, 'kind': {'type': 'string', 'enum': ['insight', 'problem']},
                    'statement': {'type': 'string', 'nullable': True},
                    'supporting_papers': {'type': 'array', 'nullable': True, 'items': {
                        'oneOf': [{'type': 'integer'}, {'type': 'string'}]}},
                    'paper_count': {'type': 'integer', 'minimum': 0,
                        'description': 'Distinct numeric IDs in supporting_papers. Missing/null/empty lists count as 0. Not external citation count, quality, or novelty.'}}},
                'Envelope': {'type': 'object', 'required': ['ok', 'data'], 'properties': {
                    'ok': {'type': 'boolean', 'enum': [True]}, 'data': {}, 'page': {
                        'type': 'object', 'properties': {'limit': {'type': 'integer'}, 'count': {'type': 'integer'},
                            'has_more': {'type': 'boolean'}, 'sort': {'type': 'string', 'enum': ['id', 'relevance', 'paper_count']},
                            'next_offset': {'type': 'integer', 'nullable': True},
                            'next_after': {'type': 'string', 'nullable': True}}}}},
                'Error': {'type': 'object', 'required': ['ok', 'error'], 'properties': {
                    'ok': {'type': 'boolean', 'enum': [False]}, 'error': {'type': 'object', 'required': ['code', 'message'],
                    'properties': {'code': {'type': 'string'}, 'message': {'type': 'string'}}}}},
            },
        },
    }