Skip to content

Commit c2719f7

Browse files
committed
improve ai chat
1 parent e8ff476 commit c2719f7

7 files changed

Lines changed: 1396 additions & 28 deletions

File tree

app/api/chat/route.ts

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { convertToModelMessages, stepCountIs, streamText, tool, type UIMessage }
33
import { z } from 'zod';
44
import { source } from '@/lib/source';
55
import { Document, type DocumentData } from 'flexsearch';
6+
import apiEndpoints from '@/lib/generated/api-endpoints.json';
67

78
interface CustomDocument extends DocumentData {
89
url: string;
@@ -39,6 +40,10 @@ async function createSearchServer() {
3940
if (doc) search.add(doc);
4041
}
4142

43+
for (const ep of apiEndpoints) {
44+
search.add(ep as CustomDocument);
45+
}
46+
4247
return search;
4348
}
4449

@@ -67,30 +72,22 @@ const systemPrompt = [
6772
].join('\n');
6873

6974
export async function POST(req: Request) {
70-
const reqJson: { messages?: UIMessage[]; pageUrl?: string } = await req.json();
71-
72-
let contextPrompt = systemPrompt;
73-
if (reqJson.pageUrl) {
74-
const page = source.getPages().find((p) => p.url === reqJson.pageUrl);
75-
if (page) {
76-
contextPrompt += `\n\nThe user is currently viewing the page "${page.data.title}" (${reqJson.pageUrl}). Use this to prioritize relevant search results.`;
77-
}
78-
}
75+
const reqJson: { messages?: UIMessage[] } = await req.json();
7976

8077
const result = streamText({
8178
model: openrouter.chat(process.env.OPENROUTER_MODEL ?? 'anthropic/claude-3.5-sonnet'),
79+
maxTokens: 4096,
8280
stopWhen: stepCountIs(5),
8381
tools: {
8482
search: searchTool,
8583
},
8684
messages: [
87-
{ role: 'system', content: contextPrompt },
85+
{ role: 'system', content: systemPrompt },
8886
...(await convertToModelMessages(reqJson.messages ?? [])),
8987
],
90-
prepareStep: ({ stepNumber }) =>
91-
stepNumber === 0 && reqJson.messages?.length === 1
92-
? { toolChoice: 'required' }
93-
: { toolChoice: 'auto' },
88+
prepareStep: ({ stepNumber }) => ({
89+
toolChoice: stepNumber === 0 ? 'required' : 'auto',
90+
}),
9491
});
9592

9693
return result.toUIMessageStreamResponse();
@@ -100,11 +97,21 @@ const searchTool = tool({
10097
description: 'Search the docs content and return raw JSON results.',
10198
inputSchema: z.object({
10299
query: z.string(),
103-
limit: z.number().int().min(1).max(100).default(10),
100+
limit: z.number().int().min(1).max(20).default(5),
104101
}),
105102
async execute({ query, limit }) {
106103
const search = await searchServer;
107-
return await search.searchAsync(query, { limit, merge: true, enrich: true });
104+
const results = await search.searchAsync(query, { limit, merge: true, enrich: true });
105+
// Truncate content to avoid flooding the context window
106+
return results.map((r: any) => ({
107+
...r,
108+
result: r.result?.map((doc: any) => ({
109+
...doc,
110+
doc: doc.doc
111+
? { ...doc.doc, content: doc.doc.content?.slice(0, 1500) }
112+
: doc.doc,
113+
})),
114+
}));
108115
},
109116
});
110117

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
title: Carts Calculate
3+
description: Calculate cart summary.
4+
full: true
5+
_openapi:
6+
method: POST
7+
toc: []
8+
structuredData:
9+
headings: []
10+
contents:
11+
- content: Calculate cart summary.
12+
---
13+
14+
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
15+
16+
<APIPage document={"public/api/campaigns/v1.yaml"} operations={[{"path":"/api/v1/carts/calculate/","method":"post"}]} />

lib/generated/api-endpoints.json

Lines changed: 1100 additions & 0 deletions
Large diffs are not rendered by default.

lib/generated/api-methods.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@
527527
"/docs/campaigns/api/campaigns/campaign-retrieve": "GET",
528528
"/docs/campaigns/api/campaigns/campaignRetrieve": "GET",
529529
"/docs/campaigns/api/carts/carts-create": "POST",
530+
"/docs/campaigns/api/carts/cartsCalculate": "POST",
530531
"/docs/campaigns/api/carts/cartsCreate": "POST",
531532
"/docs/campaigns/api/cartsCreate": "POST",
532533
"/docs/campaigns/api/orderRetrieve": "GET",

public/api/campaigns/v1.yaml

Lines changed: 196 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,29 @@ components:
375375
- lines
376376
- user
377377
type: object
378+
CartCalculateSummary:
379+
properties:
380+
currency:
381+
description: ISO 4217 currency code (e.g., USD, EUR, GBP), defaults to the
382+
campaign currency if not provided
383+
nullable: true
384+
type: string
385+
lines:
386+
description: Array of package IDs
387+
items:
388+
$ref: '#/components/schemas/LineWithUpsell'
389+
type: array
390+
shipping_method:
391+
description: Selected shipping method ID
392+
type: integer
393+
vouchers:
394+
description: Campaign offer codes or store coupon code
395+
items:
396+
type: string
397+
type: array
398+
required:
399+
- lines
400+
type: object
378401
CartLine:
379402
properties:
380403
id:
@@ -427,6 +450,48 @@ components:
427450
- id
428451
- quantity
429452
type: object
453+
CartSummary:
454+
properties:
455+
currency:
456+
description: Cart currency in ISO 4217 format (e.g., USD, EUR, GBP)
457+
maxLength: 3
458+
type: string
459+
lines:
460+
items:
461+
$ref: '#/components/schemas/SummaryLine'
462+
type: array
463+
offer_discounts:
464+
description: Array of offer discounts applied to the cart
465+
items:
466+
$ref: '#/components/schemas/Discount'
467+
type: array
468+
shipping_method:
469+
allOf:
470+
- $ref: '#/components/schemas/SummaryShippingMethod'
471+
description: Selected shipping method details
472+
subtotal:
473+
description: Cart subtotal before discounts
474+
format: decimal
475+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
476+
type: string
477+
total:
478+
description: Cart total after discounts
479+
format: decimal
480+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
481+
type: string
482+
total_discount:
483+
description: Total discount applied to the cart
484+
format: decimal
485+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
486+
type: string
487+
voucher_discounts:
488+
description: Array of voucher discounts applied to the cart
489+
items:
490+
$ref: '#/components/schemas/Discount'
491+
type: array
492+
required:
493+
- currency
494+
type: object
430495
Country:
431496
properties:
432497
code:
@@ -511,15 +576,24 @@ components:
511576
Discount:
512577
properties:
513578
amount:
579+
description: Discount amount
514580
format: decimal
515581
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
516582
type: string
517583
description:
518-
maxLength: 255
584+
description: Description of the discount
519585
type: string
520586
name:
521-
maxLength: 255
587+
description: Name of the discount
522588
type: string
589+
offer_id:
590+
description: ID of the applied offer
591+
type: integer
592+
required:
593+
- amount
594+
- description
595+
- name
596+
- offer_id
523597
type: object
524598
IntervalEnum:
525599
enum:
@@ -1402,6 +1476,98 @@ components:
14021476
required:
14031477
- price
14041478
type: object
1479+
SummaryLine:
1480+
properties:
1481+
discounts:
1482+
description: Array of discounts applied to the line
1483+
items:
1484+
$ref: '#/components/schemas/Discount'
1485+
type: array
1486+
original_package_price:
1487+
description: Package price before discounts
1488+
format: decimal
1489+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1490+
type: string
1491+
original_unit_price:
1492+
description: Unit price before discounts
1493+
format: decimal
1494+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1495+
type: string
1496+
package_id:
1497+
description: Package ID of products to add to the order
1498+
type: integer
1499+
package_price:
1500+
description: Package price after discounts
1501+
format: decimal
1502+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1503+
type: string
1504+
quantity:
1505+
description: Package quantity
1506+
type: integer
1507+
subtotal:
1508+
description: Line total before discounts
1509+
format: decimal
1510+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1511+
type: string
1512+
total:
1513+
description: Line total after discounts
1514+
format: decimal
1515+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1516+
type: string
1517+
total_discount:
1518+
description: Total discount applied to the line
1519+
format: decimal
1520+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1521+
type: string
1522+
unit_price:
1523+
description: Unit price after discounts
1524+
format: decimal
1525+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1526+
type: string
1527+
required:
1528+
- original_package_price
1529+
- original_unit_price
1530+
- package_id
1531+
- package_price
1532+
- quantity
1533+
- subtotal
1534+
- total
1535+
- total_discount
1536+
- unit_price
1537+
type: object
1538+
SummaryShippingMethod:
1539+
properties:
1540+
code:
1541+
description: Shipping method code
1542+
type: string
1543+
discounts:
1544+
description: Array of discounts applied to the shipping method
1545+
items:
1546+
$ref: '#/components/schemas/Discount'
1547+
type: array
1548+
id:
1549+
description: Shipping method ID
1550+
type: integer
1551+
name:
1552+
description: Shipping method name
1553+
type: string
1554+
original_price:
1555+
description: Shipping price before discounts
1556+
format: decimal
1557+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1558+
type: string
1559+
price:
1560+
description: Shipping price after discounts
1561+
format: decimal
1562+
pattern: ^-?\d{0,10}(?:\.\d{0,2})?$
1563+
type: string
1564+
required:
1565+
- code
1566+
- id
1567+
- name
1568+
- original_price
1569+
- price
1570+
type: object
14051571
User:
14061572
properties:
14071573
accepts_marketing:
@@ -1653,21 +1819,12 @@ paths:
16531819
get:
16541820
description: Retrieve campaign details.
16551821
operationId: campaignRetrieve
1656-
parameters:
1657-
- description: ISO 4217 currency code (e.g., USD, EUR, GBP) used to filter available
1658-
packages and shipping methods in the campaign
1659-
in: query
1660-
name: currency
1661-
schema:
1662-
type: string
16631822
responses:
16641823
'200':
16651824
content:
16661825
application/json:
16671826
schema:
1668-
items:
1669-
$ref: '#/components/schemas/Campaign'
1670-
type: array
1827+
$ref: '#/components/schemas/Campaign'
16711828
description: ''
16721829
security:
16731830
- API Authentication: []
@@ -1700,6 +1857,33 @@ paths:
17001857
- API Authentication: []
17011858
tags:
17021859
- carts
1860+
/api/v1/carts/calculate/:
1861+
post:
1862+
description: Calculate cart summary.
1863+
operationId: cartsCalculate
1864+
requestBody:
1865+
content:
1866+
application/json:
1867+
schema:
1868+
$ref: '#/components/schemas/CartCalculateSummary'
1869+
application/x-www-form-urlencoded:
1870+
schema:
1871+
$ref: '#/components/schemas/CartCalculateSummary'
1872+
multipart/form-data:
1873+
schema:
1874+
$ref: '#/components/schemas/CartCalculateSummary'
1875+
required: true
1876+
responses:
1877+
'200':
1878+
content:
1879+
application/json:
1880+
schema:
1881+
$ref: '#/components/schemas/CartSummary'
1882+
description: ''
1883+
security:
1884+
- API Authentication: []
1885+
tags:
1886+
- carts
17031887
/api/v1/orders/:
17041888
post:
17051889
description: Create a new order.

0 commit comments

Comments
 (0)