Skip to content

feat:Update /v2/chat OpenAPI examples with expanded multi-language streaming samples #228

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 15, 2025

Conversation

HavenDV
Copy link
Contributor

@HavenDV HavenDV commented Jul 15, 2025

Summary by CodeRabbit

  • Documentation
    • Enhanced and expanded example code samples for the chat streaming endpoint, including multi-language examples demonstrating usage with documents and tools.
    • Updated example payloads to use a structured document format and standardized naming conventions for streaming samples.
    • Added detailed streaming event sequences and tool integration examples to improve clarity for API users.

Copy link

coderabbitai bot commented Jul 15, 2025

Walkthrough

The changes update the OpenAPI specification for the /v2/chat endpoint, focusing on improving and expanding example code samples. Enhancements include restructuring document data in examples, standardizing example naming, and adding detailed multi-language streaming chat examples that demonstrate the use of documents and tools, as well as streaming event handling.

Changes

File(s) Change Summary
src/libs/Cohere/openapi.yaml Updated and expanded /v2/chat endpoint examples: restructured document data, standardized example names, and added comprehensive multi-language streaming chat samples with documents and tools, including detailed request/response and streaming event sequences.

Poem

In the meadow of docs, new samples appear,
Streaming with tools and documents near.
Events now flow, deltas in tow,
Examples in Python, TypeScript, and Go!
With structured delight, the endpoints ignite—
A bunny’s proud hop for specs done right.
🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bot/update-openapi_202507150201

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@HavenDV HavenDV enabled auto-merge (squash) July 15, 2025 02:01
@HavenDV HavenDV merged commit af96731 into main Jul 15, 2025
3 of 4 checks passed
@HavenDV HavenDV deleted the bot/update-openapi_202507150201 branch July 15, 2025 02:04
@coderabbitai coderabbitai bot changed the title feat:@coderabbitai feat:Update /v2/chat OpenAPI examples with expanded multi-language streaming samples Jul 15, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/libs/Cohere/openapi.yaml (3)

7713-7715: TS streaming example logs the whole message object, not the text

console.log(chatEvent.delta?.message) prints an object; most developers expect the actual text.
Replace with:

-  if (chatEvent.type === 'content-delta') {
-    console.log(chatEvent.delta?.message);
-  }
+  if (chatEvent.type === 'content-delta') {
+    console.log(chatEvent.delta?.message?.content?.text);
+  }

8060-8062: Typo: duplicated article in description

"Connects to a a product catalog ..." contains a double “a”.

- "Connects to a a product catalog
+ "Connects to a product catalog

8100-8350: Example stream is excessively verbose

The tool_plan-delta event list spells out the reply character-by-character, inflating the spec by ~500 lines. This hurts diff readability and slows Doc site rendering.

Trim the example to a handful of representative deltas (start, a mid-delta, end) and replace the middle with an ellipsis.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aacc614 and bf144df.

