-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.rs
More file actions
2475 lines (2324 loc) · 87.8 KB
/
client.rs
File metadata and controls
2475 lines (2324 loc) · 87.8 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::auth::AuthConfig;
use crate::error::{LangstarError, Result};
use crate::runs::{QueryRunsRequest, QueryRunsResponse, Run};
use futures_core::Stream;
use reqwest::{Client as HttpClient, RequestBuilder};
use serde::{Deserialize, Serialize};
use std::pin::Pin;
use std::time::Duration;
/// Base URLs for LangChain services
pub const LANGSMITH_API_BASE: &str = "https://api.smith.langchain.com";
pub const LANGGRAPH_API_BASE: &str = "https://api.langgraph.cloud";
pub const CONTROL_PLANE_API_BASE: &str = "https://api.host.langchain.com";
/// HTTP client for interacting with LangChain APIs
#[derive(Clone)]
pub struct LangchainClient {
http_client: HttpClient,
auth: AuthConfig,
langsmith_base_url: String,
langgraph_base_url: String,
control_plane_base_url: String,
/// Optional organization ID for API requests (used in x-organization-id header)
organization_id: Option<String>,
/// Optional workspace ID for narrower scoping (used in X-Tenant-Id header)
workspace_id: Option<String>,
}
impl LangchainClient {
/// Create a new client with the given authentication configuration
///
/// The client will use organization_id and workspace_id from the AuthConfig
/// to automatically add the appropriate scoping headers to API requests.
pub fn new(auth: AuthConfig) -> Result<Self> {
let http_client = HttpClient::builder()
.timeout(Duration::from_secs(30))
.build()?;
let organization_id = auth.organization_id.clone();
let workspace_id = auth.workspace_id.clone();
Ok(Self {
http_client,
auth,
langsmith_base_url: LANGSMITH_API_BASE.to_string(),
langgraph_base_url: LANGGRAPH_API_BASE.to_string(),
control_plane_base_url: CONTROL_PLANE_API_BASE.to_string(),
organization_id,
workspace_id,
})
}
/// Set the organization ID for API requests
///
/// Some write operations may require an organization ID to be specified.
/// This adds the x-organization-id header to subsequent requests.
pub fn with_organization_id(mut self, org_id: String) -> Self {
self.organization_id = Some(org_id);
self
}
/// Get the current organization ID if set
pub fn organization_id(&self) -> Option<&str> {
self.organization_id.as_deref()
}
/// Set the workspace ID for API requests
///
/// Workspace ID provides narrower scoping than organization ID.
/// This adds the X-Tenant-Id header to subsequent requests.
/// Per LangSmith documentation, both x-organization-id and X-Tenant-Id
/// can be used together for workspace-scoped requests.
pub fn with_workspace_id(mut self, workspace_id: String) -> Self {
self.workspace_id = Some(workspace_id);
self
}
/// Get the current workspace ID if set
pub fn workspace_id(&self) -> Option<&str> {
self.workspace_id.as_deref()
}
/// Override the LangGraph base URL for deployment-specific operations
///
/// This method allows you to set a custom LangGraph deployment URL
/// instead of using the default `https://api.langgraph.cloud`.
/// This is useful when targeting a specific LangGraph deployment
/// that has a custom URL (e.g., from Control Plane API's `custom_url` field).
///
/// # Arguments
/// * `url` - The custom deployment URL (e.g., "https://my-deployment.us.langgraph.app")
///
/// # Example
/// ```no_run
/// # use langstar_sdk::{LangchainClient, AuthConfig};
/// # let auth = AuthConfig::new(Some("key".into()), None, None);
/// let client = LangchainClient::new(auth).unwrap()
/// .with_langgraph_url("https://my-deployment.us.langgraph.app".to_string());
/// ```
pub fn with_langgraph_url(mut self, url: String) -> Self {
self.langgraph_base_url = url;
self
}
/// Create a new client with custom base URLs (useful for testing)
pub fn with_base_urls(
auth: AuthConfig,
langsmith_base_url: String,
langgraph_base_url: String,
control_plane_base_url: String,
) -> Result<Self> {
let http_client = HttpClient::builder()
.timeout(Duration::from_secs(30))
.build()?;
let organization_id = auth.organization_id.clone();
let workspace_id = auth.workspace_id.clone();
Ok(Self {
http_client,
auth,
langsmith_base_url,
langgraph_base_url,
control_plane_base_url,
organization_id,
workspace_id,
})
}
/// Create a GET request to LangSmith API
///
/// Per LangSmith documentation, both x-organization-id and X-Tenant-Id
/// headers can be used together for workspace-scoped requests.
pub fn langsmith_get(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langsmith_base_url, path);
let mut request = self
.http_client
.get(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json");
// Add organization ID header if set (should be present on all requests per docs)
if let Some(org_id) = &self.organization_id {
request = request.header("x-organization-id", org_id);
}
// Add workspace ID header if set (for workspace-scoped requests)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a POST request to LangSmith API
///
/// Per LangSmith documentation, both x-organization-id and X-Tenant-Id
/// headers can be used together for workspace-scoped requests.
pub fn langsmith_post(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langsmith_base_url, path);
let mut request = self
.http_client
.post(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json");
// Add organization ID header if set (should be present on all requests per docs)
if let Some(org_id) = &self.organization_id {
request = request.header("x-organization-id", org_id);
}
// Add workspace ID header if set (for workspace-scoped requests)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a PUT request to LangSmith API
///
/// Per LangSmith documentation, both x-organization-id and X-Tenant-Id
/// headers can be used together for workspace-scoped requests.
pub fn langsmith_put(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langsmith_base_url, path);
let mut request = self
.http_client
.put(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json");
// Add organization ID header if set (should be present on all requests per docs)
if let Some(org_id) = &self.organization_id {
request = request.header("x-organization-id", org_id);
}
// Add workspace ID header if set (for workspace-scoped requests)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a PATCH request to LangSmith API
///
/// Per LangSmith documentation, both x-organization-id and X-Tenant-Id
/// headers can be used together for workspace-scoped requests.
pub fn langsmith_patch(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langsmith_base_url, path);
let mut request = self
.http_client
.patch(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json");
// Add organization ID header if set (should be present on all requests per docs)
if let Some(org_id) = &self.organization_id {
request = request.header("x-organization-id", org_id);
}
// Add workspace ID header if set (for workspace-scoped requests)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a DELETE request to LangSmith API
///
/// Per LangSmith documentation, both x-organization-id and X-Tenant-Id
/// headers can be used together for workspace-scoped requests.
pub fn langsmith_delete(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langsmith_base_url, path);
let mut request = self
.http_client
.delete(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json");
// Add organization ID header if set (should be present on all requests per docs)
if let Some(org_id) = &self.organization_id {
request = request.header("x-organization-id", org_id);
}
// Add workspace ID header if set (for workspace-scoped requests)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a GET request to Control Plane API
///
/// The Control Plane API uses the same authentication as LangSmith:
/// X-Api-Key (LangSmith API key) and X-Tenant-Id (workspace ID) headers.
pub fn control_plane_get(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.control_plane_base_url, path);
let mut request = self
.http_client
.get(&url)
.header("X-Api-Key", api_key)
.header("Content-Type", "application/json");
// Add workspace ID header if set (required for Control Plane API)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a POST request to Control Plane API
///
/// The Control Plane API uses the same authentication as LangSmith:
/// X-Api-Key (LangSmith API key) and X-Tenant-Id (workspace ID) headers.
pub fn control_plane_post(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.control_plane_base_url, path);
let mut request = self
.http_client
.post(&url)
.header("X-Api-Key", api_key)
.header("Content-Type", "application/json");
// Add workspace ID header if set (required for Control Plane API)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a PATCH request to Control Plane API
///
/// The Control Plane API uses the same authentication as LangSmith:
/// X-Api-Key (LangSmith API key) and X-Tenant-Id (workspace ID) headers.
pub fn control_plane_patch(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.control_plane_base_url, path);
let mut request = self
.http_client
.patch(&url)
.header("X-Api-Key", api_key)
.header("Content-Type", "application/json");
// Add workspace ID header if set (required for Control Plane API)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a DELETE request to Control Plane API
///
/// The Control Plane API uses the same authentication as LangSmith:
/// X-Api-Key (LangSmith API key) and X-Tenant-Id (workspace ID) headers.
pub fn control_plane_delete(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.control_plane_base_url, path);
let mut request = self
.http_client
.delete(&url)
.header("X-Api-Key", api_key)
.header("Content-Type", "application/json");
// Add workspace ID header if set (required for Control Plane API)
if let Some(ws_id) = &self.workspace_id {
request = request.header("X-Tenant-Id", ws_id);
}
Ok(request)
}
/// Create a GET request to LangGraph API
///
/// ## Deployment-Level Resources
///
/// **Important:** Unlike `langsmith_get()`, this method does NOT add organization
/// or workspace scoping headers (`x-organization-id`, `X-Tenant-Id`).
///
/// LangGraph assistants are deployment-level resources. The API key used in the
/// request is tied to a specific deployment, and all operations are automatically
/// scoped to that deployment. No additional scoping is needed or supported.
///
/// ### Why No Scoping Headers?
///
/// LangGraph and LangSmith have different resource models:
/// - **LangSmith**: Hierarchical (Organization → Workspace → Prompts)
/// - **LangGraph**: Flat (API Key → Deployment → Assistants)
///
/// This is the intended design, not a limitation. Access control for LangGraph
/// resources is managed entirely at the API key/deployment level.
///
/// For more details, see the [LangGraph Cloud documentation](https://langchain-ai.github.io/langgraph/cloud/).
pub fn langgraph_get(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langgraph_base_url, path);
Ok(self
.http_client
.get(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json"))
}
/// Create a POST request to LangGraph API
///
/// ## Deployment-Level Resources
///
/// **Important:** Unlike `langsmith_post()`, this method does NOT add organization
/// or workspace scoping headers (`x-organization-id`, `X-Tenant-Id`).
///
/// LangGraph assistants are deployment-level resources. The API key used in the
/// request is tied to a specific deployment, and all operations are automatically
/// scoped to that deployment. No additional scoping is needed or supported.
///
/// ### Why No Scoping Headers?
///
/// LangGraph and LangSmith have different resource models:
/// - **LangSmith**: Hierarchical (Organization → Workspace → Prompts)
/// - **LangGraph**: Flat (API Key → Deployment → Assistants)
///
/// This is the intended design, not a limitation. Access control for LangGraph
/// resources is managed entirely at the API key/deployment level.
///
/// For more details, see the [LangGraph Cloud documentation](https://langchain-ai.github.io/langgraph/cloud/).
pub fn langgraph_post(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langgraph_base_url, path);
Ok(self
.http_client
.post(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json"))
}
/// Create a PATCH request to LangGraph API
pub fn langgraph_patch(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langgraph_base_url, path);
Ok(self
.http_client
.patch(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json"))
}
/// Create a DELETE request to LangGraph API
pub fn langgraph_delete(&self, path: &str) -> Result<RequestBuilder> {
let api_key = self.auth.require_langsmith_key()?;
let url = format!("{}{}", self.langgraph_base_url, path);
Ok(self
.http_client
.delete(&url)
.header("x-api-key", api_key)
.header("Content-Type", "application/json"))
}
/// Execute a request that returns no response body (status-only response).
///
/// This helper is used for API endpoints that only return a status code
/// without a response body (e.g., DELETE operations, some PATCH/PUT operations).
///
/// # Arguments
/// * `request` - The configured RequestBuilder to execute
///
/// # Returns
/// * `Ok(())` if the request succeeds (2xx status)
/// * `Err(LangstarError::ApiError)` if the request fails
pub async fn execute_status_only_request(&self, request: RequestBuilder) -> Result<()> {
let response = request.send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(LangstarError::ApiError {
status: status.as_u16(),
message: error_text,
});
}
Ok(())
}
/// Execute a request and parse the response
pub async fn execute<T: for<'de> Deserialize<'de>>(
&self,
request: RequestBuilder,
) -> Result<T> {
let response = request.send().await?;
let status = response.status();
if !status.is_success() {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
return Err(LangstarError::ApiError {
status: status.as_u16(),
message: error_text,
});
}
// DEBUG: Log response details before parsing (for #509 investigation)
// Check for LANGSTAR_DEBUG_HTTP environment variable
if std::env::var("LANGSTAR_DEBUG_HTTP").is_ok() {
eprintln!("=== LANGSTAR HTTP DEBUG ===");
eprintln!("Status: {}", status);
// Log headers
eprintln!("Headers:");
for (name, value) in response.headers() {
eprintln!(" {}: {:?}", name, value);
}
// Get response body as text first to inspect it
// NOTE: This consumes the response, so we parse from the captured text below
// and return early (line 546) to avoid trying to use the consumed response
let body_text = response.text().await?;
eprintln!("Body length: {} bytes", body_text.len());
// Write full response to file for detailed analysis
// Use environment variable override or platform temp dir for cross-platform support
let debug_path = std::env::var("LANGSTAR_DEBUG_FILE")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| std::env::temp_dir().join("langstar_debug_response.json"));
if let Ok(mut file) = std::fs::File::create(&debug_path) {
use std::io::Write;
let _ = file.write_all(body_text.as_bytes());
eprintln!("Full response written to: {}", debug_path.display());
}
eprintln!(
"Body preview (first 500 chars): {}",
if body_text.len() > 500 {
&body_text[..500]
} else {
&body_text
}
);
eprintln!(
"Body preview (last 100 chars): {}",
if body_text.len() > 100 {
&body_text[body_text.len() - 100..]
} else {
&body_text
}
);
eprintln!("===========================");
// Parse the body we already retrieved
let data: T = serde_json::from_str(&body_text).map_err(|e| {
eprintln!("!!! JSON PARSE ERROR !!!");
eprintln!("Error: {}", e);
eprintln!("Line: {}, Column: {}", e.line(), e.column());
if let Some(pos) = body_text.char_indices().nth(e.column().saturating_sub(1)) {
let context_start = pos.0.saturating_sub(50);
let context_end = (pos.0 + 50).min(body_text.len());
eprintln!(
"Context around error: ...{}...",
&body_text[context_start..context_end]
);
}
eprintln!("!!! END ERROR !!!");
e
})?;
return Ok(data);
}
let data = response.json::<T>().await?;
Ok(data)
}
/// Get the underlying HTTP client
pub fn http_client(&self) -> &HttpClient {
&self.http_client
}
// ═══════════════════════════════════════════════════════════════════════
// Annotation Queues API Methods
// ═══════════════════════════════════════════════════════════════════════
/// List annotation queues with optional filtering.
///
/// # Arguments
///
/// * `params` - Query parameters including filters (name, name_contains, ids)
///
/// # Returns
///
/// A vector of `AnnotationQueue` objects matching the query.
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient, ListAnnotationQueuesParams};
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let params = ListAnnotationQueuesParams {
/// name_contains: Some("review".to_string()),
/// limit: Some(50),
/// ..Default::default()
/// };
///
/// let queues = client.list_annotation_queues(params).await?;
/// println!("Found {} queues", queues.len());
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `GET /api/v1/annotation-queues`
/// - Max limit per request: 100 (per OpenAPI spec)
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn list_annotation_queues(
&self,
params: crate::annotation_queues::ListAnnotationQueuesParams,
) -> Result<Vec<crate::annotation_queues::AnnotationQueue>> {
let request = self.langsmith_get("/api/v1/annotation-queues")?;
// Add query parameters
let request = if let Some(ids) = params.ids {
request.query(&[(
"ids",
ids.iter()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(","),
)])
} else {
request
};
let request = if let Some(name) = params.name {
request.query(&[("name", name)])
} else {
request
};
let request = if let Some(name_contains) = params.name_contains {
request.query(&[("name_contains", name_contains)])
} else {
request
};
let request = if let Some(limit) = params.limit {
request.query(&[("limit", limit)])
} else {
request
};
self.execute(request).await
}
/// Create a new annotation queue.
///
/// # Arguments
///
/// * `request` - Queue creation parameters including name, description, and configuration
///
/// # Returns
///
/// The created queue with full details including rubric information.
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient, CreateAnnotationQueueRequest, QueueType};
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let request = CreateAnnotationQueueRequest {
/// name: "Production Review".to_string(),
/// description: Some("Review production LLM outputs".to_string()),
/// queue_type: Some(QueueType::Single),
/// rubric_instructions: Some("Rate accuracy and helpfulness".to_string()),
/// ..Default::default()
/// };
///
/// let queue = client.create_annotation_queue(request).await?;
/// println!("Created queue: {}", queue.base.name);
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `POST /api/v1/annotation-queues`
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn create_annotation_queue(
&self,
request: crate::annotation_queues::CreateAnnotationQueueRequest,
) -> Result<crate::annotation_queues::AnnotationQueueWithDetails> {
let request_builder = self
.langsmith_post("/api/v1/annotation-queues")?
.json(&request);
self.execute(request_builder).await
}
/// Get an annotation queue by ID.
///
/// # Arguments
///
/// * `queue_id` - The UUID of the annotation queue
///
/// # Returns
///
/// The queue with full details including rubric information.
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient};
/// # use uuid::Uuid;
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let queue_id = Uuid::parse_str("12345678-1234-1234-1234-123456789012").unwrap();
/// let queue = client.read_annotation_queue(queue_id).await?;
/// println!("Queue: {} ({})", queue.base.name, queue.base.id);
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `GET /api/v1/annotation-queues/{queue_id}`
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn read_annotation_queue(
&self,
queue_id: uuid::Uuid,
) -> Result<crate::annotation_queues::AnnotationQueueWithDetails> {
let path = format!("/api/v1/annotation-queues/{}", queue_id);
let request = self.langsmith_get(&path)?;
self.execute(request).await
}
/// Update an annotation queue.
///
/// # Arguments
///
/// * `queue_id` - The UUID of the annotation queue to update
/// * `request` - Update parameters (all fields are optional for partial updates)
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient, UpdateAnnotationQueueRequest};
/// # use uuid::Uuid;
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let queue_id = Uuid::parse_str("12345678-1234-1234-1234-123456789012").unwrap();
/// let request = UpdateAnnotationQueueRequest {
/// name: Some("Updated Queue Name".to_string()),
/// description: Some("New description".to_string()),
/// ..Default::default()
/// };
///
/// client.update_annotation_queue(queue_id, request).await?;
/// println!("Queue updated successfully");
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `PATCH /api/v1/annotation-queues/{queue_id}`
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn update_annotation_queue(
&self,
queue_id: uuid::Uuid,
request: crate::annotation_queues::UpdateAnnotationQueueRequest,
) -> Result<()> {
let path = format!("/api/v1/annotation-queues/{}", queue_id);
let request_builder = self.langsmith_put(&path)?.json(&request);
self.execute_status_only_request(request_builder).await
}
/// Delete an annotation queue.
///
/// # Arguments
///
/// * `queue_id` - The UUID of the annotation queue to delete
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient};
/// # use uuid::Uuid;
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let queue_id = Uuid::parse_str("12345678-1234-1234-1234-123456789012").unwrap();
/// client.delete_annotation_queue(queue_id).await?;
/// println!("Queue deleted successfully");
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `DELETE /api/v1/annotation-queues/{queue_id}`
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn delete_annotation_queue(&self, queue_id: uuid::Uuid) -> Result<()> {
let path = format!("/api/v1/annotation-queues/{}", queue_id);
let request = self.langsmith_delete(&path)?;
self.execute_status_only_request(request).await
}
/// Add runs to an annotation queue.
///
/// # Arguments
///
/// * `queue_id` - The UUID of the annotation queue
/// * `run_ids` - Vector of run UUIDs to add to the queue
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient};
/// # use uuid::Uuid;
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let queue_id = Uuid::parse_str("12345678-1234-1234-1234-123456789012").unwrap();
/// let run_ids = vec![
/// Uuid::parse_str("abcdef01-1234-1234-1234-123456789012").unwrap(),
/// Uuid::parse_str("abcdef02-1234-1234-1234-123456789012").unwrap(),
/// ];
///
/// client.add_runs_to_annotation_queue(queue_id, run_ids).await?;
/// println!("Runs added successfully");
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `POST /api/v1/annotation-queues/{queue_id}/runs`
/// - Request body: JSON array of UUID strings
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn add_runs_to_annotation_queue(
&self,
queue_id: uuid::Uuid,
run_ids: Vec<uuid::Uuid>,
) -> Result<()> {
let path = format!("/api/v1/annotation-queues/{}/runs", queue_id);
// Convert UUIDs to strings for JSON serialization
let run_id_strings: Vec<String> = run_ids.iter().map(|id| id.to_string()).collect();
let request_builder = self.langsmith_post(&path)?.json(&run_id_strings);
self.execute_status_only_request(request_builder).await
}
/// Remove a run from an annotation queue.
///
/// # Arguments
///
/// * `queue_id` - The UUID of the annotation queue
/// * `run_id` - The UUID of the run to remove
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient};
/// # use uuid::Uuid;
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let queue_id = Uuid::parse_str("12345678-1234-1234-1234-123456789012").unwrap();
/// let run_id = Uuid::parse_str("abcdef01-1234-1234-1234-123456789012").unwrap();
///
/// client.delete_run_from_annotation_queue(queue_id, run_id).await?;
/// println!("Run removed successfully");
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `DELETE /api/v1/annotation-queues/{queue_id}/runs/{run_id}`
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn delete_run_from_annotation_queue(
&self,
queue_id: uuid::Uuid,
run_id: uuid::Uuid,
) -> Result<()> {
let path = format!("/api/v1/annotation-queues/{}/runs/{}", queue_id, run_id);
let request = self.langsmith_delete(&path)?;
self.execute_status_only_request(request).await
}
/// Get a run from an annotation queue at the specified index.
///
/// # Arguments
///
/// * `queue_id` - The UUID of the annotation queue
/// * `index` - Zero-based index of the run in the queue
///
/// # Returns
///
/// A `RunWithAnnotationQueueInfo` containing the run data and queue-specific metadata.
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient};
/// # use uuid::Uuid;
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let queue_id = Uuid::parse_str("12345678-1234-1234-1234-123456789012").unwrap();
/// let run = client.get_run_from_annotation_queue(queue_id, 0).await?;
/// println!("Run: {} (added at: {:?})", run.run.name, run.added_at);
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `GET /api/v1/annotation-queues/{queue_id}/run/{index}`
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn get_run_from_annotation_queue(
&self,
queue_id: uuid::Uuid,
index: u32,
) -> Result<crate::annotation_queues::RunWithAnnotationQueueInfo> {
let path = format!("/api/v1/annotation-queues/{}/run/{}", queue_id, index);
let request = self.langsmith_get(&path)?;
self.execute(request).await
}
// ═══════════════════════════════════════════════════════════════════════
// Runs API Methods
// ═══════════════════════════════════════════════════════════════════════
/// Query runs from LangSmith with filtering and pagination.
///
/// Uses `POST /api/v1/runs/query` endpoint with cursor-based pagination.
/// Supports the LangSmith filter query language for complex filtering.
///
/// # Arguments
///
/// * `request` - Query parameters including filters, pagination, and field selection
///
/// # Returns
///
/// A `QueryRunsResponse` containing the matching runs and pagination cursors.
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient, QueryRunsRequest, RunType};
/// # async fn example() -> langstar_sdk::Result<()> {
/// let auth = AuthConfig::from_env()?;
/// let client = LangchainClient::new(auth)?;
///
/// let request = QueryRunsRequest {
/// is_root: Some(true),
/// run_type: Some(RunType::Llm),
/// limit: Some(50),
/// ..Default::default()
/// };
///
/// let response = client.query_runs(request).await?;
/// println!("Found {} runs", response.runs.len());
/// # Ok(())
/// # }
/// ```
///
/// # API Reference
///
/// - Endpoint: `POST /api/v1/runs/query`
/// - Max limit per request: 100 (per OpenAPI spec)
/// - OpenAPI spec: <https://api.smith.langchain.com/openapi.json>
pub async fn query_runs(&self, request: QueryRunsRequest) -> Result<QueryRunsResponse> {
let request_builder = self.langsmith_post("/api/v1/runs/query")?.json(&request);
self.execute(request_builder).await
}
/// Query runs with automatic pagination, returning a stream of runs.
///
/// This method handles cursor-based pagination automatically, fetching
/// additional pages as needed until the total limit is reached or no
/// more results are available.
///
/// # Arguments
///
/// * `request` - Base query parameters (cursor field will be managed automatically)
/// * `total_limit` - Optional maximum number of runs to return across all pages.
/// If `None`, fetches all matching runs.
///
/// # Returns
///
/// A `Stream` of `Result<Run>` that yields runs one at a time.
///
/// # Example
///
/// ```no_run
/// # use langstar_sdk::{AuthConfig, LangchainClient, QueryRunsRequest, RunType};
/// # use futures_core::Stream;
/// # async fn example() -> langstar_sdk::Result<()> {