📒 Files selected for processing (1)
  • src/libs/Cohere/openapi.yaml (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Test / Build, test and publish
🔇 Additional comments (2)
src/libs/Cohere/openapi.yaml (2)

7917-7922: Missing id field in documents array

Later samples (e.g. cURL request at 7934-7938) include id: "1", but the TS & Python “Documents” streaming examples omit it. To avoid validation errors for APIs that require an id, add the field:

-    documents: [
-      {
-        data: { text: 'Cohere is the best!' },
-      },
-    ],
+    documents: [
+      { id: '1', data: { text: 'Cohere is the best!' } },
+    ],

8057-8060: Inconsistent parameter name between SDKs (day vs date)

The Go SDK example defines the sales report parameter as "date", but every other example (and the JSON schema) uses "day". Standardise on one to prevent copy-paste errors.

Comment on lines +7573 to 7576
- code: "const { CohereClientV2 } = require('cohere-ai');\n\nconst cohere = new CohereClientV2({});\n\n(async () => {\n const response = await cohere.chat({\n model: 'command-a-03-2025',\n documents: [{ id: '1', data: { text: 'Cohere is the best!' } }],\n messages: [\n {\n role: 'user',\n content: [{ type: 'text', text: \"Who's the best?\" }],\n },\n ],\n });\n\n console.log(response);\n})();\n"
name: Documents
sdk: typescript
- code: "import cohere\n\nco = cohere.ClientV2()\n\nresponse = co.chat(\n model=\"command-a-03-2025\",\n documents=[\n {\"id\": \"1\", \"data\": {\"text\": \"Cohere is the best!\", \"title\": \"The best\"}}\n ],\n messages=[{\"role\": \"user\", \"content\": \"Who's the best?\"}],\n)\n\nprint(response)\n"
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Inconsistent message payload shape between TypeScript & Python examples

The TS snippet wraps message content in an array of { type, text } objects, while the immediately-following Python snippet passes a plain string. This discrepancy is likely to confuse users about the canonical payload shape.

Consider choosing one representation (ideally the array form that mirrors the wire format) and applying it uniformly across all SDK examples in this section.

🤖 Prompt for AI Agents
In src/libs/Cohere/openapi.yaml around lines 7573 to 7576, the TypeScript
example wraps the message content in an array of objects with type and text
fields, while the Python example uses a plain string for the message content. To
fix this inconsistency, update the Python example to use the same array of
objects format for the message content as the TypeScript example, ensuring
uniformity in the message payload shape across SDK examples.

Comment on lines +8050 to +8062
sdk: typescript
- code: "import cohere\n\nco = cohere.ClientV2()\n\nresponse = co.chat_stream(\n model=\"command-a-03-2025\",\n tools=[\n cohere.ToolV2(\n type=\"function\",\n function={\n \"name\": \"query_daily_sales_report\",\n \"description\": \"Connects to a database to retrieve overall sales volumes and sales information for a given day.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"day\": {\n \"description\": \"Retrieves sales data for this day, formatted as YYYY-MM-DD.\",\n \"type\": \"string\",\n }\n },\n \"required\": [\"day\"],\n },\n },\n ),\n cohere.ToolV2(\n type=\"function\",\n function={\n \"name\": \"query_product_catalog\",\n \"description\": \"Connects to a product catalog with information about all the products being sold, including categories, prices, and stock levels.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"category\": {\n \"description\": \"Retrieves product information data for all products in this category.\",\n \"type\": \"string\",\n }\n },\n \"required\": [\"category\"],\n },\n },\n ),\n ],\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"Can you provide a sales summary for 29th September 2023, and also give me some details about the products in the 'Electronics' category, for example their prices and stock levels?\",\n }\n ],\n)\n\nfor event in response:\n if event.type in [\"tool-call-start\", \"tool-call-delta\"]:\n for tool_call in event.delta.message.tool_calls:\n print(tool_call)\n"
name: Tools
sdk: python
- code: "/* (C)2024 */\npackage chatv2post;\n\nimport com.cohere.api.Cohere;\nimport com.cohere.api.resources.v2.requests.V2ChatStreamRequest;\nimport com.cohere.api.types.*;\nimport java.util.List;\nimport java.util.Map;\n\npublic class StreamTools {\n public static void main(String[] args) {\n Cohere cohere = Cohere.builder().clientName(\"snippet\").build();\n\n Iterable<StreamedChatResponseV2> response =\n cohere\n .v2()\n .chatStream(\n V2ChatStreamRequest.builder()\n .model(\"command-a-03-2025\")\n .tools(\n List.of(\n ToolV2.builder()\n .function(\n ToolV2Function.builder()\n .name(\"query_daily_sales_report\")\n .description(\n \"Connects to a database to retrieve overall sales volumes and sales information for a given day.\")\n .parameters(\n Map.of(\n \"day\",\n ToolParameterDefinitionsValue.builder()\n .type(\"str\")\n .description(\n \"Retrieves sales data for this day, formatted as YYYY-MM-DD.\")\n .required(true)\n .build()))\n .build())\n .build(),\n ToolV2.builder()\n .function(\n ToolV2Function.builder()\n .name(\"query_product_catalog\")\n .description(\n \"Connects to a product catalog with information about all the products being sold, including categories, prices, and stock levels.\")\n .parameters(\n Map.of(\n \"category\",\n ToolParameterDefinitionsValue.builder()\n .type(\"str\")\n .description(\n \"Retrieves product information data for all products in this category.\")\n .required(true)\n .build()))\n .build())\n .build()))\n .messages(\n List.of(\n ChatMessageV2.user(\n UserMessage.builder()\n .content(\n UserMessageContent.of(\n \"Can you provide a sales summary for 29th September 2023, and also give me some details about the products in the 'Electronics' category?\"))\n .build())))\n .build());\n\n for (StreamedChatResponseV2 chatResponse : response) {\n if (chatResponse.isContentDelta()) {\n String text =\n chatResponse\n .getContentDelta()\n .flatMap(ChatContentDeltaEvent::getDelta)\n .flatMap(ChatContentDeltaEventDelta::getMessage)\n .flatMap(ChatContentDeltaEventDeltaMessage::getContent)\n .flatMap(ChatContentDeltaEventDeltaMessageContent::getText)\n .orElse(\"\");\n System.out.println(text);\n }\n }\n }\n}\n"
name: Tools
sdk: java
- code: "package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\tcohere \"github.com/cohere-ai/cohere-go/v2\"\n\tclient \"github.com/cohere-ai/cohere-go/v2/client\"\n)\n\nfunc main() {\n\tco := client.NewClient(client.WithToken(os.Getenv(\"CO_API_KEY\")))\n\n\tresp, err := co.V2.ChatStream(\n\t\tcontext.TODO(),\n\t\t&cohere.V2ChatStreamRequest{\n\t\t\tModel: \"command-a-03-2025\",\n\t\t\tTools: []*cohere.ToolV2{\n\t\t\t\t{\n\t\t\t\t\tType: cohere.String(\"function\"),\n\t\t\t\t\tFunction: &cohere.ToolV2Function{\n\t\t\t\t\t\tName: \"query_daily_sales_report\",\n\t\t\t\t\t\tDescription: cohere.String(\"Connects to a database to retrieve overall sales volumes and sales information for a given day.\"),\n\t\t\t\t\t\tParameters: map[string]interface{}{\n\t\t\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\t\t\"properties\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"date\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\t\t\t\t\"description\": \"Retrieves sales data from this day, formatted as YYYY-MM-DD\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"required\": []string{\"date\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType: cohere.String(\"function\"),\n\t\t\t\t\tFunction: &cohere.ToolV2Function{\n\t\t\t\t\t\tName: \"query_product_catalog\",\n\t\t\t\t\t\tDescription: cohere.String(\"Connects to a product catalog with information about all the products being sold, including categories, prices, and stock levels.\"),\n\t\t\t\t\t\tParameters: map[string]interface{}{\n\t\t\t\t\t\t\t\"type\": \"object\",\n\t\t\t\t\t\t\t\"properties\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"category\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\t\"type\": \"string\",\n\t\t\t\t\t\t\t\t\t\"description\": \"Retrieves product information data for all products in this category.\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"required\": []string{\"category\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tMessages: cohere.ChatMessages{\n\t\t\t\t{\n\t\t\t\t\tRole: \"user\",\n\t\t\t\t\tUser: &cohere.UserMessage{Content: &cohere.UserMessageContent{\n\t\t\t\t\t\tString: \"Can you provide a sales summary for 29th September 2023, and also give me some details about the products in the 'Electronics' category, for example their prices and stock levels?\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Make sure to close the stream when you're done reading.\n\t// This is easily handled with defer.\n\tdefer resp.Close()\n\n\tfor {\n\t\tmessage, err := resp.Recv()\n\n\t\tif errors.Is(err, io.EOF) {\n\t\t\t// An io.EOF error means the server is done sending messages\n\t\t\t// and should be treated as a success.\n\t\t\tbreak\n\t\t}\n\n\t\t// Log the received message\n\t\tif message.ToolCallDelta != nil {\n\t\t\tlog.Printf(\"%+v\", message)\n\t\t}\n\t}\n}\n"
name: Tools
sdk: go
- code: "curl --request POST \\\n --url https://api.cohere.com/v2/chat \\\n --header 'accept: application/json' \\\n --header 'content-type: application/json' \\\n --header \"Authorization: bearer $CO_API_KEY\" \\\n --data '{\n \"stream\": true,\n \"model\": \"command-a-03-2025\",\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"query_daily_sales_report\",\n \"description\": \"Connects to a database to retrieve overall sales volumes and sales information for a given day.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"day\": {\n \"description\": \"Retrieves sales data for this day, formatted as YYYY-MM-DD.\",\n \"type\": \"string\"\n }\n }\n }\n }\n },\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"query_product_catalog\",\n \"description\": \"Connects to a a product catalog with information about all the products being sold, including categories, prices, and stock levels.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"category\": {\n \"description\": \"Retrieves product information data for all products in this category.\",\n \"type\": \"string\"\n }\n }\n }\n }\n }\n ],\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Can you provide a sales summary for 29th September 2023, and also give me some details about the products in the 'Electronics' category, for example their prices and stock levels?\"\n }\n ]\n }'\n"
name: Tools
sdk: curl
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Tool parameter schema: required array missing

In the TS “Tools” example each function’s parameters object lacks the required array that is present in the Python & OpenAPI JSON examples. Omitting it changes the schema semantics.

Add "required": ["day"] / "required": ["category"] respectively to keep SDK examples aligned with the spec.

🤖 Prompt for AI Agents
In src/libs/Cohere/openapi.yaml around lines 8050 to 8062, the TypeScript SDK
example for the Tools functions is missing the "required" arrays in the
parameters schema for both "query_daily_sales_report" and
"query_product_catalog". To fix this, add a "required" array with the
appropriate required parameter names ("day" for the daily sales report and
"category" for the product catalog) inside each function's parameters object to
align with the Python and OpenAPI JSON examples and maintain consistent schema
semantics.

Comment on lines 7715 to 7720
- code: "const { CohereClientV2 } = require('cohere-ai');\n\nconst cohere = new CohereClientV2({});\n\n(async () => {\n const stream = await cohere.chatStream({\n model: 'command-a-03-2025',\n messages: [\n {\n role: 'user',\n content: 'hello world!',\n },\n ],\n });\n\n for await (const chatEvent of stream) {\n if (chatEvent.type === 'content-delta') {\n console.log(chatEvent.delta?.message);\n }\n }\n})();\n"
name: Streaming
name: Default
sdk: typescript
- code: "import cohere\n\nco = cohere.ClientV2()\n\nresponse = co.chat_stream(\n model=\"command-a-03-2025\",\n messages=[{\"role\": \"user\", \"content\": \"hello world!\"}],\n)\n\nfor event in response:\n if event.type == \"content-delta\":\n print(event.delta.message.content.text, end=\"\")\n"
name: Streaming
name: Default
sdk: python
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

“Default” sample names collide across SDKs

All streaming code-sample blocks are renamed to "Default". When rendered by tooling (e.g. Swagger-UI, Redoc), identical names collapse into a single tab, so only the first SDK remains visible.

Rename each sample to something unique per SDK (e.g. “Default – TypeScript”, “Default – Python”).

🤖 Prompt for AI Agents
In src/libs/Cohere/openapi.yaml around lines 7715 to 7720, the code sample
blocks for different SDKs are all named "Default," causing them to collapse into
a single tab in documentation tools. Rename each sample's "name" field to a
unique value that includes the SDK name, such as "Default – TypeScript" for the
TypeScript sample and "Default – Python" for the Python sample, to ensure they
appear as separate tabs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant